CombinedText
stringlengths 8
3.42M
|
---|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
#include "base/values.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_ui.h"
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/tab_helper.h"
#endif
using content::RenderViewHost;
using content::WebContents;
using content::WebUIMessageHandler;
namespace {
const char kConstrainedWebDialogDelegateUserDataKey[] =
"ConstrainedWebDialogDelegateUserData";
class ConstrainedWebDialogDelegateUserData
: public base::SupportsUserData::Data {
public:
explicit ConstrainedWebDialogDelegateUserData(
ConstrainedWebDialogDelegate* delegate) : delegate_(delegate) {}
virtual ~ConstrainedWebDialogDelegateUserData() {}
ConstrainedWebDialogDelegate* delegate() { return delegate_; }
private:
ConstrainedWebDialogDelegate* delegate_; // unowned
DISALLOW_COPY_AND_ASSIGN(ConstrainedWebDialogDelegateUserData);
};
} // namespace
ConstrainedWebDialogUI::ConstrainedWebDialogUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
#if defined(ENABLE_EXTENSIONS)
extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
#endif
}
ConstrainedWebDialogUI::~ConstrainedWebDialogUI() {
}
void ConstrainedWebDialogUI::RenderViewCreated(
RenderViewHost* render_view_host) {
ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
if (!delegate)
return;
ui::WebDialogDelegate* dialog_delegate = delegate->GetWebDialogDelegate();
std::vector<WebUIMessageHandler*> handlers;
dialog_delegate->GetWebUIMessageHandlers(&handlers);
render_view_host->SetWebUIProperty("dialogArguments",
dialog_delegate->GetDialogArgs());
for (std::vector<WebUIMessageHandler*>::iterator it = handlers.begin();
it != handlers.end(); ++it) {
web_ui()->AddMessageHandler(*it);
}
// Add a "dialogClose" callback which matches WebDialogUI behavior.
web_ui()->RegisterMessageCallback("dialogClose",
base::Bind(&ConstrainedWebDialogUI::OnDialogCloseMessage,
base::Unretained(this)));
dialog_delegate->OnDialogShown(web_ui(), render_view_host);
}
void ConstrainedWebDialogUI::OnDialogCloseMessage(const base::ListValue* args) {
ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
if (!delegate)
return;
std::string json_retval;
if (!args->empty() && !args->GetString(0, &json_retval))
NOTREACHED() << "Could not read JSON argument";
delegate->GetWebDialogDelegate()->OnDialogClosed(json_retval);
delegate->OnDialogCloseFromWebUI();
}
// static
void ConstrainedWebDialogUI::SetConstrainedDelegate(
content::WebContents* web_contents,
ConstrainedWebDialogDelegate* delegate) {
web_contents->SetUserData(&kConstrainedWebDialogDelegateUserDataKey,
new ConstrainedWebDialogDelegateUserData(delegate));
}
ConstrainedWebDialogDelegate* ConstrainedWebDialogUI::GetConstrainedDelegate() {
ConstrainedWebDialogDelegateUserData* user_data =
static_cast<ConstrainedWebDialogDelegateUserData*>(
web_ui()->GetWebContents()->
GetUserData(&kConstrainedWebDialogDelegateUserDataKey));
return user_data ? user_data->delegate() : NULL;
}
Fix a DCHECK failure by registering a handler for 'dialogClose' message.
This fixes a DCHECK failure on chrome://print, where no handler was
registered to handle chrome.send("dialogClose").
BUG=416783
Review URL: https://codereview.chromium.org/614683002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#297199}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/constrained_web_dialog_ui.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/lazy_instance.h"
#include "base/values.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "ui/web_dialogs/web_dialog_delegate.h"
#include "ui/web_dialogs/web_dialog_ui.h"
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/tab_helper.h"
#endif
using content::RenderViewHost;
using content::WebContents;
using content::WebUIMessageHandler;
namespace {
const char kConstrainedWebDialogDelegateUserDataKey[] =
"ConstrainedWebDialogDelegateUserData";
class ConstrainedWebDialogDelegateUserData
: public base::SupportsUserData::Data {
public:
explicit ConstrainedWebDialogDelegateUserData(
ConstrainedWebDialogDelegate* delegate) : delegate_(delegate) {}
virtual ~ConstrainedWebDialogDelegateUserData() {}
ConstrainedWebDialogDelegate* delegate() { return delegate_; }
private:
ConstrainedWebDialogDelegate* delegate_; // unowned
DISALLOW_COPY_AND_ASSIGN(ConstrainedWebDialogDelegateUserData);
};
} // namespace
ConstrainedWebDialogUI::ConstrainedWebDialogUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
#if defined(ENABLE_EXTENSIONS)
extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
#endif
}
ConstrainedWebDialogUI::~ConstrainedWebDialogUI() {
}
void ConstrainedWebDialogUI::RenderViewCreated(
RenderViewHost* render_view_host) {
// Add a "dialogClose" callback which matches WebDialogUI behavior.
web_ui()->RegisterMessageCallback("dialogClose",
base::Bind(&ConstrainedWebDialogUI::OnDialogCloseMessage,
base::Unretained(this)));
ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
if (!delegate)
return;
ui::WebDialogDelegate* dialog_delegate = delegate->GetWebDialogDelegate();
std::vector<WebUIMessageHandler*> handlers;
dialog_delegate->GetWebUIMessageHandlers(&handlers);
render_view_host->SetWebUIProperty("dialogArguments",
dialog_delegate->GetDialogArgs());
for (std::vector<WebUIMessageHandler*>::iterator it = handlers.begin();
it != handlers.end(); ++it) {
web_ui()->AddMessageHandler(*it);
}
dialog_delegate->OnDialogShown(web_ui(), render_view_host);
}
void ConstrainedWebDialogUI::OnDialogCloseMessage(const base::ListValue* args) {
ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
if (!delegate)
return;
std::string json_retval;
if (!args->empty() && !args->GetString(0, &json_retval))
NOTREACHED() << "Could not read JSON argument";
delegate->GetWebDialogDelegate()->OnDialogClosed(json_retval);
delegate->OnDialogCloseFromWebUI();
}
// static
void ConstrainedWebDialogUI::SetConstrainedDelegate(
content::WebContents* web_contents,
ConstrainedWebDialogDelegate* delegate) {
web_contents->SetUserData(&kConstrainedWebDialogDelegateUserDataKey,
new ConstrainedWebDialogDelegateUserData(delegate));
}
ConstrainedWebDialogDelegate* ConstrainedWebDialogUI::GetConstrainedDelegate() {
ConstrainedWebDialogDelegateUserData* user_data =
static_cast<ConstrainedWebDialogDelegateUserData*>(
web_ui()->GetWebContents()->
GetUserData(&kConstrainedWebDialogDelegateUserDataKey));
return user_data ? user_data->delegate() : NULL;
}
|
// 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 "chrome/browser/views/frame/opaque_non_client_view.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/browser/views/window_resources.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/gfx/path.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/root_view.h"
#include "chromium_strings.h"
#include "generated_resources.h"
// An enumeration of bitmap resources used by this window.
enum {
FRAME_PART_BITMAP_FIRST = 0, // Must be first.
// Window Controls.
FRAME_CLOSE_BUTTON_ICON,
FRAME_CLOSE_BUTTON_ICON_H,
FRAME_CLOSE_BUTTON_ICON_P,
FRAME_CLOSE_BUTTON_ICON_SA,
FRAME_CLOSE_BUTTON_ICON_SA_H,
FRAME_CLOSE_BUTTON_ICON_SA_P,
FRAME_RESTORE_BUTTON_ICON,
FRAME_RESTORE_BUTTON_ICON_H,
FRAME_RESTORE_BUTTON_ICON_P,
FRAME_MAXIMIZE_BUTTON_ICON,
FRAME_MAXIMIZE_BUTTON_ICON_H,
FRAME_MAXIMIZE_BUTTON_ICON_P,
FRAME_MINIMIZE_BUTTON_ICON,
FRAME_MINIMIZE_BUTTON_ICON_H,
FRAME_MINIMIZE_BUTTON_ICON_P,
// Window Frame Border.
FRAME_BOTTOM_EDGE,
FRAME_BOTTOM_LEFT_CORNER,
FRAME_BOTTOM_RIGHT_CORNER,
FRAME_LEFT_EDGE,
FRAME_RIGHT_EDGE,
FRAME_TOP_EDGE,
FRAME_TOP_LEFT_CORNER,
FRAME_TOP_RIGHT_CORNER,
// Window Maximized Border.
FRAME_MAXIMIZED_TOP_EDGE,
FRAME_MAXIMIZED_BOTTOM_EDGE,
// Client Edge Border.
FRAME_CLIENT_EDGE_TOP_LEFT,
FRAME_CLIENT_EDGE_TOP,
FRAME_CLIENT_EDGE_TOP_RIGHT,
FRAME_CLIENT_EDGE_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM,
FRAME_CLIENT_EDGE_BOTTOM_LEFT,
FRAME_CLIENT_EDGE_LEFT,
FRAME_PART_BITMAP_COUNT // Must be last.
};
class ActiveWindowResources : public WindowResources {
public:
ActiveWindowResources() {
InitClass();
}
virtual ~ActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER, IDR_WINDOW_BOTTOM_LEFT_CORNER,
IDR_WINDOW_BOTTOM_RIGHT_CORNER, IDR_WINDOW_LEFT_SIDE,
IDR_WINDOW_RIGHT_SIDE, IDR_WINDOW_TOP_CENTER,
IDR_WINDOW_TOP_LEFT_CORNER, IDR_WINDOW_TOP_RIGHT_CORNER,
IDR_WINDOW_TOP_CENTER, IDR_WINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(ActiveWindowResources);
};
class InactiveWindowResources : public WindowResources {
public:
InactiveWindowResources() {
InitClass();
}
virtual ~InactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER, IDR_DEWINDOW_BOTTOM_LEFT_CORNER,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER, IDR_DEWINDOW_LEFT_SIDE,
IDR_DEWINDOW_RIGHT_SIDE, IDR_DEWINDOW_TOP_CENTER,
IDR_DEWINDOW_TOP_LEFT_CORNER, IDR_DEWINDOW_TOP_RIGHT_CORNER,
IDR_DEWINDOW_TOP_CENTER, IDR_DEWINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(InactiveWindowResources);
};
class OTRActiveWindowResources : public WindowResources {
public:
OTRActiveWindowResources() {
InitClass();
}
virtual ~OTRActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER_OTR, IDR_WINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_WINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_WINDOW_LEFT_SIDE_OTR,
IDR_WINDOW_RIGHT_SIDE_OTR, IDR_WINDOW_TOP_CENTER_OTR,
IDR_WINDOW_TOP_LEFT_CORNER_OTR, IDR_WINDOW_TOP_RIGHT_CORNER_OTR,
IDR_WINDOW_TOP_CENTER_OTR, IDR_WINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
DISALLOW_EVIL_CONSTRUCTORS(OTRActiveWindowResources);
};
class OTRInactiveWindowResources : public WindowResources {
public:
OTRInactiveWindowResources() {
InitClass();
}
virtual ~OTRInactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER_OTR, IDR_DEWINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_DEWINDOW_LEFT_SIDE_OTR,
IDR_DEWINDOW_RIGHT_SIDE_OTR, IDR_DEWINDOW_TOP_CENTER_OTR,
IDR_DEWINDOW_TOP_LEFT_CORNER_OTR,
IDR_DEWINDOW_TOP_RIGHT_CORNER_OTR,
IDR_DEWINDOW_TOP_CENTER_OTR, IDR_DEWINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(OTRInactiveWindowResources);
};
// static
SkBitmap* ActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* InactiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRInactiveWindowResources::standard_frame_bitmaps_[];
WindowResources* OpaqueNonClientView::active_resources_ = NULL;
WindowResources* OpaqueNonClientView::inactive_resources_ = NULL;
WindowResources* OpaqueNonClientView::active_otr_resources_ = NULL;
WindowResources* OpaqueNonClientView::inactive_otr_resources_ = NULL;
SkBitmap OpaqueNonClientView::distributor_logo_;
SkBitmap OpaqueNonClientView::app_top_left_;
SkBitmap OpaqueNonClientView::app_top_center_;
SkBitmap OpaqueNonClientView::app_top_right_;
ChromeFont OpaqueNonClientView::title_font_;
// The distance between the top of the window and the top of the window
// controls when the window is restored.
static const int kWindowControlsTopOffset = 0;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is restored.
static const int kWindowControlsRightOffset = 4;
// The distance between the top of the window and the top of the window
// controls when the window is maximized.
static const int kWindowControlsTopZoomedOffset = 4;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is maximized.
static const int kWindowControlsRightZoomedOffset = 5;
// The distance between the top of the window and the title bar/tab strip when
// the window is maximized.
static const int kWindowTopMarginZoomed = 1;
// The distance between the left edge of the window and the left of the window
// icon when a title-bar is showing.
static const int kWindowIconLeftOffset = 5;
// The distance between the top of the window and the top of the window icon
// when a title-bar is showing.
static const int kWindowIconTopOffset = 5;
// The distance between the window icon and the window title when a title-bar
// is showing.
static const int kWindowIconTitleSpacing = 3;
// The distance between the top of the window and the title text when a
// title-bar is showing.
static const int kTitleTopOffset = 6;
// The distance between the bottom of the title text and the TabStrip when a
// title-bar is showing.
static const int kTitleBottomSpacing = 6;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is restored.
static const int kNoTitleTopSpacing = 15;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is maximized.
static const int kNoTitleZoomedTopSpacing = 1;
// The amount of horizontal and vertical distance from a corner of the window
// within which a mouse-drive resize operation will resize the window in two
// dimensions.
static const int kResizeAreaCornerSize = 16;
// The width of the sizing border on the left and right edge of the window.
static const int kWindowHorizontalBorderSize = 5;
// The height of the sizing border at the top edge of the window
static const int kWindowVerticalBorderTopSize = 3;
// The height of the sizing border on the bottom edge of the window.
static const int kWindowVerticalBorderBottomSize = 5;
// The width and height of the window icon that appears at the top left of
// pop-up and app windows.
static const int kWindowIconSize = 16;
// The horizontal distance of the right edge of the distributor logo from the
// left edge of the left-most window control.
static const int kDistributorLogoHorizontalOffset = 7;
// The vertical distance of the top of the distributor logo from the top edge
// of the window.
static const int kDistributorLogoVerticalOffset = 3;
// The distance from the left of the window of the OTR avatar icon.
static const int kOTRAvatarIconMargin = 9;
// The distance from the top of the window of the OTR avatar icon when the
// window is maximized.
static const int kNoTitleOTRZoomedTopSpacing = 3;
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, public:
OpaqueNonClientView::OpaqueNonClientView(OpaqueFrame* frame,
BrowserView2* browser_view)
: NonClientView(),
minimize_button_(new ChromeViews::Button),
maximize_button_(new ChromeViews::Button),
restore_button_(new ChromeViews::Button),
close_button_(new ChromeViews::Button),
window_icon_(NULL),
frame_(frame),
browser_view_(browser_view) {
InitClass();
if (browser_view->IsOffTheRecord()) {
if (!active_otr_resources_) {
// Lazy load OTR resources only when we first show an OTR frame.
active_otr_resources_ = new OTRActiveWindowResources;
inactive_otr_resources_ = new OTRInactiveWindowResources;
}
current_active_resources_ = active_otr_resources_;
current_inactive_resources_= inactive_otr_resources_;
} else {
current_active_resources_ = active_resources_;
current_inactive_resources_ = inactive_resources_;
}
WindowResources* resources = current_active_resources_;
minimize_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON));
minimize_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_H));
minimize_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_P));
minimize_button_->SetListener(this, -1);
minimize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MINIMIZE));
AddChildView(minimize_button_);
maximize_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON));
maximize_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_H));
maximize_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_P));
maximize_button_->SetListener(this, -1);
maximize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MAXIMIZE));
AddChildView(maximize_button_);
restore_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON));
restore_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_H));
restore_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_P));
restore_button_->SetListener(this, -1);
restore_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_RESTORE));
AddChildView(restore_button_);
close_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON));
close_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_H));
close_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_P));
close_button_->SetListener(this, -1);
close_button_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_CLOSE));
AddChildView(close_button_);
// Initializing the TabIconView is expensive, so only do it if we need to.
if (browser_view_->ShouldShowWindowIcon()) {
window_icon_ = new TabIconView(this);
window_icon_->set_is_light(true);
AddChildView(window_icon_);
window_icon_->Update();
}
// Only load the title font if we're going to need to use it to paint.
// Loading fonts is expensive.
if (browser_view_->ShouldShowWindowTitle())
InitAppWindowResources();
}
OpaqueNonClientView::~OpaqueNonClientView() {
}
gfx::Rect OpaqueNonClientView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
int top_height = CalculateNonClientTopHeight();
int window_x = std::max(0, client_bounds.x() - kWindowHorizontalBorderSize);
int window_y = std::max(0, client_bounds.y() - top_height);
int window_w = client_bounds.width() + (2 * kWindowHorizontalBorderSize);
int window_h =
client_bounds.height() + top_height + kWindowVerticalBorderBottomSize;
return gfx::Rect(window_x, window_y, window_w, window_h);
}
gfx::Rect OpaqueNonClientView::GetBoundsForTabStrip(TabStrip* tabstrip) {
int tabstrip_height = tabstrip->GetPreferredHeight();
int tabstrip_x = otr_avatar_bounds_.right();
return gfx::Rect(tabstrip_x, 0, minimize_button_->x() - tabstrip_x,
tabstrip_height);
}
void OpaqueNonClientView::UpdateWindowIcon() {
if (window_icon_)
window_icon_->Update();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, TabIconView::TabContentsProvider implementation:
TabContents* OpaqueNonClientView::GetCurrentTabContents() {
return browser_view_->GetSelectedTabContents();
}
SkBitmap OpaqueNonClientView::GetFavIcon() {
return frame_->window_delegate()->GetWindowIcon();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::BaseButton::ButtonListener implementation:
void OpaqueNonClientView::ButtonPressed(ChromeViews::BaseButton* sender) {
if (sender == minimize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MINIMIZE);
} else if (sender == maximize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MAXIMIZE);
} else if (sender == restore_button_) {
frame_->ExecuteSystemMenuCommand(SC_RESTORE);
} else if (sender == close_button_) {
frame_->ExecuteSystemMenuCommand(SC_CLOSE);
}
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::NonClientView implementation:
gfx::Rect OpaqueNonClientView::CalculateClientAreaBounds(int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
return gfx::Rect(kWindowHorizontalBorderSize, top_margin,
std::max(0, width - (2 * kWindowHorizontalBorderSize)),
std::max(0, height - top_margin - kWindowVerticalBorderBottomSize));
}
gfx::Size OpaqueNonClientView::CalculateWindowSizeForClientSize(
int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
return gfx::Size(width + (2 * kWindowHorizontalBorderSize),
height + top_margin + kWindowVerticalBorderBottomSize);
}
CPoint OpaqueNonClientView::GetSystemMenuPoint() const {
CPoint system_menu_point(icon_bounds_.x(), icon_bounds_.bottom());
MapWindowPoints(frame_->GetHWND(), HWND_DESKTOP, &system_menu_point, 1);
return system_menu_point;
}
int OpaqueNonClientView::NonClientHitTest(const gfx::Point& point) {
CRect bounds;
CPoint test_point = point.ToPOINT();
// First see if it's within the grow box area, since that overlaps the client
// bounds.
int component = frame_->client_view()->NonClientHitTest(point);
if (component != HTNOWHERE)
return component;
// Then see if the point is within any of the window controls.
close_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTCLOSE;
restore_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMAXBUTTON;
maximize_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMAXBUTTON;
minimize_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMINBUTTON;
if (window_icon_) {
window_icon_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTSYSMENU;
}
component = GetHTComponentForFrame(
point,
kWindowHorizontalBorderSize,
kResizeAreaCornerSize,
kWindowVerticalBorderTopSize,
frame_->window_delegate()->CanResize());
if (component == HTNOWHERE) {
// Finally fall back to the caption.
GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
component = HTCAPTION;
// Otherwise, the point is outside the window's bounds.
}
return component;
}
void OpaqueNonClientView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
DCHECK(window_mask);
// Redefine the window visible region for the new size.
window_mask->moveTo(0, 3);
window_mask->lineTo(1, 1);
window_mask->lineTo(3, 0);
window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 3);
window_mask->lineTo(SkIntToScalar(size.width() - 0), 3);
window_mask->lineTo(SkIntToScalar(size.width()),
SkIntToScalar(size.height()));
window_mask->lineTo(0, SkIntToScalar(size.height()));
window_mask->close();
}
void OpaqueNonClientView::EnableClose(bool enable) {
close_button_->SetEnabled(enable);
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::View overrides:
void OpaqueNonClientView::Paint(ChromeCanvas* canvas) {
// Clip the content area out of the rendering.
gfx::Rect contents_bounds = browser_view_->GetClientAreaBounds();
SkRect clip;
clip.set(SkIntToScalar(contents_bounds.x()),
SkIntToScalar(contents_bounds.y()),
SkIntToScalar(contents_bounds.right()),
SkIntToScalar(contents_bounds.bottom()));
canvas->clipRect(clip, SkRegion::kDifference_Op);
// Render the remaining portions of the non-client area.
if (frame_->IsMaximized()) {
PaintMaximizedFrameBorder(canvas);
} else {
PaintFrameBorder(canvas);
}
PaintOTRAvatar(canvas);
PaintDistributorLogo(canvas);
PaintTitleBar(canvas);
PaintToolbarBackground(canvas);
PaintClientEdge(canvas);
}
void OpaqueNonClientView::Layout() {
LayoutWindowControls();
LayoutOTRAvatar();
LayoutDistributorLogo();
LayoutTitleBar();
LayoutClientView();
}
void OpaqueNonClientView::GetPreferredSize(CSize* out) {
DCHECK(out);
frame_->client_view()->GetPreferredSize(out);
out->cx += 2 * kWindowHorizontalBorderSize;
out->cy += CalculateNonClientTopHeight() + kWindowVerticalBorderBottomSize;
}
ChromeViews::View* OpaqueNonClientView::GetViewForPoint(
const CPoint& point,
bool can_create_floating) {
// We override this function because the ClientView can overlap the non -
// client view, making it impossible to click on the window controls. We need
// to ensure the window controls are checked _first_.
ChromeViews::View* views[] = { close_button_, restore_button_,
maximize_button_, minimize_button_ };
for (int i = 0; i < arraysize(views); ++i) {
if (!views[i]->IsVisible())
continue;
CRect bounds;
views[i]->GetBounds(&bounds);
if (bounds.PtInRect(point))
return views[i];
}
return View::GetViewForPoint(point, can_create_floating);
}
void OpaqueNonClientView::DidChangeBounds(const CRect& previous,
const CRect& current) {
Layout();
}
void OpaqueNonClientView::ViewHierarchyChanged(bool is_add,
ChromeViews::View* parent,
ChromeViews::View* child) {
if (is_add && child == this) {
DCHECK(GetViewContainer());
DCHECK(frame_->client_view()->GetParent() != this);
AddChildView(frame_->client_view());
// The Accessibility glue looks for the product name on these two views to
// determine if this is in fact a Chrome window.
GetRootView()->SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
}
}
bool OpaqueNonClientView::GetAccessibleRole(VARIANT* role) {
DCHECK(role);
// We aren't actually the client area of the window, but we act like it as
// far as MSAA and the UI tests are concerned.
role->vt = VT_I4;
role->lVal = ROLE_SYSTEM_CLIENT;
return true;
}
bool OpaqueNonClientView::GetAccessibleName(std::wstring* name) {
if (!accessible_name_.empty()) {
*name = accessible_name_;
return true;
}
return false;
}
void OpaqueNonClientView::SetAccessibleName(const std::wstring& name) {
accessible_name_ = name;
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, private:
void OpaqueNonClientView::SetWindowIcon(SkBitmap window_icon) {
}
int OpaqueNonClientView::CalculateNonClientTopHeight() const {
if (frame_->window_delegate()->ShouldShowWindowTitle())
return kTitleTopOffset + title_font_.height() + kTitleBottomSpacing;
return frame_->IsMaximized() ? kNoTitleZoomedTopSpacing : kNoTitleTopSpacing;
}
void OpaqueNonClientView::PaintFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_left_corner =
resources()->GetPartBitmap(FRAME_TOP_LEFT_CORNER);
SkBitmap* top_right_corner =
resources()->GetPartBitmap(FRAME_TOP_RIGHT_CORNER);
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_TOP_EDGE);
SkBitmap* right_edge = resources()->GetPartBitmap(FRAME_RIGHT_EDGE);
SkBitmap* left_edge = resources()->GetPartBitmap(FRAME_LEFT_EDGE);
SkBitmap* bottom_left_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_LEFT_CORNER);
SkBitmap* bottom_right_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_RIGHT_CORNER);
SkBitmap* bottom_edge = resources()->GetPartBitmap(FRAME_BOTTOM_EDGE);
// Top.
canvas->DrawBitmapInt(*top_left_corner, 0, 0);
canvas->TileImageInt(*top_edge, top_left_corner->width(), 0,
width() - top_right_corner->width(), top_edge->height());
canvas->DrawBitmapInt(*top_right_corner,
width() - top_right_corner->width(), 0);
// Right.
int top_stack_height = top_right_corner->height();
canvas->TileImageInt(*right_edge, width() - right_edge->width(),
top_stack_height, right_edge->width(),
height() - top_stack_height -
bottom_right_corner->height());
// Bottom.
canvas->DrawBitmapInt(*bottom_right_corner,
width() - bottom_right_corner->width(),
height() - bottom_right_corner->height());
canvas->TileImageInt(*bottom_edge, bottom_left_corner->width(),
height() - bottom_edge->height(),
width() - bottom_left_corner->width() -
bottom_right_corner->width(),
bottom_edge->height());
canvas->DrawBitmapInt(*bottom_left_corner, 0,
height() - bottom_left_corner->height());
// Left.
top_stack_height = top_left_corner->height();
canvas->TileImageInt(*left_edge, 0, top_stack_height, left_edge->width(),
height() - top_stack_height -
bottom_left_corner->height());
}
void OpaqueNonClientView::PaintMaximizedFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_MAXIMIZED_TOP_EDGE);
SkBitmap* bottom_edge =
resources()->GetPartBitmap(FRAME_MAXIMIZED_BOTTOM_EDGE);
canvas->TileImageInt(*top_edge, 0, 0, width(), top_edge->height());
canvas->TileImageInt(*bottom_edge, 0, height() - bottom_edge->height(),
width(), bottom_edge->height());
}
void OpaqueNonClientView::PaintOTRAvatar(ChromeCanvas* canvas) {
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
canvas->DrawBitmapInt(browser_view_->GetOTRAvatarIcon(),
otr_avatar_bounds_.x(), otr_avatar_bounds_.y());
}
}
void OpaqueNonClientView::PaintDistributorLogo(ChromeCanvas* canvas) {
// The distributor logo is only painted when the frame is not maximized and
// when we actually have a logo.
if (!frame_->IsMaximized() && !frame_->IsMinimized() &&
!distributor_logo_.empty()) {
canvas->DrawBitmapInt(distributor_logo_, logo_bounds_.x(),
logo_bounds_.y());
}
}
void OpaqueNonClientView::PaintTitleBar(ChromeCanvas* canvas) {
// The window icon is painted by the TabIconView.
ChromeViews::WindowDelegate* d = frame_->window_delegate();
if (d->ShouldShowWindowTitle()) {
canvas->DrawStringInt(d->GetWindowTitle(), title_font_, SK_ColorWHITE,
title_bounds_.x(), title_bounds_.y(),
title_bounds_.width(), title_bounds_.height());
}
}
void OpaqueNonClientView::PaintToolbarBackground(ChromeCanvas* canvas) {
if (browser_view_->IsToolbarVisible() ||
browser_view_->IsTabStripVisible()) {
SkBitmap* toolbar_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_LEFT);
SkBitmap* toolbar_center =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP);
SkBitmap* toolbar_right =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_RIGHT);
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
gfx::Point topleft(toolbar_bounds.x(), toolbar_bounds.y());
View::ConvertPointToView(frame_->client_view(), this, &topleft);
toolbar_bounds.set_x(topleft.x());
toolbar_bounds.set_y(topleft.y());
canvas->DrawBitmapInt(*toolbar_left,
toolbar_bounds.x() - toolbar_left->width(),
toolbar_bounds.y());
canvas->TileImageInt(*toolbar_center,
toolbar_bounds.x(), toolbar_bounds.y(),
toolbar_bounds.width(), toolbar_center->height());
canvas->DrawBitmapInt(*toolbar_right, toolbar_bounds.right(),
toolbar_bounds.y());
}
}
void OpaqueNonClientView::PaintClientEdge(ChromeCanvas* canvas) {
SkBitmap* right = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_RIGHT);
SkBitmap* bottom_right =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_RIGHT);
SkBitmap* bottom = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM);
SkBitmap* bottom_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_LEFT);
SkBitmap* left = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_LEFT);
// The toolbar renders its own client edge in PaintToolbarBackground, however
// there are other bands that need to have a client edge rendered along their
// sides, such as the Bookmark bar, infobars, etc.
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
gfx::Rect client_area_bounds = browser_view_->GetClientAreaBounds();
// For some reason things don't line up quite right, so we add and subtract
// pixels here and there for aesthetic bliss.
// Enlarge the client area to include the toolbar, since the top edge of
// the client area is the toolbar background and the client edge renders
// the left and right sides of the toolbar background.
int fudge = frame_->window_delegate()->ShouldShowWindowTitle() ? 0 : 1;
client_area_bounds.SetRect(
client_area_bounds.x(),
frame_->client_view()->y() + toolbar_bounds.bottom() - fudge,
client_area_bounds.width(),
std::max(0, height() - frame_->client_view()->y() -
toolbar_bounds.bottom() + fudge - kWindowVerticalBorderBottomSize));
// Now the fudge inverts for app vs browser windows.
fudge = 1 - fudge;
canvas->TileImageInt(*right, client_area_bounds.right(),
client_area_bounds.y() + fudge,
right->width(), client_area_bounds.height() - fudge);
canvas->DrawBitmapInt(*bottom_right, client_area_bounds.right(),
client_area_bounds.bottom());
canvas->TileImageInt(*bottom, client_area_bounds.x(),
client_area_bounds.bottom(),
client_area_bounds.width(), bottom_right->height());
canvas->DrawBitmapInt(*bottom_left,
client_area_bounds.x() - bottom_left->width(),
client_area_bounds.bottom());
canvas->TileImageInt(*left, client_area_bounds.x() - left->width(),
client_area_bounds.y() + fudge,
left->width(), client_area_bounds.height() - fudge);
if (frame_->window_delegate()->ShouldShowWindowTitle()) {
canvas->DrawBitmapInt(app_top_left_,
client_area_bounds.x() - app_top_left_.width(),
client_area_bounds.y() - app_top_left_.height() +
fudge);
canvas->TileImageInt(app_top_center_, client_area_bounds.x(),
client_area_bounds.y() - app_top_center_.height(),
client_area_bounds.width(), app_top_center_.height());
canvas->DrawBitmapInt(app_top_right_, client_area_bounds.right(),
client_area_bounds.y() - app_top_right_.height() +
fudge);
}
}
void OpaqueNonClientView::LayoutWindowControls() {
CSize ps;
if (frame_->IsMaximized() || frame_->IsMinimized()) {
maximize_button_->SetVisible(false);
restore_button_->SetVisible(true);
}
if (frame_->IsMaximized()) {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
close_button_->SetBounds(
width() - ps.cx - kWindowControlsRightZoomedOffset,
0, ps.cx + kWindowControlsRightZoomedOffset,
ps.cy + kWindowControlsTopZoomedOffset);
restore_button_->GetPreferredSize(&ps);
restore_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
restore_button_->SetBounds(close_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
minimize_button_->SetBounds(restore_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
} else if (frame_->IsMinimized()) {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
close_button_->SetBounds(
width() - ps.cx - kWindowControlsRightZoomedOffset,
0, ps.cx + kWindowControlsRightZoomedOffset,
ps.cy + kWindowControlsTopZoomedOffset);
restore_button_->GetPreferredSize(&ps);
restore_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
restore_button_->SetBounds(close_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
minimize_button_->SetBounds(restore_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
} else {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
close_button_->SetBounds(width() - kWindowControlsRightOffset - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
restore_button_->SetVisible(false);
maximize_button_->SetVisible(true);
maximize_button_->GetPreferredSize(&ps);
maximize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
maximize_button_->SetBounds(close_button_->x() - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
minimize_button_->SetBounds(maximize_button_->x() - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
}
}
void OpaqueNonClientView::LayoutOTRAvatar() {
int otr_x = 0;
int top_spacing =
frame_->IsMaximized() ? kNoTitleOTRZoomedTopSpacing : kNoTitleTopSpacing;
int otr_y = browser_view_->GetTabStripHeight() + top_spacing;
int otr_width = 0;
int otr_height = 0;
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
SkBitmap otr_avatar_icon = browser_view_->GetOTRAvatarIcon();
otr_width = otr_avatar_icon.width();
otr_height = otr_avatar_icon.height();
otr_x = kOTRAvatarIconMargin;
otr_y -= otr_avatar_icon.height() + 2;
}
otr_avatar_bounds_.SetRect(otr_x, otr_y, otr_width, otr_height);
}
void OpaqueNonClientView::LayoutDistributorLogo() {
if (distributor_logo_.empty())
return;
int logo_w = distributor_logo_.width();
int logo_h = distributor_logo_.height();
int logo_x = 0;
if (UILayoutIsRightToLeft()) {
CRect minimize_bounds;
minimize_button_->GetBounds(&minimize_bounds,
APPLY_MIRRORING_TRANSFORMATION);
logo_x = minimize_bounds.right + kDistributorLogoHorizontalOffset;
} else {
logo_x = minimize_button_->x() - logo_w -
kDistributorLogoHorizontalOffset;
}
logo_bounds_.SetRect(logo_x, kDistributorLogoVerticalOffset, logo_w, logo_h);
}
void OpaqueNonClientView::LayoutTitleBar() {
int top_offset = frame_->IsMaximized() ? kWindowTopMarginZoomed : 0;
ChromeViews::WindowDelegate* d = frame_->window_delegate();
// Size the window icon, even if it is hidden so we can size the title based
// on its position.
bool show_icon = d->ShouldShowWindowIcon();
icon_bounds_.SetRect(kWindowIconLeftOffset, kWindowIconLeftOffset,
show_icon ? kWindowIconSize : 0,
show_icon ? kWindowIconSize : 0);
if (window_icon_)
window_icon_->SetBounds(icon_bounds_.ToRECT());
// Size the title, if visible.
if (d->ShouldShowWindowTitle()) {
int spacing = d->ShouldShowWindowIcon() ? kWindowIconTitleSpacing : 0;
int title_right = minimize_button_->x();
int icon_right = icon_bounds_.right();
int title_left = icon_right + spacing;
title_bounds_.SetRect(title_left, kTitleTopOffset + top_offset,
std::max(0, static_cast<int>(title_right - icon_right)),
title_font_.height());
}
}
void OpaqueNonClientView::LayoutClientView() {
gfx::Rect client_bounds(
CalculateClientAreaBounds(width(), height()));
frame_->client_view()->SetBounds(client_bounds.ToRECT());
}
// static
void OpaqueNonClientView::InitClass() {
static bool initialized = false;
if (!initialized) {
active_resources_ = new ActiveWindowResources;
inactive_resources_ = new InactiveWindowResources;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SkBitmap* image = rb.GetBitmapNamed(IDR_DISTRIBUTOR_LOGO_LIGHT);
if (!image->isNull())
distributor_logo_ = *image;
app_top_left_ = *rb.GetBitmapNamed(IDR_APP_TOP_LEFT);
app_top_center_ = *rb.GetBitmapNamed(IDR_APP_TOP_CENTER);
app_top_right_ = *rb.GetBitmapNamed(IDR_APP_TOP_RIGHT);
initialized = true;
}
}
// static
void OpaqueNonClientView::InitAppWindowResources() {
static bool initialized = false;
if (!initialized) {
title_font_ = ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(1, ChromeFont::BOLD);
initialized = true;
}
}
Add some padding between the right edge of the new tab button and the left edge of the window controls.
http://crbug.com/2451
Review URL: http://codereview.chromium.org/3130
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@2355 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "chrome/browser/views/frame/opaque_non_client_view.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/browser/views/window_resources.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/gfx/path.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/root_view.h"
#include "chromium_strings.h"
#include "generated_resources.h"
// An enumeration of bitmap resources used by this window.
enum {
FRAME_PART_BITMAP_FIRST = 0, // Must be first.
// Window Controls.
FRAME_CLOSE_BUTTON_ICON,
FRAME_CLOSE_BUTTON_ICON_H,
FRAME_CLOSE_BUTTON_ICON_P,
FRAME_CLOSE_BUTTON_ICON_SA,
FRAME_CLOSE_BUTTON_ICON_SA_H,
FRAME_CLOSE_BUTTON_ICON_SA_P,
FRAME_RESTORE_BUTTON_ICON,
FRAME_RESTORE_BUTTON_ICON_H,
FRAME_RESTORE_BUTTON_ICON_P,
FRAME_MAXIMIZE_BUTTON_ICON,
FRAME_MAXIMIZE_BUTTON_ICON_H,
FRAME_MAXIMIZE_BUTTON_ICON_P,
FRAME_MINIMIZE_BUTTON_ICON,
FRAME_MINIMIZE_BUTTON_ICON_H,
FRAME_MINIMIZE_BUTTON_ICON_P,
// Window Frame Border.
FRAME_BOTTOM_EDGE,
FRAME_BOTTOM_LEFT_CORNER,
FRAME_BOTTOM_RIGHT_CORNER,
FRAME_LEFT_EDGE,
FRAME_RIGHT_EDGE,
FRAME_TOP_EDGE,
FRAME_TOP_LEFT_CORNER,
FRAME_TOP_RIGHT_CORNER,
// Window Maximized Border.
FRAME_MAXIMIZED_TOP_EDGE,
FRAME_MAXIMIZED_BOTTOM_EDGE,
// Client Edge Border.
FRAME_CLIENT_EDGE_TOP_LEFT,
FRAME_CLIENT_EDGE_TOP,
FRAME_CLIENT_EDGE_TOP_RIGHT,
FRAME_CLIENT_EDGE_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM,
FRAME_CLIENT_EDGE_BOTTOM_LEFT,
FRAME_CLIENT_EDGE_LEFT,
FRAME_PART_BITMAP_COUNT // Must be last.
};
class ActiveWindowResources : public WindowResources {
public:
ActiveWindowResources() {
InitClass();
}
virtual ~ActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER, IDR_WINDOW_BOTTOM_LEFT_CORNER,
IDR_WINDOW_BOTTOM_RIGHT_CORNER, IDR_WINDOW_LEFT_SIDE,
IDR_WINDOW_RIGHT_SIDE, IDR_WINDOW_TOP_CENTER,
IDR_WINDOW_TOP_LEFT_CORNER, IDR_WINDOW_TOP_RIGHT_CORNER,
IDR_WINDOW_TOP_CENTER, IDR_WINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(ActiveWindowResources);
};
class InactiveWindowResources : public WindowResources {
public:
InactiveWindowResources() {
InitClass();
}
virtual ~InactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER, IDR_DEWINDOW_BOTTOM_LEFT_CORNER,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER, IDR_DEWINDOW_LEFT_SIDE,
IDR_DEWINDOW_RIGHT_SIDE, IDR_DEWINDOW_TOP_CENTER,
IDR_DEWINDOW_TOP_LEFT_CORNER, IDR_DEWINDOW_TOP_RIGHT_CORNER,
IDR_DEWINDOW_TOP_CENTER, IDR_DEWINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(InactiveWindowResources);
};
class OTRActiveWindowResources : public WindowResources {
public:
OTRActiveWindowResources() {
InitClass();
}
virtual ~OTRActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER_OTR, IDR_WINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_WINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_WINDOW_LEFT_SIDE_OTR,
IDR_WINDOW_RIGHT_SIDE_OTR, IDR_WINDOW_TOP_CENTER_OTR,
IDR_WINDOW_TOP_LEFT_CORNER_OTR, IDR_WINDOW_TOP_RIGHT_CORNER_OTR,
IDR_WINDOW_TOP_CENTER_OTR, IDR_WINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
DISALLOW_EVIL_CONSTRUCTORS(OTRActiveWindowResources);
};
class OTRInactiveWindowResources : public WindowResources {
public:
OTRInactiveWindowResources() {
InitClass();
}
virtual ~OTRInactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER_OTR, IDR_DEWINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_DEWINDOW_LEFT_SIDE_OTR,
IDR_DEWINDOW_RIGHT_SIDE_OTR, IDR_DEWINDOW_TOP_CENTER_OTR,
IDR_DEWINDOW_TOP_LEFT_CORNER_OTR,
IDR_DEWINDOW_TOP_RIGHT_CORNER_OTR,
IDR_DEWINDOW_TOP_CENTER_OTR, IDR_DEWINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(OTRInactiveWindowResources);
};
// static
SkBitmap* ActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* InactiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRInactiveWindowResources::standard_frame_bitmaps_[];
WindowResources* OpaqueNonClientView::active_resources_ = NULL;
WindowResources* OpaqueNonClientView::inactive_resources_ = NULL;
WindowResources* OpaqueNonClientView::active_otr_resources_ = NULL;
WindowResources* OpaqueNonClientView::inactive_otr_resources_ = NULL;
SkBitmap OpaqueNonClientView::distributor_logo_;
SkBitmap OpaqueNonClientView::app_top_left_;
SkBitmap OpaqueNonClientView::app_top_center_;
SkBitmap OpaqueNonClientView::app_top_right_;
ChromeFont OpaqueNonClientView::title_font_;
// The distance between the top of the window and the top of the window
// controls when the window is restored.
static const int kWindowControlsTopOffset = 0;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is restored.
static const int kWindowControlsRightOffset = 4;
// The distance between the top of the window and the top of the window
// controls when the window is maximized.
static const int kWindowControlsTopZoomedOffset = 4;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is maximized.
static const int kWindowControlsRightZoomedOffset = 5;
// The distance between the top of the window and the title bar/tab strip when
// the window is maximized.
static const int kWindowTopMarginZoomed = 1;
// The distance between the left edge of the window and the left of the window
// icon when a title-bar is showing.
static const int kWindowIconLeftOffset = 5;
// The distance between the top of the window and the top of the window icon
// when a title-bar is showing.
static const int kWindowIconTopOffset = 5;
// The distance between the window icon and the window title when a title-bar
// is showing.
static const int kWindowIconTitleSpacing = 3;
// The distance between the top of the window and the title text when a
// title-bar is showing.
static const int kTitleTopOffset = 6;
// The distance between the bottom of the title text and the TabStrip when a
// title-bar is showing.
static const int kTitleBottomSpacing = 6;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is restored.
static const int kNoTitleTopSpacing = 15;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is maximized.
static const int kNoTitleZoomedTopSpacing = 1;
// The amount of horizontal and vertical distance from a corner of the window
// within which a mouse-drive resize operation will resize the window in two
// dimensions.
static const int kResizeAreaCornerSize = 16;
// The width of the sizing border on the left and right edge of the window.
static const int kWindowHorizontalBorderSize = 5;
// The height of the sizing border at the top edge of the window
static const int kWindowVerticalBorderTopSize = 3;
// The height of the sizing border on the bottom edge of the window.
static const int kWindowVerticalBorderBottomSize = 5;
// The width and height of the window icon that appears at the top left of
// pop-up and app windows.
static const int kWindowIconSize = 16;
// The horizontal distance of the right edge of the distributor logo from the
// left edge of the left-most window control.
static const int kDistributorLogoHorizontalOffset = 7;
// The vertical distance of the top of the distributor logo from the top edge
// of the window.
static const int kDistributorLogoVerticalOffset = 3;
// The distance from the left of the window of the OTR avatar icon.
static const int kOTRAvatarIconMargin = 9;
// The distance from the top of the window of the OTR avatar icon when the
// window is maximized.
static const int kNoTitleOTRZoomedTopSpacing = 3;
// Horizontal distance between the right edge of the new tab icon and the left
// edge of the window minimize icon when the window is maximized.
static const int kNewTabIconWindowControlsSpacing = 10;
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, public:
OpaqueNonClientView::OpaqueNonClientView(OpaqueFrame* frame,
BrowserView2* browser_view)
: NonClientView(),
minimize_button_(new ChromeViews::Button),
maximize_button_(new ChromeViews::Button),
restore_button_(new ChromeViews::Button),
close_button_(new ChromeViews::Button),
window_icon_(NULL),
frame_(frame),
browser_view_(browser_view) {
InitClass();
if (browser_view->IsOffTheRecord()) {
if (!active_otr_resources_) {
// Lazy load OTR resources only when we first show an OTR frame.
active_otr_resources_ = new OTRActiveWindowResources;
inactive_otr_resources_ = new OTRInactiveWindowResources;
}
current_active_resources_ = active_otr_resources_;
current_inactive_resources_= inactive_otr_resources_;
} else {
current_active_resources_ = active_resources_;
current_inactive_resources_ = inactive_resources_;
}
WindowResources* resources = current_active_resources_;
minimize_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON));
minimize_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_H));
minimize_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_P));
minimize_button_->SetListener(this, -1);
minimize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MINIMIZE));
AddChildView(minimize_button_);
maximize_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON));
maximize_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_H));
maximize_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_P));
maximize_button_->SetListener(this, -1);
maximize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MAXIMIZE));
AddChildView(maximize_button_);
restore_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON));
restore_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_H));
restore_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_P));
restore_button_->SetListener(this, -1);
restore_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_RESTORE));
AddChildView(restore_button_);
close_button_->SetImage(
ChromeViews::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON));
close_button_->SetImage(
ChromeViews::Button::BS_HOT,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_H));
close_button_->SetImage(
ChromeViews::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_P));
close_button_->SetListener(this, -1);
close_button_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_CLOSE));
AddChildView(close_button_);
// Initializing the TabIconView is expensive, so only do it if we need to.
if (browser_view_->ShouldShowWindowIcon()) {
window_icon_ = new TabIconView(this);
window_icon_->set_is_light(true);
AddChildView(window_icon_);
window_icon_->Update();
}
// Only load the title font if we're going to need to use it to paint.
// Loading fonts is expensive.
if (browser_view_->ShouldShowWindowTitle())
InitAppWindowResources();
}
OpaqueNonClientView::~OpaqueNonClientView() {
}
gfx::Rect OpaqueNonClientView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
int top_height = CalculateNonClientTopHeight();
int window_x = std::max(0, client_bounds.x() - kWindowHorizontalBorderSize);
int window_y = std::max(0, client_bounds.y() - top_height);
int window_w = client_bounds.width() + (2 * kWindowHorizontalBorderSize);
int window_h =
client_bounds.height() + top_height + kWindowVerticalBorderBottomSize;
return gfx::Rect(window_x, window_y, window_w, window_h);
}
gfx::Rect OpaqueNonClientView::GetBoundsForTabStrip(TabStrip* tabstrip) {
int tabstrip_height = tabstrip->GetPreferredHeight();
int tabstrip_x = otr_avatar_bounds_.right();
int tabstrip_width = minimize_button_->x() - tabstrip_x;
if (frame_->IsMaximized())
tabstrip_width -= kNewTabIconWindowControlsSpacing;
return gfx::Rect(tabstrip_x, 0, tabstrip_width, tabstrip_height);
}
void OpaqueNonClientView::UpdateWindowIcon() {
if (window_icon_)
window_icon_->Update();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, TabIconView::TabContentsProvider implementation:
TabContents* OpaqueNonClientView::GetCurrentTabContents() {
return browser_view_->GetSelectedTabContents();
}
SkBitmap OpaqueNonClientView::GetFavIcon() {
return frame_->window_delegate()->GetWindowIcon();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::BaseButton::ButtonListener implementation:
void OpaqueNonClientView::ButtonPressed(ChromeViews::BaseButton* sender) {
if (sender == minimize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MINIMIZE);
} else if (sender == maximize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MAXIMIZE);
} else if (sender == restore_button_) {
frame_->ExecuteSystemMenuCommand(SC_RESTORE);
} else if (sender == close_button_) {
frame_->ExecuteSystemMenuCommand(SC_CLOSE);
}
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::NonClientView implementation:
gfx::Rect OpaqueNonClientView::CalculateClientAreaBounds(int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
return gfx::Rect(kWindowHorizontalBorderSize, top_margin,
std::max(0, width - (2 * kWindowHorizontalBorderSize)),
std::max(0, height - top_margin - kWindowVerticalBorderBottomSize));
}
gfx::Size OpaqueNonClientView::CalculateWindowSizeForClientSize(
int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
return gfx::Size(width + (2 * kWindowHorizontalBorderSize),
height + top_margin + kWindowVerticalBorderBottomSize);
}
CPoint OpaqueNonClientView::GetSystemMenuPoint() const {
CPoint system_menu_point(icon_bounds_.x(), icon_bounds_.bottom());
MapWindowPoints(frame_->GetHWND(), HWND_DESKTOP, &system_menu_point, 1);
return system_menu_point;
}
int OpaqueNonClientView::NonClientHitTest(const gfx::Point& point) {
CRect bounds;
CPoint test_point = point.ToPOINT();
// First see if it's within the grow box area, since that overlaps the client
// bounds.
int component = frame_->client_view()->NonClientHitTest(point);
if (component != HTNOWHERE)
return component;
// Then see if the point is within any of the window controls.
close_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTCLOSE;
restore_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMAXBUTTON;
maximize_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMAXBUTTON;
minimize_button_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTMINBUTTON;
if (window_icon_) {
window_icon_->GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
return HTSYSMENU;
}
component = GetHTComponentForFrame(
point,
kWindowHorizontalBorderSize,
kResizeAreaCornerSize,
kWindowVerticalBorderTopSize,
frame_->window_delegate()->CanResize());
if (component == HTNOWHERE) {
// Finally fall back to the caption.
GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
if (bounds.PtInRect(test_point))
component = HTCAPTION;
// Otherwise, the point is outside the window's bounds.
}
return component;
}
void OpaqueNonClientView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
DCHECK(window_mask);
// Redefine the window visible region for the new size.
window_mask->moveTo(0, 3);
window_mask->lineTo(1, 1);
window_mask->lineTo(3, 0);
window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 3);
window_mask->lineTo(SkIntToScalar(size.width() - 0), 3);
window_mask->lineTo(SkIntToScalar(size.width()),
SkIntToScalar(size.height()));
window_mask->lineTo(0, SkIntToScalar(size.height()));
window_mask->close();
}
void OpaqueNonClientView::EnableClose(bool enable) {
close_button_->SetEnabled(enable);
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, ChromeViews::View overrides:
void OpaqueNonClientView::Paint(ChromeCanvas* canvas) {
// Clip the content area out of the rendering.
gfx::Rect contents_bounds = browser_view_->GetClientAreaBounds();
SkRect clip;
clip.set(SkIntToScalar(contents_bounds.x()),
SkIntToScalar(contents_bounds.y()),
SkIntToScalar(contents_bounds.right()),
SkIntToScalar(contents_bounds.bottom()));
canvas->clipRect(clip, SkRegion::kDifference_Op);
// Render the remaining portions of the non-client area.
if (frame_->IsMaximized()) {
PaintMaximizedFrameBorder(canvas);
} else {
PaintFrameBorder(canvas);
}
PaintOTRAvatar(canvas);
PaintDistributorLogo(canvas);
PaintTitleBar(canvas);
PaintToolbarBackground(canvas);
PaintClientEdge(canvas);
}
void OpaqueNonClientView::Layout() {
LayoutWindowControls();
LayoutOTRAvatar();
LayoutDistributorLogo();
LayoutTitleBar();
LayoutClientView();
}
void OpaqueNonClientView::GetPreferredSize(CSize* out) {
DCHECK(out);
frame_->client_view()->GetPreferredSize(out);
out->cx += 2 * kWindowHorizontalBorderSize;
out->cy += CalculateNonClientTopHeight() + kWindowVerticalBorderBottomSize;
}
ChromeViews::View* OpaqueNonClientView::GetViewForPoint(
const CPoint& point,
bool can_create_floating) {
// We override this function because the ClientView can overlap the non -
// client view, making it impossible to click on the window controls. We need
// to ensure the window controls are checked _first_.
ChromeViews::View* views[] = { close_button_, restore_button_,
maximize_button_, minimize_button_ };
for (int i = 0; i < arraysize(views); ++i) {
if (!views[i]->IsVisible())
continue;
CRect bounds;
views[i]->GetBounds(&bounds);
if (bounds.PtInRect(point))
return views[i];
}
return View::GetViewForPoint(point, can_create_floating);
}
void OpaqueNonClientView::DidChangeBounds(const CRect& previous,
const CRect& current) {
Layout();
}
void OpaqueNonClientView::ViewHierarchyChanged(bool is_add,
ChromeViews::View* parent,
ChromeViews::View* child) {
if (is_add && child == this) {
DCHECK(GetViewContainer());
DCHECK(frame_->client_view()->GetParent() != this);
AddChildView(frame_->client_view());
// The Accessibility glue looks for the product name on these two views to
// determine if this is in fact a Chrome window.
GetRootView()->SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
}
}
bool OpaqueNonClientView::GetAccessibleRole(VARIANT* role) {
DCHECK(role);
// We aren't actually the client area of the window, but we act like it as
// far as MSAA and the UI tests are concerned.
role->vt = VT_I4;
role->lVal = ROLE_SYSTEM_CLIENT;
return true;
}
bool OpaqueNonClientView::GetAccessibleName(std::wstring* name) {
if (!accessible_name_.empty()) {
*name = accessible_name_;
return true;
}
return false;
}
void OpaqueNonClientView::SetAccessibleName(const std::wstring& name) {
accessible_name_ = name;
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, private:
void OpaqueNonClientView::SetWindowIcon(SkBitmap window_icon) {
}
int OpaqueNonClientView::CalculateNonClientTopHeight() const {
if (frame_->window_delegate()->ShouldShowWindowTitle())
return kTitleTopOffset + title_font_.height() + kTitleBottomSpacing;
return frame_->IsMaximized() ? kNoTitleZoomedTopSpacing : kNoTitleTopSpacing;
}
void OpaqueNonClientView::PaintFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_left_corner =
resources()->GetPartBitmap(FRAME_TOP_LEFT_CORNER);
SkBitmap* top_right_corner =
resources()->GetPartBitmap(FRAME_TOP_RIGHT_CORNER);
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_TOP_EDGE);
SkBitmap* right_edge = resources()->GetPartBitmap(FRAME_RIGHT_EDGE);
SkBitmap* left_edge = resources()->GetPartBitmap(FRAME_LEFT_EDGE);
SkBitmap* bottom_left_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_LEFT_CORNER);
SkBitmap* bottom_right_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_RIGHT_CORNER);
SkBitmap* bottom_edge = resources()->GetPartBitmap(FRAME_BOTTOM_EDGE);
// Top.
canvas->DrawBitmapInt(*top_left_corner, 0, 0);
canvas->TileImageInt(*top_edge, top_left_corner->width(), 0,
width() - top_right_corner->width(), top_edge->height());
canvas->DrawBitmapInt(*top_right_corner,
width() - top_right_corner->width(), 0);
// Right.
int top_stack_height = top_right_corner->height();
canvas->TileImageInt(*right_edge, width() - right_edge->width(),
top_stack_height, right_edge->width(),
height() - top_stack_height -
bottom_right_corner->height());
// Bottom.
canvas->DrawBitmapInt(*bottom_right_corner,
width() - bottom_right_corner->width(),
height() - bottom_right_corner->height());
canvas->TileImageInt(*bottom_edge, bottom_left_corner->width(),
height() - bottom_edge->height(),
width() - bottom_left_corner->width() -
bottom_right_corner->width(),
bottom_edge->height());
canvas->DrawBitmapInt(*bottom_left_corner, 0,
height() - bottom_left_corner->height());
// Left.
top_stack_height = top_left_corner->height();
canvas->TileImageInt(*left_edge, 0, top_stack_height, left_edge->width(),
height() - top_stack_height -
bottom_left_corner->height());
}
void OpaqueNonClientView::PaintMaximizedFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_MAXIMIZED_TOP_EDGE);
SkBitmap* bottom_edge =
resources()->GetPartBitmap(FRAME_MAXIMIZED_BOTTOM_EDGE);
canvas->TileImageInt(*top_edge, 0, 0, width(), top_edge->height());
canvas->TileImageInt(*bottom_edge, 0, height() - bottom_edge->height(),
width(), bottom_edge->height());
}
void OpaqueNonClientView::PaintOTRAvatar(ChromeCanvas* canvas) {
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
canvas->DrawBitmapInt(browser_view_->GetOTRAvatarIcon(),
otr_avatar_bounds_.x(), otr_avatar_bounds_.y());
}
}
void OpaqueNonClientView::PaintDistributorLogo(ChromeCanvas* canvas) {
// The distributor logo is only painted when the frame is not maximized and
// when we actually have a logo.
if (!frame_->IsMaximized() && !frame_->IsMinimized() &&
!distributor_logo_.empty()) {
canvas->DrawBitmapInt(distributor_logo_, logo_bounds_.x(),
logo_bounds_.y());
}
}
void OpaqueNonClientView::PaintTitleBar(ChromeCanvas* canvas) {
// The window icon is painted by the TabIconView.
ChromeViews::WindowDelegate* d = frame_->window_delegate();
if (d->ShouldShowWindowTitle()) {
canvas->DrawStringInt(d->GetWindowTitle(), title_font_, SK_ColorWHITE,
title_bounds_.x(), title_bounds_.y(),
title_bounds_.width(), title_bounds_.height());
}
}
void OpaqueNonClientView::PaintToolbarBackground(ChromeCanvas* canvas) {
if (browser_view_->IsToolbarVisible() ||
browser_view_->IsTabStripVisible()) {
SkBitmap* toolbar_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_LEFT);
SkBitmap* toolbar_center =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP);
SkBitmap* toolbar_right =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_RIGHT);
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
gfx::Point topleft(toolbar_bounds.x(), toolbar_bounds.y());
View::ConvertPointToView(frame_->client_view(), this, &topleft);
toolbar_bounds.set_x(topleft.x());
toolbar_bounds.set_y(topleft.y());
canvas->DrawBitmapInt(*toolbar_left,
toolbar_bounds.x() - toolbar_left->width(),
toolbar_bounds.y());
canvas->TileImageInt(*toolbar_center,
toolbar_bounds.x(), toolbar_bounds.y(),
toolbar_bounds.width(), toolbar_center->height());
canvas->DrawBitmapInt(*toolbar_right, toolbar_bounds.right(),
toolbar_bounds.y());
}
}
void OpaqueNonClientView::PaintClientEdge(ChromeCanvas* canvas) {
SkBitmap* right = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_RIGHT);
SkBitmap* bottom_right =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_RIGHT);
SkBitmap* bottom = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM);
SkBitmap* bottom_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_LEFT);
SkBitmap* left = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_LEFT);
// The toolbar renders its own client edge in PaintToolbarBackground, however
// there are other bands that need to have a client edge rendered along their
// sides, such as the Bookmark bar, infobars, etc.
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
gfx::Rect client_area_bounds = browser_view_->GetClientAreaBounds();
// For some reason things don't line up quite right, so we add and subtract
// pixels here and there for aesthetic bliss.
// Enlarge the client area to include the toolbar, since the top edge of
// the client area is the toolbar background and the client edge renders
// the left and right sides of the toolbar background.
int fudge = frame_->window_delegate()->ShouldShowWindowTitle() ? 0 : 1;
client_area_bounds.SetRect(
client_area_bounds.x(),
frame_->client_view()->y() + toolbar_bounds.bottom() - fudge,
client_area_bounds.width(),
std::max(0, height() - frame_->client_view()->y() -
toolbar_bounds.bottom() + fudge - kWindowVerticalBorderBottomSize));
// Now the fudge inverts for app vs browser windows.
fudge = 1 - fudge;
canvas->TileImageInt(*right, client_area_bounds.right(),
client_area_bounds.y() + fudge,
right->width(), client_area_bounds.height() - fudge);
canvas->DrawBitmapInt(*bottom_right, client_area_bounds.right(),
client_area_bounds.bottom());
canvas->TileImageInt(*bottom, client_area_bounds.x(),
client_area_bounds.bottom(),
client_area_bounds.width(), bottom_right->height());
canvas->DrawBitmapInt(*bottom_left,
client_area_bounds.x() - bottom_left->width(),
client_area_bounds.bottom());
canvas->TileImageInt(*left, client_area_bounds.x() - left->width(),
client_area_bounds.y() + fudge,
left->width(), client_area_bounds.height() - fudge);
if (frame_->window_delegate()->ShouldShowWindowTitle()) {
canvas->DrawBitmapInt(app_top_left_,
client_area_bounds.x() - app_top_left_.width(),
client_area_bounds.y() - app_top_left_.height() +
fudge);
canvas->TileImageInt(app_top_center_, client_area_bounds.x(),
client_area_bounds.y() - app_top_center_.height(),
client_area_bounds.width(), app_top_center_.height());
canvas->DrawBitmapInt(app_top_right_, client_area_bounds.right(),
client_area_bounds.y() - app_top_right_.height() +
fudge);
}
}
void OpaqueNonClientView::LayoutWindowControls() {
CSize ps;
if (frame_->IsMaximized() || frame_->IsMinimized()) {
maximize_button_->SetVisible(false);
restore_button_->SetVisible(true);
}
if (frame_->IsMaximized()) {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
close_button_->SetBounds(
width() - ps.cx - kWindowControlsRightZoomedOffset,
0, ps.cx + kWindowControlsRightZoomedOffset,
ps.cy + kWindowControlsTopZoomedOffset);
restore_button_->GetPreferredSize(&ps);
restore_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
restore_button_->SetBounds(close_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
minimize_button_->SetBounds(restore_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
} else if (frame_->IsMinimized()) {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
close_button_->SetBounds(
width() - ps.cx - kWindowControlsRightZoomedOffset,
0, ps.cx + kWindowControlsRightZoomedOffset,
ps.cy + kWindowControlsTopZoomedOffset);
restore_button_->GetPreferredSize(&ps);
restore_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
restore_button_->SetBounds(close_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_BOTTOM);
minimize_button_->SetBounds(restore_button_->x() - ps.cx, 0, ps.cx,
ps.cy + kWindowControlsTopZoomedOffset);
} else {
close_button_->GetPreferredSize(&ps);
close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
close_button_->SetBounds(width() - kWindowControlsRightOffset - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
restore_button_->SetVisible(false);
maximize_button_->SetVisible(true);
maximize_button_->GetPreferredSize(&ps);
maximize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
maximize_button_->SetBounds(close_button_->x() - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
minimize_button_->GetPreferredSize(&ps);
minimize_button_->SetImageAlignment(ChromeViews::Button::ALIGN_LEFT,
ChromeViews::Button::ALIGN_TOP);
minimize_button_->SetBounds(maximize_button_->x() - ps.cx,
kWindowControlsTopOffset, ps.cx, ps.cy);
}
}
void OpaqueNonClientView::LayoutOTRAvatar() {
int otr_x = 0;
int top_spacing =
frame_->IsMaximized() ? kNoTitleOTRZoomedTopSpacing : kNoTitleTopSpacing;
int otr_y = browser_view_->GetTabStripHeight() + top_spacing;
int otr_width = 0;
int otr_height = 0;
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
SkBitmap otr_avatar_icon = browser_view_->GetOTRAvatarIcon();
otr_width = otr_avatar_icon.width();
otr_height = otr_avatar_icon.height();
otr_x = kOTRAvatarIconMargin;
otr_y -= otr_avatar_icon.height() + 2;
}
otr_avatar_bounds_.SetRect(otr_x, otr_y, otr_width, otr_height);
}
void OpaqueNonClientView::LayoutDistributorLogo() {
if (distributor_logo_.empty())
return;
int logo_w = distributor_logo_.width();
int logo_h = distributor_logo_.height();
int logo_x = 0;
if (UILayoutIsRightToLeft()) {
CRect minimize_bounds;
minimize_button_->GetBounds(&minimize_bounds,
APPLY_MIRRORING_TRANSFORMATION);
logo_x = minimize_bounds.right + kDistributorLogoHorizontalOffset;
} else {
logo_x = minimize_button_->x() - logo_w -
kDistributorLogoHorizontalOffset;
}
logo_bounds_.SetRect(logo_x, kDistributorLogoVerticalOffset, logo_w, logo_h);
}
void OpaqueNonClientView::LayoutTitleBar() {
int top_offset = frame_->IsMaximized() ? kWindowTopMarginZoomed : 0;
ChromeViews::WindowDelegate* d = frame_->window_delegate();
// Size the window icon, even if it is hidden so we can size the title based
// on its position.
bool show_icon = d->ShouldShowWindowIcon();
icon_bounds_.SetRect(kWindowIconLeftOffset, kWindowIconLeftOffset,
show_icon ? kWindowIconSize : 0,
show_icon ? kWindowIconSize : 0);
if (window_icon_)
window_icon_->SetBounds(icon_bounds_.ToRECT());
// Size the title, if visible.
if (d->ShouldShowWindowTitle()) {
int spacing = d->ShouldShowWindowIcon() ? kWindowIconTitleSpacing : 0;
int title_right = minimize_button_->x();
int icon_right = icon_bounds_.right();
int title_left = icon_right + spacing;
title_bounds_.SetRect(title_left, kTitleTopOffset + top_offset,
std::max(0, static_cast<int>(title_right - icon_right)),
title_font_.height());
}
}
void OpaqueNonClientView::LayoutClientView() {
gfx::Rect client_bounds(
CalculateClientAreaBounds(width(), height()));
frame_->client_view()->SetBounds(client_bounds.ToRECT());
}
// static
void OpaqueNonClientView::InitClass() {
static bool initialized = false;
if (!initialized) {
active_resources_ = new ActiveWindowResources;
inactive_resources_ = new InactiveWindowResources;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SkBitmap* image = rb.GetBitmapNamed(IDR_DISTRIBUTOR_LOGO_LIGHT);
if (!image->isNull())
distributor_logo_ = *image;
app_top_left_ = *rb.GetBitmapNamed(IDR_APP_TOP_LEFT);
app_top_center_ = *rb.GetBitmapNamed(IDR_APP_TOP_CENTER);
app_top_right_ = *rb.GetBitmapNamed(IDR_APP_TOP_RIGHT);
initialized = true;
}
}
// static
void OpaqueNonClientView::InitAppWindowResources() {
static bool initialized = false;
if (!initialized) {
title_font_ = ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(1, ChromeFont::BOLD);
initialized = true;
}
}
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
namespace xla {
namespace gpu {
namespace {
bool IsIEEEFloatingPointScalarConstant(const HloInstruction* constant) {
if (constant->opcode() != HloOpcode::kConstant ||
!ShapeUtil::IsScalar(constant->shape())) {
return false;
}
auto type = constant->shape().element_type();
return type == F16 || type == F32 || type == F64;
}
} // namespace
/*static*/ bool GpuInstructionFusion::IsExpensive(
const HloInstruction& instruction) {
// We say that floating-point division is cheap on the GPU.
if (instruction.opcode() == HloOpcode::kDivide &&
ShapeUtil::ElementIsFloating(instruction.shape())) {
return false;
}
// LLVM optimizes the integer division/remainder by a
// constant scalar to a few fast operations.
if ((instruction.opcode() == HloOpcode::kDivide ||
instruction.opcode() == HloOpcode::kRemainder) &&
ShapeUtil::ElementIsIntegral(instruction.shape())) {
auto* operand1 = instruction.operand(1);
if (hlo_query::IsScalarConstant(operand1)) {
return false;
}
// Broadcasted scalar is also being optimized.
if (operand1->opcode() == HloOpcode::kBroadcast &&
hlo_query::IsScalarConstant(operand1->operand(0))) {
return false;
}
}
return InstructionFusion::IsExpensive(instruction);
}
bool GpuInstructionFusion::ShouldFuseInexpensiveChecks(HloInstruction* consumer,
int64 operand_index) {
HloInstruction* producer = consumer->mutable_operand(operand_index);
// Output fusions are not currently supported on GPUs.
if (producer->opcode() == HloOpcode::kFusion) {
return false;
}
// Cost condition: not fuse (simple, expensive producers) and (consumers who
// reuse operand elements).
if (producer->opcode() != HloOpcode::kFusion &&
consumer->ReusesOperandElements(operand_index) &&
is_expensive(*producer)) {
return false;
}
if (!IsProducerConsumerFusible(*producer, *consumer) ||
!InstructionFusion::ShouldFuse(consumer, operand_index)) {
return false;
}
return true;
}
bool GpuInstructionFusion::ShouldFuse(HloInstruction* consumer,
int64 operand_index) {
if (!ShouldFuseInexpensiveChecks(consumer, operand_index)) {
return false;
}
auto producer = consumer->operand(operand_index);
// The following checks are potentially expensive.
if (FusionWouldBeTooLarge(*consumer, *producer)) {
return false;
}
// Also check that our emitter can handle the fusion node. We currently can
// have exponential time/memory requirements for emitting certain fusion
// kernels, in which case we don't want to fuse.
// TODO(b/119692968): Remove this once we have fixed our fusion emitter.
return !FusedIrEmitter::IsFusedIrEmitterInefficient(consumer, producer);
}
bool GpuInstructionFusion::ShouldFuseIntoMultiOutput(HloInstruction* consumer,
int64 operand_index) {
return false;
}
HloInstruction::FusionKind GpuInstructionFusion::ChooseKind(
const HloInstruction* producer, const HloInstruction* consumer) {
return ChooseFusionKind(*producer, *consumer);
}
} // namespace gpu
} // namespace xla
[XLA] Delete dead function.
PiperOrigin-RevId: 257489127
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
namespace xla {
namespace gpu {
/*static*/ bool GpuInstructionFusion::IsExpensive(
const HloInstruction& instruction) {
// We say that floating-point division is cheap on the GPU.
if (instruction.opcode() == HloOpcode::kDivide &&
ShapeUtil::ElementIsFloating(instruction.shape())) {
return false;
}
// LLVM optimizes the integer division/remainder by a
// constant scalar to a few fast operations.
if ((instruction.opcode() == HloOpcode::kDivide ||
instruction.opcode() == HloOpcode::kRemainder) &&
ShapeUtil::ElementIsIntegral(instruction.shape())) {
auto* operand1 = instruction.operand(1);
if (hlo_query::IsScalarConstant(operand1)) {
return false;
}
// Broadcasted scalar is also being optimized.
if (operand1->opcode() == HloOpcode::kBroadcast &&
hlo_query::IsScalarConstant(operand1->operand(0))) {
return false;
}
}
return InstructionFusion::IsExpensive(instruction);
}
bool GpuInstructionFusion::ShouldFuseInexpensiveChecks(HloInstruction* consumer,
int64 operand_index) {
HloInstruction* producer = consumer->mutable_operand(operand_index);
// Output fusions are not currently supported on GPUs.
if (producer->opcode() == HloOpcode::kFusion) {
return false;
}
// Cost condition: not fuse (simple, expensive producers) and (consumers who
// reuse operand elements).
if (producer->opcode() != HloOpcode::kFusion &&
consumer->ReusesOperandElements(operand_index) &&
is_expensive(*producer)) {
return false;
}
if (!IsProducerConsumerFusible(*producer, *consumer) ||
!InstructionFusion::ShouldFuse(consumer, operand_index)) {
return false;
}
return true;
}
bool GpuInstructionFusion::ShouldFuse(HloInstruction* consumer,
int64 operand_index) {
if (!ShouldFuseInexpensiveChecks(consumer, operand_index)) {
return false;
}
auto producer = consumer->operand(operand_index);
// The following checks are potentially expensive.
if (FusionWouldBeTooLarge(*consumer, *producer)) {
return false;
}
// Also check that our emitter can handle the fusion node. We currently can
// have exponential time/memory requirements for emitting certain fusion
// kernels, in which case we don't want to fuse.
// TODO(b/119692968): Remove this once we have fixed our fusion emitter.
return !FusedIrEmitter::IsFusedIrEmitterInefficient(consumer, producer);
}
bool GpuInstructionFusion::ShouldFuseIntoMultiOutput(HloInstruction* consumer,
int64 operand_index) {
return false;
}
HloInstruction::FusionKind GpuInstructionFusion::ChooseKind(
const HloInstruction* producer, const HloInstruction* consumer) {
return ChooseFusionKind(*producer, *consumer);
}
} // namespace gpu
} // namespace xla
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Morwenn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iterator>
#include <type_traits>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/as_function.h>
#include <cpp-sort/utility/functional.h>
#include <cpp-sort/utility/size.h>
namespace detail
{
template<
typename ForwardIterator,
typename StrictWeakOrdering,
typename Projection
>
auto bubble_sort(ForwardIterator first, StrictWeakOrdering compare,
Projection projection, std::size_t size)
-> void
{
if (size < 2) return;
auto&& proj = cppsort::utility::as_function(projection);
while (--size)
{
ForwardIterator current = first;
ForwardIterator next = std::next(current);
for (std::size_t i = 0 ; i < size ; ++i)
{
if (compare(proj(*next), proj(*current)))
{
std::iter_swap(current, next);
}
++next;
++current;
}
}
}
struct bubble_sorter_impl
{
// Pair of iterators overload
template<
typename ForwardIterator,
typename StrictWeakOrdering = std::less<>,
typename Projection = cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_iterator<
Projection, ForwardIterator, StrictWeakOrdering
>>
>
auto operator()(ForwardIterator first, ForwardIterator last,
StrictWeakOrdering compare={}, Projection projection={}) const
-> void
{
static_assert(
std::is_base_of<
std::forward_iterator_tag,
typename std::iterator_traits<ForwardIterator>::iterator_category
>::value,
"bubble_sorter requires at least forward iterators"
);
bubble_sort(first,
compare, projection,
std::distance(first, last));
}
// Iterable overload
template<
typename ForwardIterable,
typename StrictWeakOrdering = std::less<>,
typename Projection = cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection<
Projection, ForwardIterable, StrictWeakOrdering
>>
>
auto operator()(ForwardIterable& iterable, StrictWeakOrdering compare={},
Projection projection={}) const
-> void
{
static_assert(
std::is_base_of<
std::forward_iterator_tag,
typename std::iterator_traits<decltype(std::begin(iterable))>::iterator_category
>::value,
"bubble_sorter requires at least forward iterators"
);
bubble_sort(std::begin(iterable),
compare, projection,
cppsort::utility::size(iterable));
}
};
}
struct bubble_sorter:
cppsort::sorter_facade<detail::bubble_sorter_impl>
{};
namespace cppsort
{
template<>
struct sorter_traits<::bubble_sorter>
{
using iterator_category = std::forward_iterator_tag;
using is_stable = std::true_type;
};
}
#include <array>
#include <cassert>
#include <numeric>
#include <cpp-sort/sort.h>
int main()
{
// Check that the bubble_sorter can sort any permutation
// of an array of 8 values
// Fill the collection in sorted order
std::array<int, 8> collection;
std::iota(std::begin(collection), std::end(collection), 0);
// Projection to sort in descending order
auto projection = [](int n) { return -n; };
// For each possible permutation of collection
do
{
auto to_sort = collection;
// Bubble sort the collection
cppsort::sort(to_sort, bubble_sorter{}, projection);
// Check that it is indeed sorted
assert(std::is_sorted(std::begin(to_sort), std::end(to_sort), std::greater<>{}));
} while (std::next_permutation(std::begin(collection), std::end(collection)));
}
Simplify sorter traits in bubble_sorter example.
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Morwenn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iterator>
#include <type_traits>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/utility/as_function.h>
#include <cpp-sort/utility/functional.h>
#include <cpp-sort/utility/size.h>
namespace detail
{
template<
typename ForwardIterator,
typename StrictWeakOrdering,
typename Projection
>
auto bubble_sort(ForwardIterator first, StrictWeakOrdering compare,
Projection projection, std::size_t size)
-> void
{
if (size < 2) return;
auto&& proj = cppsort::utility::as_function(projection);
while (--size)
{
ForwardIterator current = first;
ForwardIterator next = std::next(current);
for (std::size_t i = 0 ; i < size ; ++i)
{
if (compare(proj(*next), proj(*current)))
{
std::iter_swap(current, next);
}
++next;
++current;
}
}
}
struct bubble_sorter_impl
{
// Pair of iterators overload
template<
typename ForwardIterator,
typename StrictWeakOrdering = std::less<>,
typename Projection = cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection_iterator<
Projection, ForwardIterator, StrictWeakOrdering
>>
>
auto operator()(ForwardIterator first, ForwardIterator last,
StrictWeakOrdering compare={}, Projection projection={}) const
-> void
{
static_assert(
std::is_base_of<
std::forward_iterator_tag,
typename std::iterator_traits<ForwardIterator>::iterator_category
>::value,
"bubble_sorter requires at least forward iterators"
);
bubble_sort(first,
compare, projection,
std::distance(first, last));
}
// Iterable overload
template<
typename ForwardIterable,
typename StrictWeakOrdering = std::less<>,
typename Projection = cppsort::utility::identity,
typename = std::enable_if_t<cppsort::is_projection<
Projection, ForwardIterable, StrictWeakOrdering
>>
>
auto operator()(ForwardIterable& iterable, StrictWeakOrdering compare={},
Projection projection={}) const
-> void
{
static_assert(
std::is_base_of<
std::forward_iterator_tag,
typename std::iterator_traits<decltype(std::begin(iterable))>::iterator_category
>::value,
"bubble_sorter requires at least forward iterators"
);
bubble_sort(std::begin(iterable),
compare, projection,
cppsort::utility::size(iterable));
}
// Sorter traits
using iterator_category = std::forward_iterator_tag;
using is_stable = std::true_type;
};
}
struct bubble_sorter:
cppsort::sorter_facade<detail::bubble_sorter_impl>
{};
#include <array>
#include <cassert>
#include <numeric>
#include <cpp-sort/sort.h>
int main()
{
// Check that the bubble_sorter can sort any permutation
// of an array of 8 values
// Fill the collection in sorted order
std::array<int, 8> collection;
std::iota(std::begin(collection), std::end(collection), 0);
// Projection to sort in descending order
auto projection = [](int n) { return -n; };
// For each possible permutation of collection
do
{
auto to_sort = collection;
// Bubble sort the collection
cppsort::sort(to_sort, bubble_sorter{}, projection);
// Check that it is indeed sorted
assert(std::is_sorted(std::begin(to_sort), std::end(to_sort), std::greater<>{}));
} while (std::next_permutation(std::begin(collection), std::end(collection)));
}
|
#include "journal.h"
#include "valexpr.h"
#include "binary.h"
#include <fstream>
#include <ctime>
#include <sys/stat.h>
#define TIMELOG_SUPPORT 1
namespace ledger {
static unsigned long binary_magic_number = 0xFFEED765;
#ifdef DEBUG_ENABLED
static unsigned long format_version = 0x0002050b;
#else
static unsigned long format_version = 0x0002050a;
#endif
static account_t ** accounts;
static account_t ** accounts_next;
static unsigned int account_index;
static commodity_t ** commodities;
static commodity_t ** commodities_next;
static unsigned int commodity_index;
extern char * bigints;
extern char * bigints_next;
extern unsigned int bigints_index;
extern unsigned int bigints_count;
#if DEBUG_LEVEL >= ALPHA
#define read_binary_guard(in, id) { \
unsigned short guard; \
in.read((char *)&guard, sizeof(guard)); \
assert(guard == id); \
}
#else
#define read_binary_guard(in, id)
#endif
template <typename T>
inline void read_binary_number(std::istream& in, T& num) {
in.read((char *)&num, sizeof(num));
}
template <typename T>
inline void read_binary_long(std::istream& in, T& num) {
unsigned char len;
in.read((char *)&len, sizeof(unsigned char));
num = 0;
unsigned char temp;
if (len > 3) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 24;
}
if (len > 2) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 16;
}
if (len > 1) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 8;
}
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp);
}
template <typename T>
inline T read_binary_number(std::istream& in) {
T num;
read_binary_number(in, num);
return num;
}
template <typename T>
inline T read_binary_long(std::istream& in) {
T num;
read_binary_long(in, num);
return num;
}
inline void read_binary_string(std::istream& in, std::string& str)
{
read_binary_guard(in, 0x3001);
unsigned char len;
read_binary_number(in, len);
if (len == 0xff) {
unsigned short slen;
read_binary_number(in, slen);
char * buf = new char[slen + 1];
in.read(buf, slen);
buf[slen] = '\0';
str = buf;
delete[] buf;
}
else if (len) {
char buf[256];
in.read(buf, len);
buf[len] = '\0';
str = buf;
} else {
str = "";
}
read_binary_guard(in, 0x3002);
}
inline std::string read_binary_string(std::istream& in)
{
std::string temp;
read_binary_string(in, temp);
return temp;
}
template <typename T>
inline void read_binary_number(char *& data, T& num) {
num = *((T *) data);
data += sizeof(T);
}
template <typename T>
inline void read_binary_long(char *& data, T& num) {
unsigned char len = *((unsigned char *)data++);
num = 0;
unsigned char temp;
if (len > 3) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 24;
}
if (len > 2) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 16;
}
if (len > 1) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 8;
}
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp);
}
template <typename T>
inline T read_binary_number(char *& data) {
T num;
read_binary_number(data, num);
return num;
}
template <typename T>
inline T read_binary_long(char *& data) {
T num;
read_binary_long(data, num);
return num;
}
inline void read_binary_string(char *& data, std::string& str)
{
#if DEBUG_LEVEL >= ALPHA
unsigned short guard;
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3001);
#endif
unsigned char len = *data++;
if (len == 0xff) {
unsigned short slen = *((unsigned short *) data);
str = std::string(data + sizeof(unsigned short), slen);
data += sizeof(unsigned short) + slen;
}
else if (len) {
str = std::string(data, len);
data += len;
}
else {
str = "";
}
#if DEBUG_LEVEL >= ALPHA
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3002);
#endif
}
inline std::string read_binary_string(char *& data)
{
std::string temp;
read_binary_string(data, temp);
return temp;
}
inline void read_binary_string(char *& data, std::string * str)
{
#if DEBUG_LEVEL >= ALPHA
unsigned short guard;
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3001);
#endif
unsigned char len = *data++;
if (len == 0xff) {
unsigned short slen = *((unsigned short *) data);
new(str) std::string(data + sizeof(unsigned short), slen);
data += sizeof(unsigned short) + slen;
}
else if (len) {
new(str) std::string(data, len);
data += len;
}
else {
new(str) std::string("");
}
#if DEBUG_LEVEL >= ALPHA
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3002);
#endif
}
inline void read_binary_amount(char *& data, amount_t& amt)
{
commodity_t::ident_t ident;
read_binary_long(data, ident);
if (ident == 0xffffffff)
amt.commodity_ = NULL;
else if (ident == 0)
amt.commodity_ = commodity_t::null_commodity;
else
amt.commodity_ = commodities[ident - 1];
amt.read_quantity(data);
}
inline void read_binary_mask(char *& data, mask_t *& mask)
{
bool exclude;
read_binary_number(data, exclude);
std::string pattern;
read_binary_string(data, pattern);
mask = new mask_t(pattern);
mask->exclude = exclude;
}
inline void read_binary_value_expr(char *& data, value_expr_t *& expr)
{
if (read_binary_number<unsigned char>(data) == 0) {
expr = NULL;
return;
}
value_expr_t::kind_t kind;
read_binary_number(data, kind);
expr = new value_expr_t(kind);
read_binary_value_expr(data, expr->left);
read_binary_value_expr(data, expr->right);
switch (expr->kind) {
case value_expr_t::CONSTANT_T:
read_binary_number(data, expr->constant_t);
break;
case value_expr_t::CONSTANT_I:
read_binary_long(data, expr->constant_i);
break;
case value_expr_t::CONSTANT_A:
read_binary_amount(data, expr->constant_a);
break;
case value_expr_t::F_FUNC:
read_binary_string(data, expr->constant_s);
break;
}
if (read_binary_number<unsigned char>(data) == 1)
read_binary_mask(data, expr->mask);
}
inline void read_binary_transaction(char *& data, transaction_t * xact)
{
read_binary_long(data, xact->_date);
read_binary_long(data, xact->_date_eff);
xact->account = accounts[read_binary_long<account_t::ident_t>(data) - 1];
if (read_binary_number<char>(data) == 1)
read_binary_value_expr(data, xact->amount_expr);
else
read_binary_amount(data, xact->amount);
if (*data++ == 1) {
xact->cost = new amount_t;
if (read_binary_number<char>(data) == 1)
read_binary_value_expr(data, xact->cost_expr);
else
read_binary_amount(data, *xact->cost);
} else {
xact->cost = NULL;
}
read_binary_number(data, xact->state);
read_binary_number(data, xact->flags);
xact->flags |= TRANSACTION_BULK_ALLOC;
read_binary_string(data, &xact->note);
xact->beg_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, xact->beg_line);
xact->end_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, xact->end_line);
xact->data = NULL;
if (xact->amount_expr)
compute_amount(xact->amount_expr, xact->amount, *xact);
if (xact->cost_expr)
compute_amount(xact->cost_expr, *xact->cost, *xact);
}
inline void read_binary_entry_base(char *& data, entry_base_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_long(data, entry->src_idx);
entry->beg_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, entry->beg_line);
entry->end_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, entry->end_line);
bool ignore_calculated = read_binary_number<char>(data) == 1;
for (unsigned long i = 0, count = read_binary_long<unsigned long>(data);
i < count;
i++) {
DEBUG_PRINT("ledger.memory.ctors", "ctor transaction_t");
read_binary_transaction(data, xact_pool);
if (ignore_calculated && xact_pool->flags & TRANSACTION_CALCULATED)
finalize = true;
entry->add_transaction(xact_pool++);
}
}
inline void read_binary_entry(char *& data, entry_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_entry_base(data, entry, xact_pool, finalize);
read_binary_long(data, entry->_date);
read_binary_long(data, entry->_date_eff);
read_binary_string(data, &entry->code);
read_binary_string(data, &entry->payee);
}
inline void read_binary_auto_entry(char *& data, auto_entry_t * entry,
transaction_t *& xact_pool)
{
bool ignore;
read_binary_entry_base(data, entry, xact_pool, ignore);
read_binary_string(data, &entry->predicate_string);
entry->predicate = new item_predicate<transaction_t>(entry->predicate_string);
}
inline void read_binary_period_entry(char *& data, period_entry_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_entry_base(data, entry, xact_pool, finalize);
read_binary_string(data, &entry->period_string);
std::istringstream stream(entry->period_string);
entry->period.parse(stream);
}
inline commodity_t * read_binary_commodity(char *& data)
{
commodity_t * commodity = new commodity_t;
*commodities_next++ = commodity;
read_binary_string(data, *(const_cast<std::string *>(&commodity->symbol)));
read_binary_number(data, commodity->quote);
read_binary_string(data, commodity->name);
read_binary_string(data, commodity->note);
read_binary_number(data, commodity->precision);
read_binary_number(data, commodity->flags);
read_binary_long(data, commodity->ident);
return commodity;
}
inline void read_binary_commodity_extra(char *& data,
commodity_t::ident_t ident)
{
commodity_t * commodity = commodities[ident];
for (unsigned long i = 0, count = read_binary_long<unsigned long>(data);
i < count;
i++) {
std::time_t when;
read_binary_long(data, when);
amount_t amt;
read_binary_amount(data, amt);
// Upon insertion, amt will be copied, which will cause the amount
// to be duplicated (and thus not lost when the journal's
// item_pool is deleted.
if (! commodity->history)
commodity->history = new commodity_t::history_t;
commodity->history->prices.insert(history_pair(when, amt));
}
if (commodity->history)
read_binary_long(data, commodity->history->last_lookup);
unsigned char flag;
flag = read_binary_number<unsigned char>(data);
if (flag) {
amount_t amt;
read_binary_amount(data, amt);
commodity->smaller = new amount_t(amt);
}
flag = read_binary_number<unsigned char>(data);
if (flag) {
amount_t amt;
read_binary_amount(data, amt);
commodity->larger = new amount_t(amt);
}
}
inline
account_t * read_binary_account(char *& data, journal_t * journal,
account_t * master = NULL)
{
account_t * acct = new account_t(NULL);
*accounts_next++ = acct;
acct->ident = read_binary_long<account_t::ident_t>(data);
acct->journal = journal;
account_t::ident_t id;
read_binary_long(data, id); // parent id
if (id == 0xffffffff)
acct->parent = NULL;
else
acct->parent = accounts[id - 1];
read_binary_string(data, acct->name);
read_binary_string(data, acct->note);
read_binary_number(data, acct->depth);
// If all of the subaccounts will be added to a different master
// account, throw away what we've learned about the recorded
// journal's own master account.
if (master) {
delete acct;
acct = master;
}
for (account_t::ident_t i = 0,
count = read_binary_long<account_t::ident_t>(data);
i < count;
i++) {
account_t * child = read_binary_account(data, journal);
child->parent = acct;
acct->add_account(child);
}
return acct;
}
unsigned int read_binary_journal(std::istream& in,
const std::string& file,
journal_t * journal,
account_t * master)
{
account_index =
commodity_index = 0;
// Read in the files that participated in this journal, so that they
// can be checked for changes on reading.
if (! file.empty()) {
for (unsigned short i = 0,
count = read_binary_number<unsigned short>(in);
i < count;
i++) {
std::string path = read_binary_string(in);
if (i == 0 && path != file)
return 0;
std::time_t old_mtime;
read_binary_long(in, old_mtime);
struct stat info;
stat(path.c_str(), &info);
if (std::difftime(info.st_mtime, old_mtime) > 0)
return 0;
journal->sources.push_back(path);
}
// Make sure that the cache uses the same price database,
// otherwise it means that LEDGER_PRICE_DB has been changed, and
// we should ignore this cache file.
if (read_binary_string(in) != journal->price_db)
return 0;
}
// Read all of the data in at once, so that we're just dealing with
// a big data buffer.
unsigned long data_size = read_binary_number<unsigned long>(in);
char * data_pool = new char[data_size];
char * data = data_pool;
in.read(data, data_size);
// Read in the accounts
account_t::ident_t a_count = read_binary_long<account_t::ident_t>(data);
accounts = accounts_next = new account_t *[a_count];
delete journal->master;
journal->master = read_binary_account(data, journal, master);
if (read_binary_number<bool>(data))
journal->basket = accounts[read_binary_long<account_t::ident_t>(data) - 1];
// Allocate the memory needed for the entries and transactions in
// one large block, which is then chopped up and custom constructed
// as necessary.
unsigned long count = read_binary_long<unsigned long>(data);
unsigned long auto_count = read_binary_long<unsigned long>(data);
unsigned long period_count = read_binary_long<unsigned long>(data);
unsigned long xact_count = read_binary_number<unsigned long>(data);
unsigned long bigint_count = read_binary_number<unsigned long>(data);
std::size_t pool_size = (sizeof(entry_t) * count +
sizeof(transaction_t) * xact_count +
sizeof_bigint_t() * bigint_count);
char * item_pool = new char[pool_size];
entry_t * entry_pool = (entry_t *) item_pool;
transaction_t * xact_pool = (transaction_t *) (item_pool +
sizeof(entry_t) * count);
bigints_index = 0;
bigints = bigints_next = (item_pool + sizeof(entry_t) * count +
sizeof(transaction_t) * xact_count);
// Read in the commodities
commodity_t::ident_t c_count = read_binary_long<commodity_t::ident_t>(data);
commodities = commodities_next = new commodity_t *[c_count];
for (commodity_t::ident_t i = 0; i < c_count; i++) {
commodity_t * commodity = read_binary_commodity(data);
if (! (commodity->flags & COMMODITY_STYLE_BUILTIN)) {
if (commodity->symbol == "") {
commodity_t::commodities.erase(commodity->symbol);
delete commodity_t::null_commodity;
commodity_t::null_commodity = commodity;
}
std::pair<commodities_map::iterator, bool> result =
commodity_t::commodities.insert(commodities_pair(commodity->symbol,
commodity));
if (! result.second)
throw error(std::string("Failed to read commodity from cache: ") +
commodity->symbol);
}
}
for (commodity_t::ident_t i = 0; i < c_count; i++)
read_binary_commodity_extra(data, i);
commodity_t::ident_t ident;
read_binary_long(data, ident);
if (ident == 0xffffffff || ident == 0)
commodity_t::default_commodity = NULL;
else
commodity_t::default_commodity = commodities[ident - 1];
// Read in the entries and transactions
for (unsigned long i = 0; i < count; i++) {
new(entry_pool) entry_t;
bool finalize = false;
read_binary_entry(data, entry_pool, xact_pool, finalize);
entry_pool->journal = journal;
if (finalize && ! entry_pool->finalize())
continue;
journal->entries.push_back(entry_pool++);
}
for (unsigned long i = 0; i < auto_count; i++) {
auto_entry_t * auto_entry = new auto_entry_t;
read_binary_auto_entry(data, auto_entry, xact_pool);
auto_entry->journal = journal;
journal->auto_entries.push_back(auto_entry);
}
for (unsigned long i = 0; i < period_count; i++) {
period_entry_t * period_entry = new period_entry_t;
bool finalize = false;
read_binary_period_entry(data, period_entry, xact_pool, finalize);
period_entry->journal = journal;
if (finalize && ! period_entry->finalize())
continue;
journal->period_entries.push_back(period_entry);
}
// Clean up and return the number of entries read
journal->item_pool = item_pool;
journal->item_pool_end = item_pool + pool_size;
delete[] accounts;
delete[] commodities;
delete[] data_pool;
VALIDATE(journal->valid());
return count;
}
bool binary_parser_t::test(std::istream& in) const
{
if (read_binary_number<unsigned long>(in) == binary_magic_number &&
read_binary_number<unsigned long>(in) == format_version)
return true;
in.clear();
in.seekg(0, std::ios::beg);
return false;
}
unsigned int binary_parser_t::parse(std::istream& in,
config_t& config,
journal_t * journal,
account_t * master,
const std::string * original_file)
{
return read_binary_journal(in, original_file ? *original_file : "",
journal, master);
}
#if DEBUG_LEVEL >= ALPHA
#define write_binary_guard(in, id) { \
unsigned short guard = id; \
out.write((char *)&guard, sizeof(guard)); \
}
#else
#define write_binary_guard(in, id)
#endif
template <typename T>
inline void write_binary_number(std::ostream& out, T num) {
out.write((char *)&num, sizeof(num));
}
template <typename T>
inline void write_binary_long(std::ostream& out, T num) {
unsigned char len = 4;
if (((unsigned long)num) < 0x00000100UL)
len = 1;
else if (((unsigned long)num) < 0x00010000UL)
len = 2;
else if (((unsigned long)num) < 0x01000000UL)
len = 3;
out.write((char *)&len, sizeof(unsigned char));
if (len > 3) {
unsigned char temp = (((unsigned long)num) & 0xFF000000UL) >> 24;
out.write((char *)&temp, sizeof(unsigned char));
}
if (len > 2) {
unsigned char temp = (((unsigned long)num) & 0x00FF0000UL) >> 16;
out.write((char *)&temp, sizeof(unsigned char));
}
if (len > 1) {
unsigned char temp = (((unsigned long)num) & 0x0000FF00UL) >> 8;
out.write((char *)&temp, sizeof(unsigned char));
}
unsigned char temp = (((unsigned long)num) & 0x000000FFUL);
out.write((char *)&temp, sizeof(unsigned char));
}
inline void write_binary_string(std::ostream& out, const std::string& str)
{
write_binary_guard(out, 0x3001);
unsigned long len = str.length();
if (len > 255) {
assert(len < 65536);
write_binary_number<unsigned char>(out, 0xff);
write_binary_number<unsigned short>(out, len);
} else {
write_binary_number<unsigned char>(out, len);
}
if (len)
out.write(str.c_str(), len);
write_binary_guard(out, 0x3002);
}
void write_binary_amount(std::ostream& out, const amount_t& amt)
{
if (amt.commodity_)
write_binary_long(out, amt.commodity().ident);
else
write_binary_long<commodity_t::ident_t>(out, 0xffffffff);
amt.write_quantity(out);
}
void write_binary_mask(std::ostream& out, mask_t * mask)
{
write_binary_number(out, mask->exclude);
write_binary_string(out, mask->pattern);
}
void write_binary_value_expr(std::ostream& out, value_expr_t * expr)
{
if (expr == NULL) {
write_binary_number<unsigned char>(out, 0);
return;
}
write_binary_number<unsigned char>(out, 1);
write_binary_number(out, expr->kind);
write_binary_value_expr(out, expr->left);
write_binary_value_expr(out, expr->right);
switch (expr->kind) {
case value_expr_t::CONSTANT_T:
write_binary_number(out, expr->constant_t);
break;
case value_expr_t::CONSTANT_I:
write_binary_long(out, expr->constant_i);
break;
case value_expr_t::CONSTANT_A:
write_binary_amount(out, expr->constant_a);
break;
case value_expr_t::F_FUNC:
write_binary_string(out, expr->constant_s);
break;
}
if (expr->mask) {
write_binary_number<char>(out, 1);
write_binary_mask(out, expr->mask);
} else {
write_binary_number<char>(out, 0);
}
}
void write_binary_transaction(std::ostream& out, transaction_t * xact,
bool ignore_calculated)
{
write_binary_long(out, xact->_date);
write_binary_long(out, xact->_date_eff);
write_binary_long(out, xact->account->ident);
if (xact->amount_expr != NULL) {
write_binary_number<char>(out, 1);
write_binary_value_expr(out, xact->amount_expr);
} else {
write_binary_number<char>(out, 0);
if (ignore_calculated && xact->flags & TRANSACTION_CALCULATED)
write_binary_amount(out, amount_t());
else
write_binary_amount(out, xact->amount);
}
if (xact->cost &&
(! (ignore_calculated && xact->flags & TRANSACTION_CALCULATED))) {
write_binary_number<char>(out, 1);
if (xact->cost_expr != NULL) {
write_binary_number<char>(out, 1);
write_binary_value_expr(out, xact->cost_expr);
} else {
write_binary_number<char>(out, 0);
write_binary_amount(out, *xact->cost);
}
} else {
write_binary_number<char>(out, 0);
}
write_binary_number(out, xact->state);
write_binary_number(out, xact->flags);
write_binary_string(out, xact->note);
write_binary_long(out, xact->beg_pos);
write_binary_long(out, xact->beg_line);
write_binary_long(out, xact->end_pos);
write_binary_long(out, xact->end_line);
}
void write_binary_entry_base(std::ostream& out, entry_base_t * entry)
{
write_binary_long(out, entry->src_idx);
write_binary_long(out, entry->beg_pos);
write_binary_long(out, entry->beg_line);
write_binary_long(out, entry->end_pos);
write_binary_long(out, entry->end_line);
bool ignore_calculated = false;
for (transactions_list::const_iterator i = entry->transactions.begin();
i != entry->transactions.end();
i++)
if ((*i)->amount_expr || (*i)->cost_expr) {
ignore_calculated = true;
break;
}
write_binary_number<char>(out, ignore_calculated ? 1 : 0);
write_binary_long(out, entry->transactions.size());
for (transactions_list::const_iterator i = entry->transactions.begin();
i != entry->transactions.end();
i++)
write_binary_transaction(out, *i, ignore_calculated);
}
void write_binary_entry(std::ostream& out, entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_long(out, entry->_date);
write_binary_long(out, entry->_date_eff);
write_binary_string(out, entry->code);
write_binary_string(out, entry->payee);
}
void write_binary_auto_entry(std::ostream& out, auto_entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_string(out, entry->predicate_string);
}
void write_binary_period_entry(std::ostream& out, period_entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_string(out, entry->period_string);
}
void write_binary_commodity(std::ostream& out, commodity_t * commodity)
{
write_binary_string(out, commodity->symbol);
write_binary_number(out, commodity->quote);
write_binary_string(out, commodity->name);
write_binary_string(out, commodity->note);
write_binary_number(out, commodity->precision);
write_binary_number(out, commodity->flags);
commodity->ident = ++commodity_index;
write_binary_long(out, commodity->ident);
}
void write_binary_commodity_extra(std::ostream& out, commodity_t * commodity)
{
if (! commodity->history) {
write_binary_long<unsigned long>(out, 0);
} else {
write_binary_long<unsigned long>(out, commodity->history->prices.size());
for (history_map::const_iterator i = commodity->history->prices.begin();
i != commodity->history->prices.end();
i++) {
write_binary_long(out, (*i).first);
write_binary_amount(out, (*i).second);
}
write_binary_long(out, commodity->history->last_lookup);
}
if (commodity->smaller) {
write_binary_number<unsigned char>(out, 1);
write_binary_amount(out, *commodity->smaller);
} else {
write_binary_number<unsigned char>(out, 0);
}
if (commodity->larger) {
write_binary_number<unsigned char>(out, 1);
write_binary_amount(out, *commodity->larger);
} else {
write_binary_number<unsigned char>(out, 0);
}
}
static inline account_t::ident_t count_accounts(account_t * account)
{
account_t::ident_t count = 1;
for (accounts_map::iterator i = account->accounts.begin();
i != account->accounts.end();
i++)
count += count_accounts((*i).second);
return count;
}
void write_binary_account(std::ostream& out, account_t * account)
{
account->ident = ++account_index;
write_binary_long(out, account->ident);
if (account->parent)
write_binary_long(out, account->parent->ident);
else
write_binary_long<account_t::ident_t>(out, 0xffffffff);
write_binary_string(out, account->name);
write_binary_string(out, account->note);
write_binary_number(out, account->depth);
write_binary_long<account_t::ident_t>(out, account->accounts.size());
for (accounts_map::iterator i = account->accounts.begin();
i != account->accounts.end();
i++)
write_binary_account(out, (*i).second);
}
void write_binary_journal(std::ostream& out, journal_t * journal)
{
account_index =
commodity_index = 0;
write_binary_number(out, binary_magic_number);
write_binary_number(out, format_version);
// Write out the files that participated in this journal, so that
// they can be checked for changes on reading.
if (journal->sources.size() == 0) {
write_binary_number<unsigned short>(out, 0);
} else {
write_binary_number<unsigned short>(out, journal->sources.size());
for (strings_list::const_iterator i = journal->sources.begin();
i != journal->sources.end();
i++) {
write_binary_string(out, *i);
struct stat info;
stat((*i).c_str(), &info);
write_binary_long(out, std::time_t(info.st_mtime));
}
// Write out the price database that relates to this data file, so
// that if it ever changes the cache can be invalidated.
write_binary_string(out, journal->price_db);
}
ostream_pos_type data_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
// Write out the accounts
write_binary_long<account_t::ident_t>(out, count_accounts(journal->master));
write_binary_account(out, journal->master);
if (journal->basket) {
write_binary_number<bool>(out, true);
write_binary_long(out, journal->basket->ident);
} else {
write_binary_number<bool>(out, false);
}
// Write out the number of entries, transactions, and amounts
write_binary_long<unsigned long>(out, journal->entries.size());
write_binary_long<unsigned long>(out, journal->auto_entries.size());
write_binary_long<unsigned long>(out, journal->period_entries.size());
ostream_pos_type xacts_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
ostream_pos_type bigints_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
bigints_count = 0;
// Write out the commodities
write_binary_long<commodity_t::ident_t>
(out, commodity_t::commodities.size());
for (commodities_map::const_iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
write_binary_commodity(out, (*i).second);
for (commodities_map::const_iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
write_binary_commodity_extra(out, (*i).second);
if (commodity_t::default_commodity)
write_binary_long(out, commodity_t::default_commodity->ident);
else
write_binary_long<commodity_t::ident_t>(out, 0xffffffff);
// Write out the entries and transactions
unsigned long xact_count = 0;
for (entries_list::const_iterator i = journal->entries.begin();
i != journal->entries.end();
i++) {
write_binary_entry(out, *i);
xact_count += (*i)->transactions.size();
}
for (auto_entries_list::const_iterator i = journal->auto_entries.begin();
i != journal->auto_entries.end();
i++) {
write_binary_auto_entry(out, *i);
xact_count += (*i)->transactions.size();
}
for (period_entries_list::const_iterator i = journal->period_entries.begin();
i != journal->period_entries.end();
i++) {
write_binary_period_entry(out, *i);
xact_count += (*i)->transactions.size();
}
// Back-patch the count for amounts
unsigned long data_size = (((unsigned long) out.tellp()) -
((unsigned long) data_val) -
sizeof(unsigned long));
out.seekp(data_val);
write_binary_number<unsigned long>(out, data_size);
out.seekp(xacts_val);
write_binary_number<unsigned long>(out, xact_count);
out.seekp(bigints_val);
write_binary_number<unsigned long>(out, bigints_count);
}
} // namespace ledger
Stopped writing out certain ident numbers which were not being used.
#include "journal.h"
#include "valexpr.h"
#include "binary.h"
#include <fstream>
#include <ctime>
#include <sys/stat.h>
#define TIMELOG_SUPPORT 1
namespace ledger {
static unsigned long binary_magic_number = 0xFFEED765;
#ifdef DEBUG_ENABLED
static unsigned long format_version = 0x0002050b;
#else
static unsigned long format_version = 0x0002050a;
#endif
static account_t ** accounts;
static account_t ** accounts_next;
static unsigned int account_index;
static commodity_t ** commodities;
static commodity_t ** commodities_next;
static unsigned int commodity_index;
extern char * bigints;
extern char * bigints_next;
extern unsigned int bigints_index;
extern unsigned int bigints_count;
#if DEBUG_LEVEL >= ALPHA
#define read_binary_guard(in, id) { \
unsigned short guard; \
in.read((char *)&guard, sizeof(guard)); \
assert(guard == id); \
}
#else
#define read_binary_guard(in, id)
#endif
template <typename T>
inline void read_binary_number(std::istream& in, T& num) {
in.read((char *)&num, sizeof(num));
}
template <typename T>
inline void read_binary_long(std::istream& in, T& num) {
unsigned char len;
in.read((char *)&len, sizeof(unsigned char));
num = 0;
unsigned char temp;
if (len > 3) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 24;
}
if (len > 2) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 16;
}
if (len > 1) {
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp) << 8;
}
in.read((char *)&temp, sizeof(unsigned char));
num |= ((unsigned long)temp);
}
template <typename T>
inline T read_binary_number(std::istream& in) {
T num;
read_binary_number(in, num);
return num;
}
template <typename T>
inline T read_binary_long(std::istream& in) {
T num;
read_binary_long(in, num);
return num;
}
inline void read_binary_string(std::istream& in, std::string& str)
{
read_binary_guard(in, 0x3001);
unsigned char len;
read_binary_number(in, len);
if (len == 0xff) {
unsigned short slen;
read_binary_number(in, slen);
char * buf = new char[slen + 1];
in.read(buf, slen);
buf[slen] = '\0';
str = buf;
delete[] buf;
}
else if (len) {
char buf[256];
in.read(buf, len);
buf[len] = '\0';
str = buf;
} else {
str = "";
}
read_binary_guard(in, 0x3002);
}
inline std::string read_binary_string(std::istream& in)
{
std::string temp;
read_binary_string(in, temp);
return temp;
}
template <typename T>
inline void read_binary_number(char *& data, T& num) {
num = *((T *) data);
data += sizeof(T);
}
template <typename T>
inline void read_binary_long(char *& data, T& num) {
unsigned char len = *((unsigned char *)data++);
num = 0;
unsigned char temp;
if (len > 3) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 24;
}
if (len > 2) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 16;
}
if (len > 1) {
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp) << 8;
}
temp = *((unsigned char *)data++);
num |= ((unsigned long)temp);
}
template <typename T>
inline T read_binary_number(char *& data) {
T num;
read_binary_number(data, num);
return num;
}
template <typename T>
inline T read_binary_long(char *& data) {
T num;
read_binary_long(data, num);
return num;
}
inline void read_binary_string(char *& data, std::string& str)
{
#if DEBUG_LEVEL >= ALPHA
unsigned short guard;
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3001);
#endif
unsigned char len = *data++;
if (len == 0xff) {
unsigned short slen = *((unsigned short *) data);
str = std::string(data + sizeof(unsigned short), slen);
data += sizeof(unsigned short) + slen;
}
else if (len) {
str = std::string(data, len);
data += len;
}
else {
str = "";
}
#if DEBUG_LEVEL >= ALPHA
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3002);
#endif
}
inline std::string read_binary_string(char *& data)
{
std::string temp;
read_binary_string(data, temp);
return temp;
}
inline void read_binary_string(char *& data, std::string * str)
{
#if DEBUG_LEVEL >= ALPHA
unsigned short guard;
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3001);
#endif
unsigned char len = *data++;
if (len == 0xff) {
unsigned short slen = *((unsigned short *) data);
new(str) std::string(data + sizeof(unsigned short), slen);
data += sizeof(unsigned short) + slen;
}
else if (len) {
new(str) std::string(data, len);
data += len;
}
else {
new(str) std::string("");
}
#if DEBUG_LEVEL >= ALPHA
guard = *((unsigned short *) data);
data += sizeof(unsigned short);
assert(guard == 0x3002);
#endif
}
inline void read_binary_amount(char *& data, amount_t& amt)
{
commodity_t::ident_t ident;
read_binary_long(data, ident);
if (ident == 0xffffffff)
amt.commodity_ = NULL;
else if (ident == 0)
amt.commodity_ = commodity_t::null_commodity;
else
amt.commodity_ = commodities[ident - 1];
amt.read_quantity(data);
}
inline void read_binary_mask(char *& data, mask_t *& mask)
{
bool exclude;
read_binary_number(data, exclude);
std::string pattern;
read_binary_string(data, pattern);
mask = new mask_t(pattern);
mask->exclude = exclude;
}
inline void read_binary_value_expr(char *& data, value_expr_t *& expr)
{
if (read_binary_number<unsigned char>(data) == 0) {
expr = NULL;
return;
}
value_expr_t::kind_t kind;
read_binary_number(data, kind);
expr = new value_expr_t(kind);
read_binary_value_expr(data, expr->left);
read_binary_value_expr(data, expr->right);
switch (expr->kind) {
case value_expr_t::CONSTANT_T:
read_binary_number(data, expr->constant_t);
break;
case value_expr_t::CONSTANT_I:
read_binary_long(data, expr->constant_i);
break;
case value_expr_t::CONSTANT_A:
read_binary_amount(data, expr->constant_a);
break;
case value_expr_t::F_FUNC:
read_binary_string(data, expr->constant_s);
break;
}
if (read_binary_number<unsigned char>(data) == 1)
read_binary_mask(data, expr->mask);
}
inline void read_binary_transaction(char *& data, transaction_t * xact)
{
read_binary_long(data, xact->_date);
read_binary_long(data, xact->_date_eff);
xact->account = accounts[read_binary_long<account_t::ident_t>(data) - 1];
if (read_binary_number<char>(data) == 1)
read_binary_value_expr(data, xact->amount_expr);
else
read_binary_amount(data, xact->amount);
if (*data++ == 1) {
xact->cost = new amount_t;
if (read_binary_number<char>(data) == 1)
read_binary_value_expr(data, xact->cost_expr);
else
read_binary_amount(data, *xact->cost);
} else {
xact->cost = NULL;
}
read_binary_number(data, xact->state);
read_binary_number(data, xact->flags);
xact->flags |= TRANSACTION_BULK_ALLOC;
read_binary_string(data, &xact->note);
xact->beg_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, xact->beg_line);
xact->end_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, xact->end_line);
xact->data = NULL;
if (xact->amount_expr)
compute_amount(xact->amount_expr, xact->amount, *xact);
if (xact->cost_expr)
compute_amount(xact->cost_expr, *xact->cost, *xact);
}
inline void read_binary_entry_base(char *& data, entry_base_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_long(data, entry->src_idx);
entry->beg_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, entry->beg_line);
entry->end_pos = read_binary_long<unsigned long>(data);
read_binary_long(data, entry->end_line);
bool ignore_calculated = read_binary_number<char>(data) == 1;
for (unsigned long i = 0, count = read_binary_long<unsigned long>(data);
i < count;
i++) {
DEBUG_PRINT("ledger.memory.ctors", "ctor transaction_t");
read_binary_transaction(data, xact_pool);
if (ignore_calculated && xact_pool->flags & TRANSACTION_CALCULATED)
finalize = true;
entry->add_transaction(xact_pool++);
}
}
inline void read_binary_entry(char *& data, entry_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_entry_base(data, entry, xact_pool, finalize);
read_binary_long(data, entry->_date);
read_binary_long(data, entry->_date_eff);
read_binary_string(data, &entry->code);
read_binary_string(data, &entry->payee);
}
inline void read_binary_auto_entry(char *& data, auto_entry_t * entry,
transaction_t *& xact_pool)
{
bool ignore;
read_binary_entry_base(data, entry, xact_pool, ignore);
read_binary_string(data, &entry->predicate_string);
entry->predicate = new item_predicate<transaction_t>(entry->predicate_string);
}
inline void read_binary_period_entry(char *& data, period_entry_t * entry,
transaction_t *& xact_pool, bool& finalize)
{
read_binary_entry_base(data, entry, xact_pool, finalize);
read_binary_string(data, &entry->period_string);
std::istringstream stream(entry->period_string);
entry->period.parse(stream);
}
inline commodity_t * read_binary_commodity(char *& data)
{
commodity_t * commodity = new commodity_t;
*commodities_next++ = commodity;
read_binary_string(data, *(const_cast<std::string *>(&commodity->symbol)));
read_binary_number(data, commodity->quote);
read_binary_string(data, commodity->name);
read_binary_string(data, commodity->note);
read_binary_number(data, commodity->precision);
read_binary_number(data, commodity->flags);
return commodity;
}
inline void read_binary_commodity_extra(char *& data,
commodity_t::ident_t ident)
{
commodity_t * commodity = commodities[ident];
for (unsigned long i = 0, count = read_binary_long<unsigned long>(data);
i < count;
i++) {
std::time_t when;
read_binary_long(data, when);
amount_t amt;
read_binary_amount(data, amt);
// Upon insertion, amt will be copied, which will cause the amount
// to be duplicated (and thus not lost when the journal's
// item_pool is deleted.
if (! commodity->history)
commodity->history = new commodity_t::history_t;
commodity->history->prices.insert(history_pair(when, amt));
}
if (commodity->history)
read_binary_long(data, commodity->history->last_lookup);
unsigned char flag;
flag = read_binary_number<unsigned char>(data);
if (flag) {
amount_t amt;
read_binary_amount(data, amt);
commodity->smaller = new amount_t(amt);
}
flag = read_binary_number<unsigned char>(data);
if (flag) {
amount_t amt;
read_binary_amount(data, amt);
commodity->larger = new amount_t(amt);
}
}
inline
account_t * read_binary_account(char *& data, journal_t * journal,
account_t * master = NULL)
{
account_t * acct = new account_t(NULL);
*accounts_next++ = acct;
acct->journal = journal;
account_t::ident_t id;
read_binary_long(data, id); // parent id
if (id == 0xffffffff)
acct->parent = NULL;
else
acct->parent = accounts[id - 1];
read_binary_string(data, acct->name);
read_binary_string(data, acct->note);
read_binary_number(data, acct->depth);
// If all of the subaccounts will be added to a different master
// account, throw away what we've learned about the recorded
// journal's own master account.
if (master) {
delete acct;
acct = master;
}
for (account_t::ident_t i = 0,
count = read_binary_long<account_t::ident_t>(data);
i < count;
i++) {
account_t * child = read_binary_account(data, journal);
child->parent = acct;
acct->add_account(child);
}
return acct;
}
unsigned int read_binary_journal(std::istream& in,
const std::string& file,
journal_t * journal,
account_t * master)
{
account_index =
commodity_index = 0;
// Read in the files that participated in this journal, so that they
// can be checked for changes on reading.
if (! file.empty()) {
for (unsigned short i = 0,
count = read_binary_number<unsigned short>(in);
i < count;
i++) {
std::string path = read_binary_string(in);
if (i == 0 && path != file)
return 0;
std::time_t old_mtime;
read_binary_long(in, old_mtime);
struct stat info;
stat(path.c_str(), &info);
if (std::difftime(info.st_mtime, old_mtime) > 0)
return 0;
journal->sources.push_back(path);
}
// Make sure that the cache uses the same price database,
// otherwise it means that LEDGER_PRICE_DB has been changed, and
// we should ignore this cache file.
if (read_binary_string(in) != journal->price_db)
return 0;
}
// Read all of the data in at once, so that we're just dealing with
// a big data buffer.
unsigned long data_size = read_binary_number<unsigned long>(in);
char * data_pool = new char[data_size];
char * data = data_pool;
in.read(data, data_size);
// Read in the accounts
account_t::ident_t a_count = read_binary_long<account_t::ident_t>(data);
accounts = accounts_next = new account_t *[a_count];
delete journal->master;
journal->master = read_binary_account(data, journal, master);
if (read_binary_number<bool>(data))
journal->basket = accounts[read_binary_long<account_t::ident_t>(data) - 1];
// Allocate the memory needed for the entries and transactions in
// one large block, which is then chopped up and custom constructed
// as necessary.
unsigned long count = read_binary_long<unsigned long>(data);
unsigned long auto_count = read_binary_long<unsigned long>(data);
unsigned long period_count = read_binary_long<unsigned long>(data);
unsigned long xact_count = read_binary_number<unsigned long>(data);
unsigned long bigint_count = read_binary_number<unsigned long>(data);
std::size_t pool_size = (sizeof(entry_t) * count +
sizeof(transaction_t) * xact_count +
sizeof_bigint_t() * bigint_count);
char * item_pool = new char[pool_size];
entry_t * entry_pool = (entry_t *) item_pool;
transaction_t * xact_pool = (transaction_t *) (item_pool +
sizeof(entry_t) * count);
bigints_index = 0;
bigints = bigints_next = (item_pool + sizeof(entry_t) * count +
sizeof(transaction_t) * xact_count);
// Read in the commodities
commodity_t::ident_t c_count = read_binary_long<commodity_t::ident_t>(data);
commodities = commodities_next = new commodity_t *[c_count];
for (commodity_t::ident_t i = 0; i < c_count; i++) {
commodity_t * commodity = read_binary_commodity(data);
if (! (commodity->flags & COMMODITY_STYLE_BUILTIN)) {
if (commodity->symbol == "") {
commodity_t::commodities.erase(commodity->symbol);
delete commodity_t::null_commodity;
commodity_t::null_commodity = commodity;
}
std::pair<commodities_map::iterator, bool> result =
commodity_t::commodities.insert(commodities_pair(commodity->symbol,
commodity));
if (! result.second)
throw error(std::string("Failed to read commodity from cache: ") +
commodity->symbol);
}
}
for (commodity_t::ident_t i = 0; i < c_count; i++)
read_binary_commodity_extra(data, i);
commodity_t::ident_t ident;
read_binary_long(data, ident);
if (ident == 0xffffffff || ident == 0)
commodity_t::default_commodity = NULL;
else
commodity_t::default_commodity = commodities[ident - 1];
// Read in the entries and transactions
for (unsigned long i = 0; i < count; i++) {
new(entry_pool) entry_t;
bool finalize = false;
read_binary_entry(data, entry_pool, xact_pool, finalize);
entry_pool->journal = journal;
if (finalize && ! entry_pool->finalize())
continue;
journal->entries.push_back(entry_pool++);
}
for (unsigned long i = 0; i < auto_count; i++) {
auto_entry_t * auto_entry = new auto_entry_t;
read_binary_auto_entry(data, auto_entry, xact_pool);
auto_entry->journal = journal;
journal->auto_entries.push_back(auto_entry);
}
for (unsigned long i = 0; i < period_count; i++) {
period_entry_t * period_entry = new period_entry_t;
bool finalize = false;
read_binary_period_entry(data, period_entry, xact_pool, finalize);
period_entry->journal = journal;
if (finalize && ! period_entry->finalize())
continue;
journal->period_entries.push_back(period_entry);
}
// Clean up and return the number of entries read
journal->item_pool = item_pool;
journal->item_pool_end = item_pool + pool_size;
delete[] accounts;
delete[] commodities;
delete[] data_pool;
VALIDATE(journal->valid());
return count;
}
bool binary_parser_t::test(std::istream& in) const
{
if (read_binary_number<unsigned long>(in) == binary_magic_number &&
read_binary_number<unsigned long>(in) == format_version)
return true;
in.clear();
in.seekg(0, std::ios::beg);
return false;
}
unsigned int binary_parser_t::parse(std::istream& in,
config_t& config,
journal_t * journal,
account_t * master,
const std::string * original_file)
{
return read_binary_journal(in, original_file ? *original_file : "",
journal, master);
}
#if DEBUG_LEVEL >= ALPHA
#define write_binary_guard(in, id) { \
unsigned short guard = id; \
out.write((char *)&guard, sizeof(guard)); \
}
#else
#define write_binary_guard(in, id)
#endif
template <typename T>
inline void write_binary_number(std::ostream& out, T num) {
out.write((char *)&num, sizeof(num));
}
template <typename T>
inline void write_binary_long(std::ostream& out, T num) {
unsigned char len = 4;
if (((unsigned long)num) < 0x00000100UL)
len = 1;
else if (((unsigned long)num) < 0x00010000UL)
len = 2;
else if (((unsigned long)num) < 0x01000000UL)
len = 3;
out.write((char *)&len, sizeof(unsigned char));
if (len > 3) {
unsigned char temp = (((unsigned long)num) & 0xFF000000UL) >> 24;
out.write((char *)&temp, sizeof(unsigned char));
}
if (len > 2) {
unsigned char temp = (((unsigned long)num) & 0x00FF0000UL) >> 16;
out.write((char *)&temp, sizeof(unsigned char));
}
if (len > 1) {
unsigned char temp = (((unsigned long)num) & 0x0000FF00UL) >> 8;
out.write((char *)&temp, sizeof(unsigned char));
}
unsigned char temp = (((unsigned long)num) & 0x000000FFUL);
out.write((char *)&temp, sizeof(unsigned char));
}
inline void write_binary_string(std::ostream& out, const std::string& str)
{
write_binary_guard(out, 0x3001);
unsigned long len = str.length();
if (len > 255) {
assert(len < 65536);
write_binary_number<unsigned char>(out, 0xff);
write_binary_number<unsigned short>(out, len);
} else {
write_binary_number<unsigned char>(out, len);
}
if (len)
out.write(str.c_str(), len);
write_binary_guard(out, 0x3002);
}
void write_binary_amount(std::ostream& out, const amount_t& amt)
{
if (amt.commodity_)
write_binary_long(out, amt.commodity().ident);
else
write_binary_long<commodity_t::ident_t>(out, 0xffffffff);
amt.write_quantity(out);
}
void write_binary_mask(std::ostream& out, mask_t * mask)
{
write_binary_number(out, mask->exclude);
write_binary_string(out, mask->pattern);
}
void write_binary_value_expr(std::ostream& out, value_expr_t * expr)
{
if (expr == NULL) {
write_binary_number<unsigned char>(out, 0);
return;
}
write_binary_number<unsigned char>(out, 1);
write_binary_number(out, expr->kind);
write_binary_value_expr(out, expr->left);
write_binary_value_expr(out, expr->right);
switch (expr->kind) {
case value_expr_t::CONSTANT_T:
write_binary_number(out, expr->constant_t);
break;
case value_expr_t::CONSTANT_I:
write_binary_long(out, expr->constant_i);
break;
case value_expr_t::CONSTANT_A:
write_binary_amount(out, expr->constant_a);
break;
case value_expr_t::F_FUNC:
write_binary_string(out, expr->constant_s);
break;
}
if (expr->mask) {
write_binary_number<char>(out, 1);
write_binary_mask(out, expr->mask);
} else {
write_binary_number<char>(out, 0);
}
}
void write_binary_transaction(std::ostream& out, transaction_t * xact,
bool ignore_calculated)
{
write_binary_long(out, xact->_date);
write_binary_long(out, xact->_date_eff);
write_binary_long(out, xact->account->ident);
if (xact->amount_expr != NULL) {
write_binary_number<char>(out, 1);
write_binary_value_expr(out, xact->amount_expr);
} else {
write_binary_number<char>(out, 0);
if (ignore_calculated && xact->flags & TRANSACTION_CALCULATED)
write_binary_amount(out, amount_t());
else
write_binary_amount(out, xact->amount);
}
if (xact->cost &&
(! (ignore_calculated && xact->flags & TRANSACTION_CALCULATED))) {
write_binary_number<char>(out, 1);
if (xact->cost_expr != NULL) {
write_binary_number<char>(out, 1);
write_binary_value_expr(out, xact->cost_expr);
} else {
write_binary_number<char>(out, 0);
write_binary_amount(out, *xact->cost);
}
} else {
write_binary_number<char>(out, 0);
}
write_binary_number(out, xact->state);
write_binary_number(out, xact->flags);
write_binary_string(out, xact->note);
write_binary_long(out, xact->beg_pos);
write_binary_long(out, xact->beg_line);
write_binary_long(out, xact->end_pos);
write_binary_long(out, xact->end_line);
}
void write_binary_entry_base(std::ostream& out, entry_base_t * entry)
{
write_binary_long(out, entry->src_idx);
write_binary_long(out, entry->beg_pos);
write_binary_long(out, entry->beg_line);
write_binary_long(out, entry->end_pos);
write_binary_long(out, entry->end_line);
bool ignore_calculated = false;
for (transactions_list::const_iterator i = entry->transactions.begin();
i != entry->transactions.end();
i++)
if ((*i)->amount_expr || (*i)->cost_expr) {
ignore_calculated = true;
break;
}
write_binary_number<char>(out, ignore_calculated ? 1 : 0);
write_binary_long(out, entry->transactions.size());
for (transactions_list::const_iterator i = entry->transactions.begin();
i != entry->transactions.end();
i++)
write_binary_transaction(out, *i, ignore_calculated);
}
void write_binary_entry(std::ostream& out, entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_long(out, entry->_date);
write_binary_long(out, entry->_date_eff);
write_binary_string(out, entry->code);
write_binary_string(out, entry->payee);
}
void write_binary_auto_entry(std::ostream& out, auto_entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_string(out, entry->predicate_string);
}
void write_binary_period_entry(std::ostream& out, period_entry_t * entry)
{
write_binary_entry_base(out, entry);
write_binary_string(out, entry->period_string);
}
void write_binary_commodity(std::ostream& out, commodity_t * commodity)
{
write_binary_string(out, commodity->symbol);
write_binary_number(out, commodity->quote);
write_binary_string(out, commodity->name);
write_binary_string(out, commodity->note);
write_binary_number(out, commodity->precision);
write_binary_number(out, commodity->flags);
commodity->ident = ++commodity_index;
}
void write_binary_commodity_extra(std::ostream& out, commodity_t * commodity)
{
if (! commodity->history) {
write_binary_long<unsigned long>(out, 0);
} else {
write_binary_long<unsigned long>(out, commodity->history->prices.size());
for (history_map::const_iterator i = commodity->history->prices.begin();
i != commodity->history->prices.end();
i++) {
write_binary_long(out, (*i).first);
write_binary_amount(out, (*i).second);
}
write_binary_long(out, commodity->history->last_lookup);
}
if (commodity->smaller) {
write_binary_number<unsigned char>(out, 1);
write_binary_amount(out, *commodity->smaller);
} else {
write_binary_number<unsigned char>(out, 0);
}
if (commodity->larger) {
write_binary_number<unsigned char>(out, 1);
write_binary_amount(out, *commodity->larger);
} else {
write_binary_number<unsigned char>(out, 0);
}
}
static inline account_t::ident_t count_accounts(account_t * account)
{
account_t::ident_t count = 1;
for (accounts_map::iterator i = account->accounts.begin();
i != account->accounts.end();
i++)
count += count_accounts((*i).second);
return count;
}
void write_binary_account(std::ostream& out, account_t * account)
{
account->ident = ++account_index;
if (account->parent)
write_binary_long(out, account->parent->ident);
else
write_binary_long<account_t::ident_t>(out, 0xffffffff);
write_binary_string(out, account->name);
write_binary_string(out, account->note);
write_binary_number(out, account->depth);
write_binary_long<account_t::ident_t>(out, account->accounts.size());
for (accounts_map::iterator i = account->accounts.begin();
i != account->accounts.end();
i++)
write_binary_account(out, (*i).second);
}
void write_binary_journal(std::ostream& out, journal_t * journal)
{
account_index =
commodity_index = 0;
write_binary_number(out, binary_magic_number);
write_binary_number(out, format_version);
// Write out the files that participated in this journal, so that
// they can be checked for changes on reading.
if (journal->sources.size() == 0) {
write_binary_number<unsigned short>(out, 0);
} else {
write_binary_number<unsigned short>(out, journal->sources.size());
for (strings_list::const_iterator i = journal->sources.begin();
i != journal->sources.end();
i++) {
write_binary_string(out, *i);
struct stat info;
stat((*i).c_str(), &info);
write_binary_long(out, std::time_t(info.st_mtime));
}
// Write out the price database that relates to this data file, so
// that if it ever changes the cache can be invalidated.
write_binary_string(out, journal->price_db);
}
ostream_pos_type data_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
// Write out the accounts
write_binary_long<account_t::ident_t>(out, count_accounts(journal->master));
write_binary_account(out, journal->master);
if (journal->basket) {
write_binary_number<bool>(out, true);
write_binary_long(out, journal->basket->ident);
} else {
write_binary_number<bool>(out, false);
}
// Write out the number of entries, transactions, and amounts
write_binary_long<unsigned long>(out, journal->entries.size());
write_binary_long<unsigned long>(out, journal->auto_entries.size());
write_binary_long<unsigned long>(out, journal->period_entries.size());
ostream_pos_type xacts_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
ostream_pos_type bigints_val = out.tellp();
write_binary_number<unsigned long>(out, 0);
bigints_count = 0;
// Write out the commodities
write_binary_long<commodity_t::ident_t>
(out, commodity_t::commodities.size());
for (commodities_map::const_iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
write_binary_commodity(out, (*i).second);
for (commodities_map::const_iterator i = commodity_t::commodities.begin();
i != commodity_t::commodities.end();
i++)
write_binary_commodity_extra(out, (*i).second);
if (commodity_t::default_commodity)
write_binary_long(out, commodity_t::default_commodity->ident);
else
write_binary_long<commodity_t::ident_t>(out, 0xffffffff);
// Write out the entries and transactions
unsigned long xact_count = 0;
for (entries_list::const_iterator i = journal->entries.begin();
i != journal->entries.end();
i++) {
write_binary_entry(out, *i);
xact_count += (*i)->transactions.size();
}
for (auto_entries_list::const_iterator i = journal->auto_entries.begin();
i != journal->auto_entries.end();
i++) {
write_binary_auto_entry(out, *i);
xact_count += (*i)->transactions.size();
}
for (period_entries_list::const_iterator i = journal->period_entries.begin();
i != journal->period_entries.end();
i++) {
write_binary_period_entry(out, *i);
xact_count += (*i)->transactions.size();
}
// Back-patch the count for amounts
unsigned long data_size = (((unsigned long) out.tellp()) -
((unsigned long) data_val) -
sizeof(unsigned long));
out.seekp(data_val);
write_binary_number<unsigned long>(out, data_size);
out.seekp(xacts_val);
write_binary_number<unsigned long>(out, xact_count);
out.seekp(bigints_val);
write_binary_number<unsigned long>(out, bigints_count);
}
} // namespace ledger
|
/**
** \file runner/interpreter.cc
** \brief Implementation of runner::Interpreter.
*/
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <algorithm>
#include <deque>
#include <boost/range/iterator_range.hpp>
#include <libport/finally.hh>
#include <libport/foreach.hh>
#include <libport/symbol.hh>
#include <kernel/exception.hh>
#include <kernel/uconnection.hh>
#include <ast/declarations-type.hh>
#include <ast/exps-type.hh>
#include <ast/print.hh>
#include <object/atom.hh>
#include <object/global-class.hh>
#include <object/idelegate.hh>
#include <object/lazy.hh>
#include <object/object.hh>
#include <object/symbols.hh>
#include <object/tag-class.hh>
#include <object/urbi-exception.hh>
#include <object/flow-exception.hh>
#include <runner/interpreter.hh>
#include <parser/uparser.hh>
namespace runner
{
using boost::bind;
using libport::Finally;
/// Address of \a Interpreter seen as a \c Job (Interpreter has multiple inheritance).
#define JOB(Interpreter) static_cast<scheduler::Job*> (Interpreter)
/// Address of \c this seen as a \c Job (Interpreter has multiple inheritance).
#define ME JOB (this)
#define AST(Ast) \
(Ast).location_get () \
<< libport::incendl \
<< "{{{" \
<< libport::incendl \
<< Ast \
<< libport::decendl \
<< "}}}" \
<< libport::decindent
/// Job echo.
#define JECHO(Title, Content) \
ECHO ("job " << ME << ", " Title ": " << Content)
/// Job & astecho.
#define JAECHO(Title, Ast) \
JECHO (Title, AST(Ast))
/* Yield and trace. */
#define YIELD() \
do \
{ \
ECHO ("job " << ME << " yielding on AST: " \
<< &e << ' ' << AST(e)); \
yield (); \
} while (0)
#define MAYBE_YIELD(Flavor) \
do \
{ \
if (Flavor == ast::flavor_semicolon) \
YIELD(); \
} while (0)
// Helper to generate a function that swaps two rObjects.
inline
boost::function0<void>
swap(Interpreter::rObject& lhs, Interpreter::rObject& rhs)
{
// Strangely, this indirection is needed
void (*f) (Interpreter::rObject&, Interpreter::rObject&) =
std::swap<Interpreter::rObject>;
return boost::bind(f, boost::ref(lhs), boost::ref(rhs));
}
// This function takes an expression and attempts to decompose it
// into a list of identifiers.
typedef std::deque<libport::Symbol> tag_chain_type;
static
tag_chain_type
decompose_tag_chain (ast::rConstExp e)
{
tag_chain_type res;
while (!e->implicit())
{
ast::rConstCall c = e.unsafe_cast<const ast::Call>();
if (!c || c->arguments_get())
throw object::ImplicitTagComponentError(e->location_get());
res.push_front (c->name_get());
e = c->target_get();
}
return res;
}
/*--------------.
| Interpreter. |
`--------------*/
Interpreter::Interpreter (rLobby lobby,
scheduler::Scheduler& sched,
ast::rConstAst ast,
const libport::Symbol& name)
: Interpreter::super_type(),
Runner(lobby, sched, name),
ast_(ast),
code_(0),
current_(0),
locals_(object::Object::make_method_scope(lobby))
{
scope_tags_.push_back(0);
init();
}
Interpreter::Interpreter(const Interpreter& model, rObject code,
const libport::Symbol& name)
: Interpreter::super_type(),
Runner(model, name),
ast_(0),
code_(code),
current_(0),
locals_(model.locals_)
{
scope_tags_.push_back(0);
init();
}
Interpreter::Interpreter(const Interpreter& model,
ast::rConstAst ast,
const libport::Symbol& name)
: Interpreter::super_type (),
Runner(model, name),
ast_(ast),
code_(0),
current_(0),
locals_(model.locals_)
{
scope_tags_.push_back(0);
}
Interpreter::~Interpreter ()
{
}
void
Interpreter::init()
{
// If the lobby has a slot connectionTag, push it
rObject connection_tag = lobby_->slot_locate(SYMBOL(connectionTag));
if (connection_tag)
push_tag(extract_tag(connection_tag->slot_get(SYMBOL(connectionTag))));
}
void
Interpreter::show_error_ (const object::UrbiException& ue)
{
std::ostringstream o;
o << "!!! " << ue.location_get () << ": " << ue.what () << std::endl;
send_message("error", o.str ());
show_backtrace(ue.backtrace_get(), "error");
}
void
Interpreter::propagate_error_ (object::UrbiException& ue, const ast::loc& l)
{
if (!ue.location_is_set())
ue.location_set(l);
if (!ue.backtrace_is_set())
ue.backtrace_set(call_stack_);
// Reset the current value: there was an error so whatever value it has,
// it must not be used.
current_.reset ();
}
void
Interpreter::work ()
{
assert (ast_ || code_);
JAECHO ("starting evaluation of AST: ", *ast_);
if (ast_)
operator()(ast_);
else
{
object::objects_type args;
args.push_back(locals_);
apply(code_, SYMBOL(task), args);
}
}
/*----------------.
| Regular visit. |
`----------------*/
void
Interpreter::operator() (ast::rConstAst e)
{
/// Catch exceptions, display the error if not already done, and
/// rethrow it.
try
{
if (e)
e->accept(*this);
}
catch (object::UrbiException& x)
{
current_.reset();
propagate_error_(x, e->location_get());
throw;
}
catch (object::FlowException&)
{
current_.reset();
throw;
}
catch (scheduler::SchedulerException&)
{
current_.reset();
throw;
}
catch (kernel::exception& x)
{
std::cerr << "Unexpected exception propagated: " << x.what() << std::endl;
throw;
}
catch (std::exception& x)
{
std::cerr << "Unexpected exception propagated: " << x.what() << std::endl;
throw;
}
catch (...)
{
std::cerr << "Unknown exception propagated" << std::endl;
throw;
}
}
void
Interpreter::visit (ast::rConstAnd e)
{
// lhs will be evaluated in another Interpreter, while rhs will be evaluated
// in this one. We will be the new runner parent, as we have the same
// tags.
JAECHO ("lhs", e->lhs_get ());
scheduler::rJob lhs = new Interpreter(*this, ast::rConstAst(e->lhs_get()));
// Propagate errors between left-hand side and right-hand side runners.
link (lhs);
lhs->start_job ();
JAECHO ("rhs", e.rhs_get ());
eval (e->rhs_get ());
// Wait for lhs to terminate
yield_until_terminated (*lhs);
current_ = object::void_class;
}
void
Interpreter::visit (ast::rConstAssignment e)
{
rObject tgt = context(e->depth_get());
tgt->slot_update(*this, e->what_get(), eval(e->value_get()));
}
// Apply a function written in Urbi.
object::rObject
Interpreter::apply_urbi (const rObject& func,
const libport::Symbol& msg,
const object::objects_type& args,
rObject call_message)
{
// The called function.
ast::rConstCode fn = func.unsafe_cast<object::Code>()->value_get().ast;
// Whether it's an explicit closure
bool closure = fn.unsafe_cast<const ast::Closure>();
// If the function is lazy and there's no call message, forge
// one. This happen when a lazy function is invoked with eval, for
// instance.
if (!fn->strict() && !call_message)
{
object::objects_type lazy_args;
foreach (const rObject& o, args)
lazy_args.push_back(mkLazy(*this, o));
call_message = build_call_message(args[0], msg, lazy_args);
}
// Create the function's outer scope, with the first argument as
// 'self'. The inner scope will be created when executing ()
// on ast::Scope.
rObject scope;
if (closure)
// For closures, use the context as parent scope.
scope = func->slot_get(SYMBOL(context));
else
{
scope = object::Object::make_method_scope(args.front());
scope->slot_set(SYMBOL(code), func);
}
// If this is a strict function, check the arity and bind the formal
// arguments. Otherwise, bind the call message.
if (fn->strict())
{
const ast::declarations_type& formals = *fn->formals_get();
object::check_arg_count (formals.size() + 1, args.size(), msg.name_get());
// Effective (evaluated) argument iterator.
// Skip "self" which has already been handled.
object::objects_type::const_iterator ei = ++args.begin();
foreach (ast::rConstDeclaration s, formals)
scope->slot_set (s->what_get(), *ei++);
}
else
if (!closure)
scope->slot_set (SYMBOL(call), call_message);
// Change the current context and call. But before, check that we
// are not exhausting the stack space, for example in an infinite
// recursion.
std::swap(scope, locals_);
Finally finally(swap(scope, locals_));
check_stack_space ();
try
{
current_ = eval (fn->body_get());
}
catch (object::BreakException& be)
{
object::PrimitiveError error("break", "outside a loop");
propagate_error_(error, be.location_get());
throw error;
}
catch (object::ContinueException& be)
{
object::PrimitiveError error("continue", "outside a loop");
propagate_error_(error, be.location_get());
throw error;
}
catch (object::ReturnException& re)
{
current_ = re.result_get();
if (!current_)
current_ = object::void_class;
}
return current_;
}
namespace
{
// Helper to determine whether a function accepts void parameters
static inline bool
acceptVoid(object::rObject f)
{
assertion(f);
try
{
return object::is_true(f->slot_get(SYMBOL(acceptVoid)));
}
catch (object::LookupError&)
{
// acceptVoid is undefined. Refuse void parameter by default.
return false;
}
}
}
object::rObject
Interpreter::apply (const rObject& func,
const libport::Symbol msg,
object::objects_type args,
rObject call_message)
{
precondition(func);
// If we try to call a C++ primitive with a call message, make it
// look like a strict function call
if (call_message &&
(func->kind_get() != object::object_kind_code
|| func->value<object::Code>().ast->strict()))
{
rObject urbi_args = urbi_call(*this, call_message, SYMBOL(evalArgs));
foreach (const rObject& arg,
urbi_args->value<object::List>())
args.push_back(arg);
call_message = 0;
}
// Even with call message, there is at least one argument: self.
assert (!args.empty());
// If we use a call message, "self" is the only argument.
assert (!call_message || args.size() == 1);
// Check if any argument is void
if (!acceptVoid(func))
{
object::objects_type::iterator end = args.end();
if (std::find(++args.begin(), end, object::void_class) != end)
throw object::WrongArgumentType (msg);
}
switch (func->kind_get ())
{
case object::object_kind_primitive:
current_ =
func.unsafe_cast<object::Primitive>()->value_get()(*this, args);
break;
case object::object_kind_delegate:
current_ =
func.unsafe_cast<object::Delegate>()
->value_get()
->operator()(*this, args);
break;
case object::object_kind_code:
current_ = apply_urbi (func, msg, args, call_message);
break;
default:
object::check_arg_count (1, args.size(), msg.name_get());
current_ = func;
break;
}
return current_;
}
void
Interpreter::push_evaluated_arguments (object::objects_type& args,
const ast::exps_type& ue_args,
bool check_void)
{
bool tail = false;
foreach (ast::rConstExp arg, ue_args)
{
// Skip target, the first argument.
if (!tail++)
continue;
eval (arg);
// Check if any argument is void. This will be checked again in
// Interpreter::apply, yet raising exception here gives better
// location (the argument and not the whole function invocation).
if (check_void && current_ == object::void_class)
{
object::WrongArgumentType e("");
e.location_set(arg->location_get());
throw e;
}
passert (*arg, current_);
args.push_back (current_);
}
}
object::rObject
Interpreter::build_call_message (const rObject& tgt,
const libport::Symbol& msg,
const object::objects_type& args)
{
rObject res = object::global_class->slot_get(SYMBOL(CallMessage))->clone();
// Set the sender to be the current self. self must always exist.
res->slot_set (SYMBOL(sender),
locals_->slot_get (SYMBOL(self)));
// Set the target to be the object on which the function is applied.
res->slot_set (SYMBOL(target), tgt);
// Set the name of the message call.
res->slot_set (SYMBOL(message), object::String::fresh(msg));
res->slot_set (SYMBOL(args), object::List::fresh(args));
// Store the current context in which the arguments must be evaluated.
res->slot_set (SYMBOL(context), object::Object::make_scope(locals_));
return res;
}
object::rObject
Interpreter::build_call_message (const rObject& tgt, const libport::Symbol& msg,
const ast::exps_type& args)
{
// Build the list of lazy arguments
object::objects_type lazy_args;
boost::sub_range<const ast::exps_type> range(args);
// The target can be unspecified.
if (!args.front() || args.front()->implicit())
{
lazy_args.push_back(object::nil_class);
range = make_iterator_range(range, 1, 0);
}
foreach (ast::rConstExp e, range)
lazy_args.push_back(object::mkLazy(*this, e));
return build_call_message(tgt, msg, lazy_args);
}
void
Interpreter::visit (ast::rConstCall e)
{
// The invoked slot (probably a function).
ast::rConstExp ast_tgt = e->target_get();
rObject tgt = ast_tgt->implicit() ?
locals_->slot_get(SYMBOL(self)) : eval(ast_tgt);
call_stack_.push_back(e);
Finally finally(bind(&call_stack_type::pop_back, &call_stack_));
apply(tgt, e->name_get(), e->arguments_get());
}
void
Interpreter::visit (ast::rConstCallMsg)
{
current_ = locals_->slot_get(SYMBOL(call));
}
Interpreter::rObject
Interpreter::apply (rObject tgt, const libport::Symbol& message,
const ast::exps_type* input_ast_args)
{
// The invoked slot (probably a function).
rObject val = tgt->slot_get(message);
assertion(val);
/*-------------------------.
| Evaluate the arguments. |
`-------------------------*/
// Gather the arguments, including the target.
object::objects_type args;
args.push_back (tgt);
ast::exps_type ast_args =
input_ast_args ? *input_ast_args : ast::exps_type();
// FIXME: This is the target, for compatibility reasons. We need
// to remove this, and stop assuming that arguments start at
// calls.args.nth(1)
ast_args.push_front(0);
// Build the call message for non-strict functions, otherwise
// the evaluated argument list.
rObject call_message;
if (val->kind_get () == object::object_kind_code
&& !val.unsafe_cast<object::Code>()->value_get().ast->strict())
call_message = build_call_message (tgt, message, ast_args);
else
push_evaluated_arguments (args, ast_args, !acceptVoid(val));
return apply (val, message, args, call_message);
}
void
Interpreter::visit (ast::rConstDeclaration d)
{
locals_->slot_set(d->what_get(), eval(d->value_get()));
}
void
Interpreter::visit (ast::rConstFloat e)
{
current_ = object::Float::fresh(e->value_get());
}
void
Interpreter::visit (ast::rConstForeach e)
{
// Evaluate the list attribute, and check its type.
JAECHO ("foreach list", e.list_get());
operator() (e->list_get());
TYPE_CHECK(current_, object::List);
JAECHO("foreach body", e.body_get());
// We need to copy the pointer on the list, otherwise the list will be
// destroyed when children are visited and current_ is modified.
object::List::value_type content = current_->value<object::List>();
// The list of runners launched for each value in the list if the flavor
// is "&".
scheduler::jobs_type runners;
if (e->flavor_get() == ast::flavor_and)
runners.reserve(content.size());
bool tail = false;
ast::rConstAst body = e->body_get();
ast::flavor_type flavor = e->flavor_get();
libport::Symbol index = e->index_get()->what_get();
// Iterate on each value.
foreach (const rObject& o, content)
{
// Define a new local scope for each loop, and set the index.
rObject locals = object::Object::fresh();
locals->locals_set(true);
locals->proto_add(locals_);
locals->slot_set(index, o);
// for& ... in loop.
if (flavor == ast::flavor_and)
{
// Create the new runner and launch it. We create a link so
// that an error in evaluation will stop other evaluations
// as well and propagate the exception.
Interpreter* new_runner = new Interpreter(*this, body);
link(new_runner);
runners.push_back(new_runner);
new_runner->locals_ = locals;
new_runner->start_job();
}
else // for| and for;
{
std::swap(locals, locals_);
Finally finally(swap(locals, locals_));
if (tail++)
MAYBE_YIELD(flavor);
try
{
operator() (body);
}
catch (object::BreakException&)
{
break;
}
catch (object::ContinueException&)
{
}
}
}
// Wait for all runners to terminate.
yield_until_terminated(runners);
// For the moment return void.
current_ = object::void_class;
}
object::rObject
Interpreter::make_code(ast::rConstCode e) const
{
rObject res = object::Code::fresh(e);
// Store the function declaration context. Use make_scope to add
// an empty object above it, so as variables injected in the
// context do not appear in the declaration scope.
res->slot_set(SYMBOL(context), locals_);
return res;
}
void
Interpreter::visit (ast::rConstFunction e)
{
current_ = make_code(e);
}
void
Interpreter::visit (ast::rConstClosure e)
{
current_ = make_code(e);
}
void
Interpreter::visit (ast::rConstIf e)
{
// Evaluate the test.
JAECHO ("test", e->test_get ());
operator() (e->test_get());
if (object::is_true(current_))
{
JAECHO ("then", e.thenclause_get ());
operator() (e->thenclause_get());
}
else
{
JAECHO ("else", e.elseclause_get ());
operator() (e->elseclause_get());
}
}
void
Interpreter::visit (ast::rConstList e)
{
object::List::value_type res;
// Evaluate every expression in the list
foreach (ast::rConstExp c, e->value_get())
res.push_back(eval(c));
current_ = object::List::fresh(res);
//ECHO ("result: " << *current_);
}
Interpreter::rObject Interpreter::context(unsigned n)
{
rObject res = locals_;
for (int i = n; i; i--)
{
res = res->slot_get(SYMBOL(code))->slot_get(SYMBOL(context));
assert(res);
}
return res;
}
void
Interpreter::visit (ast::rConstLocal e)
{
rObject tgt = context(e->depth_get());
// FIXME: Register in the call stack
if (e->arguments_get())
current_ = apply(tgt, e->name_get(), e->arguments_get());
else
current_ = tgt->slot_get(e->name_get());
}
void
Interpreter::visit (ast::rConstMessage e)
{
send_message(e->tag_get(), e->text_get() + "\n");
}
// Forward flow exceptions up to the top-level, and handle them
// there. Makes only sense in a Nary.
#define CATCH_FLOW_EXCEPTION(Type, Keyword, Error) \
catch (Type flow_exception) \
{ \
if (e->toplevel_get ()) \
{ \
object::PrimitiveError error(Keyword, Error); \
propagate_error_(error, flow_exception.location_get()); \
throw error; \
} \
else \
throw; \
}
void
Interpreter::visit (ast::rConstNary e)
{
// List of runners for Stmt flavored by a comma.
scheduler::jobs_type runners;
// In case we're empty.
current_ = object::void_class;
bool tail = false;
foreach (ast::rConstExp c, e->children_get())
{
// Allow some time to pass before we execute what follows. If
// we don't do this, the ;-operator would act almost like the
// |-operator because it would always start to execute its RHS
// immediately. However, we don't want to do it before the first
// statement or if we only have one statement in the scope.
if (tail++)
YIELD ();
current_.reset ();
JAECHO ("child", c);
if (c.unsafe_cast<const ast::Stmt>() &&
c.unsafe_cast<const ast::Stmt>()->flavor_get() == ast::flavor_comma)
{
// The new runners are attached to the same tags as we are.
Interpreter* subrunner = new Interpreter(*this, ast::rConstAst(c));
runners.push_back(subrunner);
subrunner->start_job ();
}
else
{
// If at toplevel, stop and print errors
try
{
// Rewrite flow error if we are at toplevel
try
{
operator() (c);
}
CATCH_FLOW_EXCEPTION(object::BreakException,
"break", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ContinueException,
"continue", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ReturnException,
"return", "outside a function")
if (e->toplevel_get () && current_.get ())
{
try
{
assertion(current_);
ECHO("toplevel: returning a result to the connection.");
lobby_->value_get ().connection.new_result (current_);
current_.reset ();
}
catch (std::exception &ke)
{
std::cerr << "Exception when printing result: "
<< ke.what() << std::endl;
}
catch (object::UrbiException& e)
{
show_error_(e);
}
catch (...)
{
std::cerr << "Unknown exception when printing result"
<< std::endl;
}
}
}
catch (object::UrbiException& ue)
{
if (e->toplevel_get())
show_error_(ue);
else
throw;
}
CATCH_FLOW_EXCEPTION(object::BreakException,
"break", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ContinueException,
"continue", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ReturnException,
"return", "outside a function")
}
}
// If the Nary is not the toplevel one, all subrunners must be finished when
// the runner exits the Nary node.
if (!e->toplevel_get ())
yield_until_terminated(runners);
}
void
Interpreter::visit (ast::rConstNoop)
{
current_ = object::void_class;
}
void
Interpreter::visit (ast::rConstPipe e)
{
// lhs
JAECHO ("lhs", e->lhs_get ());
operator() (e->lhs_get());
// rhs: start the execution immediately.
JAECHO ("rhs", e->rhs_get ());
operator() (e->rhs_get());
}
void
Interpreter::visit (ast::rConstAbstractScope e, rObject locals)
{
std::swap(locals, locals_);
Finally finally;
finally << swap(locals, locals_)
<< boost::bind(&scheduler::Job::non_interruptible_set,
this,
non_interruptible_get());
super_type::operator()(e->body_get());
}
scheduler::rTag
Interpreter::scope_tag()
{
scheduler::rTag tag = scope_tags_.back();
if (!tag)
{
// Create the tag on demand.
tag = scheduler::Tag::fresh
(libport::Symbol::fresh(SYMBOL(LT_scope_SP_tag_GT)));
*scope_tags_.rbegin() = tag;
}
return tag;
}
void
Interpreter::cleanup_scope_tag()
{
scheduler::rTag tag = scope_tags_.back();
scope_tags_.pop_back();
if (tag)
tag->stop(scheduler_get(), object::void_class);
}
void
Interpreter::visit (ast::rConstScope e)
{
scope_tags_.push_back(0);
libport::Finally finally(boost::bind(&Interpreter::cleanup_scope_tag,
this));
visit (e.unsafe_cast<const ast::AbstractScope>(),
object::Object::make_scope(locals_));
}
void
Interpreter::visit (ast::rConstDo e)
{
rObject tgt = eval(e->target_get());
visit (e.unsafe_cast<const ast::AbstractScope>(),
object::Object::make_method_scope(tgt, locals_));
// This is arguable. Do, just like Scope, should maybe return
// their last inner value.
current_ = tgt;
}
void
Interpreter::visit (ast::rConstStmt e)
{
JAECHO ("expression", e.expression_get ());
operator() (e->expression_get());
}
void
Interpreter::visit (ast::rConstString e)
{
current_ = object::String::fresh(libport::Symbol(e->value_get()));
}
void
Interpreter::visit (ast::rConstTag t)
{
eval_tag (t->exp_get ());
}
void
Interpreter::visit (ast::rConstTaggedStmt t)
{
int current_depth = tags_.size();
try
{
scheduler::rTag tag = extract_tag(eval(t->tag_get()));
// If tag is blocked, do not start and ignore the
// statement completely.
if (tag->blocked())
return;
push_tag (tag);
Finally finally(bind(&Interpreter::pop_tag, this));
// If the latest tag causes us to be frozen, let the
// scheduler handle this properly to avoid duplicating the
// logic.
if (tag->frozen())
yield();
eval (t->exp_get());
}
catch (scheduler::StopException& e)
{
// Rewind up to the appropriate depth.
if (e.depth_get() < current_depth)
throw;
// Extract the value from the exception.
current_ = boost::any_cast<rObject>(e.payload_get());
// If we are frozen, reenter the scheduler for a while.
if (frozen())
yield();
return;
}
}
void
Interpreter::visit (ast::rConstThis)
{
current_ = locals_->slot_get(SYMBOL(self));
}
object::rObject
Interpreter::eval_tag (ast::rConstExp e)
{
try {
// Try to evaluate e as a normal expression.
return eval(e);
}
catch (object::LookupError &ue)
{
ECHO("Implicit tag: " << *e);
// We got a lookup error. It means that we have to automatically
// create the tag. In this case, we only accept k1 style tags,
// i.e. chains of identifiers, excluding function calls.
// The reason to do that is:
// - we do not want to mix k1 non-declared syntax with k2
// clean syntax for tags
// - we have no way to know whether the lookup error arrived
// in a function call or during the direct resolution of
// the name
// Tag represents the top level tag
rObject toplevel = object::tag_class;
rObject parent = toplevel;
rObject where = locals_->slot_get(SYMBOL(self));
tag_chain_type chain = decompose_tag_chain(e);
foreach (const libport::Symbol& elt, chain)
{
// Check whether the concerned level in the chain already
// exists.
if (rObject owner = where->slot_locate (elt))
{
ECHO("Component " << elt << " exists.");
where = owner->own_slot_get (elt);
if (object::is_a(where, toplevel))
{
ECHO("It is a tag, so use it as the new parent.");
parent = where;
}
}
else
{
ECHO("Creating component " << elt << ".");
// We have to create a new tag, which will be attached
// to the upper level (hierarchical tags, implicitly
// rooted by Tag).
rObject new_tag = toplevel->clone();
object::objects_type args;
args.push_back (new_tag);
args.push_back (object::String::fresh (elt));
args.push_back (parent);
apply (toplevel->own_slot_get (SYMBOL (init)), SYMBOL(init), args);
where->slot_set (elt, new_tag);
where = parent = new_tag;
}
}
return parent;
}
}
void
Interpreter::visit (ast::rConstThrow e)
{
switch (e->kind_get())
{
case ast::Throw::exception_break:
throw object::BreakException(e->location_get());
case ast::Throw::exception_continue:
throw object::ContinueException(e->location_get());
case ast::Throw::exception_return:
if (e->value_get())
operator() (e->value_get());
else
current_.reset();
throw object::ReturnException(e->location_get(), current_);
}
}
void
Interpreter::visit (ast::rConstWhile e)
{
bool tail = false;
// Evaluate the test.
while (true)
{
if (tail++)
MAYBE_YIELD (e->flavor_get());
JAECHO ("while test", e.test_get ());
operator() (e->test_get());
if (!object::is_true(current_))
break;
JAECHO ("while body", e.body_get ());
try
{
operator() (e->body_get());
}
catch (object::BreakException&)
{
break;
}
catch (object::ContinueException&)
{
}
}
current_ = object::void_class;
}
void
Interpreter::show_backtrace(const call_stack_type& bt,
const std::string& chan)
{
foreach (ast::rConstCall c,
boost::make_iterator_range(boost::rbegin(bt),
boost::rend(bt)))
{
std::ostringstream o;
o << "!!! called from: " << c->location_get () << ": "
<< c->name_get () << std::endl;
send_message(chan, o.str());
}
}
void
Interpreter::show_backtrace(const std::string& chan)
{
show_backtrace(call_stack_, chan);
}
Interpreter::backtrace_type
Interpreter::backtrace_get() const
{
backtrace_type res;
foreach (ast::rConstCall c, call_stack_)
{
std::ostringstream o;
o << c->location_get();
res.push_back(std::make_pair(c->name_get().name_get(), o.str()));
}
return res;
}
} // namespace runner
Remove redundant assert() in acceptVoid().
One of the call sites checks that the provided pointer is not 0 in a
precondition, and the other dereferences the pointer already before
calling acceptVoid().
* src/runner/interpreter.cc (acceptVoid): Remove redundant
assert().
/**
** \file runner/interpreter.cc
** \brief Implementation of runner::Interpreter.
*/
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <algorithm>
#include <deque>
#include <boost/range/iterator_range.hpp>
#include <libport/finally.hh>
#include <libport/foreach.hh>
#include <libport/symbol.hh>
#include <kernel/exception.hh>
#include <kernel/uconnection.hh>
#include <ast/declarations-type.hh>
#include <ast/exps-type.hh>
#include <ast/print.hh>
#include <object/atom.hh>
#include <object/global-class.hh>
#include <object/idelegate.hh>
#include <object/lazy.hh>
#include <object/object.hh>
#include <object/symbols.hh>
#include <object/tag-class.hh>
#include <object/urbi-exception.hh>
#include <object/flow-exception.hh>
#include <runner/interpreter.hh>
#include <parser/uparser.hh>
namespace runner
{
using boost::bind;
using libport::Finally;
/// Address of \a Interpreter seen as a \c Job (Interpreter has multiple inheritance).
#define JOB(Interpreter) static_cast<scheduler::Job*> (Interpreter)
/// Address of \c this seen as a \c Job (Interpreter has multiple inheritance).
#define ME JOB (this)
#define AST(Ast) \
(Ast).location_get () \
<< libport::incendl \
<< "{{{" \
<< libport::incendl \
<< Ast \
<< libport::decendl \
<< "}}}" \
<< libport::decindent
/// Job echo.
#define JECHO(Title, Content) \
ECHO ("job " << ME << ", " Title ": " << Content)
/// Job & astecho.
#define JAECHO(Title, Ast) \
JECHO (Title, AST(Ast))
/* Yield and trace. */
#define YIELD() \
do \
{ \
ECHO ("job " << ME << " yielding on AST: " \
<< &e << ' ' << AST(e)); \
yield (); \
} while (0)
#define MAYBE_YIELD(Flavor) \
do \
{ \
if (Flavor == ast::flavor_semicolon) \
YIELD(); \
} while (0)
// Helper to generate a function that swaps two rObjects.
inline
boost::function0<void>
swap(Interpreter::rObject& lhs, Interpreter::rObject& rhs)
{
// Strangely, this indirection is needed
void (*f) (Interpreter::rObject&, Interpreter::rObject&) =
std::swap<Interpreter::rObject>;
return boost::bind(f, boost::ref(lhs), boost::ref(rhs));
}
// This function takes an expression and attempts to decompose it
// into a list of identifiers.
typedef std::deque<libport::Symbol> tag_chain_type;
static
tag_chain_type
decompose_tag_chain (ast::rConstExp e)
{
tag_chain_type res;
while (!e->implicit())
{
ast::rConstCall c = e.unsafe_cast<const ast::Call>();
if (!c || c->arguments_get())
throw object::ImplicitTagComponentError(e->location_get());
res.push_front (c->name_get());
e = c->target_get();
}
return res;
}
/*--------------.
| Interpreter. |
`--------------*/
Interpreter::Interpreter (rLobby lobby,
scheduler::Scheduler& sched,
ast::rConstAst ast,
const libport::Symbol& name)
: Interpreter::super_type(),
Runner(lobby, sched, name),
ast_(ast),
code_(0),
current_(0),
locals_(object::Object::make_method_scope(lobby))
{
scope_tags_.push_back(0);
init();
}
Interpreter::Interpreter(const Interpreter& model, rObject code,
const libport::Symbol& name)
: Interpreter::super_type(),
Runner(model, name),
ast_(0),
code_(code),
current_(0),
locals_(model.locals_)
{
scope_tags_.push_back(0);
init();
}
Interpreter::Interpreter(const Interpreter& model,
ast::rConstAst ast,
const libport::Symbol& name)
: Interpreter::super_type (),
Runner(model, name),
ast_(ast),
code_(0),
current_(0),
locals_(model.locals_)
{
scope_tags_.push_back(0);
}
Interpreter::~Interpreter ()
{
}
void
Interpreter::init()
{
// If the lobby has a slot connectionTag, push it
rObject connection_tag = lobby_->slot_locate(SYMBOL(connectionTag));
if (connection_tag)
push_tag(extract_tag(connection_tag->slot_get(SYMBOL(connectionTag))));
}
void
Interpreter::show_error_ (const object::UrbiException& ue)
{
std::ostringstream o;
o << "!!! " << ue.location_get () << ": " << ue.what () << std::endl;
send_message("error", o.str ());
show_backtrace(ue.backtrace_get(), "error");
}
void
Interpreter::propagate_error_ (object::UrbiException& ue, const ast::loc& l)
{
if (!ue.location_is_set())
ue.location_set(l);
if (!ue.backtrace_is_set())
ue.backtrace_set(call_stack_);
// Reset the current value: there was an error so whatever value it has,
// it must not be used.
current_.reset ();
}
void
Interpreter::work ()
{
assert (ast_ || code_);
JAECHO ("starting evaluation of AST: ", *ast_);
if (ast_)
operator()(ast_);
else
{
object::objects_type args;
args.push_back(locals_);
apply(code_, SYMBOL(task), args);
}
}
/*----------------.
| Regular visit. |
`----------------*/
void
Interpreter::operator() (ast::rConstAst e)
{
/// Catch exceptions, display the error if not already done, and
/// rethrow it.
try
{
if (e)
e->accept(*this);
}
catch (object::UrbiException& x)
{
current_.reset();
propagate_error_(x, e->location_get());
throw;
}
catch (object::FlowException&)
{
current_.reset();
throw;
}
catch (scheduler::SchedulerException&)
{
current_.reset();
throw;
}
catch (kernel::exception& x)
{
std::cerr << "Unexpected exception propagated: " << x.what() << std::endl;
throw;
}
catch (std::exception& x)
{
std::cerr << "Unexpected exception propagated: " << x.what() << std::endl;
throw;
}
catch (...)
{
std::cerr << "Unknown exception propagated" << std::endl;
throw;
}
}
void
Interpreter::visit (ast::rConstAnd e)
{
// lhs will be evaluated in another Interpreter, while rhs will be evaluated
// in this one. We will be the new runner parent, as we have the same
// tags.
JAECHO ("lhs", e->lhs_get ());
scheduler::rJob lhs = new Interpreter(*this, ast::rConstAst(e->lhs_get()));
// Propagate errors between left-hand side and right-hand side runners.
link (lhs);
lhs->start_job ();
JAECHO ("rhs", e.rhs_get ());
eval (e->rhs_get ());
// Wait for lhs to terminate
yield_until_terminated (*lhs);
current_ = object::void_class;
}
void
Interpreter::visit (ast::rConstAssignment e)
{
rObject tgt = context(e->depth_get());
tgt->slot_update(*this, e->what_get(), eval(e->value_get()));
}
// Apply a function written in Urbi.
object::rObject
Interpreter::apply_urbi (const rObject& func,
const libport::Symbol& msg,
const object::objects_type& args,
rObject call_message)
{
// The called function.
ast::rConstCode fn = func.unsafe_cast<object::Code>()->value_get().ast;
// Whether it's an explicit closure
bool closure = fn.unsafe_cast<const ast::Closure>();
// If the function is lazy and there's no call message, forge
// one. This happen when a lazy function is invoked with eval, for
// instance.
if (!fn->strict() && !call_message)
{
object::objects_type lazy_args;
foreach (const rObject& o, args)
lazy_args.push_back(mkLazy(*this, o));
call_message = build_call_message(args[0], msg, lazy_args);
}
// Create the function's outer scope, with the first argument as
// 'self'. The inner scope will be created when executing ()
// on ast::Scope.
rObject scope;
if (closure)
// For closures, use the context as parent scope.
scope = func->slot_get(SYMBOL(context));
else
{
scope = object::Object::make_method_scope(args.front());
scope->slot_set(SYMBOL(code), func);
}
// If this is a strict function, check the arity and bind the formal
// arguments. Otherwise, bind the call message.
if (fn->strict())
{
const ast::declarations_type& formals = *fn->formals_get();
object::check_arg_count (formals.size() + 1, args.size(), msg.name_get());
// Effective (evaluated) argument iterator.
// Skip "self" which has already been handled.
object::objects_type::const_iterator ei = ++args.begin();
foreach (ast::rConstDeclaration s, formals)
scope->slot_set (s->what_get(), *ei++);
}
else
if (!closure)
scope->slot_set (SYMBOL(call), call_message);
// Change the current context and call. But before, check that we
// are not exhausting the stack space, for example in an infinite
// recursion.
std::swap(scope, locals_);
Finally finally(swap(scope, locals_));
check_stack_space ();
try
{
current_ = eval (fn->body_get());
}
catch (object::BreakException& be)
{
object::PrimitiveError error("break", "outside a loop");
propagate_error_(error, be.location_get());
throw error;
}
catch (object::ContinueException& be)
{
object::PrimitiveError error("continue", "outside a loop");
propagate_error_(error, be.location_get());
throw error;
}
catch (object::ReturnException& re)
{
current_ = re.result_get();
if (!current_)
current_ = object::void_class;
}
return current_;
}
namespace
{
// Helper to determine whether a function accepts void parameters
static inline bool
acceptVoid(object::rObject f)
{
try
{
return object::is_true(f->slot_get(SYMBOL(acceptVoid)));
}
catch (object::LookupError&)
{
// acceptVoid is undefined. Refuse void parameter by default.
return false;
}
}
}
object::rObject
Interpreter::apply (const rObject& func,
const libport::Symbol msg,
object::objects_type args,
rObject call_message)
{
precondition(func);
// If we try to call a C++ primitive with a call message, make it
// look like a strict function call
if (call_message &&
(func->kind_get() != object::object_kind_code
|| func->value<object::Code>().ast->strict()))
{
rObject urbi_args = urbi_call(*this, call_message, SYMBOL(evalArgs));
foreach (const rObject& arg,
urbi_args->value<object::List>())
args.push_back(arg);
call_message = 0;
}
// Even with call message, there is at least one argument: self.
assert (!args.empty());
// If we use a call message, "self" is the only argument.
assert (!call_message || args.size() == 1);
// Check if any argument is void
if (!acceptVoid(func))
{
object::objects_type::iterator end = args.end();
if (std::find(++args.begin(), end, object::void_class) != end)
throw object::WrongArgumentType (msg);
}
switch (func->kind_get ())
{
case object::object_kind_primitive:
current_ =
func.unsafe_cast<object::Primitive>()->value_get()(*this, args);
break;
case object::object_kind_delegate:
current_ =
func.unsafe_cast<object::Delegate>()
->value_get()
->operator()(*this, args);
break;
case object::object_kind_code:
current_ = apply_urbi (func, msg, args, call_message);
break;
default:
object::check_arg_count (1, args.size(), msg.name_get());
current_ = func;
break;
}
return current_;
}
void
Interpreter::push_evaluated_arguments (object::objects_type& args,
const ast::exps_type& ue_args,
bool check_void)
{
bool tail = false;
foreach (ast::rConstExp arg, ue_args)
{
// Skip target, the first argument.
if (!tail++)
continue;
eval (arg);
// Check if any argument is void. This will be checked again in
// Interpreter::apply, yet raising exception here gives better
// location (the argument and not the whole function invocation).
if (check_void && current_ == object::void_class)
{
object::WrongArgumentType e("");
e.location_set(arg->location_get());
throw e;
}
passert (*arg, current_);
args.push_back (current_);
}
}
object::rObject
Interpreter::build_call_message (const rObject& tgt,
const libport::Symbol& msg,
const object::objects_type& args)
{
rObject res = object::global_class->slot_get(SYMBOL(CallMessage))->clone();
// Set the sender to be the current self. self must always exist.
res->slot_set (SYMBOL(sender),
locals_->slot_get (SYMBOL(self)));
// Set the target to be the object on which the function is applied.
res->slot_set (SYMBOL(target), tgt);
// Set the name of the message call.
res->slot_set (SYMBOL(message), object::String::fresh(msg));
res->slot_set (SYMBOL(args), object::List::fresh(args));
// Store the current context in which the arguments must be evaluated.
res->slot_set (SYMBOL(context), object::Object::make_scope(locals_));
return res;
}
object::rObject
Interpreter::build_call_message (const rObject& tgt, const libport::Symbol& msg,
const ast::exps_type& args)
{
// Build the list of lazy arguments
object::objects_type lazy_args;
boost::sub_range<const ast::exps_type> range(args);
// The target can be unspecified.
if (!args.front() || args.front()->implicit())
{
lazy_args.push_back(object::nil_class);
range = make_iterator_range(range, 1, 0);
}
foreach (ast::rConstExp e, range)
lazy_args.push_back(object::mkLazy(*this, e));
return build_call_message(tgt, msg, lazy_args);
}
void
Interpreter::visit (ast::rConstCall e)
{
// The invoked slot (probably a function).
ast::rConstExp ast_tgt = e->target_get();
rObject tgt = ast_tgt->implicit() ?
locals_->slot_get(SYMBOL(self)) : eval(ast_tgt);
call_stack_.push_back(e);
Finally finally(bind(&call_stack_type::pop_back, &call_stack_));
apply(tgt, e->name_get(), e->arguments_get());
}
void
Interpreter::visit (ast::rConstCallMsg)
{
current_ = locals_->slot_get(SYMBOL(call));
}
Interpreter::rObject
Interpreter::apply (rObject tgt, const libport::Symbol& message,
const ast::exps_type* input_ast_args)
{
// The invoked slot (probably a function).
rObject val = tgt->slot_get(message);
assertion(val);
/*-------------------------.
| Evaluate the arguments. |
`-------------------------*/
// Gather the arguments, including the target.
object::objects_type args;
args.push_back (tgt);
ast::exps_type ast_args =
input_ast_args ? *input_ast_args : ast::exps_type();
// FIXME: This is the target, for compatibility reasons. We need
// to remove this, and stop assuming that arguments start at
// calls.args.nth(1)
ast_args.push_front(0);
// Build the call message for non-strict functions, otherwise
// the evaluated argument list.
rObject call_message;
if (val->kind_get () == object::object_kind_code
&& !val.unsafe_cast<object::Code>()->value_get().ast->strict())
call_message = build_call_message (tgt, message, ast_args);
else
push_evaluated_arguments (args, ast_args, !acceptVoid(val));
return apply (val, message, args, call_message);
}
void
Interpreter::visit (ast::rConstDeclaration d)
{
locals_->slot_set(d->what_get(), eval(d->value_get()));
}
void
Interpreter::visit (ast::rConstFloat e)
{
current_ = object::Float::fresh(e->value_get());
}
void
Interpreter::visit (ast::rConstForeach e)
{
// Evaluate the list attribute, and check its type.
JAECHO ("foreach list", e.list_get());
operator() (e->list_get());
TYPE_CHECK(current_, object::List);
JAECHO("foreach body", e.body_get());
// We need to copy the pointer on the list, otherwise the list will be
// destroyed when children are visited and current_ is modified.
object::List::value_type content = current_->value<object::List>();
// The list of runners launched for each value in the list if the flavor
// is "&".
scheduler::jobs_type runners;
if (e->flavor_get() == ast::flavor_and)
runners.reserve(content.size());
bool tail = false;
ast::rConstAst body = e->body_get();
ast::flavor_type flavor = e->flavor_get();
libport::Symbol index = e->index_get()->what_get();
// Iterate on each value.
foreach (const rObject& o, content)
{
// Define a new local scope for each loop, and set the index.
rObject locals = object::Object::fresh();
locals->locals_set(true);
locals->proto_add(locals_);
locals->slot_set(index, o);
// for& ... in loop.
if (flavor == ast::flavor_and)
{
// Create the new runner and launch it. We create a link so
// that an error in evaluation will stop other evaluations
// as well and propagate the exception.
Interpreter* new_runner = new Interpreter(*this, body);
link(new_runner);
runners.push_back(new_runner);
new_runner->locals_ = locals;
new_runner->start_job();
}
else // for| and for;
{
std::swap(locals, locals_);
Finally finally(swap(locals, locals_));
if (tail++)
MAYBE_YIELD(flavor);
try
{
operator() (body);
}
catch (object::BreakException&)
{
break;
}
catch (object::ContinueException&)
{
}
}
}
// Wait for all runners to terminate.
yield_until_terminated(runners);
// For the moment return void.
current_ = object::void_class;
}
object::rObject
Interpreter::make_code(ast::rConstCode e) const
{
rObject res = object::Code::fresh(e);
// Store the function declaration context. Use make_scope to add
// an empty object above it, so as variables injected in the
// context do not appear in the declaration scope.
res->slot_set(SYMBOL(context), locals_);
return res;
}
void
Interpreter::visit (ast::rConstFunction e)
{
current_ = make_code(e);
}
void
Interpreter::visit (ast::rConstClosure e)
{
current_ = make_code(e);
}
void
Interpreter::visit (ast::rConstIf e)
{
// Evaluate the test.
JAECHO ("test", e->test_get ());
operator() (e->test_get());
if (object::is_true(current_))
{
JAECHO ("then", e.thenclause_get ());
operator() (e->thenclause_get());
}
else
{
JAECHO ("else", e.elseclause_get ());
operator() (e->elseclause_get());
}
}
void
Interpreter::visit (ast::rConstList e)
{
object::List::value_type res;
// Evaluate every expression in the list
foreach (ast::rConstExp c, e->value_get())
res.push_back(eval(c));
current_ = object::List::fresh(res);
//ECHO ("result: " << *current_);
}
Interpreter::rObject Interpreter::context(unsigned n)
{
rObject res = locals_;
for (int i = n; i; i--)
{
res = res->slot_get(SYMBOL(code))->slot_get(SYMBOL(context));
assert(res);
}
return res;
}
void
Interpreter::visit (ast::rConstLocal e)
{
rObject tgt = context(e->depth_get());
// FIXME: Register in the call stack
if (e->arguments_get())
current_ = apply(tgt, e->name_get(), e->arguments_get());
else
current_ = tgt->slot_get(e->name_get());
}
void
Interpreter::visit (ast::rConstMessage e)
{
send_message(e->tag_get(), e->text_get() + "\n");
}
// Forward flow exceptions up to the top-level, and handle them
// there. Makes only sense in a Nary.
#define CATCH_FLOW_EXCEPTION(Type, Keyword, Error) \
catch (Type flow_exception) \
{ \
if (e->toplevel_get ()) \
{ \
object::PrimitiveError error(Keyword, Error); \
propagate_error_(error, flow_exception.location_get()); \
throw error; \
} \
else \
throw; \
}
void
Interpreter::visit (ast::rConstNary e)
{
// List of runners for Stmt flavored by a comma.
scheduler::jobs_type runners;
// In case we're empty.
current_ = object::void_class;
bool tail = false;
foreach (ast::rConstExp c, e->children_get())
{
// Allow some time to pass before we execute what follows. If
// we don't do this, the ;-operator would act almost like the
// |-operator because it would always start to execute its RHS
// immediately. However, we don't want to do it before the first
// statement or if we only have one statement in the scope.
if (tail++)
YIELD ();
current_.reset ();
JAECHO ("child", c);
if (c.unsafe_cast<const ast::Stmt>() &&
c.unsafe_cast<const ast::Stmt>()->flavor_get() == ast::flavor_comma)
{
// The new runners are attached to the same tags as we are.
Interpreter* subrunner = new Interpreter(*this, ast::rConstAst(c));
runners.push_back(subrunner);
subrunner->start_job ();
}
else
{
// If at toplevel, stop and print errors
try
{
// Rewrite flow error if we are at toplevel
try
{
operator() (c);
}
CATCH_FLOW_EXCEPTION(object::BreakException,
"break", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ContinueException,
"continue", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ReturnException,
"return", "outside a function")
if (e->toplevel_get () && current_.get ())
{
try
{
assertion(current_);
ECHO("toplevel: returning a result to the connection.");
lobby_->value_get ().connection.new_result (current_);
current_.reset ();
}
catch (std::exception &ke)
{
std::cerr << "Exception when printing result: "
<< ke.what() << std::endl;
}
catch (object::UrbiException& e)
{
show_error_(e);
}
catch (...)
{
std::cerr << "Unknown exception when printing result"
<< std::endl;
}
}
}
catch (object::UrbiException& ue)
{
if (e->toplevel_get())
show_error_(ue);
else
throw;
}
CATCH_FLOW_EXCEPTION(object::BreakException,
"break", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ContinueException,
"continue", "outside a loop")
CATCH_FLOW_EXCEPTION(object::ReturnException,
"return", "outside a function")
}
}
// If the Nary is not the toplevel one, all subrunners must be finished when
// the runner exits the Nary node.
if (!e->toplevel_get ())
yield_until_terminated(runners);
}
void
Interpreter::visit (ast::rConstNoop)
{
current_ = object::void_class;
}
void
Interpreter::visit (ast::rConstPipe e)
{
// lhs
JAECHO ("lhs", e->lhs_get ());
operator() (e->lhs_get());
// rhs: start the execution immediately.
JAECHO ("rhs", e->rhs_get ());
operator() (e->rhs_get());
}
void
Interpreter::visit (ast::rConstAbstractScope e, rObject locals)
{
std::swap(locals, locals_);
Finally finally;
finally << swap(locals, locals_)
<< boost::bind(&scheduler::Job::non_interruptible_set,
this,
non_interruptible_get());
super_type::operator()(e->body_get());
}
scheduler::rTag
Interpreter::scope_tag()
{
scheduler::rTag tag = scope_tags_.back();
if (!tag)
{
// Create the tag on demand.
tag = scheduler::Tag::fresh
(libport::Symbol::fresh(SYMBOL(LT_scope_SP_tag_GT)));
*scope_tags_.rbegin() = tag;
}
return tag;
}
void
Interpreter::cleanup_scope_tag()
{
scheduler::rTag tag = scope_tags_.back();
scope_tags_.pop_back();
if (tag)
tag->stop(scheduler_get(), object::void_class);
}
void
Interpreter::visit (ast::rConstScope e)
{
scope_tags_.push_back(0);
libport::Finally finally(boost::bind(&Interpreter::cleanup_scope_tag,
this));
visit (e.unsafe_cast<const ast::AbstractScope>(),
object::Object::make_scope(locals_));
}
void
Interpreter::visit (ast::rConstDo e)
{
rObject tgt = eval(e->target_get());
visit (e.unsafe_cast<const ast::AbstractScope>(),
object::Object::make_method_scope(tgt, locals_));
// This is arguable. Do, just like Scope, should maybe return
// their last inner value.
current_ = tgt;
}
void
Interpreter::visit (ast::rConstStmt e)
{
JAECHO ("expression", e.expression_get ());
operator() (e->expression_get());
}
void
Interpreter::visit (ast::rConstString e)
{
current_ = object::String::fresh(libport::Symbol(e->value_get()));
}
void
Interpreter::visit (ast::rConstTag t)
{
eval_tag (t->exp_get ());
}
void
Interpreter::visit (ast::rConstTaggedStmt t)
{
int current_depth = tags_.size();
try
{
scheduler::rTag tag = extract_tag(eval(t->tag_get()));
// If tag is blocked, do not start and ignore the
// statement completely.
if (tag->blocked())
return;
push_tag (tag);
Finally finally(bind(&Interpreter::pop_tag, this));
// If the latest tag causes us to be frozen, let the
// scheduler handle this properly to avoid duplicating the
// logic.
if (tag->frozen())
yield();
eval (t->exp_get());
}
catch (scheduler::StopException& e)
{
// Rewind up to the appropriate depth.
if (e.depth_get() < current_depth)
throw;
// Extract the value from the exception.
current_ = boost::any_cast<rObject>(e.payload_get());
// If we are frozen, reenter the scheduler for a while.
if (frozen())
yield();
return;
}
}
void
Interpreter::visit (ast::rConstThis)
{
current_ = locals_->slot_get(SYMBOL(self));
}
object::rObject
Interpreter::eval_tag (ast::rConstExp e)
{
try {
// Try to evaluate e as a normal expression.
return eval(e);
}
catch (object::LookupError &ue)
{
ECHO("Implicit tag: " << *e);
// We got a lookup error. It means that we have to automatically
// create the tag. In this case, we only accept k1 style tags,
// i.e. chains of identifiers, excluding function calls.
// The reason to do that is:
// - we do not want to mix k1 non-declared syntax with k2
// clean syntax for tags
// - we have no way to know whether the lookup error arrived
// in a function call or during the direct resolution of
// the name
// Tag represents the top level tag
rObject toplevel = object::tag_class;
rObject parent = toplevel;
rObject where = locals_->slot_get(SYMBOL(self));
tag_chain_type chain = decompose_tag_chain(e);
foreach (const libport::Symbol& elt, chain)
{
// Check whether the concerned level in the chain already
// exists.
if (rObject owner = where->slot_locate (elt))
{
ECHO("Component " << elt << " exists.");
where = owner->own_slot_get (elt);
if (object::is_a(where, toplevel))
{
ECHO("It is a tag, so use it as the new parent.");
parent = where;
}
}
else
{
ECHO("Creating component " << elt << ".");
// We have to create a new tag, which will be attached
// to the upper level (hierarchical tags, implicitly
// rooted by Tag).
rObject new_tag = toplevel->clone();
object::objects_type args;
args.push_back (new_tag);
args.push_back (object::String::fresh (elt));
args.push_back (parent);
apply (toplevel->own_slot_get (SYMBOL (init)), SYMBOL(init), args);
where->slot_set (elt, new_tag);
where = parent = new_tag;
}
}
return parent;
}
}
void
Interpreter::visit (ast::rConstThrow e)
{
switch (e->kind_get())
{
case ast::Throw::exception_break:
throw object::BreakException(e->location_get());
case ast::Throw::exception_continue:
throw object::ContinueException(e->location_get());
case ast::Throw::exception_return:
if (e->value_get())
operator() (e->value_get());
else
current_.reset();
throw object::ReturnException(e->location_get(), current_);
}
}
void
Interpreter::visit (ast::rConstWhile e)
{
bool tail = false;
// Evaluate the test.
while (true)
{
if (tail++)
MAYBE_YIELD (e->flavor_get());
JAECHO ("while test", e.test_get ());
operator() (e->test_get());
if (!object::is_true(current_))
break;
JAECHO ("while body", e.body_get ());
try
{
operator() (e->body_get());
}
catch (object::BreakException&)
{
break;
}
catch (object::ContinueException&)
{
}
}
current_ = object::void_class;
}
void
Interpreter::show_backtrace(const call_stack_type& bt,
const std::string& chan)
{
foreach (ast::rConstCall c,
boost::make_iterator_range(boost::rbegin(bt),
boost::rend(bt)))
{
std::ostringstream o;
o << "!!! called from: " << c->location_get () << ": "
<< c->name_get () << std::endl;
send_message(chan, o.str());
}
}
void
Interpreter::show_backtrace(const std::string& chan)
{
show_backtrace(call_stack_, chan);
}
Interpreter::backtrace_type
Interpreter::backtrace_get() const
{
backtrace_type res;
foreach (ast::rConstCall c, call_stack_)
{
std::ostringstream o;
o << c->location_get();
res.push_back(std::make_pair(c->name_get().name_get(), o.str()));
}
return res;
}
} // namespace runner
|
Update Lab_01_Question_04.cpp
4. Write a C++ program to enter length and breadth of a rectangle and find its perimeter.
|
// 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 "chrome/browser/views/frame/opaque_non_client_view.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/gfx/path.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/win_util.h"
#include "chrome/views/root_view.h"
#include "chrome/views/window_resources.h"
#include "chromium_strings.h"
#include "generated_resources.h"
// An enumeration of bitmap resources used by this window.
enum {
FRAME_PART_BITMAP_FIRST = 0, // Must be first.
// Window Controls.
FRAME_CLOSE_BUTTON_ICON,
FRAME_CLOSE_BUTTON_ICON_H,
FRAME_CLOSE_BUTTON_ICON_P,
FRAME_CLOSE_BUTTON_ICON_SA,
FRAME_CLOSE_BUTTON_ICON_SA_H,
FRAME_CLOSE_BUTTON_ICON_SA_P,
FRAME_RESTORE_BUTTON_ICON,
FRAME_RESTORE_BUTTON_ICON_H,
FRAME_RESTORE_BUTTON_ICON_P,
FRAME_MAXIMIZE_BUTTON_ICON,
FRAME_MAXIMIZE_BUTTON_ICON_H,
FRAME_MAXIMIZE_BUTTON_ICON_P,
FRAME_MINIMIZE_BUTTON_ICON,
FRAME_MINIMIZE_BUTTON_ICON_H,
FRAME_MINIMIZE_BUTTON_ICON_P,
// Window Frame Border.
FRAME_BOTTOM_EDGE,
FRAME_BOTTOM_LEFT_CORNER,
FRAME_BOTTOM_RIGHT_CORNER,
FRAME_LEFT_EDGE,
FRAME_RIGHT_EDGE,
FRAME_TOP_EDGE,
FRAME_TOP_LEFT_CORNER,
FRAME_TOP_RIGHT_CORNER,
// Window Maximized Border.
FRAME_MAXIMIZED_TOP_EDGE,
FRAME_MAXIMIZED_BOTTOM_EDGE,
// Client Edge Border.
FRAME_CLIENT_EDGE_TOP_LEFT,
FRAME_CLIENT_EDGE_TOP,
FRAME_CLIENT_EDGE_TOP_RIGHT,
FRAME_CLIENT_EDGE_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM,
FRAME_CLIENT_EDGE_BOTTOM_LEFT,
FRAME_CLIENT_EDGE_LEFT,
FRAME_PART_BITMAP_COUNT // Must be last.
};
class ActiveWindowResources : public views::WindowResources {
public:
ActiveWindowResources() {
InitClass();
}
virtual ~ActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER, IDR_WINDOW_BOTTOM_LEFT_CORNER,
IDR_WINDOW_BOTTOM_RIGHT_CORNER, IDR_WINDOW_LEFT_SIDE,
IDR_WINDOW_RIGHT_SIDE, IDR_WINDOW_TOP_CENTER,
IDR_WINDOW_TOP_LEFT_CORNER, IDR_WINDOW_TOP_RIGHT_CORNER,
IDR_WINDOW_TOP_CENTER, IDR_WINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(ActiveWindowResources);
};
class InactiveWindowResources : public views::WindowResources {
public:
InactiveWindowResources() {
InitClass();
}
virtual ~InactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER, IDR_DEWINDOW_BOTTOM_LEFT_CORNER,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER, IDR_DEWINDOW_LEFT_SIDE,
IDR_DEWINDOW_RIGHT_SIDE, IDR_DEWINDOW_TOP_CENTER,
IDR_DEWINDOW_TOP_LEFT_CORNER, IDR_DEWINDOW_TOP_RIGHT_CORNER,
IDR_DEWINDOW_TOP_CENTER, IDR_DEWINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(InactiveWindowResources);
};
class OTRActiveWindowResources : public views::WindowResources {
public:
OTRActiveWindowResources() {
InitClass();
}
virtual ~OTRActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER_OTR, IDR_WINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_WINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_WINDOW_LEFT_SIDE_OTR,
IDR_WINDOW_RIGHT_SIDE_OTR, IDR_WINDOW_TOP_CENTER_OTR,
IDR_WINDOW_TOP_LEFT_CORNER_OTR, IDR_WINDOW_TOP_RIGHT_CORNER_OTR,
IDR_WINDOW_TOP_CENTER_OTR, IDR_WINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
DISALLOW_EVIL_CONSTRUCTORS(OTRActiveWindowResources);
};
class OTRInactiveWindowResources : public views::WindowResources {
public:
OTRInactiveWindowResources() {
InitClass();
}
virtual ~OTRInactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER_OTR, IDR_DEWINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_DEWINDOW_LEFT_SIDE_OTR,
IDR_DEWINDOW_RIGHT_SIDE_OTR, IDR_DEWINDOW_TOP_CENTER_OTR,
IDR_DEWINDOW_TOP_LEFT_CORNER_OTR,
IDR_DEWINDOW_TOP_RIGHT_CORNER_OTR,
IDR_DEWINDOW_TOP_CENTER_OTR, IDR_DEWINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(OTRInactiveWindowResources);
};
// static
SkBitmap* ActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* InactiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRInactiveWindowResources::standard_frame_bitmaps_[];
views::WindowResources* OpaqueNonClientView::active_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::inactive_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::active_otr_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::inactive_otr_resources_ = NULL;
SkBitmap OpaqueNonClientView::distributor_logo_;
SkBitmap OpaqueNonClientView::app_top_left_;
SkBitmap OpaqueNonClientView::app_top_center_;
SkBitmap OpaqueNonClientView::app_top_right_;
ChromeFont OpaqueNonClientView::title_font_;
// The distance between the top of the window and the top of the window
// controls when the window is restored.
static const int kWindowControlsTopOffset = 1;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is restored.
static const int kWindowControlsRightOffset = 4;
// The distance between the bottom of the window's top border and the top of the
// window controls' images when the window is maximized. We extend the
// clickable area all the way to the top of the window to obey Fitts' Law.
static const int kWindowControlsZoomedTopExtraHeight = 1;
// The distance between right edge of the right-most window control and the left
// edge of the window's right border when the window is maximized.
static const int kWindowControlsZoomedRightOffset = 3;
// The distance between the left edge of the window and the left edge of the
// window icon when a title-bar is showing and the window is restored.
static const int kWindowIconLeftOffset = 5;
// The distance between the right edge of the window's left border and the left
// edge of the window icon when a title-bar is showing and the window is
// maximized.
static const int kWindowIconZoomedLeftOffset = 2;
// The distance between the top edge of the window and the top edge of the
// window icon and title when a title-bar is showing and the window is restored.
static const int kWindowIconAndTitleTopOffset = 6;
// The distance between the bottom edge of the window's top border and the top
// edge of the window icon and title when a title-bar is showing and the window
// is maximized.
static const int kWindowIconAndTitleZoomedTopOffset = 4;
// The distance between the window icon and the window title when a title-bar
// is showing.
static const int kWindowIconTitleSpacing = 4;
// The distance between the right edge of the title text bounding box and the
// left edge of the distributor logo.
static const int kTitleLogoSpacing = 5;
// The distance between the bottom of the title text and the TabStrip when a
// title-bar is showing.
static const int kTitleBottomSpacing = 6;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is restored.
static const int kNoTitleTopSpacing = 15;
// The number of pixels to crop off the bottom of the images making up the top
// client edge when the window is maximized, so we only draw a shadowed titlebar
// and not a grey client area border below it.
static const int kClientEdgeZoomedBottomCrop = 1;
// The amount of horizontal and vertical distance from a corner of the window
// within which a mouse-drive resize operation will resize the window in two
// dimensions.
static const int kResizeAreaCornerSize = 16;
// The width of the sizing border on the left and right edge of the window.
static const int kWindowHorizontalBorderSize = 5;
// The height of the sizing border at the top edge of the window
static const int kWindowVerticalBorderTopSize = 3;
// The height of the sizing border on the bottom edge of the window when the
// window is restored.
static const int kWindowVerticalBorderBottomSize = 5;
// The additional height beyond the system-provided thickness of the border on
// the bottom edge of the window when the window is maximized.
static const int kWindowVerticalBorderZoomedBottomSize = 1;
// The width and height of the window icon that appears at the top left of
// pop-up and app windows.
static const int kWindowIconSize = 16;
// The horizontal distance of the right edge of the distributor logo from the
// left edge of the left-most window control.
static const int kDistributorLogoHorizontalOffset = 7;
// The vertical distance of the top of the distributor logo from the top edge
// of the window.
static const int kDistributorLogoVerticalOffset = 3;
// The distance between the left edge of the window and the OTR avatar icon when
// the window is restored.
static const int kOTRLeftOffset = 7;
// The distance between the right edge of the window's left border and the OTR
// avatar icon when the window is maximized.
static const int kOTRZoomedLeftOffset = 2;
// The distance between the top edge of the client area and the OTR avatar icon
// when the window is maximized.
static const int kOTRZoomedTopSpacing = 2;
// The distance between the bottom of the OTR avatar icon and the bottom of the
// tabstrip.
static const int kOTRBottomSpacing = 2;
// The number of pixels to crop off the top of the OTR image when the window is
// maximized.
static const int kOTRZoomedTopCrop = 4;
// Horizontal distance between the right edge of the OTR avatar icon and the
// left edge of the tabstrip.
static const int kOTRTabStripSpacing = 2;
// Horizontal distance between the right edge of the new tab icon and the left
// edge of the window minimize icon when the window is restored.
static const int kNewTabIconMinimizeSpacing = 5;
// Horizontal distance between the right edge of the new tab icon and the left
// edge of the window minimize icon when the window is maximized.
static const int kNewTabIconMinimizeZoomedSpacing = 16;
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, public:
OpaqueNonClientView::OpaqueNonClientView(OpaqueFrame* frame,
BrowserView* browser_view)
: NonClientView(),
minimize_button_(new views::Button),
maximize_button_(new views::Button),
restore_button_(new views::Button),
close_button_(new views::Button),
window_icon_(NULL),
frame_(frame),
browser_view_(browser_view) {
InitClass();
if (browser_view->IsOffTheRecord()) {
if (!active_otr_resources_) {
// Lazy load OTR resources only when we first show an OTR frame.
active_otr_resources_ = new OTRActiveWindowResources;
inactive_otr_resources_ = new OTRInactiveWindowResources;
}
current_active_resources_ = active_otr_resources_;
current_inactive_resources_= inactive_otr_resources_;
} else {
current_active_resources_ = active_resources_;
current_inactive_resources_ = inactive_resources_;
}
views::WindowResources* resources = current_active_resources_;
minimize_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON));
minimize_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_H));
minimize_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_P));
minimize_button_->SetListener(this, -1);
minimize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MINIMIZE));
AddChildView(minimize_button_);
maximize_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON));
maximize_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_H));
maximize_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_P));
maximize_button_->SetListener(this, -1);
maximize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MAXIMIZE));
AddChildView(maximize_button_);
restore_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON));
restore_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_H));
restore_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_P));
restore_button_->SetListener(this, -1);
restore_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_RESTORE));
AddChildView(restore_button_);
close_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON));
close_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_H));
close_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_P));
close_button_->SetListener(this, -1);
close_button_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_CLOSE));
AddChildView(close_button_);
// Initializing the TabIconView is expensive, so only do it if we need to.
if (browser_view_->ShouldShowWindowIcon()) {
window_icon_ = new TabIconView(this);
window_icon_->set_is_light(true);
AddChildView(window_icon_);
window_icon_->Update();
}
// Only load the title font if we're going to need to use it to paint.
// Loading fonts is expensive.
if (browser_view_->ShouldShowWindowTitle())
InitAppWindowResources();
}
OpaqueNonClientView::~OpaqueNonClientView() {
}
gfx::Rect OpaqueNonClientView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
int top_height = CalculateNonClientTopHeight();
int horizontal_border = HorizontalBorderSize();
int window_x = std::max(0, client_bounds.x() - horizontal_border);
int window_y = std::max(0, client_bounds.y() - top_height);
int window_w = client_bounds.width() + (2 * horizontal_border);
int window_h =
client_bounds.height() + top_height + VerticalBorderBottomSize();
return gfx::Rect(window_x, window_y, window_w, window_h);
}
gfx::Rect OpaqueNonClientView::GetBoundsForTabStrip(TabStrip* tabstrip) {
int tabstrip_x = browser_view_->ShouldShowOffTheRecordAvatar() ?
(otr_avatar_bounds_.right() + kOTRTabStripSpacing) :
HorizontalBorderSize();
int tabstrip_width = minimize_button_->x() - tabstrip_x -
(frame_->IsMaximized() ?
kNewTabIconMinimizeZoomedSpacing : kNewTabIconMinimizeSpacing);
return gfx::Rect(tabstrip_x, CalculateNonClientTopHeight(),
std::max(0, tabstrip_width), tabstrip->GetPreferredHeight());
}
void OpaqueNonClientView::UpdateWindowIcon() {
if (window_icon_)
window_icon_->Update();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, TabIconView::TabContentsProvider implementation:
bool OpaqueNonClientView::ShouldTabIconViewAnimate() const {
// This function is queried during the creation of the window as the
// TabIconView we host is initialized, so we need to NULL check the selected
// TabContents because in this condition there is not yet a selected tab.
TabContents* current_tab = browser_view_->GetSelectedTabContents();
return current_tab ? current_tab->is_loading() : false;
}
SkBitmap OpaqueNonClientView::GetFavIconForTabIconView() {
return frame_->window_delegate()->GetWindowIcon();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::BaseButton::ButtonListener implementation:
void OpaqueNonClientView::ButtonPressed(views::BaseButton* sender) {
if (sender == minimize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MINIMIZE);
} else if (sender == maximize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MAXIMIZE);
} else if (sender == restore_button_) {
frame_->ExecuteSystemMenuCommand(SC_RESTORE);
} else if (sender == close_button_) {
frame_->ExecuteSystemMenuCommand(SC_CLOSE);
}
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::NonClientView implementation:
gfx::Rect OpaqueNonClientView::CalculateClientAreaBounds(int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
int horizontal_border = HorizontalBorderSize();
return gfx::Rect(horizontal_border, top_margin,
std::max(0, width - (2 * horizontal_border)),
std::max(0, height - top_margin - VerticalBorderBottomSize()));
}
gfx::Size OpaqueNonClientView::CalculateWindowSizeForClientSize(
int width,
int height) const {
return gfx::Size(width + (2 * HorizontalBorderSize()),
height + CalculateNonClientTopHeight() + VerticalBorderBottomSize());
}
CPoint OpaqueNonClientView::GetSystemMenuPoint() const {
CPoint system_menu_point(icon_bounds_.x(), icon_bounds_.bottom());
MapWindowPoints(frame_->GetHWND(), HWND_DESKTOP, &system_menu_point, 1);
return system_menu_point;
}
int OpaqueNonClientView::NonClientHitTest(const gfx::Point& point) {
// First see if it's within the grow box area, since that overlaps the client
// bounds.
int frame_component = frame_->client_view()->NonClientHitTest(point);
if (frame_component != HTNOWHERE)
return frame_component;
// Then see if the point is within any of the window controls.
if (close_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return HTCLOSE;
if (restore_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMAXBUTTON;
if (maximize_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMAXBUTTON;
if (minimize_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMINBUTTON;
if (window_icon_ &&
window_icon_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return HTSYSMENU;
int window_component = GetHTComponentForFrame(point, HorizontalBorderSize(),
kResizeAreaCornerSize, kWindowVerticalBorderTopSize,
frame_->window_delegate()->CanResize());
// Fall back to the caption if no other component matches.
if ((window_component == HTNOWHERE) && bounds().Contains(point))
window_component = HTCAPTION;
return window_component;
}
void OpaqueNonClientView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
DCHECK(window_mask);
// Redefine the window visible region for the new size.
window_mask->moveTo(0, 3);
window_mask->lineTo(1, 1);
window_mask->lineTo(3, 0);
window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 3);
window_mask->lineTo(SkIntToScalar(size.width() - 0), 3);
window_mask->lineTo(SkIntToScalar(size.width()),
SkIntToScalar(size.height()));
window_mask->lineTo(0, SkIntToScalar(size.height()));
window_mask->close();
}
void OpaqueNonClientView::EnableClose(bool enable) {
close_button_->SetEnabled(enable);
}
void OpaqueNonClientView::ResetWindowControls() {
restore_button_->SetState(views::Button::BS_NORMAL);
minimize_button_->SetState(views::Button::BS_NORMAL);
maximize_button_->SetState(views::Button::BS_NORMAL);
// The close button isn't affected by this constraint.
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::View overrides:
void OpaqueNonClientView::Paint(ChromeCanvas* canvas) {
if (frame_->IsMaximized())
PaintMaximizedFrameBorder(canvas);
else
PaintFrameBorder(canvas);
PaintDistributorLogo(canvas);
PaintTitleBar(canvas);
PaintToolbarBackground(canvas);
PaintOTRAvatar(canvas);
if (frame_->IsMaximized())
PaintMaximizedClientEdge(canvas);
else
PaintClientEdge(canvas);
}
void OpaqueNonClientView::Layout() {
LayoutWindowControls();
LayoutDistributorLogo();
LayoutTitleBar();
LayoutOTRAvatar();
LayoutClientView();
}
gfx::Size OpaqueNonClientView::GetPreferredSize() {
gfx::Size prefsize(frame_->client_view()->GetPreferredSize());
prefsize.Enlarge(2 * HorizontalBorderSize(),
CalculateNonClientTopHeight() + VerticalBorderBottomSize());
return prefsize;
}
views::View* OpaqueNonClientView::GetViewForPoint(const gfx::Point& point,
bool can_create_floating) {
// We override this function because the ClientView can overlap the non -
// client view, making it impossible to click on the window controls. We need
// to ensure the window controls are checked _first_.
views::View* views[] = { close_button_, restore_button_, maximize_button_,
minimize_button_ };
for (int i = 0; i < arraysize(views); ++i) {
if (!views[i]->IsVisible())
continue;
// Apply mirroring transformation on view bounds for RTL chrome.
if (views[i]->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return views[i];
}
return View::GetViewForPoint(point, can_create_floating);
}
void OpaqueNonClientView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this) {
DCHECK(GetWidget());
DCHECK(frame_->client_view()->GetParent() != this);
AddChildView(frame_->client_view());
// The Accessibility glue looks for the product name on these two views to
// determine if this is in fact a Chrome window.
GetRootView()->SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
}
}
bool OpaqueNonClientView::GetAccessibleRole(VARIANT* role) {
DCHECK(role);
// We aren't actually the client area of the window, but we act like it as
// far as MSAA and the UI tests are concerned.
role->vt = VT_I4;
role->lVal = ROLE_SYSTEM_CLIENT;
return true;
}
bool OpaqueNonClientView::GetAccessibleName(std::wstring* name) {
if (!accessible_name_.empty()) {
*name = accessible_name_;
return true;
}
return false;
}
void OpaqueNonClientView::SetAccessibleName(const std::wstring& name) {
accessible_name_ = name;
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, private:
int OpaqueNonClientView::CalculateNonClientTopHeight() const {
if (frame_->window_delegate()->ShouldShowWindowTitle()) {
int top_offset = frame_->IsMaximized() ? (GetSystemMetrics(SM_CYSIZEFRAME) +
kWindowIconAndTitleZoomedTopOffset) : kWindowIconAndTitleTopOffset;
return top_offset + title_font_.height() + kTitleBottomSpacing;
}
return frame_->IsMaximized() ?
GetSystemMetrics(SM_CYSIZEFRAME) : kNoTitleTopSpacing;
}
int OpaqueNonClientView::HorizontalBorderSize() const {
return frame_->IsMaximized() ?
GetSystemMetrics(SM_CXSIZEFRAME) : kWindowHorizontalBorderSize;
}
int OpaqueNonClientView::VerticalBorderBottomSize() const {
return frame_->IsMaximized() ? (GetSystemMetrics(SM_CYSIZEFRAME) +
kWindowVerticalBorderZoomedBottomSize) : kWindowVerticalBorderBottomSize;
}
void OpaqueNonClientView::PaintFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_left_corner =
resources()->GetPartBitmap(FRAME_TOP_LEFT_CORNER);
SkBitmap* top_right_corner =
resources()->GetPartBitmap(FRAME_TOP_RIGHT_CORNER);
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_TOP_EDGE);
SkBitmap* right_edge = resources()->GetPartBitmap(FRAME_RIGHT_EDGE);
SkBitmap* left_edge = resources()->GetPartBitmap(FRAME_LEFT_EDGE);
SkBitmap* bottom_left_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_LEFT_CORNER);
SkBitmap* bottom_right_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_RIGHT_CORNER);
SkBitmap* bottom_edge = resources()->GetPartBitmap(FRAME_BOTTOM_EDGE);
// Top.
canvas->DrawBitmapInt(*top_left_corner, 0, 0);
canvas->TileImageInt(*top_edge, top_left_corner->width(), 0,
width() - top_right_corner->width(), top_edge->height());
canvas->DrawBitmapInt(*top_right_corner,
width() - top_right_corner->width(), 0);
// Right.
canvas->TileImageInt(*right_edge, width() - right_edge->width(),
top_right_corner->height(), right_edge->width(),
height() - top_right_corner->height() -
bottom_right_corner->height());
// Bottom.
canvas->DrawBitmapInt(*bottom_right_corner,
width() - bottom_right_corner->width(),
height() - bottom_right_corner->height());
canvas->TileImageInt(*bottom_edge, bottom_left_corner->width(),
height() - bottom_edge->height(),
width() - bottom_left_corner->width() -
bottom_right_corner->width(),
bottom_edge->height());
canvas->DrawBitmapInt(*bottom_left_corner, 0,
height() - bottom_left_corner->height());
// Left.
canvas->TileImageInt(*left_edge, 0, top_left_corner->height(),
left_edge->width(),
height() - top_left_corner->height() - bottom_left_corner->height());
}
void OpaqueNonClientView::PaintMaximizedFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_MAXIMIZED_TOP_EDGE);
int frame_thickness = GetSystemMetrics(SM_CYSIZEFRAME);
canvas->TileImageInt(*top_edge, 0, frame_thickness, width(),
top_edge->height());
SkBitmap* bottom_edge =
resources()->GetPartBitmap(FRAME_MAXIMIZED_BOTTOM_EDGE);
canvas->TileImageInt(*bottom_edge, 0,
height() - bottom_edge->height() - frame_thickness, width(),
bottom_edge->height());
}
void OpaqueNonClientView::PaintDistributorLogo(ChromeCanvas* canvas) {
// The distributor logo is only painted when the frame is not maximized and
// when we actually have a logo.
if (!frame_->IsMaximized() && !distributor_logo_.empty()) {
int logo_x = MirroredLeftPointForRect(logo_bounds_);
canvas->DrawBitmapInt(distributor_logo_, logo_x, logo_bounds_.y());
}
}
void OpaqueNonClientView::PaintTitleBar(ChromeCanvas* canvas) {
// The window icon is painted by the TabIconView.
views::WindowDelegate* d = frame_->window_delegate();
if (d->ShouldShowWindowTitle()) {
canvas->DrawStringInt(d->GetWindowTitle(), title_font_, SK_ColorWHITE,
MirroredLeftPointForRect(title_bounds_), title_bounds_.y(),
title_bounds_.width(), title_bounds_.height());
}
}
void OpaqueNonClientView::PaintToolbarBackground(ChromeCanvas* canvas) {
if (!browser_view_->IsToolbarVisible() && !browser_view_->IsTabStripVisible())
return;
gfx::Rect toolbar_bounds(browser_view_->GetToolbarBounds());
gfx::Point toolbar_origin(toolbar_bounds.origin());
View::ConvertPointToView(frame_->client_view(), this, &toolbar_origin);
toolbar_bounds.set_origin(toolbar_origin);
SkBitmap* toolbar_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_LEFT);
canvas->DrawBitmapInt(*toolbar_left,
toolbar_bounds.x() - toolbar_left->width(),
toolbar_bounds.y());
SkBitmap* toolbar_center =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP);
canvas->TileImageInt(*toolbar_center, toolbar_bounds.x(), toolbar_bounds.y(),
toolbar_bounds.width(), toolbar_center->height());
canvas->DrawBitmapInt(
*resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_RIGHT),
toolbar_bounds.right(), toolbar_bounds.y());
}
void OpaqueNonClientView::PaintOTRAvatar(ChromeCanvas* canvas) {
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
int src_y = frame_->IsMaximized() ? kOTRZoomedTopCrop : 0;
canvas->DrawBitmapInt(browser_view_->GetOTRAvatarIcon(), 0, src_y,
otr_avatar_bounds_.width(), otr_avatar_bounds_.height(),
MirroredLeftPointForRect(otr_avatar_bounds_), otr_avatar_bounds_.y(),
otr_avatar_bounds_.width(), otr_avatar_bounds_.height(), false);
}
}
void OpaqueNonClientView::PaintClientEdge(ChromeCanvas* canvas) {
// The toolbar draws a client edge along its own bottom edge when it's
// visible. However, it only draws this for the width of the actual client
// area, leaving a gap at the left and right edges:
//
// | Toolbar | <-- part of toolbar
// ----- (toolbar client edge) ----- <-- gap
// | Client area | <-- right client edge
//
// To address this, we extend the left and right client edges up one pixel to
// fill the gap, by pretending the toolbar is one pixel shorter than it really
// is.
//
// Note: We can get away with this hackery because we only draw a top edge
// when there is no toolbar. If we tried to draw a top edge over the
// toolbar's top edge, we'd need a different solution.
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
if (browser_view_->IsToolbarVisible())
toolbar_bounds.set_height(std::max(0, toolbar_bounds.height() - 1));
int client_area_top = frame_->client_view()->y() + toolbar_bounds.bottom();
// When we don't have a toolbar to draw a top edge for us, draw a top edge.
gfx::Rect client_area_bounds = CalculateClientAreaBounds(width(), height());
if (!browser_view_->IsToolbarVisible()) {
// This is necessary because the top center bitmap is shorter than the top
// left and right bitmaps. We need their top edges to line up, and we
// need the left and right edges to start below the corners' bottoms.
int top_edge_y = client_area_top - app_top_center_.height();
client_area_top = top_edge_y + app_top_left_.height();
canvas->DrawBitmapInt(app_top_left_,
client_area_bounds.x() - app_top_left_.width(),
top_edge_y);
canvas->TileImageInt(app_top_center_, client_area_bounds.x(), top_edge_y,
client_area_bounds.width(), app_top_center_.height());
canvas->DrawBitmapInt(app_top_right_, client_area_bounds.right(),
top_edge_y);
}
int client_area_bottom =
std::max(client_area_top, height() - VerticalBorderBottomSize());
int client_area_height = client_area_bottom - client_area_top;
SkBitmap* right = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_RIGHT);
canvas->TileImageInt(*right, client_area_bounds.right(), client_area_top,
right->width(), client_area_height);
canvas->DrawBitmapInt(
*resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_RIGHT),
client_area_bounds.right(), client_area_bottom);
SkBitmap* bottom = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM);
canvas->TileImageInt(*bottom, client_area_bounds.x(),
client_area_bottom, client_area_bounds.width(),
bottom->height());
SkBitmap* bottom_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_LEFT);
canvas->DrawBitmapInt(*bottom_left,
client_area_bounds.x() - bottom_left->width(), client_area_bottom);
SkBitmap* left = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_LEFT);
canvas->TileImageInt(*left, client_area_bounds.x() - left->width(),
client_area_top, left->width(), client_area_height);
}
void OpaqueNonClientView::PaintMaximizedClientEdge(ChromeCanvas* canvas) {
if (browser_view_->IsToolbarVisible())
return; // The toolbar draws its own client edge, which is sufficient.
int edge_height = app_top_center_.height() - kClientEdgeZoomedBottomCrop;
canvas->TileImageInt(app_top_center_, 0,
frame_->client_view()->y() - edge_height, width(), edge_height);
}
void OpaqueNonClientView::LayoutWindowControls() {
// TODO(pkasting): This function is almost identical to
// DefaultNonClientView::LayoutWindowControls(), they should be combined.
close_button_->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
// Maximized buttons start at window top so that even if their images aren't
// drawn flush with the screen edge, they still obey Fitts' Law.
bool is_maximized = frame_->IsMaximized();
int top_offset = is_maximized ? 0 : kWindowControlsTopOffset;
int top_extra_height = is_maximized ?
(GetSystemMetrics(SM_CYSIZEFRAME) + kWindowControlsZoomedTopExtraHeight) :
0;
int right_offset = is_maximized ?
(GetSystemMetrics(SM_CXSIZEFRAME) + kWindowControlsZoomedRightOffset) :
kWindowControlsRightOffset;
gfx::Size close_button_size = close_button_->GetPreferredSize();
close_button_->SetBounds(
(width() - close_button_size.width() - right_offset),
top_offset,
(is_maximized ?
// We extend the maximized close button to the screen corner to obey
// Fitts' Law.
(close_button_size.width() + kWindowControlsZoomedRightOffset) :
close_button_size.width()),
(close_button_size.height() + top_extra_height));
// When the window is restored, we show a maximized button; otherwise, we show
// a restore button.
bool is_restored = !is_maximized && !frame_->IsMinimized();
views::Button* invisible_button = is_restored ?
restore_button_ : maximize_button_;
invisible_button->SetVisible(false);
views::Button* visible_button = is_restored ?
maximize_button_ : restore_button_;
visible_button->SetVisible(true);
visible_button->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
gfx::Size visible_button_size = visible_button->GetPreferredSize();
visible_button->SetBounds(close_button_->x() - visible_button_size.width(),
top_offset,
visible_button_size.width(),
visible_button_size.height() + top_extra_height);
minimize_button_->SetVisible(true);
minimize_button_->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
gfx::Size minimize_button_size = minimize_button_->GetPreferredSize();
minimize_button_->SetBounds(
visible_button->x() - minimize_button_size.width(),
top_offset,
minimize_button_size.width(),
minimize_button_size.height() + top_extra_height);
}
void OpaqueNonClientView::LayoutDistributorLogo() {
logo_bounds_.SetRect(minimize_button_->x() - distributor_logo_.width() -
kDistributorLogoHorizontalOffset, kDistributorLogoVerticalOffset,
distributor_logo_.width(), distributor_logo_.height());
}
void OpaqueNonClientView::LayoutTitleBar() {
// Size the window icon, even if it is hidden so we can size the title based
// on its position.
int left_offset = frame_->IsMaximized() ?
(GetSystemMetrics(SM_CXSIZEFRAME) + kWindowIconZoomedLeftOffset) :
kWindowIconLeftOffset;
int top_offset = frame_->IsMaximized() ?
(GetSystemMetrics(SM_CYSIZEFRAME) + kWindowIconAndTitleZoomedTopOffset) :
kWindowIconAndTitleTopOffset;
views::WindowDelegate* d = frame_->window_delegate();
int icon_size = d->ShouldShowWindowIcon() ? kWindowIconSize : 0;
icon_bounds_.SetRect(left_offset, top_offset, icon_size, icon_size);
if (window_icon_)
window_icon_->SetBounds(icon_bounds_);
// Size the title, if visible.
if (d->ShouldShowWindowTitle()) {
int title_right = logo_bounds_.x() - kTitleLogoSpacing;
int icon_right = icon_bounds_.right();
int title_left =
icon_right + (d->ShouldShowWindowIcon() ? kWindowIconTitleSpacing : 0);
title_bounds_.SetRect(title_left, top_offset,
std::max(0, title_right - icon_right), title_font_.height());
}
}
void OpaqueNonClientView::LayoutOTRAvatar() {
SkBitmap otr_avatar_icon = browser_view_->GetOTRAvatarIcon();
int non_client_height = CalculateNonClientTopHeight();
int otr_bottom = non_client_height + browser_view_->GetTabStripHeight() -
kOTRBottomSpacing;
int otr_x, otr_y, otr_height;
if (frame_->IsMaximized()) {
otr_x = GetSystemMetrics(SM_CXSIZEFRAME) + kOTRZoomedLeftOffset;
otr_y = non_client_height + kOTRZoomedTopSpacing;
otr_height = otr_bottom - otr_y;
} else {
otr_x = kOTRLeftOffset;
otr_height = otr_avatar_icon.height();
otr_y = otr_bottom - otr_height;
}
otr_avatar_bounds_.SetRect(otr_x, otr_y, otr_avatar_icon.width(), otr_height);
}
void OpaqueNonClientView::LayoutClientView() {
frame_->client_view()->SetBounds(CalculateClientAreaBounds(width(),
height()));
}
// static
void OpaqueNonClientView::InitClass() {
static bool initialized = false;
if (!initialized) {
active_resources_ = new ActiveWindowResources;
inactive_resources_ = new InactiveWindowResources;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(GOOGLE_CHROME_BUILD)
distributor_logo_ = *rb.GetBitmapNamed(IDR_DISTRIBUTOR_LOGO_LIGHT);
#endif
app_top_left_ = *rb.GetBitmapNamed(IDR_APP_TOP_LEFT);
app_top_center_ = *rb.GetBitmapNamed(IDR_APP_TOP_CENTER);
app_top_right_ = *rb.GetBitmapNamed(IDR_APP_TOP_RIGHT);
initialized = true;
}
}
// static
void OpaqueNonClientView::InitAppWindowResources() {
static bool initialized = false;
if (!initialized) {
title_font_ = win_util::GetWindowTitleFont();
initialized = true;
}
}
Correct icon/title sizing/placement for varying titlebar font sizes. This matches Windows pixel-for-pixel except where we adjust things slightly in restored mode to look better with our frame shape, and in occasional cases where our scaling differs slightly, mainly because the Windows icon caching makes it almost impossible to tell what the "correct" Windows behavior actually is.
This depends on my oustanding "fix scaled icon problems" change.
BUG=5054
Review URL: http://codereview.chromium.org/18396
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@8349 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "chrome/browser/views/frame/opaque_non_client_view.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab_strip.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/gfx/path.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/win_util.h"
#include "chrome/views/root_view.h"
#include "chrome/views/window_resources.h"
#include "chromium_strings.h"
#include "generated_resources.h"
// An enumeration of bitmap resources used by this window.
enum {
FRAME_PART_BITMAP_FIRST = 0, // Must be first.
// Window Controls.
FRAME_CLOSE_BUTTON_ICON,
FRAME_CLOSE_BUTTON_ICON_H,
FRAME_CLOSE_BUTTON_ICON_P,
FRAME_CLOSE_BUTTON_ICON_SA,
FRAME_CLOSE_BUTTON_ICON_SA_H,
FRAME_CLOSE_BUTTON_ICON_SA_P,
FRAME_RESTORE_BUTTON_ICON,
FRAME_RESTORE_BUTTON_ICON_H,
FRAME_RESTORE_BUTTON_ICON_P,
FRAME_MAXIMIZE_BUTTON_ICON,
FRAME_MAXIMIZE_BUTTON_ICON_H,
FRAME_MAXIMIZE_BUTTON_ICON_P,
FRAME_MINIMIZE_BUTTON_ICON,
FRAME_MINIMIZE_BUTTON_ICON_H,
FRAME_MINIMIZE_BUTTON_ICON_P,
// Window Frame Border.
FRAME_BOTTOM_EDGE,
FRAME_BOTTOM_LEFT_CORNER,
FRAME_BOTTOM_RIGHT_CORNER,
FRAME_LEFT_EDGE,
FRAME_RIGHT_EDGE,
FRAME_TOP_EDGE,
FRAME_TOP_LEFT_CORNER,
FRAME_TOP_RIGHT_CORNER,
// Window Maximized Border.
FRAME_MAXIMIZED_TOP_EDGE,
FRAME_MAXIMIZED_BOTTOM_EDGE,
// Client Edge Border.
FRAME_CLIENT_EDGE_TOP_LEFT,
FRAME_CLIENT_EDGE_TOP,
FRAME_CLIENT_EDGE_TOP_RIGHT,
FRAME_CLIENT_EDGE_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM_RIGHT,
FRAME_CLIENT_EDGE_BOTTOM,
FRAME_CLIENT_EDGE_BOTTOM_LEFT,
FRAME_CLIENT_EDGE_LEFT,
FRAME_PART_BITMAP_COUNT // Must be last.
};
class ActiveWindowResources : public views::WindowResources {
public:
ActiveWindowResources() {
InitClass();
}
virtual ~ActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER, IDR_WINDOW_BOTTOM_LEFT_CORNER,
IDR_WINDOW_BOTTOM_RIGHT_CORNER, IDR_WINDOW_LEFT_SIDE,
IDR_WINDOW_RIGHT_SIDE, IDR_WINDOW_TOP_CENTER,
IDR_WINDOW_TOP_LEFT_CORNER, IDR_WINDOW_TOP_RIGHT_CORNER,
IDR_WINDOW_TOP_CENTER, IDR_WINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(ActiveWindowResources);
};
class InactiveWindowResources : public views::WindowResources {
public:
InactiveWindowResources() {
InitClass();
}
virtual ~InactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER, IDR_DEWINDOW_BOTTOM_LEFT_CORNER,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER, IDR_DEWINDOW_LEFT_SIDE,
IDR_DEWINDOW_RIGHT_SIDE, IDR_DEWINDOW_TOP_CENTER,
IDR_DEWINDOW_TOP_LEFT_CORNER, IDR_DEWINDOW_TOP_RIGHT_CORNER,
IDR_DEWINDOW_TOP_CENTER, IDR_DEWINDOW_BOTTOM_CENTER,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(InactiveWindowResources);
};
class OTRActiveWindowResources : public views::WindowResources {
public:
OTRActiveWindowResources() {
InitClass();
}
virtual ~OTRActiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_WINDOW_BOTTOM_CENTER_OTR, IDR_WINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_WINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_WINDOW_LEFT_SIDE_OTR,
IDR_WINDOW_RIGHT_SIDE_OTR, IDR_WINDOW_TOP_CENTER_OTR,
IDR_WINDOW_TOP_LEFT_CORNER_OTR, IDR_WINDOW_TOP_RIGHT_CORNER_OTR,
IDR_WINDOW_TOP_CENTER_OTR, IDR_WINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
DISALLOW_EVIL_CONSTRUCTORS(OTRActiveWindowResources);
};
class OTRInactiveWindowResources : public views::WindowResources {
public:
OTRInactiveWindowResources() {
InitClass();
}
virtual ~OTRInactiveWindowResources() { }
// WindowResources implementation:
virtual SkBitmap* GetPartBitmap(views::FramePartBitmap part) const {
return standard_frame_bitmaps_[part];
}
private:
static void InitClass() {
static bool initialized = false;
if (!initialized) {
static const int kFramePartBitmapIds[] = {
0,
IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P,
IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P,
IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P,
IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P,
IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P,
IDR_DEWINDOW_BOTTOM_CENTER_OTR, IDR_DEWINDOW_BOTTOM_LEFT_CORNER_OTR,
IDR_DEWINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_DEWINDOW_LEFT_SIDE_OTR,
IDR_DEWINDOW_RIGHT_SIDE_OTR, IDR_DEWINDOW_TOP_CENTER_OTR,
IDR_DEWINDOW_TOP_LEFT_CORNER_OTR,
IDR_DEWINDOW_TOP_RIGHT_CORNER_OTR,
IDR_DEWINDOW_TOP_CENTER_OTR, IDR_DEWINDOW_BOTTOM_CENTER_OTR,
IDR_CONTENT_TOP_LEFT_CORNER, IDR_CONTENT_TOP_CENTER,
IDR_CONTENT_TOP_RIGHT_CORNER, IDR_CONTENT_RIGHT_SIDE,
IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE,
0
};
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
int id = kFramePartBitmapIds[i];
if (id != 0)
standard_frame_bitmaps_[i] = rb.GetBitmapNamed(id);
}
initialized = true;
}
}
static SkBitmap* standard_frame_bitmaps_[FRAME_PART_BITMAP_COUNT];
static ChromeFont title_font_;
DISALLOW_EVIL_CONSTRUCTORS(OTRInactiveWindowResources);
};
// static
SkBitmap* ActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* InactiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRActiveWindowResources::standard_frame_bitmaps_[];
SkBitmap* OTRInactiveWindowResources::standard_frame_bitmaps_[];
views::WindowResources* OpaqueNonClientView::active_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::inactive_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::active_otr_resources_ = NULL;
views::WindowResources* OpaqueNonClientView::inactive_otr_resources_ = NULL;
SkBitmap OpaqueNonClientView::distributor_logo_;
SkBitmap OpaqueNonClientView::app_top_left_;
SkBitmap OpaqueNonClientView::app_top_center_;
SkBitmap OpaqueNonClientView::app_top_right_;
ChromeFont OpaqueNonClientView::title_font_;
// The distance between the top of the window and the top of the window
// controls when the window is restored.
static const int kWindowControlsTopOffset = 1;
// The distance between the right edge of the window and the right edge of the
// right-most window control when the window is restored.
static const int kWindowControlsRightOffset = 4;
// The distance between the bottom of the window's top border and the top of the
// window controls' images when the window is maximized. We extend the
// clickable area all the way to the top of the window to obey Fitts' Law.
static const int kWindowControlsZoomedTopExtraHeight = 1;
// The distance between right edge of the right-most window control and the left
// edge of the window's right border when the window is maximized.
static const int kWindowControlsZoomedRightOffset = 3;
// The distance between the left edge of the window and the left edge of the
// window icon when a title-bar is showing and the window is restored.
static const int kWindowIconLeftOffset = 6;
// The distance between the right edge of the window's left border and the left
// edge of the window icon when a title-bar is showing and the window is
// maximized.
static const int kWindowIconZoomedLeftOffset = 2;
// The proportion of vertical space the icon takes up after subtracting the top
// and bottom borders of the titlebar (expressed as two values to avoid
// floating point representation errors that goof up the calculation).
static const int kWindowIconFractionNumerator = 16;
static const int kWindowIconFractionDenominator = 25;
// The distance between the top edge of the window and the top edge of the
// window title when a title-bar is showing and the window is restored.
static const int kWindowTitleTopOffset = 6;
// The distance between the bottom edge of the window's top border and the top
// edge of the window title when a title-bar is showing and the window is
// maximized.
static const int kWindowTitleZoomedTopOffset = 4;
// The distance between the window icon and the window title when a title-bar
// is showing.
static const int kWindowIconTitleSpacing = 4;
// The distance between the right edge of the title text bounding box and the
// left edge of the distributor logo.
static const int kTitleLogoSpacing = 5;
// The distance between the bottom of the title text and the TabStrip when a
// title-bar is showing and the window is restored.
static const int kTitleBottomSpacing = 7;
// The distance between the bottom of the title text and the TabStrip when a
// title-bar is showing and the window is maximized.
static const int kTitleZoomedBottomSpacing = 5;
// The distance between the top edge of the window and the TabStrip when there
// is no title-bar showing, and the window is restored.
static const int kNoTitleTopSpacing = 15;
// The number of pixels to crop off the bottom of the images making up the top
// client edge when the window is maximized, so we only draw a shadowed titlebar
// and not a grey client area border below it.
static const int kClientEdgeZoomedBottomCrop = 1;
// The amount of horizontal and vertical distance from a corner of the window
// within which a mouse-drive resize operation will resize the window in two
// dimensions.
static const int kResizeAreaCornerSize = 16;
// The width of the sizing border on the left and right edge of the window.
static const int kWindowHorizontalBorderSize = 5;
// The height of the sizing border at the top edge of the window
static const int kWindowVerticalBorderTopSize = 3;
// The height of the sizing border on the bottom edge of the window when the
// window is restored.
static const int kWindowVerticalBorderBottomSize = 5;
// The additional height beyond the system-provided thickness of the border on
// the bottom edge of the window when the window is maximized.
static const int kWindowVerticalBorderZoomedBottomSize = 1;
// The minimum width and height of the window icon that appears at the top left
// of pop-up and app windows.
static const int kWindowIconMinimumSize = 16;
// The minimum height reserved for the window title font.
static const int kWindowTitleMinimumHeight = 11;
// The horizontal distance of the right edge of the distributor logo from the
// left edge of the left-most window control.
static const int kDistributorLogoHorizontalOffset = 7;
// The vertical distance of the top of the distributor logo from the top edge
// of the window.
static const int kDistributorLogoVerticalOffset = 3;
// The distance between the left edge of the window and the OTR avatar icon when
// the window is restored.
static const int kOTRLeftOffset = 7;
// The distance between the right edge of the window's left border and the OTR
// avatar icon when the window is maximized.
static const int kOTRZoomedLeftOffset = 2;
// The distance between the top edge of the client area and the OTR avatar icon
// when the window is maximized.
static const int kOTRZoomedTopSpacing = 2;
// The distance between the bottom of the OTR avatar icon and the bottom of the
// tabstrip.
static const int kOTRBottomSpacing = 2;
// The number of pixels to crop off the top of the OTR image when the window is
// maximized.
static const int kOTRZoomedTopCrop = 4;
// Horizontal distance between the right edge of the OTR avatar icon and the
// left edge of the tabstrip.
static const int kOTRTabStripSpacing = 2;
// Horizontal distance between the right edge of the new tab icon and the left
// edge of the window minimize icon when the window is restored.
static const int kNewTabIconMinimizeSpacing = 5;
// Horizontal distance between the right edge of the new tab icon and the left
// edge of the window minimize icon when the window is maximized.
static const int kNewTabIconMinimizeZoomedSpacing = 16;
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, public:
OpaqueNonClientView::OpaqueNonClientView(OpaqueFrame* frame,
BrowserView* browser_view)
: NonClientView(),
minimize_button_(new views::Button),
maximize_button_(new views::Button),
restore_button_(new views::Button),
close_button_(new views::Button),
window_icon_(NULL),
frame_(frame),
browser_view_(browser_view) {
InitClass();
if (browser_view->IsOffTheRecord()) {
if (!active_otr_resources_) {
// Lazy load OTR resources only when we first show an OTR frame.
active_otr_resources_ = new OTRActiveWindowResources;
inactive_otr_resources_ = new OTRInactiveWindowResources;
}
current_active_resources_ = active_otr_resources_;
current_inactive_resources_= inactive_otr_resources_;
} else {
current_active_resources_ = active_resources_;
current_inactive_resources_ = inactive_resources_;
}
views::WindowResources* resources = current_active_resources_;
minimize_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON));
minimize_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_H));
minimize_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MINIMIZE_BUTTON_ICON_P));
minimize_button_->SetListener(this, -1);
minimize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MINIMIZE));
AddChildView(minimize_button_);
maximize_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON));
maximize_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_H));
maximize_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_MAXIMIZE_BUTTON_ICON_P));
maximize_button_->SetListener(this, -1);
maximize_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_MAXIMIZE));
AddChildView(maximize_button_);
restore_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON));
restore_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_H));
restore_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_RESTORE_BUTTON_ICON_P));
restore_button_->SetListener(this, -1);
restore_button_->SetAccessibleName(
l10n_util::GetString(IDS_ACCNAME_RESTORE));
AddChildView(restore_button_);
close_button_->SetImage(
views::Button::BS_NORMAL,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON));
close_button_->SetImage(
views::Button::BS_HOT,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_H));
close_button_->SetImage(
views::Button::BS_PUSHED,
resources->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_P));
close_button_->SetListener(this, -1);
close_button_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_CLOSE));
AddChildView(close_button_);
// Initializing the TabIconView is expensive, so only do it if we need to.
if (browser_view_->ShouldShowWindowIcon()) {
window_icon_ = new TabIconView(this);
window_icon_->set_is_light(true);
AddChildView(window_icon_);
window_icon_->Update();
}
// Only load the title font if we're going to need to use it to paint.
// Loading fonts is expensive.
if (browser_view_->ShouldShowWindowTitle())
InitAppWindowResources();
}
OpaqueNonClientView::~OpaqueNonClientView() {
}
gfx::Rect OpaqueNonClientView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) {
int top_height = CalculateNonClientTopHeight();
int horizontal_border = HorizontalBorderSize();
int window_x = std::max(0, client_bounds.x() - horizontal_border);
int window_y = std::max(0, client_bounds.y() - top_height);
int window_w = client_bounds.width() + (2 * horizontal_border);
int window_h =
client_bounds.height() + top_height + VerticalBorderBottomSize();
return gfx::Rect(window_x, window_y, window_w, window_h);
}
gfx::Rect OpaqueNonClientView::GetBoundsForTabStrip(TabStrip* tabstrip) {
int tabstrip_x = browser_view_->ShouldShowOffTheRecordAvatar() ?
(otr_avatar_bounds_.right() + kOTRTabStripSpacing) :
HorizontalBorderSize();
int tabstrip_width = minimize_button_->x() - tabstrip_x -
(frame_->IsMaximized() ?
kNewTabIconMinimizeZoomedSpacing : kNewTabIconMinimizeSpacing);
return gfx::Rect(tabstrip_x, CalculateNonClientTopHeight(),
std::max(0, tabstrip_width), tabstrip->GetPreferredHeight());
}
void OpaqueNonClientView::UpdateWindowIcon() {
if (window_icon_)
window_icon_->Update();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, TabIconView::TabContentsProvider implementation:
bool OpaqueNonClientView::ShouldTabIconViewAnimate() const {
// This function is queried during the creation of the window as the
// TabIconView we host is initialized, so we need to NULL check the selected
// TabContents because in this condition there is not yet a selected tab.
TabContents* current_tab = browser_view_->GetSelectedTabContents();
return current_tab ? current_tab->is_loading() : false;
}
SkBitmap OpaqueNonClientView::GetFavIconForTabIconView() {
return frame_->window_delegate()->GetWindowIcon();
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::BaseButton::ButtonListener implementation:
void OpaqueNonClientView::ButtonPressed(views::BaseButton* sender) {
if (sender == minimize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MINIMIZE);
} else if (sender == maximize_button_) {
frame_->ExecuteSystemMenuCommand(SC_MAXIMIZE);
} else if (sender == restore_button_) {
frame_->ExecuteSystemMenuCommand(SC_RESTORE);
} else if (sender == close_button_) {
frame_->ExecuteSystemMenuCommand(SC_CLOSE);
}
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::NonClientView implementation:
gfx::Rect OpaqueNonClientView::CalculateClientAreaBounds(int width,
int height) const {
int top_margin = CalculateNonClientTopHeight();
int horizontal_border = HorizontalBorderSize();
return gfx::Rect(horizontal_border, top_margin,
std::max(0, width - (2 * horizontal_border)),
std::max(0, height - top_margin - VerticalBorderBottomSize()));
}
gfx::Size OpaqueNonClientView::CalculateWindowSizeForClientSize(
int width,
int height) const {
return gfx::Size(width + (2 * HorizontalBorderSize()),
height + CalculateNonClientTopHeight() + VerticalBorderBottomSize());
}
CPoint OpaqueNonClientView::GetSystemMenuPoint() const {
CPoint system_menu_point(icon_bounds_.x(), icon_bounds_.bottom());
MapWindowPoints(frame_->GetHWND(), HWND_DESKTOP, &system_menu_point, 1);
return system_menu_point;
}
int OpaqueNonClientView::NonClientHitTest(const gfx::Point& point) {
// First see if it's within the grow box area, since that overlaps the client
// bounds.
int frame_component = frame_->client_view()->NonClientHitTest(point);
if (frame_component != HTNOWHERE)
return frame_component;
// Then see if the point is within any of the window controls.
if (close_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return HTCLOSE;
if (restore_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMAXBUTTON;
if (maximize_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMAXBUTTON;
if (minimize_button_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(
point))
return HTMINBUTTON;
if (window_icon_ &&
window_icon_->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return HTSYSMENU;
int window_component = GetHTComponentForFrame(point, HorizontalBorderSize(),
kResizeAreaCornerSize, kWindowVerticalBorderTopSize,
frame_->window_delegate()->CanResize());
// Fall back to the caption if no other component matches.
if ((window_component == HTNOWHERE) && bounds().Contains(point))
window_component = HTCAPTION;
return window_component;
}
void OpaqueNonClientView::GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {
DCHECK(window_mask);
// Redefine the window visible region for the new size.
window_mask->moveTo(0, 3);
window_mask->lineTo(1, 1);
window_mask->lineTo(3, 0);
window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
window_mask->lineTo(SkIntToScalar(size.width() - 1), 3);
window_mask->lineTo(SkIntToScalar(size.width() - 0), 3);
window_mask->lineTo(SkIntToScalar(size.width()),
SkIntToScalar(size.height()));
window_mask->lineTo(0, SkIntToScalar(size.height()));
window_mask->close();
}
void OpaqueNonClientView::EnableClose(bool enable) {
close_button_->SetEnabled(enable);
}
void OpaqueNonClientView::ResetWindowControls() {
restore_button_->SetState(views::Button::BS_NORMAL);
minimize_button_->SetState(views::Button::BS_NORMAL);
maximize_button_->SetState(views::Button::BS_NORMAL);
// The close button isn't affected by this constraint.
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, views::View overrides:
void OpaqueNonClientView::Paint(ChromeCanvas* canvas) {
if (frame_->IsMaximized())
PaintMaximizedFrameBorder(canvas);
else
PaintFrameBorder(canvas);
PaintDistributorLogo(canvas);
PaintTitleBar(canvas);
PaintToolbarBackground(canvas);
PaintOTRAvatar(canvas);
if (frame_->IsMaximized())
PaintMaximizedClientEdge(canvas);
else
PaintClientEdge(canvas);
}
void OpaqueNonClientView::Layout() {
LayoutWindowControls();
LayoutDistributorLogo();
LayoutTitleBar();
LayoutOTRAvatar();
LayoutClientView();
}
gfx::Size OpaqueNonClientView::GetPreferredSize() {
gfx::Size prefsize(frame_->client_view()->GetPreferredSize());
prefsize.Enlarge(2 * HorizontalBorderSize(),
CalculateNonClientTopHeight() + VerticalBorderBottomSize());
return prefsize;
}
views::View* OpaqueNonClientView::GetViewForPoint(const gfx::Point& point,
bool can_create_floating) {
// We override this function because the ClientView can overlap the non -
// client view, making it impossible to click on the window controls. We need
// to ensure the window controls are checked _first_.
views::View* views[] = { close_button_, restore_button_, maximize_button_,
minimize_button_ };
for (int i = 0; i < arraysize(views); ++i) {
if (!views[i]->IsVisible())
continue;
// Apply mirroring transformation on view bounds for RTL chrome.
if (views[i]->GetBounds(APPLY_MIRRORING_TRANSFORMATION).Contains(point))
return views[i];
}
return View::GetViewForPoint(point, can_create_floating);
}
void OpaqueNonClientView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this) {
DCHECK(GetWidget());
DCHECK(frame_->client_view()->GetParent() != this);
AddChildView(frame_->client_view());
// The Accessibility glue looks for the product name on these two views to
// determine if this is in fact a Chrome window.
GetRootView()->SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
SetAccessibleName(l10n_util::GetString(IDS_PRODUCT_NAME));
}
}
bool OpaqueNonClientView::GetAccessibleRole(VARIANT* role) {
DCHECK(role);
// We aren't actually the client area of the window, but we act like it as
// far as MSAA and the UI tests are concerned.
role->vt = VT_I4;
role->lVal = ROLE_SYSTEM_CLIENT;
return true;
}
bool OpaqueNonClientView::GetAccessibleName(std::wstring* name) {
if (!accessible_name_.empty()) {
*name = accessible_name_;
return true;
}
return false;
}
void OpaqueNonClientView::SetAccessibleName(const std::wstring& name) {
accessible_name_ = name;
}
///////////////////////////////////////////////////////////////////////////////
// OpaqueNonClientView, private:
int OpaqueNonClientView::CalculateNonClientTopHeight() const {
bool show_title = frame_->window_delegate()->ShouldShowWindowTitle();
int title_height = std::max(title_font_.height(), kWindowTitleMinimumHeight);
if (frame_->IsMaximized()) {
int top_height = GetSystemMetrics(SM_CYSIZEFRAME);
if (show_title) {
top_height += kWindowTitleZoomedTopOffset + title_height +
kTitleZoomedBottomSpacing;
}
if (!browser_view_->IsToolbarVisible())
top_height -= kClientEdgeZoomedBottomCrop;
return top_height;
}
return show_title ?
(kWindowTitleTopOffset + title_height + kTitleBottomSpacing) :
kNoTitleTopSpacing;
}
int OpaqueNonClientView::HorizontalBorderSize() const {
return frame_->IsMaximized() ?
GetSystemMetrics(SM_CXSIZEFRAME) : kWindowHorizontalBorderSize;
}
int OpaqueNonClientView::VerticalBorderBottomSize() const {
return frame_->IsMaximized() ? (GetSystemMetrics(SM_CYSIZEFRAME) +
kWindowVerticalBorderZoomedBottomSize) : kWindowVerticalBorderBottomSize;
}
void OpaqueNonClientView::PaintFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_left_corner =
resources()->GetPartBitmap(FRAME_TOP_LEFT_CORNER);
SkBitmap* top_right_corner =
resources()->GetPartBitmap(FRAME_TOP_RIGHT_CORNER);
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_TOP_EDGE);
SkBitmap* right_edge = resources()->GetPartBitmap(FRAME_RIGHT_EDGE);
SkBitmap* left_edge = resources()->GetPartBitmap(FRAME_LEFT_EDGE);
SkBitmap* bottom_left_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_LEFT_CORNER);
SkBitmap* bottom_right_corner =
resources()->GetPartBitmap(FRAME_BOTTOM_RIGHT_CORNER);
SkBitmap* bottom_edge = resources()->GetPartBitmap(FRAME_BOTTOM_EDGE);
// Top.
canvas->DrawBitmapInt(*top_left_corner, 0, 0);
canvas->TileImageInt(*top_edge, top_left_corner->width(), 0,
width() - top_right_corner->width(), top_edge->height());
canvas->DrawBitmapInt(*top_right_corner,
width() - top_right_corner->width(), 0);
// Right.
canvas->TileImageInt(*right_edge, width() - right_edge->width(),
top_right_corner->height(), right_edge->width(),
height() - top_right_corner->height() -
bottom_right_corner->height());
// Bottom.
canvas->DrawBitmapInt(*bottom_right_corner,
width() - bottom_right_corner->width(),
height() - bottom_right_corner->height());
canvas->TileImageInt(*bottom_edge, bottom_left_corner->width(),
height() - bottom_edge->height(),
width() - bottom_left_corner->width() -
bottom_right_corner->width(),
bottom_edge->height());
canvas->DrawBitmapInt(*bottom_left_corner, 0,
height() - bottom_left_corner->height());
// Left.
canvas->TileImageInt(*left_edge, 0, top_left_corner->height(),
left_edge->width(),
height() - top_left_corner->height() - bottom_left_corner->height());
}
void OpaqueNonClientView::PaintMaximizedFrameBorder(ChromeCanvas* canvas) {
SkBitmap* top_edge = resources()->GetPartBitmap(FRAME_MAXIMIZED_TOP_EDGE);
int frame_thickness = GetSystemMetrics(SM_CYSIZEFRAME);
canvas->TileImageInt(*top_edge, 0, frame_thickness, width(),
top_edge->height());
SkBitmap* bottom_edge =
resources()->GetPartBitmap(FRAME_MAXIMIZED_BOTTOM_EDGE);
canvas->TileImageInt(*bottom_edge, 0,
height() - bottom_edge->height() - frame_thickness, width(),
bottom_edge->height());
}
void OpaqueNonClientView::PaintDistributorLogo(ChromeCanvas* canvas) {
// The distributor logo is only painted when the frame is not maximized and
// when we actually have a logo.
if (!frame_->IsMaximized() && !distributor_logo_.empty()) {
int logo_x = MirroredLeftPointForRect(logo_bounds_);
canvas->DrawBitmapInt(distributor_logo_, logo_x, logo_bounds_.y());
}
}
void OpaqueNonClientView::PaintTitleBar(ChromeCanvas* canvas) {
// The window icon is painted by the TabIconView.
views::WindowDelegate* d = frame_->window_delegate();
if (d->ShouldShowWindowTitle()) {
canvas->DrawStringInt(d->GetWindowTitle(), title_font_, SK_ColorWHITE,
MirroredLeftPointForRect(title_bounds_), title_bounds_.y(),
title_bounds_.width(), title_bounds_.height());
/* TODO(pkasting):
if (app window && active)
Draw Drop Shadow;
*/
}
}
void OpaqueNonClientView::PaintToolbarBackground(ChromeCanvas* canvas) {
if (!browser_view_->IsToolbarVisible() && !browser_view_->IsTabStripVisible())
return;
gfx::Rect toolbar_bounds(browser_view_->GetToolbarBounds());
gfx::Point toolbar_origin(toolbar_bounds.origin());
View::ConvertPointToView(frame_->client_view(), this, &toolbar_origin);
toolbar_bounds.set_origin(toolbar_origin);
SkBitmap* toolbar_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_LEFT);
canvas->DrawBitmapInt(*toolbar_left,
toolbar_bounds.x() - toolbar_left->width(),
toolbar_bounds.y());
SkBitmap* toolbar_center =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP);
canvas->TileImageInt(*toolbar_center, toolbar_bounds.x(), toolbar_bounds.y(),
toolbar_bounds.width(), toolbar_center->height());
canvas->DrawBitmapInt(
*resources()->GetPartBitmap(FRAME_CLIENT_EDGE_TOP_RIGHT),
toolbar_bounds.right(), toolbar_bounds.y());
}
void OpaqueNonClientView::PaintOTRAvatar(ChromeCanvas* canvas) {
if (browser_view_->ShouldShowOffTheRecordAvatar()) {
int src_y = frame_->IsMaximized() ? kOTRZoomedTopCrop : 0;
canvas->DrawBitmapInt(browser_view_->GetOTRAvatarIcon(), 0, src_y,
otr_avatar_bounds_.width(), otr_avatar_bounds_.height(),
MirroredLeftPointForRect(otr_avatar_bounds_), otr_avatar_bounds_.y(),
otr_avatar_bounds_.width(), otr_avatar_bounds_.height(), false);
}
}
void OpaqueNonClientView::PaintClientEdge(ChromeCanvas* canvas) {
// The toolbar draws a client edge along its own bottom edge when it's
// visible. However, it only draws this for the width of the actual client
// area, leaving a gap at the left and right edges:
//
// | Toolbar | <-- part of toolbar
// ----- (toolbar client edge) ----- <-- gap
// | Client area | <-- right client edge
//
// To address this, we extend the left and right client edges up one pixel to
// fill the gap, by pretending the toolbar is one pixel shorter than it really
// is.
//
// Note: We can get away with this hackery because we only draw a top edge
// when there is no toolbar. If we tried to draw a top edge over the
// toolbar's top edge, we'd need a different solution.
gfx::Rect toolbar_bounds = browser_view_->GetToolbarBounds();
if (browser_view_->IsToolbarVisible())
toolbar_bounds.set_height(std::max(0, toolbar_bounds.height() - 1));
int client_area_top = frame_->client_view()->y() + toolbar_bounds.bottom();
// When we don't have a toolbar to draw a top edge for us, draw a top edge.
gfx::Rect client_area_bounds = CalculateClientAreaBounds(width(), height());
if (!browser_view_->IsToolbarVisible()) {
// This is necessary because the top center bitmap is shorter than the top
// left and right bitmaps. We need their top edges to line up, and we
// need the left and right edges to start below the corners' bottoms.
int top_edge_y = client_area_top - app_top_center_.height();
client_area_top = top_edge_y + app_top_left_.height();
canvas->DrawBitmapInt(app_top_left_,
client_area_bounds.x() - app_top_left_.width(),
top_edge_y);
canvas->TileImageInt(app_top_center_, client_area_bounds.x(), top_edge_y,
client_area_bounds.width(), app_top_center_.height());
canvas->DrawBitmapInt(app_top_right_, client_area_bounds.right(),
top_edge_y);
}
int client_area_bottom =
std::max(client_area_top, height() - VerticalBorderBottomSize());
int client_area_height = client_area_bottom - client_area_top;
SkBitmap* right = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_RIGHT);
canvas->TileImageInt(*right, client_area_bounds.right(), client_area_top,
right->width(), client_area_height);
canvas->DrawBitmapInt(
*resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_RIGHT),
client_area_bounds.right(), client_area_bottom);
SkBitmap* bottom = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM);
canvas->TileImageInt(*bottom, client_area_bounds.x(),
client_area_bottom, client_area_bounds.width(),
bottom->height());
SkBitmap* bottom_left =
resources()->GetPartBitmap(FRAME_CLIENT_EDGE_BOTTOM_LEFT);
canvas->DrawBitmapInt(*bottom_left,
client_area_bounds.x() - bottom_left->width(), client_area_bottom);
SkBitmap* left = resources()->GetPartBitmap(FRAME_CLIENT_EDGE_LEFT);
canvas->TileImageInt(*left, client_area_bounds.x() - left->width(),
client_area_top, left->width(), client_area_height);
}
void OpaqueNonClientView::PaintMaximizedClientEdge(ChromeCanvas* canvas) {
if (browser_view_->IsToolbarVisible())
return; // The toolbar draws its own client edge, which is sufficient.
int edge_height = app_top_center_.height() - kClientEdgeZoomedBottomCrop;
canvas->TileImageInt(app_top_center_, 0,
frame_->client_view()->y() - edge_height, width(), edge_height);
}
void OpaqueNonClientView::LayoutWindowControls() {
// TODO(pkasting): This function is almost identical to
// DefaultNonClientView::LayoutWindowControls(), they should be combined.
close_button_->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
// Maximized buttons start at window top so that even if their images aren't
// drawn flush with the screen edge, they still obey Fitts' Law.
bool is_maximized = frame_->IsMaximized();
int top_offset = is_maximized ? 0 : kWindowControlsTopOffset;
int top_extra_height = is_maximized ?
(GetSystemMetrics(SM_CYSIZEFRAME) + kWindowControlsZoomedTopExtraHeight) :
0;
int right_offset = is_maximized ?
(GetSystemMetrics(SM_CXSIZEFRAME) + kWindowControlsZoomedRightOffset) :
kWindowControlsRightOffset;
gfx::Size close_button_size = close_button_->GetPreferredSize();
close_button_->SetBounds(
(width() - close_button_size.width() - right_offset),
top_offset,
(is_maximized ?
// We extend the maximized close button to the screen corner to obey
// Fitts' Law.
(close_button_size.width() + kWindowControlsZoomedRightOffset) :
close_button_size.width()),
(close_button_size.height() + top_extra_height));
// When the window is restored, we show a maximized button; otherwise, we show
// a restore button.
bool is_restored = !is_maximized && !frame_->IsMinimized();
views::Button* invisible_button = is_restored ?
restore_button_ : maximize_button_;
invisible_button->SetVisible(false);
views::Button* visible_button = is_restored ?
maximize_button_ : restore_button_;
visible_button->SetVisible(true);
visible_button->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
gfx::Size visible_button_size = visible_button->GetPreferredSize();
visible_button->SetBounds(close_button_->x() - visible_button_size.width(),
top_offset,
visible_button_size.width(),
visible_button_size.height() + top_extra_height);
minimize_button_->SetVisible(true);
minimize_button_->SetImageAlignment(views::Button::ALIGN_LEFT,
views::Button::ALIGN_BOTTOM);
gfx::Size minimize_button_size = minimize_button_->GetPreferredSize();
minimize_button_->SetBounds(
visible_button->x() - minimize_button_size.width(),
top_offset,
minimize_button_size.width(),
minimize_button_size.height() + top_extra_height);
}
void OpaqueNonClientView::LayoutDistributorLogo() {
logo_bounds_.SetRect(minimize_button_->x() - distributor_logo_.width() -
kDistributorLogoHorizontalOffset, kDistributorLogoVerticalOffset,
distributor_logo_.width(), distributor_logo_.height());
}
void OpaqueNonClientView::LayoutTitleBar() {
// Size the window icon, even if it is hidden so we can size the title based
// on its position.
int left_offset = frame_->IsMaximized() ?
(GetSystemMetrics(SM_CXSIZEFRAME) + kWindowIconZoomedLeftOffset) :
kWindowIconLeftOffset;
// The usable height of the titlebar area is the total height minus the top
// resize border, the one shadow pixel at the bottom, and any client edge area
// we draw below that shadow pixel (only in restored mode).
// TODO(pkasting): Clean up this "4" hack.
int top_border_height =
frame_->IsMaximized() ? GetSystemMetrics(SM_CYSIZEFRAME) : 4;
int available_height = CalculateNonClientTopHeight() - top_border_height - 1;
if (!frame_->IsMaximized())
available_height -= kClientEdgeZoomedBottomCrop;
// The icon takes up a constant fraction of the available height, down to a
// minimum size, and is always an even number of pixels on a side (presumably
// to make scaled icons look better). It's centered within the usable height.
int icon_size = std::max((available_height * kWindowIconFractionNumerator /
kWindowIconFractionDenominator) / 2 * 2, kWindowIconMinimumSize);
int icon_top_offset =
((available_height - icon_size) / 2) + top_border_height;
// Hack: Our frame border has a different "3D look" than Windows'. Theirs has
// a more complex gradient on the top that they push their icon/title below;
// then the maximized window cuts this off and the icon/title are centered in
// the remaining space. Because the apparent shape of our border is simpler,
// using the same positioning makes things look slightly uncentered with
// restored windows, so we come up one pixel to compensate.
if (!frame_->IsMaximized())
--icon_top_offset;
views::WindowDelegate* d = frame_->window_delegate();
if (!d->ShouldShowWindowIcon())
icon_size = 0;
icon_bounds_.SetRect(left_offset, icon_top_offset, icon_size, icon_size);
if (window_icon_)
window_icon_->SetBounds(icon_bounds_);
// Size the title, if visible.
if (d->ShouldShowWindowTitle()) {
int title_right = logo_bounds_.x() - kTitleLogoSpacing;
int icon_right = icon_bounds_.right();
int title_left =
icon_right + (d->ShouldShowWindowIcon() ? kWindowIconTitleSpacing : 0);
int title_top_offset = frame_->IsMaximized() ?
(GetSystemMetrics(SM_CYSIZEFRAME) + kWindowTitleZoomedTopOffset) :
kWindowTitleTopOffset;
if (title_font_.height() < kWindowTitleMinimumHeight) {
title_top_offset +=
(kWindowTitleMinimumHeight - title_font_.height()) / 2;
}
title_bounds_.SetRect(title_left, title_top_offset,
std::max(0, title_right - icon_right), title_font_.height());
}
}
void OpaqueNonClientView::LayoutOTRAvatar() {
SkBitmap otr_avatar_icon = browser_view_->GetOTRAvatarIcon();
int non_client_height = CalculateNonClientTopHeight();
int otr_bottom = non_client_height + browser_view_->GetTabStripHeight() -
kOTRBottomSpacing;
int otr_x, otr_y, otr_height;
if (frame_->IsMaximized()) {
otr_x = GetSystemMetrics(SM_CXSIZEFRAME) + kOTRZoomedLeftOffset;
otr_y = non_client_height + kOTRZoomedTopSpacing;
otr_height = otr_bottom - otr_y;
} else {
otr_x = kOTRLeftOffset;
otr_height = otr_avatar_icon.height();
otr_y = otr_bottom - otr_height;
}
otr_avatar_bounds_.SetRect(otr_x, otr_y, otr_avatar_icon.width(), otr_height);
}
void OpaqueNonClientView::LayoutClientView() {
frame_->client_view()->SetBounds(CalculateClientAreaBounds(width(),
height()));
}
// static
void OpaqueNonClientView::InitClass() {
static bool initialized = false;
if (!initialized) {
active_resources_ = new ActiveWindowResources;
inactive_resources_ = new InactiveWindowResources;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(GOOGLE_CHROME_BUILD)
distributor_logo_ = *rb.GetBitmapNamed(IDR_DISTRIBUTOR_LOGO_LIGHT);
#endif
app_top_left_ = *rb.GetBitmapNamed(IDR_APP_TOP_LEFT);
app_top_center_ = *rb.GetBitmapNamed(IDR_APP_TOP_CENTER);
app_top_right_ = *rb.GetBitmapNamed(IDR_APP_TOP_RIGHT);
initialized = true;
}
}
// static
void OpaqueNonClientView::InitAppWindowResources() {
static bool initialized = false;
if (!initialized) {
title_font_ = win_util::GetWindowTitleFont();
initialized = true;
}
}
|
/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "runtime/rest/rest.h"
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include "api/serialization/serializer.h"
#include "runtime/util/iterator_impl.h"
#include "runtime/api/runtimecb.h"
#include "runtime/api/plan_wrapper.h"
#include "runtime/api/plan_iterator_wrapper.h"
#include "store/api/iterator.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "store/api/copymode.h"
#include "types/root_typemanager.h"
#include "context/static_context.h"
#include "context/namespace_context.h"
#include "zorbatypes/numconversions.h"
#include "zorbatypes/datetime/parse.h"
#include "util/web/web.h"
#include "system/globalenv.h"
#include "zorbaerrors/error_manager.h"
#include <iostream>
#include <fstream>
#include <istream>
#include <sstream>
#include "util/web/web.h"
using namespace std;
namespace zorba {
using namespace store;
static const char expect_buf[] = "Expect:";
/****************************************************************************
*
* CurlStreamBuffer
*
****************************************************************************/
CurlStreamBuffer::CurlStreamBuffer(CURLM* aMultiHandle, CURL* aEasyHandle)
: std::streambuf(), MultiHandle(aMultiHandle), EasyHandle(aEasyHandle)
{
CurlErrorBuffer = new char[CURLOPT_ERRORBUFFER];
memset(CurlErrorBuffer, 0, CURLOPT_ERRORBUFFER);
curl_easy_setopt(EasyHandle, CURLOPT_ERRORBUFFER, CurlErrorBuffer);
curl_easy_setopt(EasyHandle, CURLOPT_WRITEDATA, this);
curl_easy_setopt(EasyHandle, CURLOPT_WRITEFUNCTION, CurlStreamBuffer::write_callback);
curl_easy_setopt(EasyHandle, CURLOPT_BUFFERSIZE, INITIAL_BUFFER_SIZE);
}
int CurlStreamBuffer::multi_perform()
{
CURLMsg* msg;
int MsgsInQueue;
int StillRunning = 0;
bool done = false;
int error = 0;
while (!done)
{
while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(MultiHandle, &StillRunning))
;
while ((msg = curl_multi_info_read(MultiHandle, &MsgsInQueue)))
if (msg->msg == CURLMSG_DONE)
{
error = msg->data.result;
done = true;
}
}
return error;
}
CurlStreamBuffer::~CurlStreamBuffer()
{
delete[] CurlErrorBuffer;
::free(eback());
}
size_t CurlStreamBuffer::write_callback(char* buffer, size_t size, size_t nitems, void* userp)
{
CurlStreamBuffer* sbuffer = static_cast<CurlStreamBuffer*>(userp);
size_t result = sbuffer->sputn(buffer, size*nitems);
sbuffer->setg(sbuffer->eback(), sbuffer->gptr(), sbuffer->pptr());
return result;
}
int CurlStreamBuffer::overflow(int c)
{
char* _pptr = pptr();
char* _gptr = gptr();
char* _eback = eback();
int new_size = 2 * (epptr() - _eback);
if (new_size == 0)
new_size = INITIAL_BUFFER_SIZE;
char* new_buffer = (char*)realloc(_eback, new_size);
if (new_buffer != _eback)
{
_pptr = new_buffer + (_pptr - _eback);
_gptr = new_buffer + (_gptr - _eback);
_eback = new_buffer;
}
setp(_pptr, new_buffer + new_size);
sputc(c);
setg(_eback, _gptr, pptr());
return 0;
}
int CurlStreamBuffer::underflow()
{
return EOF;
}
const char* CurlStreamBuffer::getErrorBuffer() const
{
return CurlErrorBuffer;
}
/****************************************************************************
*
* rest-get Iterator
*
****************************************************************************/
bool createTypeHelper(store::Item_t& result, xqpString type_name)
{
xqpString xs_ns = "http://www.w3.org/2001/XMLSchema";
xqpString xs_pre = "xs";
return GENV_ITEMFACTORY->createQName(result, xs_ns.theStrStore, xs_pre.theStrStore, type_name.theStrStore);
}
bool createQNameHelper(store::Item_t& result, xqpString name)
{
xqpString ns = ZORBA_REST_FN_NS;
xqpString pre = "zorba-rest";
return GENV_ITEMFACTORY->createQName(result, ns.getStore(), pre.getStore(), name.getStore());
}
bool createNodeHelper(store::Item_t parent, PlanState& planState, xqpString name, store::Item_t* result = NULL)
{
store::Item_t qname, temp_result, type_qname;
store::NsBindings bindings;
xqpStringStore_t baseUri = planState.theRuntimeCB->theStaticContext->final_baseuri().getStore();
createQNameHelper(qname, name);
createTypeHelper(type_qname, "untyped");
bool status = GENV_ITEMFACTORY->createElementNode(
temp_result,
parent,
-1,
qname,
type_qname,
true,
false,
false,
false,
bindings,
baseUri,
true);
if (result != NULL)
*result = temp_result;
return status;
}
bool createAttributeHelper(store::Item_t parent, xqpString name, xqpString value, store::Item_t* result = NULL)
{
store::Item_t qname, temp_result, str_item;
createQNameHelper(qname, name);
store::Item_t type_qname;
createTypeHelper(type_qname, "string");
GENV_ITEMFACTORY->createString(str_item, value.theStrStore);
GENV_ITEMFACTORY->createAttributeNode(
temp_result,
parent,
-1,
qname,
type_qname,
str_item,
false,
false);
if (result != NULL)
*result = temp_result;
return true;
}
/****************************************************************************
*
* rest-get Iterator
*
****************************************************************************/
ZorbaRestGetIteratorState::ZorbaRestGetIteratorState()
{
}
ZorbaRestGetIteratorState::~ZorbaRestGetIteratorState()
{
}
void
ZorbaRestGetIteratorState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
}
void
ZorbaRestGetIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
}
#if 0
static int readSome(std::istream& stream, char *buffer, int maxlen) {
stream.read(buffer, maxlen);
return stream.gcount();
}
#endif
int processReply(store::Item_t& result,
PlanState& planState,
xqpString& lUriString,
int code,
std::vector<std::string>& headers,
CurlStreamBuffer* theStreamBuffer,
const char* tidyUserOpt,
bool ignore_payload = false)
{
int reply_code;
xqpString content_type;
store::Item_t payload, error_node, headers_node, text_code, status_code;
store::Item_t doc = NULL;
createNodeHelper(NULL, planState, "result", &result);
createNodeHelper(result, planState, "status-code", &status_code);
if (headers.size() == 0)
{
// No headers -- create error message node
xqpStringStore_t temp = new xqpStringStore(theStreamBuffer->getErrorBuffer());
createNodeHelper(result, planState, "error-message", &error_node);
GENV_ITEMFACTORY->createTextNode(text_code, error_node, -1, temp);
}
createNodeHelper(result, planState, "headers", &headers_node);
if (!ignore_payload)
createNodeHelper(result, planState, "payload", &payload);
if (headers.size() == 0)
{
// No headers, use cURL's error code.
reply_code = code;
}
else
{
if (parse_int_const_position<int>(headers.operator[](0), 9, reply_code, 1))
{
// No status code in the reply. Put a -1 in there.
reply_code = -1;
}
for (unsigned int i = 1; i < headers.size(); i++)
{
int pos = headers.operator[](i).find(':');
if (pos > -1)
{
store::Item_t header, header_value;
createNodeHelper(headers_node, planState, "header", &header);
xqpString name_string = headers.operator[](i).substr(0, pos);
createAttributeHelper(header, "name", name_string);
string temp = headers.operator[](i).substr(pos+2);
xqpString value_string = temp;
GENV_ITEMFACTORY->createTextNode(header_value, header, -1, value_string.theStrStore);
// extract content-type
if (name_string.lowercase() == "content-type")
content_type = temp;;
}
else
{
// invalid header, ignore it
}
}
}
xqpString temp = NumConversions::intToStr(reply_code);
GENV_ITEMFACTORY->createTextNode(text_code, status_code, -1, temp.theStrStore);
if ((!ignore_payload) && reply_code >= 200 && reply_code < 300)
{
int doc_type; // values: 3 - xml, 2 - text, 1 - everything else (base64), 0 - do nothing, document has bee processed.
if (content_type.theStrStore.getp() == NULL)
doc_type = 1;
else if (content_type.indexOf("application/xml") == 0
||
content_type.indexOf("application/xhtml") == 0
||
content_type.indexOf("text/xml") == 0
||
content_type.indexOf("text/xhtml") == 0) // XMLs
doc_type = 3;
else if (content_type.indexOf("+xml") > -1)
doc_type = 3;
else if (content_type == "text/html")
doc_type = 4;
else if (content_type.indexOf("text/") == 0)
doc_type = 2;
else
doc_type = 1;
switch (doc_type)
{
case 4:
{
store::Item_t temp;
if(tidyUserOpt == NULL)
{
std::istream is(theStreamBuffer);
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
}
else
{
#ifdef ZORBA_WITH_TIDY
std::string input;
char lBuf[1024];
int lRes = 0;
xqp_string diag, strOut;
std::istream lStream(theStreamBuffer);
while ( (lRes = readSome(lStream, lBuf, 1023)) > 0 ) {
lBuf[lRes] = 0;
input += lBuf;
}
int res = tidy(input.c_str(), strOut, diag, (NULL != tidyUserOpt? tidyUserOpt: NULL));
if( res < 0){
ZORBA_ERROR_DESC_OSS(API0036_TIDY_ERROR, diag.c_str());
}
std::istringstream is(strOut, istringstream::in);
#else
std::istream is(theStreamBuffer);
#endif
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
}
if (temp != NULL)
{
store::Iterator_t doc_children = temp->getChildren();
doc_children->open();
doc_children->next(doc);
CopyMode copyMode;
copyMode.theDoCopy = false;
doc->copy(payload, -1, CopyMode());
}
else
{
// xml could not parsed
ZORBA_ERROR(XQP0017_LOADER_PARSING_ERROR);
}
}
break;
case 3: // xml
{
store::Item_t temp;
std::istream is(theStreamBuffer);
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
if (temp != NULL)
{
store::Iterator_t doc_children = temp->getChildren();
doc_children->open();
doc_children->next(doc);
CopyMode copyMode;
copyMode.theDoCopy = false;
doc->copy(payload, -1, CopyMode());
}
else
{
// xml could not be parsed
ZORBA_ERROR(XQP0017_LOADER_PARSING_ERROR);
}
}
break;
case 2: // text
{
store::Item_t temp_item;
stringstream str;
str << theStreamBuffer;
xqpString temp = str.str();
GENV_ITEMFACTORY->createTextNode(temp_item, payload, -1, temp.theStrStore);
}
break;
case 1: // base64
{
store::Item_t temp_item;
xqp_base64Binary base64;
std::istream is(theStreamBuffer);
xqpString temp = Base64::encode(is);
GENV_ITEMFACTORY->createTextNode(temp_item, payload, -1, temp.theStrStore);
}
break;
}
}
return 0;
}
static size_t getHeaderData(void *ptr, size_t size, size_t nmemb, void *aState)
{
ZorbaRestGetIteratorState* state = static_cast<ZorbaRestGetIteratorState*>(aState);
std::string temp(static_cast<char*>(ptr), size*nmemb-1);
if (temp.size() > 0)
{
if (temp[temp.size()-1] == 0x0D) // delete the 0xD at the end.
temp.erase(temp.end()-1);
state->headers->push_back(temp);
// std::cout << "header: " << temp << std::endl;
}
return size * nmemb;
}
static void setupConnection(ZorbaRestGetIteratorState* state, int get_method)
{
state->MultiHandle = curl_multi_init();
state->EasyHandle = curl_easy_init();
curl_easy_setopt(state->EasyHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(state->EasyHandle, CURLOPT_HEADERFUNCTION, getHeaderData);
curl_easy_setopt(state->EasyHandle, CURLOPT_WRITEHEADER, state);
if (get_method == 0)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPGET, 1);
else if (get_method == 1)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, 1);
else if (get_method == 2)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "PUT");
else if (get_method == 3)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "DELETE");
else if (get_method == 4)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_multi_add_handle(state->MultiHandle, state->EasyHandle);
state->headers = std::auto_ptr<std::vector<std::string> >(new std::vector<std::string>);
state->theStreamBuffer = new CurlStreamBuffer(state->MultiHandle, state->EasyHandle);
}
static void cleanupConnection(ZorbaRestGetIteratorState* state)
{
curl_multi_remove_handle(state->MultiHandle, state->EasyHandle);
curl_easy_cleanup(state->EasyHandle);
curl_multi_cleanup(state->MultiHandle);
state->theStreamBuffer = NULL;
state->headers.reset();
}
void processHeader(store::Item_t& headers, curl_slist** headers_list)
{
store::Iterator_t it;
store::Item_t child, name;
if (headers->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
return;
}
if (xqpString("headers") == headers->getNodeName()->getLocalName())
{
it = headers->getChildren();
it->open();
while (it->next(child))
processHeader(child, headers_list);
return;
}
it = headers->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
}
if (name.getp() == NULL)
{
// header without an associated name
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
return;
}
it = headers->getChildren();
it->open();
it->next(child);
if (child == NULL)
{
// HTTP header without a value
xqpString temp = xqpString(name->getStringValue()) + xqpString(": ");
*headers_list = curl_slist_append(*headers_list , temp.c_str());
}
else if (child->getNodeKind() == store::StoreConsts::textNode)
{
xqpString temp = xqpString(name->getStringValue()) + xqpString(": ") + child->getStringValue().getp();
*headers_list = curl_slist_append(*headers_list , temp.c_str());
}
else
{
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
}
}
// Returns all the children of a node as a concatenated string (text nodes + serialized
// element nodes) in the children_string out-paramter, and sets the has_element_child flag
static void getSerializedChildren(store::Item_t node, xqpString& children_string, bool& has_element_child)
{
store::Iterator_t it;
store::Item_t child;
children_string = "";
has_element_child = false;
it = node->getChildren();
it->open();
while (it->next(child))
{
if (child->getNodeKind() == store::StoreConsts::textNode)
{
children_string += xqpString(child->getStringValue());
}
else if (child->getNodeKind() == store::StoreConsts::elementNode)
{
stringstream ss;
error::ErrorManager lErrorManager;
serializer ser(&lErrorManager);
ser.set_parameter("omit-xml-declaration","yes");
ser.serialize(child, ss);
children_string += ss.str().c_str();
has_element_child = true;
}
// ignore other nodes
}
}
static void processPayload(Item_t& payload_data, struct curl_httppost** first, struct curl_httppost** last)
{
store::Iterator_t it;
store::Item_t child, name, filename, content_type;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return;
}
if (xqpString("payload") == payload_data->getNodeName()->getLocalName())
{
it = payload_data->getChildren();
it->open();
while (it->next(child))
if (child->getNodeKind() == store::StoreConsts::elementNode)
processPayload(child, first, last);
return;
}
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
if (xqpString("filename") == child->getNodeName()->getLocalName())
filename = child;
if (xqpString("content-type") == child->getNodeName()->getLocalName())
content_type = child;
}
if (name.getp() == NULL)
{
// payload part without an associated name
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return;
}
if (filename.getp() != NULL)
{
if (content_type != NULL)
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_FILE, filename->getStringValue()->c_str(),
CURLFORM_CONTENTTYPE, content_type->getStringValue()->c_str(),
CURLFORM_END);
else curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_FILE, filename->getStringValue()->c_str(),
CURLFORM_END);
}
else
{
xqpString payload_string;
bool has_element_child;
getSerializedChildren(payload_data, payload_string, has_element_child);
if (has_element_child)
{
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_COPYCONTENTS, payload_string.c_str(),
CURLFORM_CONTENTTYPE, "text/html",
CURLFORM_END);
}
else
{
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_COPYCONTENTS, payload_string.c_str(),
CURLFORM_END);
}
}
}
static bool processSinglePayload(Item_t& payload_data, CURL* EasyHandle, curl_slist **headers_list, std::auto_ptr<char>& buffer)
{
store::Iterator_t it;
store::Item_t child, name, filename, content_type;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
return false;
if (xqpString("payload") != payload_data->getNodeName()->getLocalName())
return false;
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
if (xqpString("filename") == child->getNodeName()->getLocalName())
filename = child;
if (xqpString("content-type") == child->getNodeName()->getLocalName())
content_type = child;
}
if (content_type.getp() != NULL
&&
xqpString("multipart/form-data") == content_type->getStringValue().getp())
return false;
if (filename.getp() != NULL)
{
xqpString test = filename->getStringValue()->c_str();
ifstream ifs(filename->getStringValue()->c_str());
if (!ifs)
{
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return false;
}
filebuf* pbuf = ifs.rdbuf();
long size = pbuf->pubseekoff(0,ios::end,ios::in);
pbuf->pubseekpos(0,ios::in);
buffer = std::auto_ptr<char>(new char[size]);
#ifdef WIN32
pbuf->_Sgetn_s(buffer.get(), size, size);
#else
pbuf->sgetn(buffer.get(), size);
#endif
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDSIZE , size);
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDS, buffer.get());
if (content_type.getp() == NULL)
*headers_list = curl_slist_append(*headers_list, "Content-Type: application/octet-stream");
ifs.close();
}
else
{
xqpString payload_string;
bool has_element_child;
getSerializedChildren(payload_data, payload_string, has_element_child);
buffer = std::auto_ptr<char>(new char[payload_string.bytes()]);
memcpy(buffer.get(), payload_string.c_str(), payload_string.bytes());
// curl_easy_setopt(EasyHandle, CURLOPT_COPYPOSTFIELDS, payload_string.c_str());
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDSIZE , payload_string.bytes());
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDS, buffer.get());
curl_easy_setopt(EasyHandle, CURLOPT_POST, 1);
if (content_type.getp() == NULL)
{
if (has_element_child)
*headers_list = curl_slist_append(*headers_list, "Content-Type: text/xml");
else
*headers_list = curl_slist_append(*headers_list, "Content-Type: text/plain");
}
}
if (content_type.getp() != NULL)
*headers_list = curl_slist_append(*headers_list,
(xqpString("Content-Type: ") + xqpString(content_type->getStringValue())).c_str());
return true;
}
static xqpString processGetPayload(Item_t& payload_data, xqpString& Uri)
{
store::Iterator_t it;
store::Item_t child, name;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return Uri;
}
if (xqpString("payload") == payload_data->getNodeName()->getLocalName())
{
it = payload_data->getChildren();
it->open();
while (it->next(child))
if (child->getNodeKind() == store::StoreConsts::elementNode)
Uri = processGetPayload(child, Uri);
return Uri;
}
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
}
if (name.getp() == NULL)
{
// payload part without an associated name
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return Uri;
}
it = payload_data->getChildren();
it->open();
it->next(child);
if (child->getNodeKind() == store::StoreConsts::textNode)
{
xqpStringStore_t encoded_name = name->getStringValue()->encodeForUri();
xqpStringStore_t value = child->getStringValue()->encodeForUri();
if (Uri.indexOf("?") == -1)
Uri = Uri + "?" + encoded_name.getp() + "=" + value.getp();
else
Uri = Uri + "&" + encoded_name.getp() + "=" + value.getp();
}
return Uri;
}
bool ZorbaRestGetIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t item, lUri, payload_data, headers, tidyUserOpt;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
unsigned int index = 1;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 0);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST get() function.");
}
Uri = lUri->getStringValue()->str();
#ifdef ZORBA_WITH_TIDY
if(isGetTidy)
{
index = 2;
if (theChildren.size() > 1)
CONSUME(tidyUserOpt, 1);
}
#endif
if (theChildren.size() > index)
while (CONSUME(payload_data, index))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > (index + 1))
while (CONSUME(headers, (index + 1)))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that
//the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result,
planState,
Uri,
code,
*state->headers,
state->theStreamBuffer.getp(),
(tidyUserOpt!=NULL)?tidyUserOpt->getStringValue()->c_str():NULL);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestPostIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_httppost *first = NULL, *last = NULL;
curl_slist *headers_list = NULL;
std::auto_ptr<char> buffer;
int code;
bool single_payload = false;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 1);
if (CONSUME(lUri, 0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST post() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
{
store::Item_t payload_data;
int status = CONSUME(payload_data, 1);
if (status)
{
if (processSinglePayload(payload_data, state->EasyHandle, &headers_list, buffer))
{
single_payload = true;
}
else
{
processPayload(payload_data, &first, &last);
while (CONSUME(payload_data, 1))
processPayload(payload_data, &first, &last);
}
}
}
if (!single_payload)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, first);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
headers_list = curl_slist_append(headers_list , expect_buf);
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL);
curl_formfree(first);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestPutIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_httppost *first = NULL, *last = NULL;
curl_slist *headers_list = NULL;
std::auto_ptr<char> buffer;
int code;
bool single_payload = false;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 2);
if (CONSUME(lUri, 0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST put() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
{
store::Item_t payload_data;
int status = CONSUME(payload_data, 1);
if (status)
{
if (processSinglePayload(payload_data, state->EasyHandle, &headers_list, buffer))
{
single_payload = true;
}
else
{
processPayload(payload_data, &first, &last);
while (CONSUME(payload_data, 1))
processPayload(payload_data, &first, &last);
}
}
}
if (!single_payload)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, first);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
headers_list = curl_slist_append(headers_list , expect_buf);
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL);
curl_formfree(first);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestDeleteIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 3);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST delete() function.");;
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
while (CONSUME(payload_data, 1))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL, true);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestHeadIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 4);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST head() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
while (CONSUME(payload_data, 1))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL, true);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
} /* namespace zorba */
put readSome within #if ZORBA_WITH_TIDY
/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "runtime/rest/rest.h"
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include "api/serialization/serializer.h"
#include "runtime/util/iterator_impl.h"
#include "runtime/api/runtimecb.h"
#include "runtime/api/plan_wrapper.h"
#include "runtime/api/plan_iterator_wrapper.h"
#include "store/api/iterator.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "store/api/copymode.h"
#include "types/root_typemanager.h"
#include "context/static_context.h"
#include "context/namespace_context.h"
#include "zorbatypes/numconversions.h"
#include "zorbatypes/datetime/parse.h"
#include "util/web/web.h"
#include "system/globalenv.h"
#include "zorbaerrors/error_manager.h"
#include <iostream>
#include <fstream>
#include <istream>
#include <sstream>
#include "util/web/web.h"
using namespace std;
namespace zorba {
using namespace store;
static const char expect_buf[] = "Expect:";
/****************************************************************************
*
* CurlStreamBuffer
*
****************************************************************************/
CurlStreamBuffer::CurlStreamBuffer(CURLM* aMultiHandle, CURL* aEasyHandle)
: std::streambuf(), MultiHandle(aMultiHandle), EasyHandle(aEasyHandle)
{
CurlErrorBuffer = new char[CURLOPT_ERRORBUFFER];
memset(CurlErrorBuffer, 0, CURLOPT_ERRORBUFFER);
curl_easy_setopt(EasyHandle, CURLOPT_ERRORBUFFER, CurlErrorBuffer);
curl_easy_setopt(EasyHandle, CURLOPT_WRITEDATA, this);
curl_easy_setopt(EasyHandle, CURLOPT_WRITEFUNCTION, CurlStreamBuffer::write_callback);
curl_easy_setopt(EasyHandle, CURLOPT_BUFFERSIZE, INITIAL_BUFFER_SIZE);
}
int CurlStreamBuffer::multi_perform()
{
CURLMsg* msg;
int MsgsInQueue;
int StillRunning = 0;
bool done = false;
int error = 0;
while (!done)
{
while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(MultiHandle, &StillRunning))
;
while ((msg = curl_multi_info_read(MultiHandle, &MsgsInQueue)))
if (msg->msg == CURLMSG_DONE)
{
error = msg->data.result;
done = true;
}
}
return error;
}
CurlStreamBuffer::~CurlStreamBuffer()
{
delete[] CurlErrorBuffer;
::free(eback());
}
size_t CurlStreamBuffer::write_callback(char* buffer, size_t size, size_t nitems, void* userp)
{
CurlStreamBuffer* sbuffer = static_cast<CurlStreamBuffer*>(userp);
size_t result = sbuffer->sputn(buffer, size*nitems);
sbuffer->setg(sbuffer->eback(), sbuffer->gptr(), sbuffer->pptr());
return result;
}
int CurlStreamBuffer::overflow(int c)
{
char* _pptr = pptr();
char* _gptr = gptr();
char* _eback = eback();
int new_size = 2 * (epptr() - _eback);
if (new_size == 0)
new_size = INITIAL_BUFFER_SIZE;
char* new_buffer = (char*)realloc(_eback, new_size);
if (new_buffer != _eback)
{
_pptr = new_buffer + (_pptr - _eback);
_gptr = new_buffer + (_gptr - _eback);
_eback = new_buffer;
}
setp(_pptr, new_buffer + new_size);
sputc(c);
setg(_eback, _gptr, pptr());
return 0;
}
int CurlStreamBuffer::underflow()
{
return EOF;
}
const char* CurlStreamBuffer::getErrorBuffer() const
{
return CurlErrorBuffer;
}
/****************************************************************************
*
* rest-get Iterator
*
****************************************************************************/
bool createTypeHelper(store::Item_t& result, xqpString type_name)
{
xqpString xs_ns = "http://www.w3.org/2001/XMLSchema";
xqpString xs_pre = "xs";
return GENV_ITEMFACTORY->createQName(result, xs_ns.theStrStore, xs_pre.theStrStore, type_name.theStrStore);
}
bool createQNameHelper(store::Item_t& result, xqpString name)
{
xqpString ns = ZORBA_REST_FN_NS;
xqpString pre = "zorba-rest";
return GENV_ITEMFACTORY->createQName(result, ns.getStore(), pre.getStore(), name.getStore());
}
bool createNodeHelper(store::Item_t parent, PlanState& planState, xqpString name, store::Item_t* result = NULL)
{
store::Item_t qname, temp_result, type_qname;
store::NsBindings bindings;
xqpStringStore_t baseUri = planState.theRuntimeCB->theStaticContext->final_baseuri().getStore();
createQNameHelper(qname, name);
createTypeHelper(type_qname, "untyped");
bool status = GENV_ITEMFACTORY->createElementNode(
temp_result,
parent,
-1,
qname,
type_qname,
true,
false,
false,
false,
bindings,
baseUri,
true);
if (result != NULL)
*result = temp_result;
return status;
}
bool createAttributeHelper(store::Item_t parent, xqpString name, xqpString value, store::Item_t* result = NULL)
{
store::Item_t qname, temp_result, str_item;
createQNameHelper(qname, name);
store::Item_t type_qname;
createTypeHelper(type_qname, "string");
GENV_ITEMFACTORY->createString(str_item, value.theStrStore);
GENV_ITEMFACTORY->createAttributeNode(
temp_result,
parent,
-1,
qname,
type_qname,
str_item,
false,
false);
if (result != NULL)
*result = temp_result;
return true;
}
/****************************************************************************
*
* rest-get Iterator
*
****************************************************************************/
ZorbaRestGetIteratorState::ZorbaRestGetIteratorState()
{
}
ZorbaRestGetIteratorState::~ZorbaRestGetIteratorState()
{
}
void
ZorbaRestGetIteratorState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
}
void
ZorbaRestGetIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
}
#ifdef ZORBA_WITH_TIDY
static int readSome(std::istream& stream, char *buffer, int maxlen) {
stream.read(buffer, maxlen);
return stream.gcount();
}
#endif
int processReply(store::Item_t& result,
PlanState& planState,
xqpString& lUriString,
int code,
std::vector<std::string>& headers,
CurlStreamBuffer* theStreamBuffer,
const char* tidyUserOpt,
bool ignore_payload = false)
{
int reply_code;
xqpString content_type;
store::Item_t payload, error_node, headers_node, text_code, status_code;
store::Item_t doc = NULL;
createNodeHelper(NULL, planState, "result", &result);
createNodeHelper(result, planState, "status-code", &status_code);
if (headers.size() == 0)
{
// No headers -- create error message node
xqpStringStore_t temp = new xqpStringStore(theStreamBuffer->getErrorBuffer());
createNodeHelper(result, planState, "error-message", &error_node);
GENV_ITEMFACTORY->createTextNode(text_code, error_node, -1, temp);
}
createNodeHelper(result, planState, "headers", &headers_node);
if (!ignore_payload)
createNodeHelper(result, planState, "payload", &payload);
if (headers.size() == 0)
{
// No headers, use cURL's error code.
reply_code = code;
}
else
{
if (parse_int_const_position<int>(headers.operator[](0), 9, reply_code, 1))
{
// No status code in the reply. Put a -1 in there.
reply_code = -1;
}
for (unsigned int i = 1; i < headers.size(); i++)
{
int pos = headers.operator[](i).find(':');
if (pos > -1)
{
store::Item_t header, header_value;
createNodeHelper(headers_node, planState, "header", &header);
xqpString name_string = headers.operator[](i).substr(0, pos);
createAttributeHelper(header, "name", name_string);
string temp = headers.operator[](i).substr(pos+2);
xqpString value_string = temp;
GENV_ITEMFACTORY->createTextNode(header_value, header, -1, value_string.theStrStore);
// extract content-type
if (name_string.lowercase() == "content-type")
content_type = temp;;
}
else
{
// invalid header, ignore it
}
}
}
xqpString temp = NumConversions::intToStr(reply_code);
GENV_ITEMFACTORY->createTextNode(text_code, status_code, -1, temp.theStrStore);
if ((!ignore_payload) && reply_code >= 200 && reply_code < 300)
{
int doc_type; // values: 3 - xml, 2 - text, 1 - everything else (base64), 0 - do nothing, document has bee processed.
if (content_type.theStrStore.getp() == NULL)
doc_type = 1;
else if (content_type.indexOf("application/xml") == 0
||
content_type.indexOf("application/xhtml") == 0
||
content_type.indexOf("text/xml") == 0
||
content_type.indexOf("text/xhtml") == 0) // XMLs
doc_type = 3;
else if (content_type.indexOf("+xml") > -1)
doc_type = 3;
else if (content_type == "text/html")
doc_type = 4;
else if (content_type.indexOf("text/") == 0)
doc_type = 2;
else
doc_type = 1;
switch (doc_type)
{
case 4:
{
store::Item_t temp;
if(tidyUserOpt == NULL)
{
std::istream is(theStreamBuffer);
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
}
else
{
#ifdef ZORBA_WITH_TIDY
std::string input;
char lBuf[1024];
int lRes = 0;
xqp_string diag, strOut;
std::istream lStream(theStreamBuffer);
while ( (lRes = readSome(lStream, lBuf, 1023)) > 0 ) {
lBuf[lRes] = 0;
input += lBuf;
}
int res = tidy(input.c_str(), strOut, diag, (NULL != tidyUserOpt? tidyUserOpt: NULL));
if( res < 0){
ZORBA_ERROR_DESC_OSS(API0036_TIDY_ERROR, diag.c_str());
}
std::istringstream is(strOut, istringstream::in);
#else
std::istream is(theStreamBuffer);
#endif
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
}
if (temp != NULL)
{
store::Iterator_t doc_children = temp->getChildren();
doc_children->open();
doc_children->next(doc);
CopyMode copyMode;
copyMode.theDoCopy = false;
doc->copy(payload, -1, CopyMode());
}
else
{
// xml could not parsed
ZORBA_ERROR(XQP0017_LOADER_PARSING_ERROR);
}
}
break;
case 3: // xml
{
store::Item_t temp;
std::istream is(theStreamBuffer);
temp = GENV_STORE.loadDocument(lUriString.theStrStore, is, false);
if (temp != NULL)
{
store::Iterator_t doc_children = temp->getChildren();
doc_children->open();
doc_children->next(doc);
CopyMode copyMode;
copyMode.theDoCopy = false;
doc->copy(payload, -1, CopyMode());
}
else
{
// xml could not be parsed
ZORBA_ERROR(XQP0017_LOADER_PARSING_ERROR);
}
}
break;
case 2: // text
{
store::Item_t temp_item;
stringstream str;
str << theStreamBuffer;
xqpString temp = str.str();
GENV_ITEMFACTORY->createTextNode(temp_item, payload, -1, temp.theStrStore);
}
break;
case 1: // base64
{
store::Item_t temp_item;
xqp_base64Binary base64;
std::istream is(theStreamBuffer);
xqpString temp = Base64::encode(is);
GENV_ITEMFACTORY->createTextNode(temp_item, payload, -1, temp.theStrStore);
}
break;
}
}
return 0;
}
static size_t getHeaderData(void *ptr, size_t size, size_t nmemb, void *aState)
{
ZorbaRestGetIteratorState* state = static_cast<ZorbaRestGetIteratorState*>(aState);
std::string temp(static_cast<char*>(ptr), size*nmemb-1);
if (temp.size() > 0)
{
if (temp[temp.size()-1] == 0x0D) // delete the 0xD at the end.
temp.erase(temp.end()-1);
state->headers->push_back(temp);
// std::cout << "header: " << temp << std::endl;
}
return size * nmemb;
}
static void setupConnection(ZorbaRestGetIteratorState* state, int get_method)
{
state->MultiHandle = curl_multi_init();
state->EasyHandle = curl_easy_init();
curl_easy_setopt(state->EasyHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(state->EasyHandle, CURLOPT_HEADERFUNCTION, getHeaderData);
curl_easy_setopt(state->EasyHandle, CURLOPT_WRITEHEADER, state);
if (get_method == 0)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPGET, 1);
else if (get_method == 1)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, 1);
else if (get_method == 2)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "PUT");
else if (get_method == 3)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "DELETE");
else if (get_method == 4)
curl_easy_setopt(state->EasyHandle, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_multi_add_handle(state->MultiHandle, state->EasyHandle);
state->headers = std::auto_ptr<std::vector<std::string> >(new std::vector<std::string>);
state->theStreamBuffer = new CurlStreamBuffer(state->MultiHandle, state->EasyHandle);
}
static void cleanupConnection(ZorbaRestGetIteratorState* state)
{
curl_multi_remove_handle(state->MultiHandle, state->EasyHandle);
curl_easy_cleanup(state->EasyHandle);
curl_multi_cleanup(state->MultiHandle);
state->theStreamBuffer = NULL;
state->headers.reset();
}
void processHeader(store::Item_t& headers, curl_slist** headers_list)
{
store::Iterator_t it;
store::Item_t child, name;
if (headers->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
return;
}
if (xqpString("headers") == headers->getNodeName()->getLocalName())
{
it = headers->getChildren();
it->open();
while (it->next(child))
processHeader(child, headers_list);
return;
}
it = headers->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
}
if (name.getp() == NULL)
{
// header without an associated name
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
return;
}
it = headers->getChildren();
it->open();
it->next(child);
if (child == NULL)
{
// HTTP header without a value
xqpString temp = xqpString(name->getStringValue()) + xqpString(": ");
*headers_list = curl_slist_append(*headers_list , temp.c_str());
}
else if (child->getNodeKind() == store::StoreConsts::textNode)
{
xqpString temp = xqpString(name->getStringValue()) + xqpString(": ") + child->getStringValue().getp();
*headers_list = curl_slist_append(*headers_list , temp.c_str());
}
else
{
ZORBA_ERROR(API0050_REST_ERROR_HEADER);
}
}
// Returns all the children of a node as a concatenated string (text nodes + serialized
// element nodes) in the children_string out-paramter, and sets the has_element_child flag
static void getSerializedChildren(store::Item_t node, xqpString& children_string, bool& has_element_child)
{
store::Iterator_t it;
store::Item_t child;
children_string = "";
has_element_child = false;
it = node->getChildren();
it->open();
while (it->next(child))
{
if (child->getNodeKind() == store::StoreConsts::textNode)
{
children_string += xqpString(child->getStringValue());
}
else if (child->getNodeKind() == store::StoreConsts::elementNode)
{
stringstream ss;
error::ErrorManager lErrorManager;
serializer ser(&lErrorManager);
ser.set_parameter("omit-xml-declaration","yes");
ser.serialize(child, ss);
children_string += ss.str().c_str();
has_element_child = true;
}
// ignore other nodes
}
}
static void processPayload(Item_t& payload_data, struct curl_httppost** first, struct curl_httppost** last)
{
store::Iterator_t it;
store::Item_t child, name, filename, content_type;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return;
}
if (xqpString("payload") == payload_data->getNodeName()->getLocalName())
{
it = payload_data->getChildren();
it->open();
while (it->next(child))
if (child->getNodeKind() == store::StoreConsts::elementNode)
processPayload(child, first, last);
return;
}
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
if (xqpString("filename") == child->getNodeName()->getLocalName())
filename = child;
if (xqpString("content-type") == child->getNodeName()->getLocalName())
content_type = child;
}
if (name.getp() == NULL)
{
// payload part without an associated name
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return;
}
if (filename.getp() != NULL)
{
if (content_type != NULL)
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_FILE, filename->getStringValue()->c_str(),
CURLFORM_CONTENTTYPE, content_type->getStringValue()->c_str(),
CURLFORM_END);
else curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_FILE, filename->getStringValue()->c_str(),
CURLFORM_END);
}
else
{
xqpString payload_string;
bool has_element_child;
getSerializedChildren(payload_data, payload_string, has_element_child);
if (has_element_child)
{
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_COPYCONTENTS, payload_string.c_str(),
CURLFORM_CONTENTTYPE, "text/html",
CURLFORM_END);
}
else
{
curl_formadd(first, last,
CURLFORM_COPYNAME, name->getStringValue()->c_str(),
CURLFORM_COPYCONTENTS, payload_string.c_str(),
CURLFORM_END);
}
}
}
static bool processSinglePayload(Item_t& payload_data, CURL* EasyHandle, curl_slist **headers_list, std::auto_ptr<char>& buffer)
{
store::Iterator_t it;
store::Item_t child, name, filename, content_type;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
return false;
if (xqpString("payload") != payload_data->getNodeName()->getLocalName())
return false;
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
if (xqpString("filename") == child->getNodeName()->getLocalName())
filename = child;
if (xqpString("content-type") == child->getNodeName()->getLocalName())
content_type = child;
}
if (content_type.getp() != NULL
&&
xqpString("multipart/form-data") == content_type->getStringValue().getp())
return false;
if (filename.getp() != NULL)
{
xqpString test = filename->getStringValue()->c_str();
ifstream ifs(filename->getStringValue()->c_str());
if (!ifs)
{
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return false;
}
filebuf* pbuf = ifs.rdbuf();
long size = pbuf->pubseekoff(0,ios::end,ios::in);
pbuf->pubseekpos(0,ios::in);
buffer = std::auto_ptr<char>(new char[size]);
#ifdef WIN32
pbuf->_Sgetn_s(buffer.get(), size, size);
#else
pbuf->sgetn(buffer.get(), size);
#endif
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDSIZE , size);
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDS, buffer.get());
if (content_type.getp() == NULL)
*headers_list = curl_slist_append(*headers_list, "Content-Type: application/octet-stream");
ifs.close();
}
else
{
xqpString payload_string;
bool has_element_child;
getSerializedChildren(payload_data, payload_string, has_element_child);
buffer = std::auto_ptr<char>(new char[payload_string.bytes()]);
memcpy(buffer.get(), payload_string.c_str(), payload_string.bytes());
// curl_easy_setopt(EasyHandle, CURLOPT_COPYPOSTFIELDS, payload_string.c_str());
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDSIZE , payload_string.bytes());
curl_easy_setopt(EasyHandle, CURLOPT_POSTFIELDS, buffer.get());
curl_easy_setopt(EasyHandle, CURLOPT_POST, 1);
if (content_type.getp() == NULL)
{
if (has_element_child)
*headers_list = curl_slist_append(*headers_list, "Content-Type: text/xml");
else
*headers_list = curl_slist_append(*headers_list, "Content-Type: text/plain");
}
}
if (content_type.getp() != NULL)
*headers_list = curl_slist_append(*headers_list,
(xqpString("Content-Type: ") + xqpString(content_type->getStringValue())).c_str());
return true;
}
static xqpString processGetPayload(Item_t& payload_data, xqpString& Uri)
{
store::Iterator_t it;
store::Item_t child, name;
if (payload_data->getNodeKind() != store::StoreConsts::elementNode)
{
// top node should be element node
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return Uri;
}
if (xqpString("payload") == payload_data->getNodeName()->getLocalName())
{
it = payload_data->getChildren();
it->open();
while (it->next(child))
if (child->getNodeKind() == store::StoreConsts::elementNode)
Uri = processGetPayload(child, Uri);
return Uri;
}
it = payload_data->getAttributes();
it->open();
while (it->next(child))
{
if (xqpString("name") == child->getNodeName()->getLocalName())
name = child;
}
if (name.getp() == NULL)
{
// payload part without an associated name
ZORBA_ERROR(API0051_REST_ERROR_PAYLOAD);
return Uri;
}
it = payload_data->getChildren();
it->open();
it->next(child);
if (child->getNodeKind() == store::StoreConsts::textNode)
{
xqpStringStore_t encoded_name = name->getStringValue()->encodeForUri();
xqpStringStore_t value = child->getStringValue()->encodeForUri();
if (Uri.indexOf("?") == -1)
Uri = Uri + "?" + encoded_name.getp() + "=" + value.getp();
else
Uri = Uri + "&" + encoded_name.getp() + "=" + value.getp();
}
return Uri;
}
bool ZorbaRestGetIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t item, lUri, payload_data, headers, tidyUserOpt;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
unsigned int index = 1;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 0);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST get() function.");
}
Uri = lUri->getStringValue()->str();
#ifdef ZORBA_WITH_TIDY
if(isGetTidy)
{
index = 2;
if (theChildren.size() > 1)
CONSUME(tidyUserOpt, 1);
}
#endif
if (theChildren.size() > index)
while (CONSUME(payload_data, index))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > (index + 1))
while (CONSUME(headers, (index + 1)))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that
//the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result,
planState,
Uri,
code,
*state->headers,
state->theStreamBuffer.getp(),
(tidyUserOpt!=NULL)?tidyUserOpt->getStringValue()->c_str():NULL);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestPostIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_httppost *first = NULL, *last = NULL;
curl_slist *headers_list = NULL;
std::auto_ptr<char> buffer;
int code;
bool single_payload = false;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 1);
if (CONSUME(lUri, 0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST post() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
{
store::Item_t payload_data;
int status = CONSUME(payload_data, 1);
if (status)
{
if (processSinglePayload(payload_data, state->EasyHandle, &headers_list, buffer))
{
single_payload = true;
}
else
{
processPayload(payload_data, &first, &last);
while (CONSUME(payload_data, 1))
processPayload(payload_data, &first, &last);
}
}
}
if (!single_payload)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, first);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
headers_list = curl_slist_append(headers_list , expect_buf);
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL);
curl_formfree(first);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestPutIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_httppost *first = NULL, *last = NULL;
curl_slist *headers_list = NULL;
std::auto_ptr<char> buffer;
int code;
bool single_payload = false;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 2);
if (CONSUME(lUri, 0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST put() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
{
store::Item_t payload_data;
int status = CONSUME(payload_data, 1);
if (status)
{
if (processSinglePayload(payload_data, state->EasyHandle, &headers_list, buffer))
{
single_payload = true;
}
else
{
processPayload(payload_data, &first, &last);
while (CONSUME(payload_data, 1))
processPayload(payload_data, &first, &last);
}
}
}
if (!single_payload)
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPPOST, first);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
headers_list = curl_slist_append(headers_list , expect_buf);
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL);
curl_formfree(first);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestDeleteIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 3);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST delete() function.");;
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
while (CONSUME(payload_data, 1))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL, true);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
bool ZorbaRestHeadIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t lUri, payload_data, headers;
xqpString Uri;
curl_slist *headers_list = NULL;
int code;
ZorbaRestGetIteratorState* state;
DEFAULT_STACK_INIT(ZorbaRestGetIteratorState, state, planState);
setupConnection(state, 4);
if (CONSUME(lUri,0) == false)
{
ZORBA_ERROR_DESC(XQP0020_INVALID_URI, "No URI given to the REST head() function.");
}
Uri = lUri->getStringValue()->str();
if (theChildren.size() > 1)
while (CONSUME(payload_data, 1))
Uri = processGetPayload(payload_data, Uri);
if (theChildren.size() > 2)
while (CONSUME(headers, 2))
processHeader(headers, &headers_list);
curl_easy_setopt(state->EasyHandle, CURLOPT_URL, Uri.c_str());
curl_easy_setopt(state->EasyHandle, CURLOPT_HTTPHEADER, headers_list );
#ifndef ZORBA_VERIFY_PEER_SSL_CERTIFICATE//default is to not verify root certif
curl_easy_setopt(state->EasyHandle, CURLOPT_SSL_VERIFYPEER, 0);
//but CURLOPT_SSL_VERIFYHOST is left default, value 2, meaning verify that the Common Name or Subject Alternate Name field in the certificate matches the name of the server
//tested with https://www.npr.org/rss/rss.php?id=1001
//about using ssl certs in curl: http://curl.haxx.se/docs/sslcerts.html
#else
#if defined WIN32
//set the root CA certificates file path
if(GENV.g_curl_root_CA_certificates_path[0])
curl_easy_setopt(state->EasyHandle, CURLOPT_CAINFO, GENV.g_curl_root_CA_certificates_path);
#endif
#endif
code = state->theStreamBuffer->multi_perform();
processReply(result, planState, Uri, code, *state->headers, state->theStreamBuffer.getp(), NULL, true);
curl_slist_free_all(headers_list);
cleanupConnection(state);
STACK_PUSH(true, state);
STACK_END (state);
}
} /* namespace zorba */
|
/*************************************************************************
*
* 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: translatechanges.cxx,v $
* $Revision: 1.12 $
*
* 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_configmgr.hxx"
#include "translatechanges.hxx"
#include "noderef.hxx"
#include "nodechange.hxx"
#include "nodechangeinfo.hxx"
#include "apifactory.hxx"
namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
namespace css = ::com::sun::star;
namespace uno = css::uno;
namespace lang = css::lang;
namespace util = css::util;
namespace beans = css::beans;
namespace container = css::container;
// ---------------------------------------------------------------------------------------------------
namespace configuration
{
class NodeChange;
class NodeChanges;
class Tree;
class NodeRef;
class NodeID;
}
// ---------------------------------------------------------------------------------------------------
namespace configapi
{
using configuration::Tree;
using configuration::TreeRef;
using configuration::Name;
using configuration::AbsolutePath;
using configuration::RelativePath;
using configuration::NodeRef;
using configuration::NodeID;
using configuration::NodeChangeInformation;
using configuration::NodeChangeData;
using configuration::NodeChangeLocation;
// ---------------------------------------------------------------------------------------------------
//interpreting NodeChanges
// resolve the relative path from a given base to the changed node
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree)
{
return resolveChangeLocation(aPath,aChange,aBaseTree,aBaseTree.getRootNode());
}
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree, NodeRef const& aBaseNode)
{
OSL_ENSURE(aChange.isValidLocation(), "Trying to resolve against change location that wasn't set up properly");
namespace Path = configuration::Path;
typedef Path::Iterator Iter;
Tree aChangeBaseTree = aChange.getBaseTree();
AbsolutePath aOuterBasePath = aBaseTree.getAbsolutePath(aBaseNode);
AbsolutePath aChangeBasePath = aChangeBaseTree.getAbsolutePath(aChange.getBaseNode());
Iter aChangeIt = aChangeBasePath.begin(), aChangeEnd = aChangeBasePath.end();
Iter aOuterIt = aOuterBasePath.begin(), aOuterEnd = aOuterBasePath.end();
// First by resolve the base node pathes
while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
{
if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
++aOuterIt;
++aChangeIt;
}
// Next consider the stored accessor
if (aChangeIt != aChangeEnd) // stepping outward - prepend
{
Path::Rep aRemaining(aChangeIt, aChangeEnd);
aPath = RelativePath(aRemaining).compose(aChange.getAccessor());
}
else if (aOuterIt == aOuterEnd) // exact match outside
{
aPath = aChange.getAccessor();
}
else //(aChangeIt == aChangeEnd) but outer left
{
RelativePath aAccessor = aChange.getAccessor();
aChangeIt = aAccessor.begin();
aChangeEnd = aAccessor.end();
// resolve the outer path against the change accessor
while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
{
if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
++aOuterIt;
++aChangeIt;
}
if (aOuterIt == aOuterEnd)
{
Path::Rep aRemaining(aChangeIt, aChangeEnd);
aPath = RelativePath( aRemaining );
}
}
return (aOuterIt == aOuterEnd); // resolved completely and assigned ??
}
// ---------------------------------------------------------------------------------------------------
// change path and base settings to start from the given base
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef)
{
return rebaseChange(aChange,_aBaseTreeRef,_aBaseTreeRef.getRootNode());
}
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef, NodeRef const& aBaseNode)
{
OSL_ENSURE(aChange.isValidLocation(), "Trying to rebase change location that wasn't set up properly");
Tree aBaseTree(_aBaseTreeRef);
RelativePath aNewPath;
if (resolveChangeLocation(aNewPath,aChange,aBaseTree,aBaseNode))
{
aChange.setBase( aBaseTree, aBaseNode);
aChange.setAccessor( aNewPath );
return true;
}
else
return false;
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects
bool resolveUnoObjects(UnoChange& aUnoChange, NodeChangeData const& aChange,
Factory& rFactory)
{
if (aChange.isSetChange())
{
//Check we have ElementTree
if ((aChange.element.newValue == NULL) &&
(aChange.element.oldValue == NULL))
{
if( ( aChange.unoData.newValue.getValue()!=NULL) ||
( aChange.unoData.newValue.getValue()!=NULL))
{
return true;
}
else return false;
}
//Check if complex or simple type
Tree aTree = aChange.isRemoveSetChange()?
aChange.getOldElementTree():
aChange.getNewElementTree();
NodeRef aNodeRef = aTree.getRootNode();
if (configuration::isStructuralNode(aTree, aNodeRef))
{
uno::Reference<uno::XInterface> aNewUnoObject = rFactory.findUnoElement(aChange.getNewElementNodeID());
uno::Reference<uno::XInterface> aOldUnoObject = rFactory.findUnoElement(aChange.getOldElementNodeID());
bool bFound = aNewUnoObject.is() || aOldUnoObject.is();
aUnoChange.newValue <<= aNewUnoObject;
aUnoChange.oldValue <<= aOldUnoObject;
return bFound;
}
else
{
aUnoChange.newValue = configuration::getSimpleElementValue(aTree, aNodeRef);
if (aChange.isReplaceSetChange() )
{
Tree aOldTree = aChange.getOldElementTree();
aNodeRef = aOldTree.getRootNode();
OSL_ENSURE(!configuration::isStructuralNode(aOldTree, aNodeRef), "resolveUnoObject types mismatch");
aUnoChange.oldValue = configuration::getSimpleElementValue(aOldTree, aNodeRef);
}
bool bFound = aUnoChange.newValue.hasValue() || aUnoChange.oldValue.hasValue();
return bFound;
}
}
else if (aChange.isValueChange())
{
aUnoChange.newValue = aChange.unoData.newValue;
aUnoChange.oldValue = aChange.unoData.oldValue;
return true;
}
else
{
return false;
}
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects inplace
bool resolveToUno(NodeChangeData& aChange, Factory& rFactory)
{
struct UnoChange aUnoChange;
if (resolveUnoObjects(aUnoChange,aChange, rFactory))
{
aChange.unoData.newValue = aUnoChange.newValue;
aChange.unoData.oldValue = aUnoChange.oldValue;
return true;
}
else
return false;
}
// ---------------------------------------------------------------------------------------------------
// building events
/// find the sending api object
void fillEventSource(lang::EventObject& rEvent, Tree const& aTree, NodeRef const& aNode, Factory& rFactory)
{
rEvent.Source = rFactory.findUnoElement( NodeID(aTree,aNode) );
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, Factory& rFactory)
{
fillChange(rChange,aInfo,aBaseTree,aBaseTree.getRootNode(),rFactory);
}
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, NodeRef const& aBaseNode, Factory& rFactory)
{
RelativePath aRelativePath;
if (!resolveChangeLocation(aRelativePath, aInfo.location, aBaseTree, aBaseNode))
OSL_ENSURE(false, "WARNING: Change is not part of the given Tree");
UnoChange aUnoChange;
if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
rChange.Accessor <<= aRelativePath.toString();
rChange.Element = aUnoChange.newValue;
rChange.ReplacedElement = aUnoChange.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
void fillChangeFromResolved(util::ElementChange& rChange, NodeChangeInformation const& aInfo)
{
rChange.Accessor <<= aInfo.location.getAccessor().toString();
rChange.Element = aInfo.change.unoData.newValue;
rChange.ReplacedElement = aInfo.change.unoData.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo
bool fillEventData(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory)
{
UnoChange aUnoChange;
if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
{
OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
return false;
}
rEvent.Accessor <<= aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.Element = aUnoChange.newValue;
rEvent.ReplacedElement = aUnoChange.oldValue;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo)
{
rEvent.Accessor <<= aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.Element = aInfo.change.unoData.newValue;
rEvent.ReplacedElement = aInfo.change.unoData.oldValue;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventData(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore)
{
if (!aInfo.isValueChange())
return false;
UnoChange aUnoChange;
if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
rEvent.PropertyName = aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.NewValue = aUnoChange.newValue;
rEvent.OldValue = aUnoChange.oldValue;
rEvent.PropertyHandle = -1;
rEvent.Further = bMore;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, bool bMore)
{
if (!aInfo.isValueChange())
return false;
rEvent.PropertyName = aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.NewValue = aInfo.change.unoData.newValue;
rEvent.OldValue = aInfo.change.unoData.oldValue;
rEvent.PropertyHandle = -1;
rEvent.Further = bMore;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
}
// ---------------------------------------------------------------------------------------------------
}
INTEGRATION: CWS sb88 (1.12.10); FILE MERGED
2008/06/03 15:29:46 sb 1.12.10.1: #i89553 applied patch by cmc
/*************************************************************************
*
* 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: translatechanges.cxx,v $
* $Revision: 1.13 $
*
* 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_configmgr.hxx"
#include "translatechanges.hxx"
#include "noderef.hxx"
#include "nodechange.hxx"
#include "nodechangeinfo.hxx"
#include "apifactory.hxx"
namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
namespace css = ::com::sun::star;
namespace uno = css::uno;
namespace lang = css::lang;
namespace util = css::util;
namespace beans = css::beans;
namespace container = css::container;
// ---------------------------------------------------------------------------------------------------
namespace configuration
{
class NodeChange;
class NodeChanges;
class Tree;
class NodeRef;
class NodeID;
}
// ---------------------------------------------------------------------------------------------------
namespace configapi
{
using configuration::Tree;
using configuration::TreeRef;
using configuration::Name;
using configuration::AbsolutePath;
using configuration::RelativePath;
using configuration::NodeRef;
using configuration::NodeID;
using configuration::NodeChangeInformation;
using configuration::NodeChangeData;
using configuration::NodeChangeLocation;
// ---------------------------------------------------------------------------------------------------
//interpreting NodeChanges
// resolve the relative path from a given base to the changed node
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree, NodeRef const& aBaseNode)
{
OSL_ENSURE(aChange.isValidLocation(), "Trying to resolve against change location that wasn't set up properly");
namespace Path = configuration::Path;
typedef Path::Iterator Iter;
Tree aChangeBaseTree = aChange.getBaseTree();
AbsolutePath aOuterBasePath = aBaseTree.getAbsolutePath(aBaseNode);
AbsolutePath aChangeBasePath = aChangeBaseTree.getAbsolutePath(aChange.getBaseNode());
Iter aChangeIt = aChangeBasePath.begin(), aChangeEnd = aChangeBasePath.end();
Iter aOuterIt = aOuterBasePath.begin(), aOuterEnd = aOuterBasePath.end();
// First by resolve the base node pathes
while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
{
if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
++aOuterIt;
++aChangeIt;
}
// Next consider the stored accessor
if (aChangeIt != aChangeEnd) // stepping outward - prepend
{
Path::Rep aRemaining(aChangeIt, aChangeEnd);
aPath = RelativePath(aRemaining).compose(aChange.getAccessor());
}
else if (aOuterIt == aOuterEnd) // exact match outside
{
aPath = aChange.getAccessor();
}
else //(aChangeIt == aChangeEnd) but outer left
{
RelativePath aAccessor = aChange.getAccessor();
aChangeIt = aAccessor.begin();
aChangeEnd = aAccessor.end();
// resolve the outer path against the change accessor
while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
{
if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
++aOuterIt;
++aChangeIt;
}
if (aOuterIt == aOuterEnd)
{
Path::Rep aRemaining(aChangeIt, aChangeEnd);
aPath = RelativePath( aRemaining );
}
}
return (aOuterIt == aOuterEnd); // resolved completely and assigned ??
}
// ---------------------------------------------------------------------------------------------------
// change path and base settings to start from the given base
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef)
{
return rebaseChange(aChange,_aBaseTreeRef,_aBaseTreeRef.getRootNode());
}
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef, NodeRef const& aBaseNode)
{
OSL_ENSURE(aChange.isValidLocation(), "Trying to rebase change location that wasn't set up properly");
Tree aBaseTree(_aBaseTreeRef);
RelativePath aNewPath;
if (resolveChangeLocation(aNewPath,aChange,aBaseTree,aBaseNode))
{
aChange.setBase( aBaseTree, aBaseNode);
aChange.setAccessor( aNewPath );
return true;
}
else
return false;
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects
bool resolveUnoObjects(UnoChange& aUnoChange, NodeChangeData const& aChange,
Factory& rFactory)
{
if (aChange.isSetChange())
{
//Check we have ElementTree
if ((aChange.element.newValue == NULL) &&
(aChange.element.oldValue == NULL))
{
if( ( aChange.unoData.newValue.getValue()!=NULL) ||
( aChange.unoData.newValue.getValue()!=NULL))
{
return true;
}
else return false;
}
//Check if complex or simple type
Tree aTree = aChange.isRemoveSetChange()?
aChange.getOldElementTree():
aChange.getNewElementTree();
NodeRef aNodeRef = aTree.getRootNode();
if (configuration::isStructuralNode(aTree, aNodeRef))
{
uno::Reference<uno::XInterface> aNewUnoObject = rFactory.findUnoElement(aChange.getNewElementNodeID());
uno::Reference<uno::XInterface> aOldUnoObject = rFactory.findUnoElement(aChange.getOldElementNodeID());
bool bFound = aNewUnoObject.is() || aOldUnoObject.is();
aUnoChange.newValue <<= aNewUnoObject;
aUnoChange.oldValue <<= aOldUnoObject;
return bFound;
}
else
{
aUnoChange.newValue = configuration::getSimpleElementValue(aTree, aNodeRef);
if (aChange.isReplaceSetChange() )
{
Tree aOldTree = aChange.getOldElementTree();
aNodeRef = aOldTree.getRootNode();
OSL_ENSURE(!configuration::isStructuralNode(aOldTree, aNodeRef), "resolveUnoObject types mismatch");
aUnoChange.oldValue = configuration::getSimpleElementValue(aOldTree, aNodeRef);
}
bool bFound = aUnoChange.newValue.hasValue() || aUnoChange.oldValue.hasValue();
return bFound;
}
}
else if (aChange.isValueChange())
{
aUnoChange.newValue = aChange.unoData.newValue;
aUnoChange.oldValue = aChange.unoData.oldValue;
return true;
}
else
{
return false;
}
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects inplace
bool resolveToUno(NodeChangeData& aChange, Factory& rFactory)
{
struct UnoChange aUnoChange;
if (resolveUnoObjects(aUnoChange,aChange, rFactory))
{
aChange.unoData.newValue = aUnoChange.newValue;
aChange.unoData.oldValue = aUnoChange.oldValue;
return true;
}
else
return false;
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, Factory& rFactory)
{
fillChange(rChange,aInfo,aBaseTree,aBaseTree.getRootNode(),rFactory);
}
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, NodeRef const& aBaseNode, Factory& rFactory)
{
RelativePath aRelativePath;
if (!resolveChangeLocation(aRelativePath, aInfo.location, aBaseTree, aBaseNode))
OSL_ENSURE(false, "WARNING: Change is not part of the given Tree");
UnoChange aUnoChange;
if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
rChange.Accessor <<= aRelativePath.toString();
rChange.Element = aUnoChange.newValue;
rChange.ReplacedElement = aUnoChange.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
void fillChangeFromResolved(util::ElementChange& rChange, NodeChangeInformation const& aInfo)
{
rChange.Accessor <<= aInfo.location.getAccessor().toString();
rChange.Element = aInfo.change.unoData.newValue;
rChange.ReplacedElement = aInfo.change.unoData.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo)
{
rEvent.Accessor <<= aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.Element = aInfo.change.unoData.newValue;
rEvent.ReplacedElement = aInfo.change.unoData.oldValue;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, bool bMore)
{
if (!aInfo.isValueChange())
return false;
rEvent.PropertyName = aInfo.location.getAccessor().getLocalName().getName().toString();
rEvent.NewValue = aInfo.change.unoData.newValue;
rEvent.OldValue = aInfo.change.unoData.oldValue;
rEvent.PropertyHandle = -1;
rEvent.Further = bMore;
return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
}
// ---------------------------------------------------------------------------------------------------
}
|
// AudioEndPointLibrary.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "AudioEndPointLibrary.h"
#include "MMNotificationClient.h"
#include <DefSoundEndpointColl.h>
#include <algorithm>
namespace AudioEndPoint {
// This is the constructor of a class that has been exported.
// see AudioEndPointLibrary.h for the class definition
CAudioEndPointLibrary::CAudioEndPointLibrary()
{
return;
}
HRESULT CAudioEndPointLibrary::OnDeviceStateChanged(LPCWSTR pwstr_device_id, DWORD dw_new_state)
{
auto m_playback = this->GetPlaybackDevices(DefSound::EDeviceState::All);
auto m_recording = this->GetRecordingDevices(DefSound::EDeviceState::All);
auto audio_device = find_if(m_playback.begin(), m_playback.end(),[pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
auto e_device_state = static_cast<DefSound::EDeviceState>(dw_new_state);
if(audio_device != m_playback.end())
{
auto prevState = (*audio_device)->GetEndPoint().m_State.state;
(*audio_device)->GetEndPoint().m_State.state = e_device_state;
Signals.DeviceStateChanged.Notify((*audio_device), prevState, e_device_state);
}
audio_device = find_if(m_recording.begin(), m_recording.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_recording.end())
{
auto prevState = (*audio_device)->GetEndPoint().m_State.state;
(*audio_device)->GetEndPoint().m_State.state = e_device_state;
Signals.DeviceStateChanged.Notify((*audio_device), prevState, e_device_state);
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDeviceRemoved(LPCWSTR pwstr_device_id)
{
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstr_default_device_id)
{
AudioDeviceList list;
if(flow == ::eRender)
{
list = this->GetPlaybackDevices(DefSound::EDeviceState::All);
}
else if(flow == ::eCapture)
{
list = this->GetRecordingDevices(DefSound::EDeviceState::All);
} else
{
return S_FALSE;
}
auto audio_device = find_if(list.begin(), list.end(), [pwstr_default_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_default_device_id) == 0;
});
if (audio_device != list.end())
{
Signals.DeviceDefaultChanged.Notify((*audio_device), role);
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDeviceAdded(LPCWSTR pwstr_device_id)
{
auto m_playback = this->GetPlaybackDevices(DefSound::EDeviceState::All);
auto m_recording = this->GetRecordingDevices(DefSound::EDeviceState::All);
auto audio_device = find_if(m_playback.begin(), m_playback.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_playback.end())
{
Signals.DeviceAdded.Notify(*audio_device);
}
audio_device = find_if(m_recording.begin(), m_recording.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_recording.end())
{
Signals.DeviceAdded.Notify(*audio_device);
}
return S_OK;
}
CAudioEndPointLibrary::~CAudioEndPointLibrary()
{
UnRegisterNotificationClient();
}
CAudioEndPointLibrary& CAudioEndPointLibrary::GetInstance()
{
static CAudioEndPointLibrary instance;
return instance;
}
AudioDeviceList CAudioEndPointLibrary::GetPlaybackDevices(DefSound::EDeviceState state) const
{
AudioDeviceList list;
auto collection = DefSound::CEndpointCollection(state, ::eRender);
for (auto &endpoint : collection.Get())
{
list.push_back(std::make_unique<AudioDevice>(endpoint, Playback));
}
return list;
}
AudioDeviceList CAudioEndPointLibrary::GetRecordingDevices(DefSound::EDeviceState state) const
{
AudioDeviceList list;
auto collection = DefSound::CEndpointCollection(state, ::eCapture);
for (auto &endpoint : collection.Get())
{
list.push_back(std::make_unique<AudioDevice>(endpoint, Playback));
}
return list;
}
HRESULT CAudioEndPointLibrary::RegisterNotificationClient()
{
HRESULT Result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if(!m_container.m_DeviceEnumerator)
{
Result = m_container.m_DeviceEnumerator.CreateInstance(__uuidof(MMDeviceEnumerator));
ReturnIfFailed(Result);
}
if (!m_container.m_notif_client) {
m_container.m_notif_client = new CMMNotificationClient;
Result = m_container.m_DeviceEnumerator->RegisterEndpointNotificationCallback(m_container.m_notif_client);
return Result;
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::UnRegisterNotificationClient() const
{
if (m_container.m_notif_client) {
HRESULT hr = m_container.m_DeviceEnumerator->UnregisterEndpointNotificationCallback(m_container.m_notif_client);
if(SUCCEEDED(hr))
{
m_container.m_notif_client->Release();
}
return hr;
}
return S_FALSE;
}
}
[FIX] Always release the Notification Client on unregister
// AudioEndPointLibrary.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "AudioEndPointLibrary.h"
#include "MMNotificationClient.h"
#include <DefSoundEndpointColl.h>
#include <algorithm>
namespace AudioEndPoint {
// This is the constructor of a class that has been exported.
// see AudioEndPointLibrary.h for the class definition
CAudioEndPointLibrary::CAudioEndPointLibrary()
{
this->RegisterNotificationClient();
}
CAudioEndPointLibrary::~CAudioEndPointLibrary()
{
this->UnRegisterNotificationClient();
}
HRESULT CAudioEndPointLibrary::OnDeviceStateChanged(LPCWSTR pwstr_device_id, DWORD dw_new_state)
{
auto m_playback = this->GetPlaybackDevices(DefSound::EDeviceState::All);
auto m_recording = this->GetRecordingDevices(DefSound::EDeviceState::All);
auto audio_device = find_if(m_playback.begin(), m_playback.end(),[pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
auto e_device_state = static_cast<DefSound::EDeviceState>(dw_new_state);
if(audio_device != m_playback.end())
{
auto prevState = (*audio_device)->GetEndPoint().m_State.state;
(*audio_device)->GetEndPoint().m_State.state = e_device_state;
Signals.DeviceStateChanged.Notify((*audio_device), prevState, e_device_state);
}
audio_device = find_if(m_recording.begin(), m_recording.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_recording.end())
{
auto prevState = (*audio_device)->GetEndPoint().m_State.state;
(*audio_device)->GetEndPoint().m_State.state = e_device_state;
Signals.DeviceStateChanged.Notify((*audio_device), prevState, e_device_state);
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDeviceRemoved(LPCWSTR pwstr_device_id)
{
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstr_default_device_id)
{
AudioDeviceList list;
if(flow == ::eRender)
{
list = this->GetPlaybackDevices(DefSound::EDeviceState::All);
}
else if(flow == ::eCapture)
{
list = this->GetRecordingDevices(DefSound::EDeviceState::All);
} else
{
return S_FALSE;
}
auto audio_device = find_if(list.begin(), list.end(), [pwstr_default_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_default_device_id) == 0;
});
if (audio_device != list.end())
{
Signals.DeviceDefaultChanged.Notify((*audio_device), role);
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::OnDeviceAdded(LPCWSTR pwstr_device_id)
{
auto m_playback = this->GetPlaybackDevices(DefSound::EDeviceState::All);
auto m_recording = this->GetRecordingDevices(DefSound::EDeviceState::All);
auto audio_device = find_if(m_playback.begin(), m_playback.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_playback.end())
{
Signals.DeviceAdded.Notify(*audio_device);
}
audio_device = find_if(m_recording.begin(), m_recording.end(), [pwstr_device_id](AudioDevicePtr device) {
return wcscmp(device->ID, pwstr_device_id) == 0;
});
if (audio_device != m_recording.end())
{
Signals.DeviceAdded.Notify(*audio_device);
}
return S_OK;
}
CAudioEndPointLibrary& CAudioEndPointLibrary::GetInstance()
{
static CAudioEndPointLibrary instance;
return instance;
}
AudioDeviceList CAudioEndPointLibrary::GetPlaybackDevices(DefSound::EDeviceState state) const
{
AudioDeviceList list;
auto collection = DefSound::CEndpointCollection(state, ::eRender);
for (auto &endpoint : collection.Get())
{
list.push_back(std::make_unique<AudioDevice>(endpoint, Playback));
}
return list;
}
AudioDeviceList CAudioEndPointLibrary::GetRecordingDevices(DefSound::EDeviceState state) const
{
AudioDeviceList list;
auto collection = DefSound::CEndpointCollection(state, ::eCapture);
for (auto &endpoint : collection.Get())
{
list.push_back(std::make_unique<AudioDevice>(endpoint, Playback));
}
return list;
}
HRESULT CAudioEndPointLibrary::RegisterNotificationClient()
{
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if(!m_container.m_DeviceEnumerator)
{
hr = m_container.m_DeviceEnumerator.CreateInstance(__uuidof(MMDeviceEnumerator));
ReturnIfFailed(hr);
}
if (!m_container.m_notif_client) {
m_container.m_notif_client = new CMMNotificationClient;
hr = m_container.m_DeviceEnumerator->RegisterEndpointNotificationCallback(m_container.m_notif_client);
return hr;
}
return S_OK;
}
HRESULT CAudioEndPointLibrary::UnRegisterNotificationClient() const
{
if (m_container.m_notif_client) {
m_container.m_notif_client->Release();
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
hr = m_container.m_DeviceEnumerator->UnregisterEndpointNotificationCallback(m_container.m_notif_client);
return hr;
}
return S_FALSE;
}
}
|
// 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 <string>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/scoped_temp_dir.h"
#include "base/string_number_conversions.h"
#include "base/test/test_suite.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/test_launcher/test_runner.h"
#include "chrome/test/unit/chrome_test_suite.h"
#if defined(OS_WIN)
#include "base/base_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/sandbox_policy.h"
#include "sandbox/src/dep.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/src/sandbox_types.h"
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);
#endif
// This version of the test launcher forks a new process for each test it runs.
namespace {
const char kGTestHelpFlag[] = "gtest_help";
const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestOutputFlag[] = "gtest_output";
const char kGTestRepeatFlag[] = "gtest_repeat";
const char kSingleProcessTestsFlag[] = "single_process";
const char kSingleProcessTestsAndChromeFlag[] = "single-process";
const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout";
// The following is kept for historical reasons (so people that are used to
// using it don't get surprised).
const char kChildProcessFlag[] = "child";
const char kHelpFlag[] = "help";
// How long we wait for the subprocess to exit (with a success/failure code).
// See http://crbug.com/43862 for some discussion of the value.
const int64 kDefaultTestTimeoutMs = 20000;
class OutOfProcTestRunner : public tests::TestRunner {
public:
OutOfProcTestRunner() {
}
virtual ~OutOfProcTestRunner() {
}
bool Init() {
return true;
}
// Returns true if the test succeeded, false if it failed.
bool RunTest(const std::string& test_name) {
// Some of the below method calls will leak objects if there is no
// autorelease pool in place.
base::ScopedNSAutoreleasePool pool;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
CommandLine new_cmd_line(cmd_line->GetProgram());
CommandLine::SwitchMap switches = cmd_line->GetSwitches();
// Strip out gtest_output flag because otherwise we would overwrite results
// of the previous test. We will generate the final output file later
// in RunTests().
switches.erase(kGTestOutputFlag);
// Strip out gtest_repeat flag because we can only run one test in the child
// process (restarting the browser in the same process is illegal after it
// has been shut down and will actually crash).
switches.erase(kGTestRepeatFlag);
// Strip out user-data-dir if present. We will add it back in again later.
switches.erase(switches::kUserDataDir);
for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
iter != switches.end(); ++iter) {
new_cmd_line.AppendSwitchNative((*iter).first, (*iter).second);
}
// Always enable disabled tests. This method is not called with disabled
// tests unless this flag was specified to the browser test executable.
new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
new_cmd_line.AppendSwitchASCII("gtest_filter", test_name);
new_cmd_line.AppendSwitch(kChildProcessFlag);
// Do not let the child ignore failures. We need to propagate the
// failure status back to the parent.
new_cmd_line.AppendSwitch(base::TestSuite::kStrictFailureHandling);
// Create a new user data dir and pass it to the child.
ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDir() || !temp_dir.IsValid()) {
LOG(ERROR) << "Error creating temp profile directory";
return false;
}
new_cmd_line.AppendSwitchPath(switches::kUserDataDir, temp_dir.path());
base::ProcessHandle process_handle;
#if defined(OS_POSIX)
// On POSIX, we launch the test in a new process group with pgid equal to
// its pid. Any child processes that the test may create will inherit the
// same pgid. This way, if the test is abruptly terminated, we can clean up
// any orphaned child processes it may have left behind.
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
if (!base::LaunchAppInNewProcessGroup(new_cmd_line.argv(), no_env, no_files,
false, &process_handle))
#else
if (!base::LaunchApp(new_cmd_line, false, false, &process_handle))
#endif
return false;
int test_terminate_timeout_ms = kDefaultTestTimeoutMs;
if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) {
std::string timeout_str =
cmd_line->GetSwitchValueASCII(kTestTerminateTimeoutFlag);
int timeout;
base::StringToInt(timeout_str, &timeout);
test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout);
}
int exit_code = 0;
if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code,
test_terminate_timeout_ms)) {
LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms
<< " ms) exceeded for " << test_name;
exit_code = -1; // Set a non-zero exit code to signal a failure.
// Ensure that the process terminates.
base::KillProcess(process_handle, -1, true);
#if defined(OS_POSIX)
// On POSIX, we need to clean up any child processes that the test might
// have created. On windows, child processes are automatically cleaned up
// using JobObjects.
base::KillProcessGroup(process_handle);
#endif
}
return exit_code == 0;
}
private:
DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner);
};
class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory {
public:
OutOfProcTestRunnerFactory() { }
virtual tests::TestRunner* CreateTestRunner() const {
return new OutOfProcTestRunner();
}
private:
DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory);
};
void PrintUsage() {
fprintf(stdout,
"Runs tests using the gtest framework, each test being run in its own\n"
"process. Any gtest flags can be specified.\n"
" --single_process\n"
" Runs the tests and the launcher in the same process. Useful for \n"
" debugging a specific test in a debugger.\n"
" --single-process\n"
" Same as above, and also runs Chrome in single-process mode.\n"
" --test-terminate-timeout\n"
" Specifies a timeout (in milliseconds) after which a running test\n"
" will be forcefully terminated.\n"
" --help\n"
" Shows this message.\n"
" --gtest_help\n"
" Shows the gtest help message.\n");
}
} // namespace
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kHelpFlag)) {
PrintUsage();
return 0;
}
// TODO(pkasting): This "single_process vs. single-process" design is terrible
// UI. Instead, there should be some sort of signal flag on the command line,
// with all subsequent arguments passed through to the underlying browser.
if (command_line->HasSwitch(kChildProcessFlag) ||
command_line->HasSwitch(kSingleProcessTestsFlag) ||
command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) ||
command_line->HasSwitch(kGTestListTestsFlag) ||
command_line->HasSwitch(kGTestHelpFlag)) {
#if defined(OS_WIN)
if (command_line->HasSwitch(kChildProcessFlag) ||
command_line->HasSwitch(kSingleProcessTestsFlag)) {
// This is the browser process, so setup the sandbox broker.
sandbox::BrokerServices* broker_services =
sandbox::SandboxFactory::GetBrokerServices();
if (broker_services) {
sandbox::InitBrokerServices(broker_services);
// Precreate the desktop and window station used by the renderers.
sandbox::TargetPolicy* policy = broker_services->CreatePolicy();
sandbox::ResultCode result = policy->CreateAlternateDesktop(true);
CHECK(sandbox::SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION != result);
policy->Release();
}
}
#endif
return ChromeTestSuite(argc, argv).Run();
}
#if defined(OS_WIN)
if (command_line->HasSwitch(switches::kProcessType)) {
// This is a child process, call ChromeMain.
FilePath chrome_path(command_line->GetProgram().DirName());
chrome_path = chrome_path.Append(chrome::kBrowserResourcesDll);
HMODULE dll = LoadLibrary(chrome_path.value().c_str());
DLL_MAIN entry_point =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll, "ChromeMain"));
if (!entry_point)
return -1;
// Initialize the sandbox services.
sandbox::SandboxInterfaceInfo sandbox_info = {0};
sandbox_info.target_services = sandbox::SandboxFactory::GetTargetServices();
return entry_point(GetModuleHandle(NULL), &sandbox_info, GetCommandLineW());
}
#endif
fprintf(stdout,
"Starting tests...\n"
"IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
"For debugging a test inside a debugger, use the\n"
"--gtest_filter=<your_test_name> flag along with either\n"
"--single_process (to run all tests in one launcher/browser process) or\n"
"--single-process (to do the above, and also run Chrome in single-\n"
"process mode).\n");
OutOfProcTestRunnerFactory test_runner_factory;
int cycles = 1;
if (command_line->HasSwitch(kGTestRepeatFlag)) {
base::StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag),
&cycles);
}
int exit_code = 0;
while (cycles != 0) {
if (!tests::RunTests(test_runner_factory)) {
exit_code = 1;
break;
}
// Special value "-1" means "repeat indefinitely".
if (cycles != -1)
cycles--;
}
return exit_code;
}
Correcting orphaned process cleanup in out_of_proc_test_runner.cc.
The fix in http://src.chromium.org/viewvc/chrome?view=rev&revision=60192
cleans up orphaned testserver processes only when a test times out and
is killed. However, when a test case crashes and does not trigger a time
out, the clean up doesn't happen.
This patch fixes the clean up logic, and makes sure that testservers are
killed if the test case did not exit cleanly.
BUG=55808
TEST=inject failures in a test suite that uses out_of_proc_test_runner
Review URL: http://codereview.chromium.org/3570004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@61112 0039d316-1c4b-4281-b951-d872f2087c98
// 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 <string>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/scoped_temp_dir.h"
#include "base/string_number_conversions.h"
#include "base/test/test_suite.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/test_launcher/test_runner.h"
#include "chrome/test/unit/chrome_test_suite.h"
#if defined(OS_WIN)
#include "base/base_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/sandbox_policy.h"
#include "sandbox/src/dep.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/src/sandbox_types.h"
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);
#endif
// This version of the test launcher forks a new process for each test it runs.
namespace {
const char kGTestHelpFlag[] = "gtest_help";
const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestOutputFlag[] = "gtest_output";
const char kGTestRepeatFlag[] = "gtest_repeat";
const char kSingleProcessTestsFlag[] = "single_process";
const char kSingleProcessTestsAndChromeFlag[] = "single-process";
const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout";
// The following is kept for historical reasons (so people that are used to
// using it don't get surprised).
const char kChildProcessFlag[] = "child";
const char kHelpFlag[] = "help";
// How long we wait for the subprocess to exit (with a success/failure code).
// See http://crbug.com/43862 for some discussion of the value.
const int64 kDefaultTestTimeoutMs = 20000;
class OutOfProcTestRunner : public tests::TestRunner {
public:
OutOfProcTestRunner() {
}
virtual ~OutOfProcTestRunner() {
}
bool Init() {
return true;
}
// Returns true if the test succeeded, false if it failed.
bool RunTest(const std::string& test_name) {
// Some of the below method calls will leak objects if there is no
// autorelease pool in place.
base::ScopedNSAutoreleasePool pool;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
CommandLine new_cmd_line(cmd_line->GetProgram());
CommandLine::SwitchMap switches = cmd_line->GetSwitches();
// Strip out gtest_output flag because otherwise we would overwrite results
// of the previous test. We will generate the final output file later
// in RunTests().
switches.erase(kGTestOutputFlag);
// Strip out gtest_repeat flag because we can only run one test in the child
// process (restarting the browser in the same process is illegal after it
// has been shut down and will actually crash).
switches.erase(kGTestRepeatFlag);
// Strip out user-data-dir if present. We will add it back in again later.
switches.erase(switches::kUserDataDir);
for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
iter != switches.end(); ++iter) {
new_cmd_line.AppendSwitchNative((*iter).first, (*iter).second);
}
// Always enable disabled tests. This method is not called with disabled
// tests unless this flag was specified to the browser test executable.
new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
new_cmd_line.AppendSwitchASCII("gtest_filter", test_name);
new_cmd_line.AppendSwitch(kChildProcessFlag);
// Do not let the child ignore failures. We need to propagate the
// failure status back to the parent.
new_cmd_line.AppendSwitch(base::TestSuite::kStrictFailureHandling);
// Create a new user data dir and pass it to the child.
ScopedTempDir temp_dir;
if (!temp_dir.CreateUniqueTempDir() || !temp_dir.IsValid()) {
LOG(ERROR) << "Error creating temp profile directory";
return false;
}
new_cmd_line.AppendSwitchPath(switches::kUserDataDir, temp_dir.path());
base::ProcessHandle process_handle;
#if defined(OS_POSIX)
// On POSIX, we launch the test in a new process group with pgid equal to
// its pid. Any child processes that the test may create will inherit the
// same pgid. This way, if the test is abruptly terminated, we can clean up
// any orphaned child processes it may have left behind.
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
if (!base::LaunchAppInNewProcessGroup(new_cmd_line.argv(), no_env, no_files,
false, &process_handle))
#else
if (!base::LaunchApp(new_cmd_line, false, false, &process_handle))
#endif
return false;
int test_terminate_timeout_ms = kDefaultTestTimeoutMs;
if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) {
std::string timeout_str =
cmd_line->GetSwitchValueASCII(kTestTerminateTimeoutFlag);
int timeout;
base::StringToInt(timeout_str, &timeout);
test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout);
}
int exit_code = 0;
if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code,
test_terminate_timeout_ms)) {
LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms
<< " ms) exceeded for " << test_name;
exit_code = -1; // Set a non-zero exit code to signal a failure.
// Ensure that the process terminates.
base::KillProcess(process_handle, -1, true);
}
#if defined(OS_POSIX)
if (exit_code != 0) {
// On POSIX, in case the test does not exit cleanly, either due to a crash
// or due to it timing out, we need to clean up any child processes that
// it might have created. On Windows, child processes are automatically
// cleaned up using JobObjects.
base::KillProcessGroup(process_handle);
}
#endif
return exit_code == 0;
}
private:
DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner);
};
class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory {
public:
OutOfProcTestRunnerFactory() { }
virtual tests::TestRunner* CreateTestRunner() const {
return new OutOfProcTestRunner();
}
private:
DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory);
};
void PrintUsage() {
fprintf(stdout,
"Runs tests using the gtest framework, each test being run in its own\n"
"process. Any gtest flags can be specified.\n"
" --single_process\n"
" Runs the tests and the launcher in the same process. Useful for \n"
" debugging a specific test in a debugger.\n"
" --single-process\n"
" Same as above, and also runs Chrome in single-process mode.\n"
" --test-terminate-timeout\n"
" Specifies a timeout (in milliseconds) after which a running test\n"
" will be forcefully terminated.\n"
" --help\n"
" Shows this message.\n"
" --gtest_help\n"
" Shows the gtest help message.\n");
}
} // namespace
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kHelpFlag)) {
PrintUsage();
return 0;
}
// TODO(pkasting): This "single_process vs. single-process" design is terrible
// UI. Instead, there should be some sort of signal flag on the command line,
// with all subsequent arguments passed through to the underlying browser.
if (command_line->HasSwitch(kChildProcessFlag) ||
command_line->HasSwitch(kSingleProcessTestsFlag) ||
command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) ||
command_line->HasSwitch(kGTestListTestsFlag) ||
command_line->HasSwitch(kGTestHelpFlag)) {
#if defined(OS_WIN)
if (command_line->HasSwitch(kChildProcessFlag) ||
command_line->HasSwitch(kSingleProcessTestsFlag)) {
// This is the browser process, so setup the sandbox broker.
sandbox::BrokerServices* broker_services =
sandbox::SandboxFactory::GetBrokerServices();
if (broker_services) {
sandbox::InitBrokerServices(broker_services);
// Precreate the desktop and window station used by the renderers.
sandbox::TargetPolicy* policy = broker_services->CreatePolicy();
sandbox::ResultCode result = policy->CreateAlternateDesktop(true);
CHECK(sandbox::SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION != result);
policy->Release();
}
}
#endif
return ChromeTestSuite(argc, argv).Run();
}
#if defined(OS_WIN)
if (command_line->HasSwitch(switches::kProcessType)) {
// This is a child process, call ChromeMain.
FilePath chrome_path(command_line->GetProgram().DirName());
chrome_path = chrome_path.Append(chrome::kBrowserResourcesDll);
HMODULE dll = LoadLibrary(chrome_path.value().c_str());
DLL_MAIN entry_point =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll, "ChromeMain"));
if (!entry_point)
return -1;
// Initialize the sandbox services.
sandbox::SandboxInterfaceInfo sandbox_info = {0};
sandbox_info.target_services = sandbox::SandboxFactory::GetTargetServices();
return entry_point(GetModuleHandle(NULL), &sandbox_info, GetCommandLineW());
}
#endif
fprintf(stdout,
"Starting tests...\n"
"IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
"For debugging a test inside a debugger, use the\n"
"--gtest_filter=<your_test_name> flag along with either\n"
"--single_process (to run all tests in one launcher/browser process) or\n"
"--single-process (to do the above, and also run Chrome in single-\n"
"process mode).\n");
OutOfProcTestRunnerFactory test_runner_factory;
int cycles = 1;
if (command_line->HasSwitch(kGTestRepeatFlag)) {
base::StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag),
&cycles);
}
int exit_code = 0;
while (cycles != 0) {
if (!tests::RunTests(test_runner_factory)) {
exit_code = 1;
break;
}
// Special value "-1" means "repeat indefinitely".
if (cycles != -1)
cycles--;
}
return exit_code;
}
|
// 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/process_singleton.h"
#include <shellapi.h>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/process/process.h"
#include "base/process/process_info.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/win/metro.h"
#include "base/win/registry.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "chrome/browser/chrome_process_finder_win.h"
#include "content/public/common/result_codes.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/win/hwnd_util.h"
namespace {
const char kLockfile[] = "lockfile";
// A helper class that acquires the given |mutex| while the AutoLockMutex is in
// scope.
class AutoLockMutex {
public:
explicit AutoLockMutex(HANDLE mutex) : mutex_(mutex) {
DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
}
~AutoLockMutex() {
BOOL released = ::ReleaseMutex(mutex_);
DPCHECK(released);
}
private:
HANDLE mutex_;
DISALLOW_COPY_AND_ASSIGN(AutoLockMutex);
};
// A helper class that releases the given |mutex| while the AutoUnlockMutex is
// in scope and immediately re-acquires it when going out of scope.
class AutoUnlockMutex {
public:
explicit AutoUnlockMutex(HANDLE mutex) : mutex_(mutex) {
BOOL released = ::ReleaseMutex(mutex_);
DPCHECK(released);
}
~AutoUnlockMutex() {
DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
}
private:
HANDLE mutex_;
DISALLOW_COPY_AND_ASSIGN(AutoUnlockMutex);
};
// Checks the visibility of the enumerated window and signals once a visible
// window has been found.
BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) {
bool* result = reinterpret_cast<bool*>(param);
*result = ::IsWindowVisible(window) != 0;
// Stops enumeration if a visible window has been found.
return !*result;
}
bool ParseCommandLine(const COPYDATASTRUCT* cds,
base::CommandLine* parsed_command_line,
base::FilePath* current_directory) {
// We should have enough room for the shortest command (min_message_size)
// and also be a multiple of wchar_t bytes. The shortest command
// possible is L"START\0\0" (empty current directory and command line).
static const int min_message_size = 7;
if (cds->cbData < min_message_size * sizeof(wchar_t) ||
cds->cbData % sizeof(wchar_t) != 0) {
LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
return false;
}
// We split the string into 4 parts on NULLs.
DCHECK(cds->lpData);
const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
cds->cbData / sizeof(wchar_t));
const std::wstring::size_type first_null = msg.find_first_of(L'\0');
if (first_null == 0 || first_null == std::wstring::npos) {
// no NULL byte, don't know what to do
LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
", first null = " << first_null;
return false;
}
// Decode the command, which is everything until the first NULL.
if (msg.substr(0, first_null) == L"START") {
// Another instance is starting parse the command line & do what it would
// have done.
VLOG(1) << "Handling STARTUP request from another process";
const std::wstring::size_type second_null =
msg.find_first_of(L'\0', first_null + 1);
if (second_null == std::wstring::npos ||
first_null == msg.length() - 1 || second_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs";
return false;
}
// Get current directory.
*current_directory = base::FilePath(msg.substr(first_null + 1,
second_null - first_null));
const std::wstring::size_type third_null =
msg.find_first_of(L'\0', second_null + 1);
if (third_null == std::wstring::npos ||
third_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs";
}
// Get command line.
const std::wstring cmd_line =
msg.substr(second_null + 1, third_null - second_null);
*parsed_command_line = base::CommandLine::FromString(cmd_line);
return true;
}
return false;
}
bool ProcessLaunchNotification(
const ProcessSingleton::NotificationCallback& notification_callback,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (message != WM_COPYDATA)
return false;
// Handle the WM_COPYDATA message from another process.
const COPYDATASTRUCT* cds = reinterpret_cast<COPYDATASTRUCT*>(lparam);
base::CommandLine parsed_command_line(base::CommandLine::NO_PROGRAM);
base::FilePath current_directory;
if (!ParseCommandLine(cds, &parsed_command_line, ¤t_directory)) {
*result = TRUE;
return true;
}
*result = notification_callback.Run(parsed_command_line, current_directory) ?
TRUE : FALSE;
return true;
}
bool TerminateAppWithError() {
// TODO: This is called when the secondary process can't ping the primary
// process. Need to find out what to do here.
return false;
}
} // namespace
ProcessSingleton::ProcessSingleton(
const base::FilePath& user_data_dir,
const NotificationCallback& notification_callback)
: notification_callback_(notification_callback),
is_virtualized_(false),
lock_file_(INVALID_HANDLE_VALUE),
user_data_dir_(user_data_dir),
should_kill_remote_process_callback_(
base::Bind(&TerminateAppWithError)) {
}
ProcessSingleton::~ProcessSingleton() {
if (lock_file_ != INVALID_HANDLE_VALUE)
::CloseHandle(lock_file_);
}
// Code roughly based on Mozilla.
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
if (is_virtualized_)
return PROCESS_NOTIFIED; // We already spawned the process in this case.
if (lock_file_ == INVALID_HANDLE_VALUE && !remote_window_) {
return LOCK_ERROR;
} else if (!remote_window_) {
return PROCESS_NONE;
}
switch (chrome::AttemptToNotifyRunningChrome(remote_window_, false)) {
case chrome::NOTIFY_SUCCESS:
return PROCESS_NOTIFIED;
case chrome::NOTIFY_FAILED:
remote_window_ = NULL;
return PROCESS_NONE;
case chrome::NOTIFY_WINDOW_HUNG:
// Fall through and potentially terminate the hung browser.
break;
}
DWORD process_id = 0;
DWORD thread_id = ::GetWindowThreadProcessId(remote_window_, &process_id);
if (!thread_id || !process_id) {
remote_window_ = NULL;
return PROCESS_NONE;
}
base::Process process = base::Process::Open(process_id);
// The window is hung. Scan for every window to find a visible one.
bool visible_window = false;
::EnumThreadWindows(thread_id,
&BrowserWindowEnumeration,
reinterpret_cast<LPARAM>(&visible_window));
// If there is a visible browser window, ask the user before killing it.
if (visible_window && !should_kill_remote_process_callback_.Run()) {
// The user denied. Quit silently.
return PROCESS_NOTIFIED;
}
// Time to take action. Kill the browser process.
process.Terminate(content::RESULT_CODE_HUNG, true);
remote_window_ = NULL;
return PROCESS_NONE;
}
ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessOrCreate() {
ProcessSingleton::NotifyResult result = PROCESS_NONE;
if (!Create()) {
result = NotifyOtherProcess();
if (result == PROCESS_NONE)
result = PROFILE_IN_USE;
} else {
// TODO: Figure out how to implement this
//g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
// *base::CommandLine::ForCurrentProcess());
}
return result;
}
// Look for a Chrome instance that uses the same profile directory. If there
// isn't one, create a message window with its title set to the profile
// directory path.
bool ProcessSingleton::Create() {
static const wchar_t kMutexName[] = L"Local\\AtomProcessSingletonStartup!";
remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
if (!remote_window_) {
// Make sure we will be the one and only process creating the window.
// We use a named Mutex since we are protecting against multi-process
// access. As documented, it's clearer to NOT request ownership on creation
// since it isn't guaranteed we will get it. It is better to create it
// without ownership and explicitly get the ownership afterward.
base::win::ScopedHandle only_me(::CreateMutex(NULL, FALSE, kMutexName));
if (!only_me.IsValid()) {
DPLOG(FATAL) << "CreateMutex failed";
return false;
}
AutoLockMutex auto_lock_only_me(only_me.Get());
// We now own the mutex so we are the only process that can create the
// window at this time, but we must still check if someone created it
// between the time where we looked for it above and the time the mutex
// was given to us.
remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
if (!remote_window_) {
// We have to make sure there is no Chrome instance running on another
// machine that uses the same profile.
base::FilePath lock_file_path = user_data_dir_.AppendASCII(kLockfile);
lock_file_ = ::CreateFile(lock_file_path.value().c_str(),
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
DWORD error = ::GetLastError();
LOG_IF(WARNING, lock_file_ != INVALID_HANDLE_VALUE &&
error == ERROR_ALREADY_EXISTS) << "Lock file exists but is writable.";
LOG_IF(ERROR, lock_file_ == INVALID_HANDLE_VALUE)
<< "Lock file can not be created! Error code: " << error;
if (lock_file_ != INVALID_HANDLE_VALUE) {
// Set the window's title to the path of our user data directory so
// other Chrome instances can decide if they should forward to us.
bool result = window_.CreateNamed(
base::Bind(&ProcessLaunchNotification, notification_callback_),
user_data_dir_.value());
CHECK(result && window_.hwnd());
}
}
}
return window_.hwnd() != NULL;
}
void ProcessSingleton::Cleanup() {
}
void ProcessSingleton::OverrideShouldKillRemoteProcessCallbackForTesting(
const ShouldKillRemoteProcessCallback& display_dialog_callback) {
should_kill_remote_process_callback_ = display_dialog_callback;
}
I don't think we need this
// 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/process_singleton.h"
#include <shellapi.h>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/process/process.h"
#include "base/process/process_info.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/win/metro.h"
#include "base/win/registry.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "chrome/browser/chrome_process_finder_win.h"
#include "content/public/common/result_codes.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/win/hwnd_util.h"
namespace {
const char kLockfile[] = "lockfile";
// A helper class that acquires the given |mutex| while the AutoLockMutex is in
// scope.
class AutoLockMutex {
public:
explicit AutoLockMutex(HANDLE mutex) : mutex_(mutex) {
DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
}
~AutoLockMutex() {
BOOL released = ::ReleaseMutex(mutex_);
DPCHECK(released);
}
private:
HANDLE mutex_;
DISALLOW_COPY_AND_ASSIGN(AutoLockMutex);
};
// A helper class that releases the given |mutex| while the AutoUnlockMutex is
// in scope and immediately re-acquires it when going out of scope.
class AutoUnlockMutex {
public:
explicit AutoUnlockMutex(HANDLE mutex) : mutex_(mutex) {
BOOL released = ::ReleaseMutex(mutex_);
DPCHECK(released);
}
~AutoUnlockMutex() {
DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
}
private:
HANDLE mutex_;
DISALLOW_COPY_AND_ASSIGN(AutoUnlockMutex);
};
// Checks the visibility of the enumerated window and signals once a visible
// window has been found.
BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) {
bool* result = reinterpret_cast<bool*>(param);
*result = ::IsWindowVisible(window) != 0;
// Stops enumeration if a visible window has been found.
return !*result;
}
bool ParseCommandLine(const COPYDATASTRUCT* cds,
base::CommandLine* parsed_command_line,
base::FilePath* current_directory) {
// We should have enough room for the shortest command (min_message_size)
// and also be a multiple of wchar_t bytes. The shortest command
// possible is L"START\0\0" (empty current directory and command line).
static const int min_message_size = 7;
if (cds->cbData < min_message_size * sizeof(wchar_t) ||
cds->cbData % sizeof(wchar_t) != 0) {
LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
return false;
}
// We split the string into 4 parts on NULLs.
DCHECK(cds->lpData);
const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
cds->cbData / sizeof(wchar_t));
const std::wstring::size_type first_null = msg.find_first_of(L'\0');
if (first_null == 0 || first_null == std::wstring::npos) {
// no NULL byte, don't know what to do
LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
", first null = " << first_null;
return false;
}
// Decode the command, which is everything until the first NULL.
if (msg.substr(0, first_null) == L"START") {
// Another instance is starting parse the command line & do what it would
// have done.
VLOG(1) << "Handling STARTUP request from another process";
const std::wstring::size_type second_null =
msg.find_first_of(L'\0', first_null + 1);
if (second_null == std::wstring::npos ||
first_null == msg.length() - 1 || second_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs";
return false;
}
// Get current directory.
*current_directory = base::FilePath(msg.substr(first_null + 1,
second_null - first_null));
const std::wstring::size_type third_null =
msg.find_first_of(L'\0', second_null + 1);
if (third_null == std::wstring::npos ||
third_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs";
}
// Get command line.
const std::wstring cmd_line =
msg.substr(second_null + 1, third_null - second_null);
*parsed_command_line = base::CommandLine::FromString(cmd_line);
return true;
}
return false;
}
bool ProcessLaunchNotification(
const ProcessSingleton::NotificationCallback& notification_callback,
UINT message,
WPARAM wparam,
LPARAM lparam,
LRESULT* result) {
if (message != WM_COPYDATA)
return false;
// Handle the WM_COPYDATA message from another process.
const COPYDATASTRUCT* cds = reinterpret_cast<COPYDATASTRUCT*>(lparam);
base::CommandLine parsed_command_line(base::CommandLine::NO_PROGRAM);
base::FilePath current_directory;
if (!ParseCommandLine(cds, &parsed_command_line, ¤t_directory)) {
*result = TRUE;
return true;
}
*result = notification_callback.Run(parsed_command_line, current_directory) ?
TRUE : FALSE;
return true;
}
bool TerminateAppWithError() {
// TODO: This is called when the secondary process can't ping the primary
// process. Need to find out what to do here.
return false;
}
} // namespace
ProcessSingleton::ProcessSingleton(
const base::FilePath& user_data_dir,
const NotificationCallback& notification_callback)
: notification_callback_(notification_callback),
is_virtualized_(false),
lock_file_(INVALID_HANDLE_VALUE),
user_data_dir_(user_data_dir),
should_kill_remote_process_callback_(
base::Bind(&TerminateAppWithError)) {
}
ProcessSingleton::~ProcessSingleton() {
if (lock_file_ != INVALID_HANDLE_VALUE)
::CloseHandle(lock_file_);
}
// Code roughly based on Mozilla.
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
if (is_virtualized_)
return PROCESS_NOTIFIED; // We already spawned the process in this case.
if (lock_file_ == INVALID_HANDLE_VALUE && !remote_window_) {
return LOCK_ERROR;
} else if (!remote_window_) {
return PROCESS_NONE;
}
switch (chrome::AttemptToNotifyRunningChrome(remote_window_, false)) {
case chrome::NOTIFY_SUCCESS:
return PROCESS_NOTIFIED;
case chrome::NOTIFY_FAILED:
remote_window_ = NULL;
return PROCESS_NONE;
case chrome::NOTIFY_WINDOW_HUNG:
// Fall through and potentially terminate the hung browser.
break;
}
DWORD process_id = 0;
DWORD thread_id = ::GetWindowThreadProcessId(remote_window_, &process_id);
if (!thread_id || !process_id) {
remote_window_ = NULL;
return PROCESS_NONE;
}
base::Process process = base::Process::Open(process_id);
// The window is hung. Scan for every window to find a visible one.
bool visible_window = false;
::EnumThreadWindows(thread_id,
&BrowserWindowEnumeration,
reinterpret_cast<LPARAM>(&visible_window));
// If there is a visible browser window, ask the user before killing it.
if (visible_window && !should_kill_remote_process_callback_.Run()) {
// The user denied. Quit silently.
return PROCESS_NOTIFIED;
}
// Time to take action. Kill the browser process.
process.Terminate(content::RESULT_CODE_HUNG, true);
remote_window_ = NULL;
return PROCESS_NONE;
}
ProcessSingleton::NotifyResult
ProcessSingleton::NotifyOtherProcessOrCreate() {
ProcessSingleton::NotifyResult result = PROCESS_NONE;
if (!Create()) {
result = NotifyOtherProcess();
if (result == PROCESS_NONE)
result = PROFILE_IN_USE;
}
return result;
}
// Look for a Chrome instance that uses the same profile directory. If there
// isn't one, create a message window with its title set to the profile
// directory path.
bool ProcessSingleton::Create() {
static const wchar_t kMutexName[] = L"Local\\AtomProcessSingletonStartup!";
remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
if (!remote_window_) {
// Make sure we will be the one and only process creating the window.
// We use a named Mutex since we are protecting against multi-process
// access. As documented, it's clearer to NOT request ownership on creation
// since it isn't guaranteed we will get it. It is better to create it
// without ownership and explicitly get the ownership afterward.
base::win::ScopedHandle only_me(::CreateMutex(NULL, FALSE, kMutexName));
if (!only_me.IsValid()) {
DPLOG(FATAL) << "CreateMutex failed";
return false;
}
AutoLockMutex auto_lock_only_me(only_me.Get());
// We now own the mutex so we are the only process that can create the
// window at this time, but we must still check if someone created it
// between the time where we looked for it above and the time the mutex
// was given to us.
remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
if (!remote_window_) {
// We have to make sure there is no Chrome instance running on another
// machine that uses the same profile.
base::FilePath lock_file_path = user_data_dir_.AppendASCII(kLockfile);
lock_file_ = ::CreateFile(lock_file_path.value().c_str(),
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
DWORD error = ::GetLastError();
LOG_IF(WARNING, lock_file_ != INVALID_HANDLE_VALUE &&
error == ERROR_ALREADY_EXISTS) << "Lock file exists but is writable.";
LOG_IF(ERROR, lock_file_ == INVALID_HANDLE_VALUE)
<< "Lock file can not be created! Error code: " << error;
if (lock_file_ != INVALID_HANDLE_VALUE) {
// Set the window's title to the path of our user data directory so
// other Chrome instances can decide if they should forward to us.
bool result = window_.CreateNamed(
base::Bind(&ProcessLaunchNotification, notification_callback_),
user_data_dir_.value());
CHECK(result && window_.hwnd());
}
}
}
return window_.hwnd() != NULL;
}
void ProcessSingleton::Cleanup() {
}
void ProcessSingleton::OverrideShouldKillRemoteProcessCallbackForTesting(
const ShouldKillRemoteProcessCallback& display_dialog_callback) {
should_kill_remote_process_callback_ = display_dialog_callback;
}
|
#include "server_functions.h"
#include <string.h>
#include <iostream>
#include <sstream>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <netdb.h>
#include <stdlib.h>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "rpc.h"
#include "constants.h"
#include "helper_function.h"
using namespace std;
//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN
static map<procedure_signature, list<server_info *> * > proc_loc_dict;
static list<server_function_info *> roundRobinList;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void registration_request_handler(RegisterRequestMessage * message, int sock){
char * name = message->getName();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
procedure_signature * key = new procedure_signature(name, argTypes);
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
int status = 0;
//if no key dosnt exist in map
if (proc_loc_dict.find(key) == proc_loc_dict.end()) {
//Adding to the map
//int *memArgTypes = copyArgTypes(argTypes);
//key = procedure_signature(name, memArgTypes);
proc_loc_dict[key] = new list<server_info *>();
server_info * entry = new server_info(server_identifier, port, sock);
//Adding to roundRobinList
server_function_info * info = new server_function_info(entry, key);
roundRobinList.push_back(info);
}else{
bool sameLoc = false;
list<service_info *> *hostList = proc_loc_dict.find[key];
for (list<service_info *>::iterator it = hostList->begin(); it != hostList->end(); it++) {
if(it == new_msg_loc){
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something
sameLoc = true;
}
}
//Same procedure signature, different location
if(!sameLoc){
hostList.push_back(new_msg_loc);
}
}
RegisterSuccessMessage * success_message = new RegisterSuccessMessage(status);
success_message->send(sock);
}
/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
int location_request_handler(LocRequestMessage * message, int sock){
bool exist = false;
for (list<server_function_info *>::iterator it = roundRobinList->begin(); it != roundRobinList->end(); it++){
//If the name are the same
if(it->ps->name == message->name && compareArr(it->ps->arrTypes, message->arrTypes)){
//When we have identified the correct procedure_signature use round robin and move that service to the end
roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
exist = true;
break;
}
}
if(exist){
LocSuccessMessage * success_message = new LocSuccessMessage(it->server_identifier, it->port);
success_message->send(sock);
}else{
LocFailureMessage * failure_message = new LocFailureMessage(0);
failure_message->send(sock);
}
return 0; //LOC_FAILURE
}
int request_handler(Segment * segment, int sock){
int retval;
if(segment.getType() == MSG_TYPE_LOC_REQUEST){ //'LOC_REQUEST'
retval = registration_request_handler(segment->getMessage(), sock);
}else if (segment.getType() == MSG_TYPE_REGISTER_REQUEST){ //'REGISTER'
retval = location_request_handler(segment->getMessage(), sock);
}
return retval;
}
//TODO:
//Create helper functions that can be used for rpcServer.cc
int main(){
vector<int> myConnections;
vector<int> myToRemove;
int status;
struct addrinfo hints;
struct addrinfo* servinfo;
struct addrinfo* p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
status = getaddrinfo(NULL, "0", &hints, &servinfo);
if (status != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return 0;
}
p = servinfo;
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen);
status = listen(sock, 5);
char hostname[256];
gethostname(hostname, 256);
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
getsockname(sock, (struct sockaddr *)&sin, &len);
stringstream ss;
ss << ntohs(sin.sin_port);
string ps = ss.str();
cout << "BINDER_ADDRESS " << hostname << endl;
cout << "BINDER_PORT " << ntohs(sin.sin_port) << endl;
fd_set readfds;
int n;
struct sockaddr_storage their_addr;
while(true){
//CONNECTIONS VECTOR
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
n = sock;
for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
int connection = *it;
FD_SET(connection, &readfds);
if (connection > n){
n = connection;
}
}
n = n+1;
status = select(n, &readfds, NULL, NULL, NULL);
if (status == -1) {
cerr << "ERROR: select failed." << endl;
} else {
if (FD_ISSET(sock, &readfds)) {
socklen_t addr_size = sizeof their_addr;
int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size);
if (new_sock < 0) {
cerr << "ERROR: while accepting connection" << endl;
close(new_sock);
continue;
}
myConnections.push_back(new_sock);
} else {
for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
int tempConnection = *it;
if (FD_ISSET(tempConnection, &readfds)) {
Segment * segment = null;
Segment::receive(sock, segment, status);
if (status < 0) {
RegisterFailureMessage * failure_message = new RegisterFailureMessage(status);
failure_message->send(sock);
return errorMsg;
}
if (status == 0) {
// client has closed the connection
myToRemove.push_back(sock);
return errorMsg;
}
request_handler(segment, sock);
}
}
}
for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
close(*it);
}
myToRemove.clear();
}
}
freeaddrinfo(servinfo);
}
update
#include "server_functions.h"
#include <string.h>
#include <iostream>
#include <sstream>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <netdb.h>
#include <stdlib.h>
#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "rpc.h"
#include "constants.h"
#include "helper_function.h"
using namespace std;
//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN
static map<procedure_signature, list<server_info *> * > proc_loc_dict;
static list<server_function_info *> roundRobinList;
/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/
void registration_request_handler(RegisterRequestMessage * message, int sock){
char * name = message->getName();
int * argTypes = message->getArgTypes();
string server_identifier = message->getServerIdentifier();
int port = message->getPort();
procedure_signature * key = new procedure_signature(name, argTypes);
server_info * new_msg_loc = new server_info(server_identifier, port, sock);
int status = 0;
//if no key dosnt exist in map
if (proc_loc_dict.find(key) == proc_loc_dict.end()) {
//Adding to the map
//int *memArgTypes = copyArgTypes(argTypes);
//key = procedure_signature(name, memArgTypes);
proc_loc_dict[key] = new list<server_info *>();
server_info * entry = new server_info(server_identifier, port, sock);
//Adding to roundRobinList
server_function_info * info = new server_function_info(entry, key);
roundRobinList.push_back(info);
}else{
bool sameLoc = false;
list<service_info *> *hostList = proc_loc_dict.find[key];
for (list<service_info *>::iterator it = hostList->begin(); it != hostList->end(); it++) {
if(it == new_msg_loc){
//The same procedure signature already exists on the same location
//TODO: Move to end of round robin or something
sameLoc = true;
}
}
//Same procedure signature, different location
if(!sameLoc){
hostList.push_back(new_msg_loc);
}
}
RegisterSuccessMessage * success_message = new RegisterSuccessMessage(status);
success_message->send(sock);
}
/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
int location_request_handler(LocRequestMessage * message, int sock){
bool exist = false;
for (list<server_function_info *>::iterator it = roundRobinList->begin(); it != roundRobinList->end(); it++){
//If the name are the same
if(it->ps->name == message->getName() && compareArr(it->ps->argTypes, message->getArgTypes() )){
//When we have identified the correct procedure_signature use round robin and move that service to the end
roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
exist = true;
break;
}
}
if(exist){
LocSuccessMessage * success_message = new LocSuccessMessage(it->server_identifier, it->port);
success_message->send(sock);
}else{
LocFailureMessage * failure_message = new LocFailureMessage(0);
failure_message->send(sock);
}
return 0; //LOC_FAILURE
}
int request_handler(Segment * segment, int sock){
int retval;
if(segment.getType() == MSG_TYPE_LOC_REQUEST){ //'LOC_REQUEST'
retval = registration_request_handler(segment->getMessage(), sock);
}else if (segment.getType() == MSG_TYPE_REGISTER_REQUEST){ //'REGISTER'
retval = location_request_handler(segment->getMessage(), sock);
}
return retval;
}
//TODO:
//Create helper functions that can be used for rpcServer.cc
int main(){
vector<int> myConnections;
vector<int> myToRemove;
int status;
struct addrinfo hints;
struct addrinfo* servinfo;
struct addrinfo* p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
status = getaddrinfo(NULL, "0", &hints, &servinfo);
if (status != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return 0;
}
p = servinfo;
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
status = bind(sock, servinfo->ai_addr, servinfo->ai_addrlen);
status = listen(sock, 5);
char hostname[256];
gethostname(hostname, 256);
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
getsockname(sock, (struct sockaddr *)&sin, &len);
stringstream ss;
ss << ntohs(sin.sin_port);
string ps = ss.str();
cout << "BINDER_ADDRESS " << hostname << endl;
cout << "BINDER_PORT " << ntohs(sin.sin_port) << endl;
fd_set readfds;
int n;
struct sockaddr_storage their_addr;
while(true){
//CONNECTIONS VECTOR
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
n = sock;
for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
int connection = *it;
FD_SET(connection, &readfds);
if (connection > n){
n = connection;
}
}
n = n+1;
status = select(n, &readfds, NULL, NULL, NULL);
if (status == -1) {
cerr << "ERROR: select failed." << endl;
} else {
if (FD_ISSET(sock, &readfds)) {
socklen_t addr_size = sizeof their_addr;
int new_sock = accept(sock, (struct sockaddr*)&their_addr, &addr_size);
if (new_sock < 0) {
cerr << "ERROR: while accepting connection" << endl;
close(new_sock);
continue;
}
myConnections.push_back(new_sock);
} else {
for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
int tempConnection = *it;
if (FD_ISSET(tempConnection, &readfds)) {
Segment * segment = null;
Segment::receive(sock, segment, status);
if (status < 0) {
RegisterFailureMessage * failure_message = new RegisterFailureMessage(status);
failure_message->send(sock);
return errorMsg;
}
if (status == 0) {
// client has closed the connection
myToRemove.push_back(sock);
return errorMsg;
}
request_handler(segment, sock);
}
}
}
for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
close(*it);
}
myToRemove.clear();
}
}
freeaddrinfo(servinfo);
}
|
#include "../include/base_realsense_node.h"
#include "../include/sr300_node.h"
using namespace realsense2_camera;
std::string BaseRealSenseNode::getNamespaceStr()
{
auto ns = ros::this_node::getNamespace();
ns.erase(std::remove(ns.begin(), ns.end(), '/'), ns.end());
return ns;
}
BaseRealSenseNode::BaseRealSenseNode(ros::NodeHandle& nodeHandle,
ros::NodeHandle& privateNodeHandle,
rs2::device dev,
const std::string& serial_no) :
_dev(dev), _node_handle(nodeHandle),
_pnh(privateNodeHandle), _json_file_path(""),
_serial_no(serial_no), _base_frame_id(""),
_intialize_time_base(false),
_namespace(getNamespaceStr())
{
// Types for depth stream
_is_frame_arrived[DEPTH] = false;
_format[DEPTH] = RS2_FORMAT_Z16; // libRS type
_image_format[DEPTH] = CV_16UC1; // CVBridge type
_encoding[DEPTH] = sensor_msgs::image_encodings::TYPE_16UC1; // ROS message type
_unit_step_size[DEPTH] = sizeof(uint16_t); // sensor_msgs::ImagePtr row step size
_stream_name[DEPTH] = "depth";
_depth_aligned_encoding[DEPTH] = sensor_msgs::image_encodings::TYPE_16UC1;
// Infrared stream - Left
_is_frame_arrived[INFRA1] = false;
_format[INFRA1] = RS2_FORMAT_Y8; // libRS type
_image_format[INFRA1] = CV_8UC1; // CVBridge type
_encoding[INFRA1] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[INFRA1] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[INFRA1] = "infra1";
_depth_aligned_encoding[INFRA1] = sensor_msgs::image_encodings::TYPE_16UC1;
// Infrared stream - Right
_is_frame_arrived[INFRA2] = false;
_format[INFRA2] = RS2_FORMAT_Y8; // libRS type
_image_format[INFRA2] = CV_8UC1; // CVBridge type
_encoding[INFRA2] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[INFRA2] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[INFRA2] = "infra2";
_depth_aligned_encoding[INFRA2] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for color stream
_is_frame_arrived[COLOR] = false;
_format[COLOR] = RS2_FORMAT_RGB8; // libRS type
_image_format[COLOR] = CV_8UC3; // CVBridge type
_encoding[COLOR] = sensor_msgs::image_encodings::RGB8; // ROS message type
_unit_step_size[COLOR] = 3; // sensor_msgs::ImagePtr row step size
_stream_name[COLOR] = "color";
_depth_aligned_encoding[COLOR] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for fisheye stream
_is_frame_arrived[FISHEYE] = false;
_format[FISHEYE] = RS2_FORMAT_RAW8; // libRS type
_image_format[FISHEYE] = CV_8UC1; // CVBridge type
_encoding[FISHEYE] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[FISHEYE] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[FISHEYE] = "fisheye";
_depth_aligned_encoding[FISHEYE] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for Motion-Module streams
_is_frame_arrived[GYRO] = false;
_format[GYRO] = RS2_FORMAT_MOTION_XYZ32F; // libRS type
_image_format[GYRO] = CV_8UC1; // CVBridge type
_encoding[GYRO] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[GYRO] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[GYRO] = "gyro";
_is_frame_arrived[ACCEL] = false;
_format[ACCEL] = RS2_FORMAT_MOTION_XYZ32F; // libRS type
_image_format[ACCEL] = CV_8UC1; // CVBridge type
_encoding[ACCEL] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[ACCEL] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[ACCEL] = "accel";
}
void BaseRealSenseNode::publishTopics()
{
getParameters();
setupDevice();
setupPublishers();
setupStreams();
publishStaticTransforms();
ROS_INFO_STREAM("RealSense Node Is Up!");
}
void BaseRealSenseNode::registerDynamicReconfigCb()
{
ROS_INFO("Dynamic reconfig parameters is not implemented in the base node.");
}
void BaseRealSenseNode::getParameters()
{
ROS_INFO("getParameters...");
_pnh.param("align_depth", _align_depth, ALIGN_DEPTH);
_pnh.param("enable_pointcloud", _pointcloud, POINTCLOUD);
_pnh.param("enable_sync", _sync_frames, SYNC_FRAMES);
if (_pointcloud || _align_depth)
_sync_frames = true;
_pnh.param("json_file_path", _json_file_path, std::string(""));
_pnh.param("depth_width", _width[DEPTH], DEPTH_WIDTH);
_pnh.param("depth_height", _height[DEPTH], DEPTH_HEIGHT);
_pnh.param("depth_fps", _fps[DEPTH], DEPTH_FPS);
_pnh.param("enable_depth", _enable[DEPTH], ENABLE_DEPTH);
_aligned_depth_images[DEPTH].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("infra1_width", _width[INFRA1], INFRA1_WIDTH);
_pnh.param("infra1_height", _height[INFRA1], INFRA1_HEIGHT);
_pnh.param("infra1_fps", _fps[INFRA1], INFRA1_FPS);
_pnh.param("enable_infra1", _enable[INFRA1], ENABLE_INFRA1);
_aligned_depth_images[INFRA1].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("infra2_width", _width[INFRA2], INFRA2_WIDTH);
_pnh.param("infra2_height", _height[INFRA2], INFRA2_HEIGHT);
_pnh.param("infra2_fps", _fps[INFRA2], INFRA2_FPS);
_pnh.param("enable_infra2", _enable[INFRA2], ENABLE_INFRA2);
_aligned_depth_images[INFRA2].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("color_width", _width[COLOR], COLOR_WIDTH);
_pnh.param("color_height", _height[COLOR], COLOR_HEIGHT);
_pnh.param("color_fps", _fps[COLOR], COLOR_FPS);
_pnh.param("enable_color", _enable[COLOR], ENABLE_COLOR);
_aligned_depth_images[COLOR].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("fisheye_width", _width[FISHEYE], FISHEYE_WIDTH);
_pnh.param("fisheye_height", _height[FISHEYE], FISHEYE_HEIGHT);
_pnh.param("fisheye_fps", _fps[FISHEYE], FISHEYE_FPS);
_pnh.param("enable_fisheye", _enable[FISHEYE], ENABLE_FISHEYE);
_aligned_depth_images[FISHEYE].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("gyro_fps", _fps[GYRO], GYRO_FPS);
_pnh.param("accel_fps", _fps[ACCEL], ACCEL_FPS);
_pnh.param("enable_imu", _enable[GYRO], ENABLE_IMU);
_pnh.param("enable_imu", _enable[ACCEL], ENABLE_IMU);
_pnh.param("base_frame_id", _base_frame_id, DEFAULT_BASE_FRAME_ID);
_pnh.param("depth_frame_id", _frame_id[DEPTH], DEFAULT_DEPTH_FRAME_ID);
_pnh.param("infra1_frame_id", _frame_id[INFRA1], DEFAULT_INFRA1_FRAME_ID);
_pnh.param("infra2_frame_id", _frame_id[INFRA2], DEFAULT_INFRA2_FRAME_ID);
_pnh.param("color_frame_id", _frame_id[COLOR], DEFAULT_COLOR_FRAME_ID);
_pnh.param("fisheye_frame_id", _frame_id[FISHEYE], DEFAULT_FISHEYE_FRAME_ID);
_pnh.param("imu_gyro_frame_id", _frame_id[GYRO], DEFAULT_IMU_FRAME_ID);
_pnh.param("imu_accel_frame_id", _frame_id[ACCEL], DEFAULT_IMU_FRAME_ID);
_pnh.param("depth_optical_frame_id", _optical_frame_id[DEPTH], DEFAULT_DEPTH_OPTICAL_FRAME_ID);
_pnh.param("infra1_optical_frame_id", _optical_frame_id[INFRA1], DEFAULT_INFRA1_OPTICAL_FRAME_ID);
_pnh.param("infra2_optical_frame_id", _optical_frame_id[INFRA2], DEFAULT_INFRA2_OPTICAL_FRAME_ID);
_pnh.param("color_optical_frame_id", _optical_frame_id[COLOR], DEFAULT_COLOR_OPTICAL_FRAME_ID);
_pnh.param("fisheye_optical_frame_id", _optical_frame_id[FISHEYE], DEFAULT_FISHEYE_OPTICAL_FRAME_ID);
_pnh.param("gyro_optical_frame_id", _optical_frame_id[GYRO], DEFAULT_GYRO_OPTICAL_FRAME_ID);
_pnh.param("accel_optical_frame_id", _optical_frame_id[ACCEL], DEFAULT_ACCEL_OPTICAL_FRAME_ID);
_pnh.param("aligned_depth_to_color_frame_id", _depth_aligned_frame_id[COLOR], DEFAULT_ALIGNED_DEPTH_TO_COLOR_FRAME_ID);
_pnh.param("aligned_depth_to_infra1_frame_id", _depth_aligned_frame_id[INFRA1], DEFAULT_ALIGNED_DEPTH_TO_INFRA1_FRAME_ID);
_pnh.param("aligned_depth_to_infra2_frame_id", _depth_aligned_frame_id[INFRA2], DEFAULT_ALIGNED_DEPTH_TO_INFRA2_FRAME_ID);
_pnh.param("aligned_depth_to_fisheye_frame_id", _depth_aligned_frame_id[FISHEYE], DEFAULT_ALIGNED_DEPTH_TO_FISHEYE_FRAME_ID);
}
void BaseRealSenseNode::setupDevice()
{
ROS_INFO("setupDevice...");
try{
if (!_json_file_path.empty())
{
if (_dev.is<rs400::advanced_mode>())
{
std::stringstream ss;
std::ifstream in(_json_file_path);
if (in.is_open())
{
ss << in.rdbuf();
std::string json_file_content = ss.str();
auto adv = _dev.as<rs400::advanced_mode>();
adv.load_json(json_file_content);
ROS_INFO_STREAM("JSON file is loaded! (" << _json_file_path << ")");
}
else
ROS_WARN_STREAM("JSON file provided doesn't exist! (" << _json_file_path << ")");
}
else
ROS_WARN("Device does not support advanced settings!");
}
else
ROS_INFO("JSON file is not provided");
ROS_INFO_STREAM("ROS Node Namespace: " << _namespace);
auto camera_name = _dev.get_info(RS2_CAMERA_INFO_NAME);
ROS_INFO_STREAM("Device Name: " << camera_name);
ROS_INFO_STREAM("Device Serial No: " << _serial_no);
auto fw_ver = _dev.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION);
ROS_INFO_STREAM("Device FW version: " << fw_ver);
auto pid = _dev.get_info(RS2_CAMERA_INFO_PRODUCT_ID);
ROS_INFO_STREAM("Device Product ID: 0x" << pid);
ROS_INFO_STREAM("Enable PointCloud: " << ((_pointcloud)?"On":"Off"));
ROS_INFO_STREAM("Align Depth: " << ((_align_depth)?"On":"Off"));
ROS_INFO_STREAM("Sync Mode: " << ((_sync_frames)?"On":"Off"));
auto dev_sensors = _dev.query_sensors();
ROS_INFO_STREAM("Device Sensors: ");
for(auto&& elem : dev_sensors)
{
std::string module_name = elem.get_info(RS2_CAMERA_INFO_NAME);
if ("Stereo Module" == module_name)
{
_sensors[DEPTH] = elem;
_sensors[INFRA1] = elem;
_sensors[INFRA2] = elem;
}
else if ("Coded-Light Depth Sensor" == module_name)
{
_sensors[DEPTH] = elem;
_sensors[INFRA1] = elem;
}
else if ("RGB Camera" == module_name)
{
_sensors[COLOR] = elem;
}
else if ("Wide FOV Camera" == module_name)
{
_sensors[FISHEYE] = elem;
}
else if ("Motion Module" == module_name)
{
_sensors[GYRO] = elem;
_sensors[ACCEL] = elem;
}
else
{
ROS_ERROR_STREAM("Module Name \"" << module_name << "\" isn't supported by LibRealSense! Terminating RealSense Node...");
ros::shutdown();
exit(1);
}
ROS_INFO_STREAM(std::string(elem.get_info(RS2_CAMERA_INFO_NAME)) << " was found.");
}
// Update "enable" map
std::vector<std::vector<stream_index_pair>> streams(IMAGE_STREAMS);
streams.insert(streams.end(), HID_STREAMS.begin(), HID_STREAMS.end());
for (auto& elem : streams)
{
for (auto& stream_index : elem)
{
if (_enable[stream_index] && _sensors.find(stream_index) == _sensors.end()) // check if device supports the enabled stream
{
ROS_INFO_STREAM("(" << rs2_stream_to_string(stream_index.first) << ", " << stream_index.second << ") sensor isn't supported by current device! -- Skipping...");
_enable[stream_index] = false;
}
}
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An exception has been thrown: " << ex.what());
throw;
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception has occured!");
throw;
}
}
void BaseRealSenseNode::setupPublishers()
{
ROS_INFO("setupPublishers...");
image_transport::ImageTransport image_transport(_node_handle);
std::vector<stream_index_pair> image_stream_types;
for (auto& stream_vec : IMAGE_STREAMS)
{
for (auto& stream : stream_vec)
{
image_stream_types.push_back(stream);
}
}
for (auto& stream : image_stream_types)
{
if (_enable[stream])
{
std::stringstream image_raw, camera_info;
bool rectified_image = false;
if (stream == DEPTH || stream == INFRA1 || stream == INFRA2)
rectified_image = true;
image_raw << _stream_name[stream] << "/image_" << ((rectified_image)?"rect_":"") << "raw";
camera_info << _stream_name[stream] << "/camera_info";
std::shared_ptr<FrequencyDiagnostics> frequency_diagnostics(new FrequencyDiagnostics(_fps[stream], _stream_name[stream], _serial_no));
_image_publishers[stream] = {image_transport.advertise(image_raw.str(), 1), frequency_diagnostics};
_info_publisher[stream] = _node_handle.advertise<sensor_msgs::CameraInfo>(camera_info.str(), 1);
if (_align_depth && (stream != DEPTH))
{
std::stringstream aligned_image_raw, aligned_camera_info;
aligned_image_raw << "aligned_depth_to_" << _stream_name[stream] << "/image_raw";
aligned_camera_info << "aligned_depth_to_" << _stream_name[stream] << "/camera_info";
std::string aligned_stream_name = "aligned_depth_to_" + _stream_name[stream];
std::shared_ptr<FrequencyDiagnostics> frequency_diagnostics(new FrequencyDiagnostics(_fps[stream], aligned_stream_name, _serial_no));
_depth_aligned_image_publishers[stream] = {image_transport.advertise(aligned_image_raw.str(), 1), frequency_diagnostics};
_depth_aligned_info_publisher[stream] = _node_handle.advertise<sensor_msgs::CameraInfo>(aligned_camera_info.str(), 1);
}
if (stream == DEPTH && _pointcloud)
{
_pointcloud_publisher = _node_handle.advertise<sensor_msgs::PointCloud2>("depth/color/points", 1);
}
}
}
if (_enable[FISHEYE] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[FISHEYE] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_fisheye", 1, true);
}
if (_enable[COLOR] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[COLOR] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_color", 1, true);
}
if (_enable[INFRA1] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[INFRA1] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_infra1", 1, true);
}
if (_enable[INFRA2] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[INFRA2] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_infra2", 1, true);
}
if (_enable[GYRO])
{
_imu_publishers[GYRO] = _node_handle.advertise<sensor_msgs::Imu>("gyro/sample", 100);
_info_publisher[GYRO] = _node_handle.advertise<IMUInfo>("gyro/imu_info", 1, true);
}
if (_enable[ACCEL])
{
_imu_publishers[ACCEL] = _node_handle.advertise<sensor_msgs::Imu>("accel/sample", 100);
_info_publisher[ACCEL] = _node_handle.advertise<IMUInfo>("accel/imu_info", 1, true);
}
}
void BaseRealSenseNode::alignFrame(const rs2_intrinsics& from_intrin,
const rs2_intrinsics& other_intrin,
rs2::frame from_image,
uint32_t output_image_bytes_per_pixel,
const rs2_extrinsics& from_to_other,
std::vector<uint8_t>& out_vec)
{
static const auto meter_to_mm = 0.001f;
uint8_t* p_out_frame = out_vec.data();
auto from_vid_frame = from_image.as<rs2::video_frame>();
auto from_bytes_per_pixel = from_vid_frame.get_bytes_per_pixel();
static const auto blank_color = 0x00;
memset(p_out_frame, blank_color, other_intrin.height * other_intrin.width * output_image_bytes_per_pixel);
auto p_from_frame = reinterpret_cast<const uint8_t*>(from_image.get_data());
auto from_stream_type = from_image.get_profile().stream_type();
float depth_units = ((from_stream_type == RS2_STREAM_DEPTH)?_depth_scale_meters:1.f);
#pragma omp parallel for schedule(dynamic)
for (int from_y = 0; from_y < from_intrin.height; ++from_y)
{
int from_pixel_index = from_y * from_intrin.width;
for (int from_x = 0; from_x < from_intrin.width; ++from_x, ++from_pixel_index)
{
// Skip over depth pixels with the value of zero
float depth = (from_stream_type == RS2_STREAM_DEPTH)?(depth_units * ((const uint16_t*)p_from_frame)[from_pixel_index]): 1.f;
if (depth)
{
// Map the top-left corner of the depth pixel onto the other image
float from_pixel[2] = { from_x - 0.5f, from_y - 0.5f }, from_point[3], other_point[3], other_pixel[2];
rs2_deproject_pixel_to_point(from_point, &from_intrin, from_pixel, depth);
rs2_transform_point_to_point(other_point, &from_to_other, from_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x0 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y0 = static_cast<int>(other_pixel[1] + 0.5f);
// Map the bottom-right corner of the depth pixel onto the other image
from_pixel[0] = from_x + 0.5f; from_pixel[1] = from_y + 0.5f;
rs2_deproject_pixel_to_point(from_point, &from_intrin, from_pixel, depth);
rs2_transform_point_to_point(other_point, &from_to_other, from_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x1 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y1 = static_cast<int>(other_pixel[1] + 0.5f);
if (other_x0 < 0 || other_y0 < 0 || other_x1 >= other_intrin.width || other_y1 >= other_intrin.height)
continue;
for (int y = other_y0; y <= other_y1; ++y)
{
for (int x = other_x0; x <= other_x1; ++x)
{
int out_pixel_index = y * other_intrin.width + x;
//Tranfer n-bit pixel to n-bit pixel
for (int i = 0; i < from_bytes_per_pixel; i++)
{
const auto out_offset = out_pixel_index * output_image_bytes_per_pixel + i;
const auto from_offset = from_pixel_index * output_image_bytes_per_pixel + i;
p_out_frame[out_offset] = p_from_frame[from_offset] * (depth_units / meter_to_mm);
}
}
}
}
}
}
}
void BaseRealSenseNode::updateIsFrameArrived(std::map<stream_index_pair, bool>& is_frame_arrived,
rs2_stream stream_type, int stream_index)
{
try
{
is_frame_arrived.at({stream_type, stream_index}) = true;
}
catch (std::out_of_range)
{
ROS_ERROR_STREAM("Stream type is not supported! (" << stream_type << ", " << stream_index << ")");
}
}
void BaseRealSenseNode::publishAlignedDepthToOthers(rs2::frame depth_frame, const std::vector<rs2::frame>& frames, const ros::Time& t)
{
for (auto&& other_frame : frames)
{
auto stream_type = other_frame.get_profile().stream_type();
if (RS2_STREAM_DEPTH == stream_type)
continue;
auto stream_index = other_frame.get_profile().stream_index();
stream_index_pair sip{stream_type, stream_index};
auto& info_publisher = _depth_aligned_info_publisher.at(sip);
auto& image_publisher = _depth_aligned_image_publishers.at(sip);
if(0 != info_publisher.getNumSubscribers() ||
0 != image_publisher.first.getNumSubscribers())
{
auto from_image_frame = depth_frame.as<rs2::video_frame>();
auto& out_vec = _aligned_depth_images[sip];
alignFrame(_stream_intrinsics[DEPTH], _stream_intrinsics[sip],
depth_frame, from_image_frame.get_bytes_per_pixel(),
_depth_to_other_extrinsics[sip], out_vec);
auto& from_image = _depth_aligned_image[sip];
from_image.data = out_vec.data();
publishFrame(depth_frame, t, sip,
_depth_aligned_image,
_depth_aligned_info_publisher,
_depth_aligned_image_publishers, _depth_aligned_seq,
_depth_aligned_camera_info, _optical_frame_id,
_depth_aligned_encoding, false);
}
}
}
void BaseRealSenseNode::setupStreams()
{
ROS_INFO("setupStreams...");
try{
for (auto& streams : IMAGE_STREAMS)
{
for (auto& elem : streams)
{
if (_enable[elem])
{
auto& sens = _sensors[elem];
auto profiles = sens.get_stream_profiles();
for (auto& profile : profiles)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
if (video_profile.format() == _format[elem] &&
video_profile.width() == _width[elem] &&
video_profile.height() == _height[elem] &&
video_profile.fps() == _fps[elem] &&
video_profile.stream_index() == elem.second)
{
_enabled_profiles[elem].push_back(profile);
_image[elem] = cv::Mat(_width[elem], _height[elem], _image_format[elem], cv::Scalar(0, 0, 0));
if (_align_depth)
_depth_aligned_image[elem] = cv::Mat(_width[DEPTH], _height[DEPTH], _image_format[DEPTH], cv::Scalar(0, 0, 0));
ROS_INFO_STREAM(_stream_name[elem] << " stream is enabled - width: " << _width[elem] << ", height: " << _height[elem] << ", fps: " << _fps[elem]);
break;
}
}
if (_enabled_profiles.find(elem) == _enabled_profiles.end())
{
ROS_WARN_STREAM("Given stream configuration is not supported by the device! " <<
" Stream: " << rs2_stream_to_string(elem.first) <<
", Stream Index: " << elem.second <<
", Format: " << _format[elem] <<
", Width: " << _width[elem] <<
", Height: " << _height[elem] <<
", FPS: " << _fps[elem]);
_enable[elem] = false;
}
}
}
}
// Publish image stream info
for (auto& profiles : _enabled_profiles)
{
for (auto& profile : profiles.second)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
updateStreamCalibData(video_profile);
}
}
auto frame_callback = [this](rs2::frame frame)
{
try{
// We compute a ROS timestamp which is based on an initial ROS time at point of first frame,
// and the incremental timestamp from the camera.
// In sync mode the timestamp is based on ROS time
if (false == _intialize_time_base)
{
if (RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME == frame.get_frame_timestamp_domain())
ROS_WARN("Frame metadata isn't available! (frame_timestamp_domain = RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)");
_intialize_time_base = true;
_ros_time_base = ros::Time::now();
_camera_time_base = frame.get_timestamp();
}
ros::Time t;
if (_sync_frames)
t = ros::Time::now();
else
t = ros::Time(_ros_time_base.toSec()+ (/*ms*/ frame.get_timestamp() - /*ms*/ _camera_time_base) / /*ms to seconds*/ 1000);
std::map<stream_index_pair, bool> is_frame_arrived(_is_frame_arrived);
std::vector<rs2::frame> frames;
if (frame.is<rs2::frameset>())
{
ROS_DEBUG("Frameset arrived.");
bool is_depth_arrived = false;
rs2::frame depth_frame;
auto frameset = frame.as<rs2::frameset>();
for (auto it = frameset.begin(); it != frameset.end(); ++it)
{
auto f = (*it);
auto stream_type = f.get_profile().stream_type();
auto stream_index = f.get_profile().stream_index();
updateIsFrameArrived(is_frame_arrived, stream_type, stream_index);
ROS_DEBUG("Frameset contain (%s, %d) frame. frame_number: %llu ; frame_TS: %f ; ros_TS(NSec): %lu",
rs2_stream_to_string(stream_type), stream_index, frame.get_frame_number(), frame.get_timestamp(), t.toNSec());
stream_index_pair sip{stream_type,stream_index};
publishFrame(f, t,
sip,
_image,
_info_publisher,
_image_publishers, _seq,
_camera_info, _optical_frame_id,
_encoding);
if (_align_depth && stream_type != RS2_STREAM_DEPTH)
{
frames.push_back(f);
}
else
{
depth_frame = f;
is_depth_arrived = true;
}
}
if (_align_depth && is_depth_arrived)
{
ROS_DEBUG("publishAlignedDepthToOthers(...)");
publishAlignedDepthToOthers(depth_frame, frames, t);
}
}
else
{
auto stream_type = frame.get_profile().stream_type();
auto stream_index = frame.get_profile().stream_index();
updateIsFrameArrived(is_frame_arrived, stream_type, stream_index);
ROS_DEBUG("Single video frame arrived (%s, %d). frame_number: %llu ; frame_TS: %f ; ros_TS(NSec): %lu",
rs2_stream_to_string(stream_type), stream_index, frame.get_frame_number(), frame.get_timestamp(), t.toNSec());
stream_index_pair sip{stream_type,stream_index};
publishFrame(frame, t,
sip,
_image,
_info_publisher,
_image_publishers, _seq,
_camera_info, _optical_frame_id,
_encoding);
}
if(_pointcloud && (0 != _pointcloud_publisher.getNumSubscribers()))
{
ROS_DEBUG("publishPCTopic(...)");
publishRgbToDepthPCTopic(t, is_frame_arrived);
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An error has occurred during frame callback: " << ex.what());
}
}; // frame_callback
// Streaming IMAGES
for (auto& streams : IMAGE_STREAMS)
{
std::vector<rs2::stream_profile> profiles;
for (auto& elem : streams)
{
if (!_enabled_profiles[elem].empty())
{
profiles.insert(profiles.begin(),
_enabled_profiles[elem].begin(),
_enabled_profiles[elem].end());
}
}
if (!profiles.empty())
{
auto stream = streams.front();
auto& sens = _sensors[stream];
sens.open(profiles);
if (DEPTH == stream)
{
auto depth_sensor = sens.as<rs2::depth_sensor>();
_depth_scale_meters = depth_sensor.get_depth_scale();
}
if (_sync_frames)
{
sens.start(_syncer);
}
else
{
sens.start(frame_callback);
}
}
}//end for
if (_sync_frames)
{
_syncer.start(frame_callback);
}
// Streaming HID
for (const auto streams : HID_STREAMS)
{
for (auto& elem : streams)
{
if (_enable[elem])
{
auto& sens = _sensors[elem];
auto profiles = sens.get_stream_profiles();
for (rs2::stream_profile& profile : profiles)
{
if (profile.fps() == _fps[elem] &&
profile.format() == _format[elem])
{
_enabled_profiles[elem].push_back(profile);
break;
}
}
}
}
}
auto gyro_profile = _enabled_profiles.find(GYRO);
auto accel_profile = _enabled_profiles.find(ACCEL);
if (gyro_profile != _enabled_profiles.end() &&
accel_profile != _enabled_profiles.end())
{
std::vector<rs2::stream_profile> profiles;
profiles.insert(profiles.begin(), gyro_profile->second.begin(), gyro_profile->second.end());
profiles.insert(profiles.begin(), accel_profile->second.begin(), accel_profile->second.end());
auto& sens = _sensors[GYRO];
sens.open(profiles);
sens.start([this](rs2::frame frame){
auto stream = frame.get_profile().stream_type();
if (false == _intialize_time_base)
return;
ROS_DEBUG("Frame arrived: stream: %s ; index: %d ; Timestamp Domain: %s",
rs2_stream_to_string(frame.get_profile().stream_type()),
frame.get_profile().stream_index(),
rs2_timestamp_domain_to_string(frame.get_frame_timestamp_domain()));
auto stream_index = (stream == GYRO.first)?GYRO:ACCEL;
if (0 != _info_publisher[stream_index].getNumSubscribers() ||
0 != _imu_publishers[stream_index].getNumSubscribers())
{
double elapsed_camera_ms = (/*ms*/ frame.get_timestamp() - /*ms*/ _camera_time_base) / /*ms to seconds*/ 1000;
ros::Time t(_ros_time_base.toSec() + elapsed_camera_ms);
auto imu_msg = sensor_msgs::Imu();
imu_msg.header.frame_id = _optical_frame_id[stream_index];
imu_msg.orientation.x = 0.0;
imu_msg.orientation.y = 0.0;
imu_msg.orientation.z = 0.0;
imu_msg.orientation.w = 0.0;
imu_msg.orientation_covariance = { -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
auto axes = *(reinterpret_cast<const float3*>(frame.get_data()));
if (GYRO == stream_index)
{
imu_msg.angular_velocity.x = axes.x;
imu_msg.angular_velocity.y = axes.y;
imu_msg.angular_velocity.z = axes.z;
}
else if (ACCEL == stream_index)
{
imu_msg.linear_acceleration.x = axes.x;
imu_msg.linear_acceleration.y = axes.y;
imu_msg.linear_acceleration.z = axes.z;
}
_seq[stream_index] += 1;
imu_msg.header.seq = _seq[stream_index];
imu_msg.header.stamp = t;
_imu_publishers[stream_index].publish(imu_msg);
ROS_DEBUG("Publish %s stream", rs2_stream_to_string(frame.get_profile().stream_type()));
}
});
if (_enable[GYRO])
{
ROS_INFO_STREAM(_stream_name[GYRO] << " stream is enabled - " << "fps: " << _fps[GYRO]);
auto gyroInfo = getImuInfo(GYRO);
_info_publisher[GYRO].publish(gyroInfo);
}
if (_enable[ACCEL])
{
ROS_INFO_STREAM(_stream_name[ACCEL] << " stream is enabled - " << "fps: " << _fps[ACCEL]);
auto accelInfo = getImuInfo(ACCEL);
_info_publisher[ACCEL].publish(accelInfo);
}
}
if (_enable[DEPTH] &&
_enable[FISHEYE])
{
static const char* frame_id = "depth_to_fisheye_extrinsics";
auto ex = getRsExtrinsics(DEPTH, FISHEYE);
_depth_to_other_extrinsics[FISHEYE] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[FISHEYE].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[COLOR])
{
static const char* frame_id = "depth_to_color_extrinsics";
auto ex = getRsExtrinsics(DEPTH, COLOR);
_depth_to_other_extrinsics[COLOR] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[COLOR].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[INFRA1])
{
static const char* frame_id = "depth_to_infra1_extrinsics";
auto ex = getRsExtrinsics(DEPTH, INFRA1);
_depth_to_other_extrinsics[INFRA1] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[INFRA1].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[INFRA2])
{
static const char* frame_id = "depth_to_infra2_extrinsics";
auto ex = getRsExtrinsics(DEPTH, INFRA2);
_depth_to_other_extrinsics[INFRA2] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[INFRA2].publish(rsExtrinsicsToMsg(ex, frame_id));
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An exception has been thrown: " << ex.what());
throw;
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception has occured!");
throw;
}
}
void BaseRealSenseNode::updateStreamCalibData(const rs2::video_stream_profile& video_profile)
{
stream_index_pair stream_index{video_profile.stream_type(), video_profile.stream_index()};
auto intrinsic = video_profile.get_intrinsics();
_stream_intrinsics[stream_index] = intrinsic;
_camera_info[stream_index].width = intrinsic.width;
_camera_info[stream_index].height = intrinsic.height;
_camera_info[stream_index].header.frame_id = _optical_frame_id[stream_index];
_camera_info[stream_index].K.at(0) = intrinsic.fx;
_camera_info[stream_index].K.at(2) = intrinsic.ppx;
_camera_info[stream_index].K.at(4) = intrinsic.fy;
_camera_info[stream_index].K.at(5) = intrinsic.ppy;
_camera_info[stream_index].K.at(8) = 1;
_camera_info[stream_index].P.at(0) = _camera_info[stream_index].K.at(0);
_camera_info[stream_index].P.at(1) = 0;
_camera_info[stream_index].P.at(2) = _camera_info[stream_index].K.at(2);
_camera_info[stream_index].P.at(3) = 0;
_camera_info[stream_index].P.at(4) = 0;
_camera_info[stream_index].P.at(5) = _camera_info[stream_index].K.at(4);
_camera_info[stream_index].P.at(6) = _camera_info[stream_index].K.at(5);
_camera_info[stream_index].P.at(7) = 0;
_camera_info[stream_index].P.at(8) = 0;
_camera_info[stream_index].P.at(9) = 0;
_camera_info[stream_index].P.at(10) = 1;
_camera_info[stream_index].P.at(11) = 0;
rs2::stream_profile depth_profile;
if (!getEnabledProfile(DEPTH, depth_profile))
{
ROS_ERROR_STREAM("Given depth profile is not supported by current device!");
ros::shutdown();
exit(1);
}
_camera_info[stream_index].distortion_model = "plumb_bob";
// set R (rotation matrix) values to identity matrix
_camera_info[stream_index].R.at(0) = 1.0;
_camera_info[stream_index].R.at(1) = 0.0;
_camera_info[stream_index].R.at(2) = 0.0;
_camera_info[stream_index].R.at(3) = 0.0;
_camera_info[stream_index].R.at(4) = 1.0;
_camera_info[stream_index].R.at(5) = 0.0;
_camera_info[stream_index].R.at(6) = 0.0;
_camera_info[stream_index].R.at(7) = 0.0;
_camera_info[stream_index].R.at(8) = 1.0;
for (int i = 0; i < 5; i++)
{
_camera_info[stream_index].D.push_back(intrinsic.coeffs[i]);
}
if (stream_index == DEPTH && _enable[DEPTH] && _enable[COLOR])
{
_camera_info[stream_index].P.at(3) = 0; // Tx
_camera_info[stream_index].P.at(7) = 0; // Ty
}
if (_align_depth)
{
for (auto& profiles : _enabled_profiles)
{
for (auto& profile : profiles.second)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
stream_index_pair stream_index{video_profile.stream_type(), video_profile.stream_index()};
_depth_aligned_camera_info[stream_index] = _camera_info[stream_index];
}
}
}
}
Eigen::Quaternionf BaseRealSenseNode::rotationMatrixToQuaternion(const float rotation[3]) const
{
Eigen::Matrix3f m;
m << rotation[0], rotation[1], rotation[2],
rotation[3], rotation[4], rotation[5],
rotation[6], rotation[7], rotation[8];
Eigen::Quaternionf q(m);
return q;
}
void BaseRealSenseNode::publish_static_tf(const ros::Time& t,
const float3& trans,
const quaternion& q,
const std::string& from,
const std::string& to)
{
geometry_msgs::TransformStamped msg;
msg.header.stamp = t;
msg.header.frame_id = from;
msg.child_frame_id = to;
msg.transform.translation.x = trans.z;
msg.transform.translation.y = -trans.x;
msg.transform.translation.z = -trans.y;
msg.transform.rotation.x = q.x;
msg.transform.rotation.y = q.y;
msg.transform.rotation.z = q.z;
msg.transform.rotation.w = q.w;
_static_tf_broadcaster.sendTransform(msg);
}
void BaseRealSenseNode::publishStaticTransforms()
{
ROS_INFO("publishStaticTransforms...");
// Publish static transforms
tf::Quaternion quaternion_optical;
quaternion_optical.setRPY(-M_PI / 2, 0.0, -M_PI / 2);
// Get the current timestamp for all static transforms
ros::Time transform_ts_ = ros::Time::now();
// The depth frame is used as the base link.
// Hence no additional transformation is done from base link to depth frame.
// Transform base link to depth frame
float3 zero_trans{0, 0, 0};
publish_static_tf(transform_ts_, zero_trans, quaternion{0, 0, 0, 1}, _base_frame_id, _frame_id[DEPTH]);
// Transform depth frame to depth optical frame
quaternion q{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q, _frame_id[DEPTH], _optical_frame_id[DEPTH]);
rs2::stream_profile depth_profile;
if (!getEnabledProfile(DEPTH, depth_profile))
{
ROS_ERROR_STREAM("Given depth profile is not supported by current device!");
ros::shutdown();
exit(1);
}
if (_enable[COLOR])
{
// Transform base to color
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, COLOR));
auto Q = rotationMatrixToQuaternion(ex.rotation);
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[COLOR]);
// Transform color frame to color optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[COLOR], _optical_frame_id[COLOR]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[COLOR]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[COLOR], _optical_frame_id[COLOR]);
}
}
if (_enable[INFRA1])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, INFRA1));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra1
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[INFRA1]);
// Transform infra1 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[INFRA1], _optical_frame_id[INFRA1]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[INFRA1]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[INFRA1], _optical_frame_id[INFRA1]);
}
}
if (_enable[INFRA2])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, INFRA2));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra2
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[INFRA2]);
// Transform infra2 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[INFRA2], _optical_frame_id[INFRA2]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[INFRA2]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[INFRA2], _optical_frame_id[INFRA2]);
}
}
if (_enable[FISHEYE])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, FISHEYE));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra2
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[FISHEYE]);
// Transform infra2 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[FISHEYE], _optical_frame_id[FISHEYE]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[FISHEYE]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[FISHEYE], _optical_frame_id[FISHEYE]);
}
}
}
void BaseRealSenseNode::publishRgbToDepthPCTopic(const ros::Time& t, const std::map<stream_index_pair, bool>& is_frame_arrived)
{
try
{
if (!is_frame_arrived.at(COLOR) || !is_frame_arrived.at(DEPTH))
{
ROS_DEBUG("Skipping publish PC topic! Color or Depth frame didn't arrive.");
return;
}
}
catch (std::out_of_range)
{
ROS_DEBUG("Skipping publish PC topic! Color or Depth frame didn't configure.");
return;
}
auto& depth2color_extrinsics = _depth_to_other_extrinsics[COLOR];
auto color_intrinsics = _stream_intrinsics[COLOR];
auto image_depth16 = reinterpret_cast<const uint16_t*>(_image[DEPTH].data);
auto depth_intrinsics = _stream_intrinsics[DEPTH];
sensor_msgs::PointCloud2 msg_pointcloud;
msg_pointcloud.header.stamp = t;
msg_pointcloud.header.frame_id = _optical_frame_id[DEPTH];
msg_pointcloud.width = depth_intrinsics.width;
msg_pointcloud.height = depth_intrinsics.height;
msg_pointcloud.is_dense = true;
sensor_msgs::PointCloud2Modifier modifier(msg_pointcloud);
modifier.setPointCloud2Fields(4,
"x", 1, sensor_msgs::PointField::FLOAT32,
"y", 1, sensor_msgs::PointField::FLOAT32,
"z", 1, sensor_msgs::PointField::FLOAT32,
"rgb", 1, sensor_msgs::PointField::FLOAT32);
modifier.setPointCloud2FieldsByString(2, "xyz", "rgb");
sensor_msgs::PointCloud2Iterator<float>iter_x(msg_pointcloud, "x");
sensor_msgs::PointCloud2Iterator<float>iter_y(msg_pointcloud, "y");
sensor_msgs::PointCloud2Iterator<float>iter_z(msg_pointcloud, "z");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_r(msg_pointcloud, "r");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_g(msg_pointcloud, "g");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_b(msg_pointcloud, "b");
float depth_point[3], color_point[3], color_pixel[2], scaled_depth;
unsigned char* color_data = _image[COLOR].data;
// Fill the PointCloud2 fields
for (int y = 0; y < depth_intrinsics.height; ++y)
{
for (int x = 0; x < depth_intrinsics.width; ++x)
{
scaled_depth = static_cast<float>(*image_depth16) * _depth_scale_meters;
float depth_pixel[2] = {static_cast<float>(x), static_cast<float>(y)};
rs2_deproject_pixel_to_point(depth_point, &depth_intrinsics, depth_pixel, scaled_depth);
if (depth_point[2] <= 0.f || depth_point[2] > 5.f)
{
depth_point[0] = 0.f;
depth_point[1] = 0.f;
depth_point[2] = 0.f;
}
*iter_x = depth_point[0];
*iter_y = depth_point[1];
*iter_z = depth_point[2];
rs2_transform_point_to_point(color_point, &depth2color_extrinsics, depth_point);
rs2_project_point_to_pixel(color_pixel, &color_intrinsics, color_point);
if (color_pixel[1] < 0.f || color_pixel[1] > color_intrinsics.height
|| color_pixel[0] < 0.f || color_pixel[0] > color_intrinsics.width)
{
// For out of bounds color data, default to a shade of blue in order to visually distinguish holes.
// This color value is same as the librealsense out of bounds color value.
*iter_r = static_cast<uint8_t>(96);
*iter_g = static_cast<uint8_t>(157);
*iter_b = static_cast<uint8_t>(198);
}
else
{
auto i = static_cast<int>(color_pixel[0]);
auto j = static_cast<int>(color_pixel[1]);
auto offset = i * 3 + j * color_intrinsics.width * 3;
*iter_r = static_cast<uint8_t>(color_data[offset]);
*iter_g = static_cast<uint8_t>(color_data[offset + 1]);
*iter_b = static_cast<uint8_t>(color_data[offset + 2]);
}
++image_depth16;
++iter_x; ++iter_y; ++iter_z;
++iter_r; ++iter_g; ++iter_b;
}
}
_pointcloud_publisher.publish(msg_pointcloud);
}
Extrinsics BaseRealSenseNode::rsExtrinsicsToMsg(const rs2_extrinsics& extrinsics, const std::string& frame_id) const
{
Extrinsics extrinsicsMsg;
for (int i = 0; i < 9; ++i)
{
extrinsicsMsg.rotation[i] = extrinsics.rotation[i];
if (i < 3)
extrinsicsMsg.translation[i] = extrinsics.translation[i];
}
extrinsicsMsg.header.frame_id = frame_id;
return extrinsicsMsg;
}
rs2_extrinsics BaseRealSenseNode::getRsExtrinsics(const stream_index_pair& from_stream, const stream_index_pair& to_stream)
{
auto& from = _enabled_profiles[from_stream].front();
auto& to = _enabled_profiles[to_stream].front();
return from.get_extrinsics_to(to);
}
IMUInfo BaseRealSenseNode::getImuInfo(const stream_index_pair& stream_index)
{
IMUInfo info{};
auto sp = _enabled_profiles[stream_index].front().as<rs2::motion_stream_profile>();
auto imuIntrinsics = sp.get_motion_intrinsics();
if (GYRO == stream_index)
{
info.header.frame_id = "imu_gyro";
}
else if (ACCEL == stream_index)
{
info.header.frame_id = "imu_accel";
}
auto index = 0;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
info.data[index] = imuIntrinsics.data[i][j];
++index;
}
info.noise_variances[i] = imuIntrinsics.noise_variances[i];
info.bias_variances[i] = imuIntrinsics.bias_variances[i];
}
return info;
}
void BaseRealSenseNode::publishFrame(rs2::frame f, const ros::Time& t,
const stream_index_pair& stream,
std::map<stream_index_pair, cv::Mat>& images,
const std::map<stream_index_pair, ros::Publisher>& info_publishers,
const std::map<stream_index_pair, ImagePublisherWithFrequencyDiagnostics>& image_publishers,
std::map<stream_index_pair, int>& seq,
std::map<stream_index_pair, sensor_msgs::CameraInfo>& camera_info,
const std::map<stream_index_pair, std::string>& optical_frame_id,
const std::map<stream_index_pair, std::string>& encoding,
bool copy_data_from_frame)
{
ROS_DEBUG("publishFrame(...)");
auto& image = images[stream];
if (copy_data_from_frame)
image.data = (uint8_t*)f.get_data();
++(seq[stream]);
auto& info_publisher = info_publishers.at(stream);
auto& image_publisher = image_publishers.at(stream);
if(0 != info_publisher.getNumSubscribers() ||
0 != image_publisher.first.getNumSubscribers())
{
auto width = 0;
auto height = 0;
auto bpp = 1;
if (f.is<rs2::video_frame>())
{
auto image = f.as<rs2::video_frame>();
width = image.get_width();
height = image.get_height();
bpp = image.get_bytes_per_pixel();
}
sensor_msgs::ImagePtr img;
img = cv_bridge::CvImage(std_msgs::Header(), encoding.at(stream), image).toImageMsg();
img->width = width;
img->height = height;
img->is_bigendian = false;
img->step = width * bpp;
img->header.frame_id = optical_frame_id.at(stream);
img->header.stamp = t;
img->header.seq = seq[stream];
auto& cam_info = camera_info.at(stream);
cam_info.header.stamp = t;
cam_info.header.seq = seq[stream];
info_publisher.publish(cam_info);
image_publisher.first.publish(img);
image_publisher.second->update();
ROS_DEBUG("%s stream published", rs2_stream_to_string(f.get_profile().stream_type()));
}
}
bool BaseRealSenseNode::getEnabledProfile(const stream_index_pair& stream_index, rs2::stream_profile& profile)
{
// Assuming that all D400 SKUs have depth sensor
auto profiles = _enabled_profiles[stream_index];
auto it = std::find_if(profiles.begin(), profiles.end(),
[&](const rs2::stream_profile& profile)
{ return (profile.stream_type() == stream_index.first); });
if (it == profiles.end())
return false;
profile = *it;
return true;
}
BaseD400Node::BaseD400Node(ros::NodeHandle& nodeHandle,
ros::NodeHandle& privateNodeHandle,
rs2::device dev, const std::string& serial_no)
: BaseRealSenseNode(nodeHandle,
privateNodeHandle,
dev, serial_no)
{}
void BaseD400Node::callback(base_d400_paramsConfig &config, uint32_t level)
{
ROS_DEBUG_STREAM("D400 - Level: " << level);
if (set_default_dynamic_reconfig_values == level)
{
for (int i = 1 ; i < base_depth_count ; ++i)
{
ROS_DEBUG_STREAM("base_depth_param = " << i);
setParam(config ,(base_depth_param)i);
}
}
else
{
setParam(config, (base_depth_param)level);
}
}
void BaseD400Node::setOption(stream_index_pair sip, rs2_option opt, float val)
{
_sensors[sip].set_option(opt, val);
}
void BaseD400Node::setParam(rs435_paramsConfig &config, base_depth_param param)
{
base_d400_paramsConfig base_config;
base_config.base_depth_gain = config.rs435_depth_gain;
base_config.base_depth_enable_auto_exposure = config.rs435_depth_enable_auto_exposure;
base_config.base_depth_visual_preset = config.rs435_depth_visual_preset;
base_config.base_depth_frames_queue_size = config.rs435_depth_frames_queue_size;
base_config.base_depth_error_polling_enabled = config.rs435_depth_error_polling_enabled;
base_config.base_depth_output_trigger_enabled = config.rs435_depth_output_trigger_enabled;
base_config.base_depth_units = config.rs435_depth_units;
base_config.base_JSON_file_path = config.rs435_JSON_file_path;
setParam(base_config, param);
}
void BaseD400Node::setParam(rs415_paramsConfig &config, base_depth_param param)
{
base_d400_paramsConfig base_config;
base_config.base_depth_gain = config.rs415_depth_gain;
base_config.base_depth_enable_auto_exposure = config.rs415_depth_enable_auto_exposure;
base_config.base_depth_visual_preset = config.rs415_depth_visual_preset;
base_config.base_depth_frames_queue_size = config.rs415_depth_frames_queue_size;
base_config.base_depth_error_polling_enabled = config.rs415_depth_error_polling_enabled;
base_config.base_depth_output_trigger_enabled = config.rs415_depth_output_trigger_enabled;
base_config.base_depth_units = config.rs415_depth_units;
base_config.base_JSON_file_path = config.rs415_JSON_file_path;
setParam(base_config, param);
}
void BaseD400Node::setParam(base_d400_paramsConfig &config, base_depth_param param)
{
// W/O for zero param
if (0 == param)
return;
switch (param) {
case base_depth_gain:
ROS_DEBUG_STREAM("base_depth_gain: " << config.base_depth_gain);
setOption(DEPTH, RS2_OPTION_GAIN, config.base_depth_gain);
break;
case base_depth_enable_auto_exposure:
ROS_DEBUG_STREAM("base_depth_enable_auto_exposure: " << config.base_depth_enable_auto_exposure);
setOption(DEPTH, RS2_OPTION_ENABLE_AUTO_EXPOSURE, config.base_depth_enable_auto_exposure);
break;
case base_depth_visual_preset:
ROS_DEBUG_STREAM("base_depth_enable_auto_exposure: " << config.base_depth_visual_preset);
setOption(DEPTH, RS2_OPTION_VISUAL_PRESET, config.base_depth_visual_preset);
break;
case base_depth_frames_queue_size:
ROS_DEBUG_STREAM("base_depth_frames_queue_size: " << config.base_depth_frames_queue_size);
setOption(DEPTH, RS2_OPTION_FRAMES_QUEUE_SIZE, config.base_depth_frames_queue_size);
break;
case base_depth_error_polling_enabled:
ROS_DEBUG_STREAM("base_depth_error_polling_enabled: " << config.base_depth_error_polling_enabled);
setOption(DEPTH, RS2_OPTION_ERROR_POLLING_ENABLED, config.base_depth_error_polling_enabled);
break;
case base_depth_output_trigger_enabled:
ROS_DEBUG_STREAM("base_depth_error_polling_enabled: " << config.base_depth_output_trigger_enabled);
setOption(DEPTH, RS2_OPTION_OUTPUT_TRIGGER_ENABLED, config.base_depth_output_trigger_enabled);
break;
case base_depth_units:
break;
case base_JSON_file_path:
{
ROS_DEBUG_STREAM("base_JSON_file_path: " << config.base_JSON_file_path);
auto adv_dev = _dev.as<rs400::advanced_mode>();
if (!adv_dev)
{
ROS_WARN_STREAM("Device doesn't support Advanced Mode!");
return;
}
if (!config.base_JSON_file_path.empty())
{
std::ifstream in(config.base_JSON_file_path);
if (!in.is_open())
{
ROS_WARN_STREAM("JSON file provided doesn't exist!");
return;
}
adv_dev.load_json(config.base_JSON_file_path);
}
break;
}
default:
ROS_WARN_STREAM("Unrecognized D400 param (" << param << ")");
break;
}
}
void BaseD400Node::registerDynamicReconfigCb()
{
_server = std::make_shared<dynamic_reconfigure::Server<base_d400_paramsConfig>>();
_f = boost::bind(&BaseD400Node::callback, this, _1, _2);
_server->setCallback(_f);
}
fix the aligned depth frame unit conversion issue
#include "../include/base_realsense_node.h"
#include "../include/sr300_node.h"
using namespace realsense2_camera;
std::string BaseRealSenseNode::getNamespaceStr()
{
auto ns = ros::this_node::getNamespace();
ns.erase(std::remove(ns.begin(), ns.end(), '/'), ns.end());
return ns;
}
BaseRealSenseNode::BaseRealSenseNode(ros::NodeHandle& nodeHandle,
ros::NodeHandle& privateNodeHandle,
rs2::device dev,
const std::string& serial_no) :
_dev(dev), _node_handle(nodeHandle),
_pnh(privateNodeHandle), _json_file_path(""),
_serial_no(serial_no), _base_frame_id(""),
_intialize_time_base(false),
_namespace(getNamespaceStr())
{
// Types for depth stream
_is_frame_arrived[DEPTH] = false;
_format[DEPTH] = RS2_FORMAT_Z16; // libRS type
_image_format[DEPTH] = CV_16UC1; // CVBridge type
_encoding[DEPTH] = sensor_msgs::image_encodings::TYPE_16UC1; // ROS message type
_unit_step_size[DEPTH] = sizeof(uint16_t); // sensor_msgs::ImagePtr row step size
_stream_name[DEPTH] = "depth";
_depth_aligned_encoding[DEPTH] = sensor_msgs::image_encodings::TYPE_16UC1;
// Infrared stream - Left
_is_frame_arrived[INFRA1] = false;
_format[INFRA1] = RS2_FORMAT_Y8; // libRS type
_image_format[INFRA1] = CV_8UC1; // CVBridge type
_encoding[INFRA1] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[INFRA1] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[INFRA1] = "infra1";
_depth_aligned_encoding[INFRA1] = sensor_msgs::image_encodings::TYPE_16UC1;
// Infrared stream - Right
_is_frame_arrived[INFRA2] = false;
_format[INFRA2] = RS2_FORMAT_Y8; // libRS type
_image_format[INFRA2] = CV_8UC1; // CVBridge type
_encoding[INFRA2] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[INFRA2] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[INFRA2] = "infra2";
_depth_aligned_encoding[INFRA2] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for color stream
_is_frame_arrived[COLOR] = false;
_format[COLOR] = RS2_FORMAT_RGB8; // libRS type
_image_format[COLOR] = CV_8UC3; // CVBridge type
_encoding[COLOR] = sensor_msgs::image_encodings::RGB8; // ROS message type
_unit_step_size[COLOR] = 3; // sensor_msgs::ImagePtr row step size
_stream_name[COLOR] = "color";
_depth_aligned_encoding[COLOR] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for fisheye stream
_is_frame_arrived[FISHEYE] = false;
_format[FISHEYE] = RS2_FORMAT_RAW8; // libRS type
_image_format[FISHEYE] = CV_8UC1; // CVBridge type
_encoding[FISHEYE] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[FISHEYE] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[FISHEYE] = "fisheye";
_depth_aligned_encoding[FISHEYE] = sensor_msgs::image_encodings::TYPE_16UC1;
// Types for Motion-Module streams
_is_frame_arrived[GYRO] = false;
_format[GYRO] = RS2_FORMAT_MOTION_XYZ32F; // libRS type
_image_format[GYRO] = CV_8UC1; // CVBridge type
_encoding[GYRO] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[GYRO] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[GYRO] = "gyro";
_is_frame_arrived[ACCEL] = false;
_format[ACCEL] = RS2_FORMAT_MOTION_XYZ32F; // libRS type
_image_format[ACCEL] = CV_8UC1; // CVBridge type
_encoding[ACCEL] = sensor_msgs::image_encodings::TYPE_8UC1; // ROS message type
_unit_step_size[ACCEL] = sizeof(uint8_t); // sensor_msgs::ImagePtr row step size
_stream_name[ACCEL] = "accel";
}
void BaseRealSenseNode::publishTopics()
{
getParameters();
setupDevice();
setupPublishers();
setupStreams();
publishStaticTransforms();
ROS_INFO_STREAM("RealSense Node Is Up!");
}
void BaseRealSenseNode::registerDynamicReconfigCb()
{
ROS_INFO("Dynamic reconfig parameters is not implemented in the base node.");
}
void BaseRealSenseNode::getParameters()
{
ROS_INFO("getParameters...");
_pnh.param("align_depth", _align_depth, ALIGN_DEPTH);
_pnh.param("enable_pointcloud", _pointcloud, POINTCLOUD);
_pnh.param("enable_sync", _sync_frames, SYNC_FRAMES);
if (_pointcloud || _align_depth)
_sync_frames = true;
_pnh.param("json_file_path", _json_file_path, std::string(""));
_pnh.param("depth_width", _width[DEPTH], DEPTH_WIDTH);
_pnh.param("depth_height", _height[DEPTH], DEPTH_HEIGHT);
_pnh.param("depth_fps", _fps[DEPTH], DEPTH_FPS);
_pnh.param("enable_depth", _enable[DEPTH], ENABLE_DEPTH);
_aligned_depth_images[DEPTH].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("infra1_width", _width[INFRA1], INFRA1_WIDTH);
_pnh.param("infra1_height", _height[INFRA1], INFRA1_HEIGHT);
_pnh.param("infra1_fps", _fps[INFRA1], INFRA1_FPS);
_pnh.param("enable_infra1", _enable[INFRA1], ENABLE_INFRA1);
_aligned_depth_images[INFRA1].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("infra2_width", _width[INFRA2], INFRA2_WIDTH);
_pnh.param("infra2_height", _height[INFRA2], INFRA2_HEIGHT);
_pnh.param("infra2_fps", _fps[INFRA2], INFRA2_FPS);
_pnh.param("enable_infra2", _enable[INFRA2], ENABLE_INFRA2);
_aligned_depth_images[INFRA2].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("color_width", _width[COLOR], COLOR_WIDTH);
_pnh.param("color_height", _height[COLOR], COLOR_HEIGHT);
_pnh.param("color_fps", _fps[COLOR], COLOR_FPS);
_pnh.param("enable_color", _enable[COLOR], ENABLE_COLOR);
_aligned_depth_images[COLOR].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("fisheye_width", _width[FISHEYE], FISHEYE_WIDTH);
_pnh.param("fisheye_height", _height[FISHEYE], FISHEYE_HEIGHT);
_pnh.param("fisheye_fps", _fps[FISHEYE], FISHEYE_FPS);
_pnh.param("enable_fisheye", _enable[FISHEYE], ENABLE_FISHEYE);
_aligned_depth_images[FISHEYE].resize(_width[DEPTH] * _height[DEPTH] * _unit_step_size[DEPTH]);
_pnh.param("gyro_fps", _fps[GYRO], GYRO_FPS);
_pnh.param("accel_fps", _fps[ACCEL], ACCEL_FPS);
_pnh.param("enable_imu", _enable[GYRO], ENABLE_IMU);
_pnh.param("enable_imu", _enable[ACCEL], ENABLE_IMU);
_pnh.param("base_frame_id", _base_frame_id, DEFAULT_BASE_FRAME_ID);
_pnh.param("depth_frame_id", _frame_id[DEPTH], DEFAULT_DEPTH_FRAME_ID);
_pnh.param("infra1_frame_id", _frame_id[INFRA1], DEFAULT_INFRA1_FRAME_ID);
_pnh.param("infra2_frame_id", _frame_id[INFRA2], DEFAULT_INFRA2_FRAME_ID);
_pnh.param("color_frame_id", _frame_id[COLOR], DEFAULT_COLOR_FRAME_ID);
_pnh.param("fisheye_frame_id", _frame_id[FISHEYE], DEFAULT_FISHEYE_FRAME_ID);
_pnh.param("imu_gyro_frame_id", _frame_id[GYRO], DEFAULT_IMU_FRAME_ID);
_pnh.param("imu_accel_frame_id", _frame_id[ACCEL], DEFAULT_IMU_FRAME_ID);
_pnh.param("depth_optical_frame_id", _optical_frame_id[DEPTH], DEFAULT_DEPTH_OPTICAL_FRAME_ID);
_pnh.param("infra1_optical_frame_id", _optical_frame_id[INFRA1], DEFAULT_INFRA1_OPTICAL_FRAME_ID);
_pnh.param("infra2_optical_frame_id", _optical_frame_id[INFRA2], DEFAULT_INFRA2_OPTICAL_FRAME_ID);
_pnh.param("color_optical_frame_id", _optical_frame_id[COLOR], DEFAULT_COLOR_OPTICAL_FRAME_ID);
_pnh.param("fisheye_optical_frame_id", _optical_frame_id[FISHEYE], DEFAULT_FISHEYE_OPTICAL_FRAME_ID);
_pnh.param("gyro_optical_frame_id", _optical_frame_id[GYRO], DEFAULT_GYRO_OPTICAL_FRAME_ID);
_pnh.param("accel_optical_frame_id", _optical_frame_id[ACCEL], DEFAULT_ACCEL_OPTICAL_FRAME_ID);
_pnh.param("aligned_depth_to_color_frame_id", _depth_aligned_frame_id[COLOR], DEFAULT_ALIGNED_DEPTH_TO_COLOR_FRAME_ID);
_pnh.param("aligned_depth_to_infra1_frame_id", _depth_aligned_frame_id[INFRA1], DEFAULT_ALIGNED_DEPTH_TO_INFRA1_FRAME_ID);
_pnh.param("aligned_depth_to_infra2_frame_id", _depth_aligned_frame_id[INFRA2], DEFAULT_ALIGNED_DEPTH_TO_INFRA2_FRAME_ID);
_pnh.param("aligned_depth_to_fisheye_frame_id", _depth_aligned_frame_id[FISHEYE], DEFAULT_ALIGNED_DEPTH_TO_FISHEYE_FRAME_ID);
}
void BaseRealSenseNode::setupDevice()
{
ROS_INFO("setupDevice...");
try{
if (!_json_file_path.empty())
{
if (_dev.is<rs400::advanced_mode>())
{
std::stringstream ss;
std::ifstream in(_json_file_path);
if (in.is_open())
{
ss << in.rdbuf();
std::string json_file_content = ss.str();
auto adv = _dev.as<rs400::advanced_mode>();
adv.load_json(json_file_content);
ROS_INFO_STREAM("JSON file is loaded! (" << _json_file_path << ")");
}
else
ROS_WARN_STREAM("JSON file provided doesn't exist! (" << _json_file_path << ")");
}
else
ROS_WARN("Device does not support advanced settings!");
}
else
ROS_INFO("JSON file is not provided");
ROS_INFO_STREAM("ROS Node Namespace: " << _namespace);
auto camera_name = _dev.get_info(RS2_CAMERA_INFO_NAME);
ROS_INFO_STREAM("Device Name: " << camera_name);
ROS_INFO_STREAM("Device Serial No: " << _serial_no);
auto fw_ver = _dev.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION);
ROS_INFO_STREAM("Device FW version: " << fw_ver);
auto pid = _dev.get_info(RS2_CAMERA_INFO_PRODUCT_ID);
ROS_INFO_STREAM("Device Product ID: 0x" << pid);
ROS_INFO_STREAM("Enable PointCloud: " << ((_pointcloud)?"On":"Off"));
ROS_INFO_STREAM("Align Depth: " << ((_align_depth)?"On":"Off"));
ROS_INFO_STREAM("Sync Mode: " << ((_sync_frames)?"On":"Off"));
auto dev_sensors = _dev.query_sensors();
ROS_INFO_STREAM("Device Sensors: ");
for(auto&& elem : dev_sensors)
{
std::string module_name = elem.get_info(RS2_CAMERA_INFO_NAME);
if ("Stereo Module" == module_name)
{
_sensors[DEPTH] = elem;
_sensors[INFRA1] = elem;
_sensors[INFRA2] = elem;
}
else if ("Coded-Light Depth Sensor" == module_name)
{
_sensors[DEPTH] = elem;
_sensors[INFRA1] = elem;
}
else if ("RGB Camera" == module_name)
{
_sensors[COLOR] = elem;
}
else if ("Wide FOV Camera" == module_name)
{
_sensors[FISHEYE] = elem;
}
else if ("Motion Module" == module_name)
{
_sensors[GYRO] = elem;
_sensors[ACCEL] = elem;
}
else
{
ROS_ERROR_STREAM("Module Name \"" << module_name << "\" isn't supported by LibRealSense! Terminating RealSense Node...");
ros::shutdown();
exit(1);
}
ROS_INFO_STREAM(std::string(elem.get_info(RS2_CAMERA_INFO_NAME)) << " was found.");
}
// Update "enable" map
std::vector<std::vector<stream_index_pair>> streams(IMAGE_STREAMS);
streams.insert(streams.end(), HID_STREAMS.begin(), HID_STREAMS.end());
for (auto& elem : streams)
{
for (auto& stream_index : elem)
{
if (_enable[stream_index] && _sensors.find(stream_index) == _sensors.end()) // check if device supports the enabled stream
{
ROS_INFO_STREAM("(" << rs2_stream_to_string(stream_index.first) << ", " << stream_index.second << ") sensor isn't supported by current device! -- Skipping...");
_enable[stream_index] = false;
}
}
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An exception has been thrown: " << ex.what());
throw;
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception has occured!");
throw;
}
}
void BaseRealSenseNode::setupPublishers()
{
ROS_INFO("setupPublishers...");
image_transport::ImageTransport image_transport(_node_handle);
std::vector<stream_index_pair> image_stream_types;
for (auto& stream_vec : IMAGE_STREAMS)
{
for (auto& stream : stream_vec)
{
image_stream_types.push_back(stream);
}
}
for (auto& stream : image_stream_types)
{
if (_enable[stream])
{
std::stringstream image_raw, camera_info;
bool rectified_image = false;
if (stream == DEPTH || stream == INFRA1 || stream == INFRA2)
rectified_image = true;
image_raw << _stream_name[stream] << "/image_" << ((rectified_image)?"rect_":"") << "raw";
camera_info << _stream_name[stream] << "/camera_info";
std::shared_ptr<FrequencyDiagnostics> frequency_diagnostics(new FrequencyDiagnostics(_fps[stream], _stream_name[stream], _serial_no));
_image_publishers[stream] = {image_transport.advertise(image_raw.str(), 1), frequency_diagnostics};
_info_publisher[stream] = _node_handle.advertise<sensor_msgs::CameraInfo>(camera_info.str(), 1);
if (_align_depth && (stream != DEPTH))
{
std::stringstream aligned_image_raw, aligned_camera_info;
aligned_image_raw << "aligned_depth_to_" << _stream_name[stream] << "/image_raw";
aligned_camera_info << "aligned_depth_to_" << _stream_name[stream] << "/camera_info";
std::string aligned_stream_name = "aligned_depth_to_" + _stream_name[stream];
std::shared_ptr<FrequencyDiagnostics> frequency_diagnostics(new FrequencyDiagnostics(_fps[stream], aligned_stream_name, _serial_no));
_depth_aligned_image_publishers[stream] = {image_transport.advertise(aligned_image_raw.str(), 1), frequency_diagnostics};
_depth_aligned_info_publisher[stream] = _node_handle.advertise<sensor_msgs::CameraInfo>(aligned_camera_info.str(), 1);
}
if (stream == DEPTH && _pointcloud)
{
_pointcloud_publisher = _node_handle.advertise<sensor_msgs::PointCloud2>("depth/color/points", 1);
}
}
}
if (_enable[FISHEYE] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[FISHEYE] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_fisheye", 1, true);
}
if (_enable[COLOR] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[COLOR] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_color", 1, true);
}
if (_enable[INFRA1] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[INFRA1] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_infra1", 1, true);
}
if (_enable[INFRA2] &&
_enable[DEPTH])
{
_depth_to_other_extrinsics_publishers[INFRA2] = _node_handle.advertise<Extrinsics>("extrinsics/depth_to_infra2", 1, true);
}
if (_enable[GYRO])
{
_imu_publishers[GYRO] = _node_handle.advertise<sensor_msgs::Imu>("gyro/sample", 100);
_info_publisher[GYRO] = _node_handle.advertise<IMUInfo>("gyro/imu_info", 1, true);
}
if (_enable[ACCEL])
{
_imu_publishers[ACCEL] = _node_handle.advertise<sensor_msgs::Imu>("accel/sample", 100);
_info_publisher[ACCEL] = _node_handle.advertise<IMUInfo>("accel/imu_info", 1, true);
}
}
void BaseRealSenseNode::alignFrame(const rs2_intrinsics& from_intrin,
const rs2_intrinsics& other_intrin,
rs2::frame from_image,
uint32_t output_image_bytes_per_pixel,
const rs2_extrinsics& from_to_other,
std::vector<uint8_t>& out_vec)
{
static const auto meter_to_mm = 0.001f;
uint8_t* p_out_frame = out_vec.data();
static const auto blank_color = 0x00;
memset(p_out_frame, blank_color, other_intrin.height * other_intrin.width * output_image_bytes_per_pixel);
auto p_from_frame = reinterpret_cast<const uint8_t*>(from_image.get_data());
auto from_stream_type = from_image.get_profile().stream_type();
float depth_units = ((from_stream_type == RS2_STREAM_DEPTH)?_depth_scale_meters:1.f);
#pragma omp parallel for schedule(dynamic)
for (int from_y = 0; from_y < from_intrin.height; ++from_y)
{
int from_pixel_index = from_y * from_intrin.width;
for (int from_x = 0; from_x < from_intrin.width; ++from_x, ++from_pixel_index)
{
// Skip over depth pixels with the value of zero
float depth = (from_stream_type == RS2_STREAM_DEPTH)?(depth_units * ((const uint16_t*)p_from_frame)[from_pixel_index]): 1.f;
if (depth)
{
// Map the top-left corner of the depth pixel onto the other image
float from_pixel[2] = { from_x - 0.5f, from_y - 0.5f }, from_point[3], other_point[3], other_pixel[2];
rs2_deproject_pixel_to_point(from_point, &from_intrin, from_pixel, depth);
rs2_transform_point_to_point(other_point, &from_to_other, from_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x0 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y0 = static_cast<int>(other_pixel[1] + 0.5f);
// Map the bottom-right corner of the depth pixel onto the other image
from_pixel[0] = from_x + 0.5f; from_pixel[1] = from_y + 0.5f;
rs2_deproject_pixel_to_point(from_point, &from_intrin, from_pixel, depth);
rs2_transform_point_to_point(other_point, &from_to_other, from_point);
rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point);
const int other_x1 = static_cast<int>(other_pixel[0] + 0.5f);
const int other_y1 = static_cast<int>(other_pixel[1] + 0.5f);
if (other_x0 < 0 || other_y0 < 0 || other_x1 >= other_intrin.width || other_y1 >= other_intrin.height)
continue;
for (int y = other_y0; y <= other_y1; ++y)
{
for (int x = other_x0; x <= other_x1; ++x)
{
int out_pixel_index = y * other_intrin.width + x;
uint16_t* p_from_depth_frame = (uint16_t*)p_from_frame;
uint16_t* p_out_depth_frame = (uint16_t*)p_out_frame;
p_out_depth_frame[out_pixel_index] = p_from_depth_frame[from_pixel_index] * (depth_units / meter_to_mm);
}
}
}
}
}
}
void BaseRealSenseNode::updateIsFrameArrived(std::map<stream_index_pair, bool>& is_frame_arrived,
rs2_stream stream_type, int stream_index)
{
try
{
is_frame_arrived.at({stream_type, stream_index}) = true;
}
catch (std::out_of_range)
{
ROS_ERROR_STREAM("Stream type is not supported! (" << stream_type << ", " << stream_index << ")");
}
}
void BaseRealSenseNode::publishAlignedDepthToOthers(rs2::frame depth_frame, const std::vector<rs2::frame>& frames, const ros::Time& t)
{
for (auto&& other_frame : frames)
{
auto stream_type = other_frame.get_profile().stream_type();
if (RS2_STREAM_DEPTH == stream_type)
continue;
auto stream_index = other_frame.get_profile().stream_index();
stream_index_pair sip{stream_type, stream_index};
auto& info_publisher = _depth_aligned_info_publisher.at(sip);
auto& image_publisher = _depth_aligned_image_publishers.at(sip);
if(0 != info_publisher.getNumSubscribers() ||
0 != image_publisher.first.getNumSubscribers())
{
auto from_image_frame = depth_frame.as<rs2::video_frame>();
auto& out_vec = _aligned_depth_images[sip];
alignFrame(_stream_intrinsics[DEPTH], _stream_intrinsics[sip],
depth_frame, from_image_frame.get_bytes_per_pixel(),
_depth_to_other_extrinsics[sip], out_vec);
auto& from_image = _depth_aligned_image[sip];
from_image.data = out_vec.data();
publishFrame(depth_frame, t, sip,
_depth_aligned_image,
_depth_aligned_info_publisher,
_depth_aligned_image_publishers, _depth_aligned_seq,
_depth_aligned_camera_info, _optical_frame_id,
_depth_aligned_encoding, false);
}
}
}
void BaseRealSenseNode::setupStreams()
{
ROS_INFO("setupStreams...");
try{
for (auto& streams : IMAGE_STREAMS)
{
for (auto& elem : streams)
{
if (_enable[elem])
{
auto& sens = _sensors[elem];
auto profiles = sens.get_stream_profiles();
for (auto& profile : profiles)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
if (video_profile.format() == _format[elem] &&
video_profile.width() == _width[elem] &&
video_profile.height() == _height[elem] &&
video_profile.fps() == _fps[elem] &&
video_profile.stream_index() == elem.second)
{
_enabled_profiles[elem].push_back(profile);
_image[elem] = cv::Mat(_width[elem], _height[elem], _image_format[elem], cv::Scalar(0, 0, 0));
if (_align_depth)
_depth_aligned_image[elem] = cv::Mat(_width[DEPTH], _height[DEPTH], _image_format[DEPTH], cv::Scalar(0, 0, 0));
ROS_INFO_STREAM(_stream_name[elem] << " stream is enabled - width: " << _width[elem] << ", height: " << _height[elem] << ", fps: " << _fps[elem]);
break;
}
}
if (_enabled_profiles.find(elem) == _enabled_profiles.end())
{
ROS_WARN_STREAM("Given stream configuration is not supported by the device! " <<
" Stream: " << rs2_stream_to_string(elem.first) <<
", Stream Index: " << elem.second <<
", Format: " << _format[elem] <<
", Width: " << _width[elem] <<
", Height: " << _height[elem] <<
", FPS: " << _fps[elem]);
_enable[elem] = false;
}
}
}
}
// Publish image stream info
for (auto& profiles : _enabled_profiles)
{
for (auto& profile : profiles.second)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
updateStreamCalibData(video_profile);
}
}
auto frame_callback = [this](rs2::frame frame)
{
try{
// We compute a ROS timestamp which is based on an initial ROS time at point of first frame,
// and the incremental timestamp from the camera.
// In sync mode the timestamp is based on ROS time
if (false == _intialize_time_base)
{
if (RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME == frame.get_frame_timestamp_domain())
ROS_WARN("Frame metadata isn't available! (frame_timestamp_domain = RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)");
_intialize_time_base = true;
_ros_time_base = ros::Time::now();
_camera_time_base = frame.get_timestamp();
}
ros::Time t;
if (_sync_frames)
t = ros::Time::now();
else
t = ros::Time(_ros_time_base.toSec()+ (/*ms*/ frame.get_timestamp() - /*ms*/ _camera_time_base) / /*ms to seconds*/ 1000);
std::map<stream_index_pair, bool> is_frame_arrived(_is_frame_arrived);
std::vector<rs2::frame> frames;
if (frame.is<rs2::frameset>())
{
ROS_DEBUG("Frameset arrived.");
bool is_depth_arrived = false;
rs2::frame depth_frame;
auto frameset = frame.as<rs2::frameset>();
for (auto it = frameset.begin(); it != frameset.end(); ++it)
{
auto f = (*it);
auto stream_type = f.get_profile().stream_type();
auto stream_index = f.get_profile().stream_index();
updateIsFrameArrived(is_frame_arrived, stream_type, stream_index);
ROS_DEBUG("Frameset contain (%s, %d) frame. frame_number: %llu ; frame_TS: %f ; ros_TS(NSec): %lu",
rs2_stream_to_string(stream_type), stream_index, frame.get_frame_number(), frame.get_timestamp(), t.toNSec());
stream_index_pair sip{stream_type,stream_index};
publishFrame(f, t,
sip,
_image,
_info_publisher,
_image_publishers, _seq,
_camera_info, _optical_frame_id,
_encoding);
if (_align_depth && stream_type != RS2_STREAM_DEPTH)
{
frames.push_back(f);
}
else
{
depth_frame = f;
is_depth_arrived = true;
}
}
if (_align_depth && is_depth_arrived)
{
ROS_DEBUG("publishAlignedDepthToOthers(...)");
publishAlignedDepthToOthers(depth_frame, frames, t);
}
}
else
{
auto stream_type = frame.get_profile().stream_type();
auto stream_index = frame.get_profile().stream_index();
updateIsFrameArrived(is_frame_arrived, stream_type, stream_index);
ROS_DEBUG("Single video frame arrived (%s, %d). frame_number: %llu ; frame_TS: %f ; ros_TS(NSec): %lu",
rs2_stream_to_string(stream_type), stream_index, frame.get_frame_number(), frame.get_timestamp(), t.toNSec());
stream_index_pair sip{stream_type,stream_index};
publishFrame(frame, t,
sip,
_image,
_info_publisher,
_image_publishers, _seq,
_camera_info, _optical_frame_id,
_encoding);
}
if(_pointcloud && (0 != _pointcloud_publisher.getNumSubscribers()))
{
ROS_DEBUG("publishPCTopic(...)");
publishRgbToDepthPCTopic(t, is_frame_arrived);
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An error has occurred during frame callback: " << ex.what());
}
}; // frame_callback
// Streaming IMAGES
for (auto& streams : IMAGE_STREAMS)
{
std::vector<rs2::stream_profile> profiles;
for (auto& elem : streams)
{
if (!_enabled_profiles[elem].empty())
{
profiles.insert(profiles.begin(),
_enabled_profiles[elem].begin(),
_enabled_profiles[elem].end());
}
}
if (!profiles.empty())
{
auto stream = streams.front();
auto& sens = _sensors[stream];
sens.open(profiles);
if (DEPTH == stream)
{
auto depth_sensor = sens.as<rs2::depth_sensor>();
_depth_scale_meters = depth_sensor.get_depth_scale();
}
if (_sync_frames)
{
sens.start(_syncer);
}
else
{
sens.start(frame_callback);
}
}
}//end for
if (_sync_frames)
{
_syncer.start(frame_callback);
}
// Streaming HID
for (const auto streams : HID_STREAMS)
{
for (auto& elem : streams)
{
if (_enable[elem])
{
auto& sens = _sensors[elem];
auto profiles = sens.get_stream_profiles();
for (rs2::stream_profile& profile : profiles)
{
if (profile.fps() == _fps[elem] &&
profile.format() == _format[elem])
{
_enabled_profiles[elem].push_back(profile);
break;
}
}
}
}
}
auto gyro_profile = _enabled_profiles.find(GYRO);
auto accel_profile = _enabled_profiles.find(ACCEL);
if (gyro_profile != _enabled_profiles.end() &&
accel_profile != _enabled_profiles.end())
{
std::vector<rs2::stream_profile> profiles;
profiles.insert(profiles.begin(), gyro_profile->second.begin(), gyro_profile->second.end());
profiles.insert(profiles.begin(), accel_profile->second.begin(), accel_profile->second.end());
auto& sens = _sensors[GYRO];
sens.open(profiles);
sens.start([this](rs2::frame frame){
auto stream = frame.get_profile().stream_type();
if (false == _intialize_time_base)
return;
ROS_DEBUG("Frame arrived: stream: %s ; index: %d ; Timestamp Domain: %s",
rs2_stream_to_string(frame.get_profile().stream_type()),
frame.get_profile().stream_index(),
rs2_timestamp_domain_to_string(frame.get_frame_timestamp_domain()));
auto stream_index = (stream == GYRO.first)?GYRO:ACCEL;
if (0 != _info_publisher[stream_index].getNumSubscribers() ||
0 != _imu_publishers[stream_index].getNumSubscribers())
{
double elapsed_camera_ms = (/*ms*/ frame.get_timestamp() - /*ms*/ _camera_time_base) / /*ms to seconds*/ 1000;
ros::Time t(_ros_time_base.toSec() + elapsed_camera_ms);
auto imu_msg = sensor_msgs::Imu();
imu_msg.header.frame_id = _optical_frame_id[stream_index];
imu_msg.orientation.x = 0.0;
imu_msg.orientation.y = 0.0;
imu_msg.orientation.z = 0.0;
imu_msg.orientation.w = 0.0;
imu_msg.orientation_covariance = { -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
auto axes = *(reinterpret_cast<const float3*>(frame.get_data()));
if (GYRO == stream_index)
{
imu_msg.angular_velocity.x = axes.x;
imu_msg.angular_velocity.y = axes.y;
imu_msg.angular_velocity.z = axes.z;
}
else if (ACCEL == stream_index)
{
imu_msg.linear_acceleration.x = axes.x;
imu_msg.linear_acceleration.y = axes.y;
imu_msg.linear_acceleration.z = axes.z;
}
_seq[stream_index] += 1;
imu_msg.header.seq = _seq[stream_index];
imu_msg.header.stamp = t;
_imu_publishers[stream_index].publish(imu_msg);
ROS_DEBUG("Publish %s stream", rs2_stream_to_string(frame.get_profile().stream_type()));
}
});
if (_enable[GYRO])
{
ROS_INFO_STREAM(_stream_name[GYRO] << " stream is enabled - " << "fps: " << _fps[GYRO]);
auto gyroInfo = getImuInfo(GYRO);
_info_publisher[GYRO].publish(gyroInfo);
}
if (_enable[ACCEL])
{
ROS_INFO_STREAM(_stream_name[ACCEL] << " stream is enabled - " << "fps: " << _fps[ACCEL]);
auto accelInfo = getImuInfo(ACCEL);
_info_publisher[ACCEL].publish(accelInfo);
}
}
if (_enable[DEPTH] &&
_enable[FISHEYE])
{
static const char* frame_id = "depth_to_fisheye_extrinsics";
auto ex = getRsExtrinsics(DEPTH, FISHEYE);
_depth_to_other_extrinsics[FISHEYE] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[FISHEYE].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[COLOR])
{
static const char* frame_id = "depth_to_color_extrinsics";
auto ex = getRsExtrinsics(DEPTH, COLOR);
_depth_to_other_extrinsics[COLOR] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[COLOR].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[INFRA1])
{
static const char* frame_id = "depth_to_infra1_extrinsics";
auto ex = getRsExtrinsics(DEPTH, INFRA1);
_depth_to_other_extrinsics[INFRA1] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[INFRA1].publish(rsExtrinsicsToMsg(ex, frame_id));
}
if (_enable[DEPTH] &&
_enable[INFRA2])
{
static const char* frame_id = "depth_to_infra2_extrinsics";
auto ex = getRsExtrinsics(DEPTH, INFRA2);
_depth_to_other_extrinsics[INFRA2] = ex;
if (_align_depth)
ex = _i_ex;
_depth_to_other_extrinsics_publishers[INFRA2].publish(rsExtrinsicsToMsg(ex, frame_id));
}
}
catch(const std::exception& ex)
{
ROS_ERROR_STREAM("An exception has been thrown: " << ex.what());
throw;
}
catch(...)
{
ROS_ERROR_STREAM("Unknown exception has occured!");
throw;
}
}
void BaseRealSenseNode::updateStreamCalibData(const rs2::video_stream_profile& video_profile)
{
stream_index_pair stream_index{video_profile.stream_type(), video_profile.stream_index()};
auto intrinsic = video_profile.get_intrinsics();
_stream_intrinsics[stream_index] = intrinsic;
_camera_info[stream_index].width = intrinsic.width;
_camera_info[stream_index].height = intrinsic.height;
_camera_info[stream_index].header.frame_id = _optical_frame_id[stream_index];
_camera_info[stream_index].K.at(0) = intrinsic.fx;
_camera_info[stream_index].K.at(2) = intrinsic.ppx;
_camera_info[stream_index].K.at(4) = intrinsic.fy;
_camera_info[stream_index].K.at(5) = intrinsic.ppy;
_camera_info[stream_index].K.at(8) = 1;
_camera_info[stream_index].P.at(0) = _camera_info[stream_index].K.at(0);
_camera_info[stream_index].P.at(1) = 0;
_camera_info[stream_index].P.at(2) = _camera_info[stream_index].K.at(2);
_camera_info[stream_index].P.at(3) = 0;
_camera_info[stream_index].P.at(4) = 0;
_camera_info[stream_index].P.at(5) = _camera_info[stream_index].K.at(4);
_camera_info[stream_index].P.at(6) = _camera_info[stream_index].K.at(5);
_camera_info[stream_index].P.at(7) = 0;
_camera_info[stream_index].P.at(8) = 0;
_camera_info[stream_index].P.at(9) = 0;
_camera_info[stream_index].P.at(10) = 1;
_camera_info[stream_index].P.at(11) = 0;
rs2::stream_profile depth_profile;
if (!getEnabledProfile(DEPTH, depth_profile))
{
ROS_ERROR_STREAM("Given depth profile is not supported by current device!");
ros::shutdown();
exit(1);
}
_camera_info[stream_index].distortion_model = "plumb_bob";
// set R (rotation matrix) values to identity matrix
_camera_info[stream_index].R.at(0) = 1.0;
_camera_info[stream_index].R.at(1) = 0.0;
_camera_info[stream_index].R.at(2) = 0.0;
_camera_info[stream_index].R.at(3) = 0.0;
_camera_info[stream_index].R.at(4) = 1.0;
_camera_info[stream_index].R.at(5) = 0.0;
_camera_info[stream_index].R.at(6) = 0.0;
_camera_info[stream_index].R.at(7) = 0.0;
_camera_info[stream_index].R.at(8) = 1.0;
for (int i = 0; i < 5; i++)
{
_camera_info[stream_index].D.push_back(intrinsic.coeffs[i]);
}
if (stream_index == DEPTH && _enable[DEPTH] && _enable[COLOR])
{
_camera_info[stream_index].P.at(3) = 0; // Tx
_camera_info[stream_index].P.at(7) = 0; // Ty
}
if (_align_depth)
{
for (auto& profiles : _enabled_profiles)
{
for (auto& profile : profiles.second)
{
auto video_profile = profile.as<rs2::video_stream_profile>();
stream_index_pair stream_index{video_profile.stream_type(), video_profile.stream_index()};
_depth_aligned_camera_info[stream_index] = _camera_info[stream_index];
}
}
}
}
Eigen::Quaternionf BaseRealSenseNode::rotationMatrixToQuaternion(const float rotation[3]) const
{
Eigen::Matrix3f m;
m << rotation[0], rotation[1], rotation[2],
rotation[3], rotation[4], rotation[5],
rotation[6], rotation[7], rotation[8];
Eigen::Quaternionf q(m);
return q;
}
void BaseRealSenseNode::publish_static_tf(const ros::Time& t,
const float3& trans,
const quaternion& q,
const std::string& from,
const std::string& to)
{
geometry_msgs::TransformStamped msg;
msg.header.stamp = t;
msg.header.frame_id = from;
msg.child_frame_id = to;
msg.transform.translation.x = trans.z;
msg.transform.translation.y = -trans.x;
msg.transform.translation.z = -trans.y;
msg.transform.rotation.x = q.x;
msg.transform.rotation.y = q.y;
msg.transform.rotation.z = q.z;
msg.transform.rotation.w = q.w;
_static_tf_broadcaster.sendTransform(msg);
}
void BaseRealSenseNode::publishStaticTransforms()
{
ROS_INFO("publishStaticTransforms...");
// Publish static transforms
tf::Quaternion quaternion_optical;
quaternion_optical.setRPY(-M_PI / 2, 0.0, -M_PI / 2);
// Get the current timestamp for all static transforms
ros::Time transform_ts_ = ros::Time::now();
// The depth frame is used as the base link.
// Hence no additional transformation is done from base link to depth frame.
// Transform base link to depth frame
float3 zero_trans{0, 0, 0};
publish_static_tf(transform_ts_, zero_trans, quaternion{0, 0, 0, 1}, _base_frame_id, _frame_id[DEPTH]);
// Transform depth frame to depth optical frame
quaternion q{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q, _frame_id[DEPTH], _optical_frame_id[DEPTH]);
rs2::stream_profile depth_profile;
if (!getEnabledProfile(DEPTH, depth_profile))
{
ROS_ERROR_STREAM("Given depth profile is not supported by current device!");
ros::shutdown();
exit(1);
}
if (_enable[COLOR])
{
// Transform base to color
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, COLOR));
auto Q = rotationMatrixToQuaternion(ex.rotation);
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[COLOR]);
// Transform color frame to color optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[COLOR], _optical_frame_id[COLOR]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[COLOR]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[COLOR], _optical_frame_id[COLOR]);
}
}
if (_enable[INFRA1])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, INFRA1));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra1
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[INFRA1]);
// Transform infra1 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[INFRA1], _optical_frame_id[INFRA1]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[INFRA1]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[INFRA1], _optical_frame_id[INFRA1]);
}
}
if (_enable[INFRA2])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, INFRA2));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra2
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[INFRA2]);
// Transform infra2 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[INFRA2], _optical_frame_id[INFRA2]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[INFRA2]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[INFRA2], _optical_frame_id[INFRA2]);
}
}
if (_enable[FISHEYE])
{
auto& ex = (_align_depth)?(_i_ex):(getRsExtrinsics(DEPTH, FISHEYE));
auto Q = rotationMatrixToQuaternion(ex.rotation);
// Transform base to infra2
float3 trans{ex.translation[0], ex.translation[1], ex.translation[2]};
quaternion q1{Q.x(), Q.y(), Q.z(), Q.w()};
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _frame_id[FISHEYE]);
// Transform infra2 frame to infra1 optical frame
quaternion q2{quaternion_optical.getX(), quaternion_optical.getY(), quaternion_optical.getZ(), quaternion_optical.getW()};
publish_static_tf(transform_ts_, zero_trans, q2, _frame_id[FISHEYE], _optical_frame_id[FISHEYE]);
if (_align_depth)
{
publish_static_tf(transform_ts_, trans, q1, _base_frame_id, _depth_aligned_frame_id[FISHEYE]);
publish_static_tf(transform_ts_, zero_trans, q2, _depth_aligned_frame_id[FISHEYE], _optical_frame_id[FISHEYE]);
}
}
}
void BaseRealSenseNode::publishRgbToDepthPCTopic(const ros::Time& t, const std::map<stream_index_pair, bool>& is_frame_arrived)
{
try
{
if (!is_frame_arrived.at(COLOR) || !is_frame_arrived.at(DEPTH))
{
ROS_DEBUG("Skipping publish PC topic! Color or Depth frame didn't arrive.");
return;
}
}
catch (std::out_of_range)
{
ROS_DEBUG("Skipping publish PC topic! Color or Depth frame didn't configure.");
return;
}
auto& depth2color_extrinsics = _depth_to_other_extrinsics[COLOR];
auto color_intrinsics = _stream_intrinsics[COLOR];
auto image_depth16 = reinterpret_cast<const uint16_t*>(_image[DEPTH].data);
auto depth_intrinsics = _stream_intrinsics[DEPTH];
sensor_msgs::PointCloud2 msg_pointcloud;
msg_pointcloud.header.stamp = t;
msg_pointcloud.header.frame_id = _optical_frame_id[DEPTH];
msg_pointcloud.width = depth_intrinsics.width;
msg_pointcloud.height = depth_intrinsics.height;
msg_pointcloud.is_dense = true;
sensor_msgs::PointCloud2Modifier modifier(msg_pointcloud);
modifier.setPointCloud2Fields(4,
"x", 1, sensor_msgs::PointField::FLOAT32,
"y", 1, sensor_msgs::PointField::FLOAT32,
"z", 1, sensor_msgs::PointField::FLOAT32,
"rgb", 1, sensor_msgs::PointField::FLOAT32);
modifier.setPointCloud2FieldsByString(2, "xyz", "rgb");
sensor_msgs::PointCloud2Iterator<float>iter_x(msg_pointcloud, "x");
sensor_msgs::PointCloud2Iterator<float>iter_y(msg_pointcloud, "y");
sensor_msgs::PointCloud2Iterator<float>iter_z(msg_pointcloud, "z");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_r(msg_pointcloud, "r");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_g(msg_pointcloud, "g");
sensor_msgs::PointCloud2Iterator<uint8_t>iter_b(msg_pointcloud, "b");
float depth_point[3], color_point[3], color_pixel[2], scaled_depth;
unsigned char* color_data = _image[COLOR].data;
// Fill the PointCloud2 fields
for (int y = 0; y < depth_intrinsics.height; ++y)
{
for (int x = 0; x < depth_intrinsics.width; ++x)
{
scaled_depth = static_cast<float>(*image_depth16) * _depth_scale_meters;
float depth_pixel[2] = {static_cast<float>(x), static_cast<float>(y)};
rs2_deproject_pixel_to_point(depth_point, &depth_intrinsics, depth_pixel, scaled_depth);
if (depth_point[2] <= 0.f || depth_point[2] > 5.f)
{
depth_point[0] = 0.f;
depth_point[1] = 0.f;
depth_point[2] = 0.f;
}
*iter_x = depth_point[0];
*iter_y = depth_point[1];
*iter_z = depth_point[2];
rs2_transform_point_to_point(color_point, &depth2color_extrinsics, depth_point);
rs2_project_point_to_pixel(color_pixel, &color_intrinsics, color_point);
if (color_pixel[1] < 0.f || color_pixel[1] > color_intrinsics.height
|| color_pixel[0] < 0.f || color_pixel[0] > color_intrinsics.width)
{
// For out of bounds color data, default to a shade of blue in order to visually distinguish holes.
// This color value is same as the librealsense out of bounds color value.
*iter_r = static_cast<uint8_t>(96);
*iter_g = static_cast<uint8_t>(157);
*iter_b = static_cast<uint8_t>(198);
}
else
{
auto i = static_cast<int>(color_pixel[0]);
auto j = static_cast<int>(color_pixel[1]);
auto offset = i * 3 + j * color_intrinsics.width * 3;
*iter_r = static_cast<uint8_t>(color_data[offset]);
*iter_g = static_cast<uint8_t>(color_data[offset + 1]);
*iter_b = static_cast<uint8_t>(color_data[offset + 2]);
}
++image_depth16;
++iter_x; ++iter_y; ++iter_z;
++iter_r; ++iter_g; ++iter_b;
}
}
_pointcloud_publisher.publish(msg_pointcloud);
}
Extrinsics BaseRealSenseNode::rsExtrinsicsToMsg(const rs2_extrinsics& extrinsics, const std::string& frame_id) const
{
Extrinsics extrinsicsMsg;
for (int i = 0; i < 9; ++i)
{
extrinsicsMsg.rotation[i] = extrinsics.rotation[i];
if (i < 3)
extrinsicsMsg.translation[i] = extrinsics.translation[i];
}
extrinsicsMsg.header.frame_id = frame_id;
return extrinsicsMsg;
}
rs2_extrinsics BaseRealSenseNode::getRsExtrinsics(const stream_index_pair& from_stream, const stream_index_pair& to_stream)
{
auto& from = _enabled_profiles[from_stream].front();
auto& to = _enabled_profiles[to_stream].front();
return from.get_extrinsics_to(to);
}
IMUInfo BaseRealSenseNode::getImuInfo(const stream_index_pair& stream_index)
{
IMUInfo info{};
auto sp = _enabled_profiles[stream_index].front().as<rs2::motion_stream_profile>();
auto imuIntrinsics = sp.get_motion_intrinsics();
if (GYRO == stream_index)
{
info.header.frame_id = "imu_gyro";
}
else if (ACCEL == stream_index)
{
info.header.frame_id = "imu_accel";
}
auto index = 0;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
info.data[index] = imuIntrinsics.data[i][j];
++index;
}
info.noise_variances[i] = imuIntrinsics.noise_variances[i];
info.bias_variances[i] = imuIntrinsics.bias_variances[i];
}
return info;
}
void BaseRealSenseNode::publishFrame(rs2::frame f, const ros::Time& t,
const stream_index_pair& stream,
std::map<stream_index_pair, cv::Mat>& images,
const std::map<stream_index_pair, ros::Publisher>& info_publishers,
const std::map<stream_index_pair, ImagePublisherWithFrequencyDiagnostics>& image_publishers,
std::map<stream_index_pair, int>& seq,
std::map<stream_index_pair, sensor_msgs::CameraInfo>& camera_info,
const std::map<stream_index_pair, std::string>& optical_frame_id,
const std::map<stream_index_pair, std::string>& encoding,
bool copy_data_from_frame)
{
ROS_DEBUG("publishFrame(...)");
auto& image = images[stream];
if (copy_data_from_frame)
image.data = (uint8_t*)f.get_data();
++(seq[stream]);
auto& info_publisher = info_publishers.at(stream);
auto& image_publisher = image_publishers.at(stream);
if(0 != info_publisher.getNumSubscribers() ||
0 != image_publisher.first.getNumSubscribers())
{
auto width = 0;
auto height = 0;
auto bpp = 1;
if (f.is<rs2::video_frame>())
{
auto image = f.as<rs2::video_frame>();
width = image.get_width();
height = image.get_height();
bpp = image.get_bytes_per_pixel();
}
sensor_msgs::ImagePtr img;
img = cv_bridge::CvImage(std_msgs::Header(), encoding.at(stream), image).toImageMsg();
img->width = width;
img->height = height;
img->is_bigendian = false;
img->step = width * bpp;
img->header.frame_id = optical_frame_id.at(stream);
img->header.stamp = t;
img->header.seq = seq[stream];
auto& cam_info = camera_info.at(stream);
cam_info.header.stamp = t;
cam_info.header.seq = seq[stream];
info_publisher.publish(cam_info);
image_publisher.first.publish(img);
image_publisher.second->update();
ROS_DEBUG("%s stream published", rs2_stream_to_string(f.get_profile().stream_type()));
}
}
bool BaseRealSenseNode::getEnabledProfile(const stream_index_pair& stream_index, rs2::stream_profile& profile)
{
// Assuming that all D400 SKUs have depth sensor
auto profiles = _enabled_profiles[stream_index];
auto it = std::find_if(profiles.begin(), profiles.end(),
[&](const rs2::stream_profile& profile)
{ return (profile.stream_type() == stream_index.first); });
if (it == profiles.end())
return false;
profile = *it;
return true;
}
BaseD400Node::BaseD400Node(ros::NodeHandle& nodeHandle,
ros::NodeHandle& privateNodeHandle,
rs2::device dev, const std::string& serial_no)
: BaseRealSenseNode(nodeHandle,
privateNodeHandle,
dev, serial_no)
{}
void BaseD400Node::callback(base_d400_paramsConfig &config, uint32_t level)
{
ROS_DEBUG_STREAM("D400 - Level: " << level);
if (set_default_dynamic_reconfig_values == level)
{
for (int i = 1 ; i < base_depth_count ; ++i)
{
ROS_DEBUG_STREAM("base_depth_param = " << i);
setParam(config ,(base_depth_param)i);
}
}
else
{
setParam(config, (base_depth_param)level);
}
}
void BaseD400Node::setOption(stream_index_pair sip, rs2_option opt, float val)
{
_sensors[sip].set_option(opt, val);
}
void BaseD400Node::setParam(rs435_paramsConfig &config, base_depth_param param)
{
base_d400_paramsConfig base_config;
base_config.base_depth_gain = config.rs435_depth_gain;
base_config.base_depth_enable_auto_exposure = config.rs435_depth_enable_auto_exposure;
base_config.base_depth_visual_preset = config.rs435_depth_visual_preset;
base_config.base_depth_frames_queue_size = config.rs435_depth_frames_queue_size;
base_config.base_depth_error_polling_enabled = config.rs435_depth_error_polling_enabled;
base_config.base_depth_output_trigger_enabled = config.rs435_depth_output_trigger_enabled;
base_config.base_depth_units = config.rs435_depth_units;
base_config.base_JSON_file_path = config.rs435_JSON_file_path;
setParam(base_config, param);
}
void BaseD400Node::setParam(rs415_paramsConfig &config, base_depth_param param)
{
base_d400_paramsConfig base_config;
base_config.base_depth_gain = config.rs415_depth_gain;
base_config.base_depth_enable_auto_exposure = config.rs415_depth_enable_auto_exposure;
base_config.base_depth_visual_preset = config.rs415_depth_visual_preset;
base_config.base_depth_frames_queue_size = config.rs415_depth_frames_queue_size;
base_config.base_depth_error_polling_enabled = config.rs415_depth_error_polling_enabled;
base_config.base_depth_output_trigger_enabled = config.rs415_depth_output_trigger_enabled;
base_config.base_depth_units = config.rs415_depth_units;
base_config.base_JSON_file_path = config.rs415_JSON_file_path;
setParam(base_config, param);
}
void BaseD400Node::setParam(base_d400_paramsConfig &config, base_depth_param param)
{
// W/O for zero param
if (0 == param)
return;
switch (param) {
case base_depth_gain:
ROS_DEBUG_STREAM("base_depth_gain: " << config.base_depth_gain);
setOption(DEPTH, RS2_OPTION_GAIN, config.base_depth_gain);
break;
case base_depth_enable_auto_exposure:
ROS_DEBUG_STREAM("base_depth_enable_auto_exposure: " << config.base_depth_enable_auto_exposure);
setOption(DEPTH, RS2_OPTION_ENABLE_AUTO_EXPOSURE, config.base_depth_enable_auto_exposure);
break;
case base_depth_visual_preset:
ROS_DEBUG_STREAM("base_depth_enable_auto_exposure: " << config.base_depth_visual_preset);
setOption(DEPTH, RS2_OPTION_VISUAL_PRESET, config.base_depth_visual_preset);
break;
case base_depth_frames_queue_size:
ROS_DEBUG_STREAM("base_depth_frames_queue_size: " << config.base_depth_frames_queue_size);
setOption(DEPTH, RS2_OPTION_FRAMES_QUEUE_SIZE, config.base_depth_frames_queue_size);
break;
case base_depth_error_polling_enabled:
ROS_DEBUG_STREAM("base_depth_error_polling_enabled: " << config.base_depth_error_polling_enabled);
setOption(DEPTH, RS2_OPTION_ERROR_POLLING_ENABLED, config.base_depth_error_polling_enabled);
break;
case base_depth_output_trigger_enabled:
ROS_DEBUG_STREAM("base_depth_error_polling_enabled: " << config.base_depth_output_trigger_enabled);
setOption(DEPTH, RS2_OPTION_OUTPUT_TRIGGER_ENABLED, config.base_depth_output_trigger_enabled);
break;
case base_depth_units:
break;
case base_JSON_file_path:
{
ROS_DEBUG_STREAM("base_JSON_file_path: " << config.base_JSON_file_path);
auto adv_dev = _dev.as<rs400::advanced_mode>();
if (!adv_dev)
{
ROS_WARN_STREAM("Device doesn't support Advanced Mode!");
return;
}
if (!config.base_JSON_file_path.empty())
{
std::ifstream in(config.base_JSON_file_path);
if (!in.is_open())
{
ROS_WARN_STREAM("JSON file provided doesn't exist!");
return;
}
adv_dev.load_json(config.base_JSON_file_path);
}
break;
}
default:
ROS_WARN_STREAM("Unrecognized D400 param (" << param << ")");
break;
}
}
void BaseD400Node::registerDynamicReconfigCb()
{
_server = std::make_shared<dynamic_reconfigure::Server<base_d400_paramsConfig>>();
_f = boost::bind(&BaseD400Node::callback, this, _1, _2);
_server->setCallback(_f);
}
|
/*************************************************************************
*
* $RCSfile: FValue.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: oj $ $Date: 2001-10-01 11:24:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include "connectivity/FValue.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
using namespace connectivity;
using namespace dbtools;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::io;
namespace {
static sal_Bool isStorageCompatible(sal_Int32 _eType1, sal_Int32 _eType2)
{
sal_Bool bIsCompatible = sal_True;
if (_eType1 != _eType2)
{
switch (_eType1)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
bIsCompatible = (DataType::CHAR == _eType2)
|| (DataType::VARCHAR == _eType2)
|| (DataType::DECIMAL == _eType2)
|| (DataType::NUMERIC == _eType2);
break;
case DataType::FLOAT:
bIsCompatible = (DataType::FLOAT == _eType2);
break;
case DataType::DOUBLE:
case DataType::REAL:
bIsCompatible = (DataType::DOUBLE == _eType2)
|| (DataType::FLOAT == _eType2)
|| (DataType::REAL == _eType2);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
bIsCompatible = (DataType::BINARY == _eType2)
|| (DataType::VARBINARY == _eType2)
|| (DataType::LONGVARBINARY == _eType2)
|| (DataType::LONGVARCHAR == _eType2);
break;
case DataType::INTEGER:
bIsCompatible = (DataType::SMALLINT == _eType2)
|| (DataType::TINYINT == _eType2)
|| (DataType::BIT == _eType2);
break;
case DataType::SMALLINT:
bIsCompatible = (DataType::TINYINT == _eType2)
|| (DataType::BIT == _eType2);
break;
case DataType::TINYINT:
bIsCompatible = (DataType::BIT == _eType2);
break;
default:
bIsCompatible = sal_False;
}
}
return bIsCompatible;
}
}
// -----------------------------------------------------------------------------
void ORowSetValue::setTypeKind(sal_Int32 _eType)
{
if (!m_bNull)
if (!isStorageCompatible(_eType, m_eTypeKind))
{
switch(_eType)
{
case DataType::VARCHAR:
case DataType::CHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
(*this) = getString();
break;
case DataType::BIGINT:
(*this) = getLong();
break;
case DataType::LONGVARCHAR:
(*this) = getSequence();
break;
case DataType::FLOAT:
(*this) = getFloat();
break;
case DataType::DOUBLE:
case DataType::REAL:
(*this) = getDouble();
break;
case DataType::TINYINT:
(*this) = getInt8();
break;
case DataType::SMALLINT:
(*this) = getInt16();
break;
case DataType::INTEGER:
(*this) = getInt32();
break;
case DataType::BIT:
(*this) = getBool();
break;
case DataType::DATE:
(*this) = getDate();
break;
case DataType::TIME:
(*this) = getTime();
break;
case DataType::TIMESTAMP:
(*this) = getDateTime();
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
(*this) = getSequence();
break;
default:
OSL_ENSURE(0,"ORowSetValue:operator==(): UNSPUPPORTED TYPE!");
}
}
m_eTypeKind = _eType;
}
// -----------------------------------------------------------------------------
void ORowSetValue::free()
{
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
OSL_ENSURE(m_aValue.m_pString,"String pointer is null!");
rtl_uString_release(m_aValue.m_pString);
m_aValue.m_pString = NULL;
break;
case DataType::BIGINT:
delete (sal_Int64*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::FLOAT:
delete (float*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::DOUBLE:
case DataType::REAL:
delete (double*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::DATE:
delete (::com::sun::star::util::Date*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::TIME:
delete (::com::sun::star::util::Time*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::TIMESTAMP:
delete (::com::sun::star::util::DateTime*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
delete (Sequence<sal_Int8>*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::OBJECT:
delete (Any*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
}
m_bNull = sal_True;
}
}
// -----------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const ORowSetValue& _rRH)
{
if(&_rRH == this)
return *this;
if(m_eTypeKind != _rRH.m_eTypeKind || _rRH.m_bNull)
free();
m_bBound = _rRH.m_bBound;
m_eTypeKind = _rRH.m_eTypeKind;
if(m_bNull && !_rRH.m_bNull)
{
switch(_rRH.m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
m_aValue.m_pString = _rRH.m_aValue.m_pString;
rtl_uString_acquire(m_aValue.m_pString);
break;
case DataType::BIGINT:
m_aValue.m_pValue = new sal_Int64(*(sal_Int64*)_rRH.m_aValue.m_pValue);
break;
case DataType::FLOAT:
m_aValue.m_pValue = new float(*(float*)_rRH.m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
m_aValue.m_pValue = new double(*(double*)_rRH.m_aValue.m_pValue);
break;
case DataType::DATE:
m_aValue.m_pValue = new Date(*(Date*)_rRH.m_aValue.m_pValue);
break;
case DataType::TIME:
m_aValue.m_pValue = new Time(*(Time*)_rRH.m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
m_aValue.m_pValue = new DateTime(*(DateTime*)_rRH.m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
m_aValue.m_pValue = new Sequence<sal_Int8>(*(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue);
break;
case DataType::BIT:
m_aValue.m_bBool = _rRH.m_aValue.m_bBool;
break;
case DataType::TINYINT:
case DataType::SMALLINT:
case DataType::INTEGER:
m_aValue.m_nInt32 = _rRH.m_aValue.m_nInt32;
break;
default:
m_aValue.m_pValue = new Any(*(Any*)_rRH.m_aValue.m_pValue);
}
}
else if(!_rRH.m_bNull)
{
switch(_rRH.m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
(*this) = ::rtl::OUString(_rRH.m_aValue.m_pString);
break;
case DataType::BIGINT:
(*this) = *(sal_Int64*)_rRH.m_aValue.m_pValue;
break;
case DataType::FLOAT:
(*this) = *(float*)_rRH.m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
(*this) = *(double*)_rRH.m_aValue.m_pValue;
break;
case DataType::DATE:
(*this) = *(Date*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIME:
(*this) = *(Time*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
(*this) = *(DateTime*)_rRH.m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
(*this) = *(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue;
break;
case DataType::BIT:
m_aValue.m_bBool = _rRH.m_aValue.m_bBool;
break;
case DataType::TINYINT:
m_aValue.m_nInt8 = _rRH.m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
m_aValue.m_nInt16 = _rRH.m_aValue.m_nInt16;
break;
case DataType::INTEGER:
m_aValue.m_nInt32 = _rRH.m_aValue.m_nInt32;
break;
default:
(*(Any*)m_aValue.m_pValue) = (*(Any*)_rRH.m_aValue.m_pValue);
}
}
m_bNull = _rRH.m_bNull;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Date& _rRH)
{
if(m_eTypeKind != DataType::DATE)
free();
if(m_bNull)
{
m_aValue.m_pValue = new Date(_rRH);
m_eTypeKind = DataType::DATE;
m_bNull = sal_False;
}
else
*(Date*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Time& _rRH)
{
if(m_eTypeKind != DataType::TIME)
free();
if(m_bNull)
{
m_aValue.m_pValue = new Time(_rRH);
m_eTypeKind = DataType::TIME;
m_bNull = sal_False;
}
else
*(Time*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const DateTime& _rRH)
{
if(m_eTypeKind != DataType::TIMESTAMP)
free();
if(m_bNull)
{
m_aValue.m_pValue = new DateTime(_rRH);
m_eTypeKind = DataType::TIMESTAMP;
m_bNull = sal_False;
}
else
*(DateTime*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const ::rtl::OUString& _rRH)
{
if(m_eTypeKind != DataType::VARCHAR || m_aValue.m_pString != _rRH.pData)
{
free();
m_bNull = sal_False;
m_aValue.m_pString = _rRH.pData;
rtl_uString_acquire(m_aValue.m_pString);
m_eTypeKind = DataType::VARCHAR;
}
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const double& _rRH)
{
if(m_eTypeKind != DataType::DOUBLE)
free();
if(m_bNull)
{
m_aValue.m_pValue = new double(_rRH);
m_eTypeKind = DataType::DOUBLE;
m_bNull = sal_False;
}
else
*(double*)m_aValue.m_pValue = _rRH;
return *this;
}
// -----------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const float& _rRH)
{
if(m_eTypeKind != DataType::FLOAT)
free();
if(m_bNull)
{
m_aValue.m_pValue = new float(_rRH);
m_eTypeKind = DataType::FLOAT;
m_bNull = sal_False;
}
else
*(double*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int8& _rRH)
{
if(m_eTypeKind != DataType::TINYINT)
free();
m_aValue.m_nInt8 = _rRH;
m_eTypeKind = DataType::TINYINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int16& _rRH)
{
if(m_eTypeKind != DataType::SMALLINT)
free();
m_aValue.m_nInt16 = _rRH;
m_eTypeKind = DataType::SMALLINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int32& _rRH)
{
if(m_eTypeKind != DataType::INTEGER)
free();
m_aValue.m_nInt32 = _rRH;
m_eTypeKind = DataType::INTEGER;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Bool _rRH)
{
if(m_eTypeKind != DataType::BIT)
free();
m_aValue.m_bBool = _rRH;
m_eTypeKind = DataType::BIT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int64& _rRH)
{
if (DataType::BIGINT != m_eTypeKind)
free();
if(m_bNull)
m_aValue.m_pValue = new sal_Int64(_rRH);
else
*static_cast<sal_Int64*>(m_aValue.m_pValue) = _rRH;
m_eTypeKind = DataType::BIGINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Sequence<sal_Int8>& _rRH)
{
if (!isStorageCompatible(DataType::LONGVARCHAR,m_eTypeKind))
free();
if (m_bNull)
m_aValue.m_pValue = new Sequence<sal_Int8>(_rRH);
else
*static_cast< Sequence< sal_Int8 >* >(m_aValue.m_pValue) = _rRH;
m_eTypeKind = DataType::LONGVARCHAR;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Any& _rAny)
{
if (DataType::OBJECT != m_eTypeKind && !m_bNull)
free();
if(m_bNull)
m_aValue.m_pValue = new Any(_rAny);
else
*static_cast<Any*>(m_aValue.m_pValue) = _rAny;
m_eTypeKind = DataType::OBJECT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const Date& _rLH,const Date& _rRH)
{
return _rLH.Day == _rRH.Day && _rLH.Month == _rRH.Month && _rLH.Year == _rRH.Year;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const Time& _rLH,const Time& _rRH)
{
return _rLH.Minutes == _rRH.Minutes && _rLH.Hours == _rRH.Hours && _rLH.Seconds == _rRH.Seconds && _rLH.HundredthSeconds == _rRH.HundredthSeconds;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const DateTime& _rLH,const DateTime& _rRH)
{
return _rLH.Day == _rRH.Day && _rLH.Month == _rRH.Month && _rLH.Year == _rRH.Year &&
_rLH.Minutes == _rRH.Minutes && _rLH.Hours == _rRH.Hours && _rLH.Seconds == _rRH.Seconds && _rLH.HundredthSeconds == _rRH.HundredthSeconds;
}
// -------------------------------------------------------------------------
ORowSetValue::operator==(const ORowSetValue& _rRH) const
{
if(m_eTypeKind != _rRH.m_eTypeKind)
return sal_False;
if(m_bNull != _rRH.isNull())
return sal_False;
if(m_bNull && _rRH.isNull())
return sal_True;
sal_Bool bRet = sal_False;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::VARCHAR:
case DataType::CHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
{
::rtl::OUString aVal1(m_aValue.m_pString);
::rtl::OUString aVal2(_rRH.m_aValue.m_pString);
bRet = aVal1 == aVal2;
break;
}
case DataType::BIGINT:
bRet = *(sal_Int64*)m_aValue.m_pValue == *(sal_Int64*)_rRH.m_aValue.m_pValue;
break;
case DataType::LONGVARCHAR:
bRet = *(Sequence<sal_Int8>*)m_aValue.m_pValue == *(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue;
break;
case DataType::FLOAT:
bRet = *(float*)m_aValue.m_pValue == *(float*)_rRH.m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
bRet = *(double*)m_aValue.m_pValue == *(double*)_rRH.m_aValue.m_pValue;
break;
case DataType::TINYINT:
bRet = m_aValue.m_nInt8 == _rRH.m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
bRet = m_aValue.m_nInt16 == _rRH.m_aValue.m_nInt16;
break;
case DataType::INTEGER:
bRet = m_aValue.m_nInt32 == _rRH.m_aValue.m_nInt32;
break;
case DataType::BIT:
bRet = m_aValue.m_bBool == _rRH.m_aValue.m_bBool;
break;
case DataType::DATE:
bRet = *(Date*)m_aValue.m_pValue == *(Date*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIME:
bRet = *(Time*)m_aValue.m_pValue == *(Time*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
bRet = *(DateTime*)m_aValue.m_pValue == *(DateTime*)_rRH.m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
bRet = sal_False;
break;
default:
OSL_ENSURE(0,"ORowSetValue::operator==(): UNSPUPPORTED TYPE!");
}
}
return bRet;
}
// -------------------------------------------------------------------------
Any ORowSetValue::makeAny() const
{
Any rValue;
if(isBound() && !isNull())
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
OSL_ENSURE(m_aValue.m_pString,"Value is null!");
rValue <<= (::rtl::OUString)m_aValue.m_pString;
break;
case DataType::BIGINT:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(sal_Int64*)m_aValue.m_pValue;
break;
case DataType::FLOAT:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Date*)m_aValue.m_pValue;
break;
case DataType::TIME:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Time*)m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(DateTime*)m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Sequence<sal_Int8>*)m_aValue.m_pValue;
break;
case DataType::OBJECT:
rValue = getAny();
break;
case DataType::BIT:
rValue.setValue( &m_aValue.m_bBool, ::getCppuBooleanType() );
break;
case DataType::TINYINT:
rValue <<= m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
rValue <<= m_aValue.m_nInt16;
break;
case DataType::INTEGER:
rValue <<= m_aValue.m_nInt32;
break;
default:
OSL_ENSURE(0,"ORowSetValue::makeAny(): UNSPUPPORTED TYPE!");
}
}
return rValue;
}
// -------------------------------------------------------------------------
::rtl::OUString ORowSetValue::getString( ) const
{
::rtl::OUString aRet;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
aRet = m_aValue.m_pString;
break;
case DataType::BIGINT:
aRet = ::rtl::OUString::valueOf((sal_Int64)*this);
break;
case DataType::LONGVARCHAR:
{
Sequence<sal_Int8> aSeq(getSequence());
if(aSeq.getLength())
aRet = ::rtl::OUString(reinterpret_cast<sal_Unicode*>(aSeq.getArray()),aSeq.getLength()/sizeof(sal_Unicode));
}
break;
case DataType::FLOAT:
aRet = ::rtl::OUString::valueOf((float)*this);
break;
case DataType::DOUBLE:
case DataType::REAL:
aRet = ::rtl::OUString::valueOf((double)*this);
break;
case DataType::DATE:
aRet = connectivity::toDateString(*this);
break;
case DataType::TIME:
aRet = connectivity::toTimeString(*this);
break;
case DataType::TIMESTAMP:
aRet = connectivity::toDateTimeString(*this);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
{
aRet = ::rtl::OUString::createFromAscii("0x");
Sequence<sal_Int8> aSeq(getSequence());
const sal_Int8* pBegin = aSeq.getConstArray();
const sal_Int8* pEnd = pBegin + aSeq.getLength();
for(;pBegin != pEnd;++pBegin)
aRet += ::rtl::OUString::valueOf((sal_Int32)*pBegin,16);
}
break;
case DataType::BIT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Bool)*this);
break;
case DataType::TINYINT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Int8)*this);
break;
case DataType::SMALLINT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Int16)*this);
break;
case DataType::INTEGER:
aRet = ::rtl::OUString::valueOf((sal_Int32)*this);
break;
}
}
return aRet;
}
// -------------------------------------------------------------------------
sal_Bool ORowSetValue::getBool() const
{
sal_Bool bRet = sal_False;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
bRet = ::rtl::OUString(m_aValue.m_pString).toInt32() != 0;
break;
case DataType::BIGINT:
bRet = *(sal_Int64*)m_aValue.m_pValue != 0.0;
break;
case DataType::LONGVARCHAR:
bRet = getString().toInt32() != 0;
break;
case DataType::FLOAT:
bRet = *(float*)m_aValue.m_pValue != 0.0;
break;
case DataType::DOUBLE:
case DataType::REAL:
bRet = *(double*)m_aValue.m_pValue != 0.0;
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getBool() for this type is not allowed!");
break;
case DataType::BIT:
bRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
bRet = m_aValue.m_nInt8 != 0;
break;
case DataType::SMALLINT:
bRet = m_aValue.m_nInt16 != 0;
break;
case DataType::INTEGER:
bRet = m_aValue.m_nInt32 != 0;
break;
}
}
return bRet;
}
// -------------------------------------------------------------------------
sal_Int8 ORowSetValue::getInt8() const
{
sal_Int8 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = sal_Int8(::rtl::OUString(m_aValue.m_pString).toInt32());
break;
case DataType::BIGINT:
nRet = sal_Int8(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = sal_Int8(getString().toInt32());
break;
case DataType::FLOAT:
nRet = sal_Int8(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int8(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getInt8() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = sal_Int8(m_aValue.m_nInt16);
break;
case DataType::INTEGER:
nRet = sal_Int8(m_aValue.m_nInt32);
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int16 ORowSetValue::getInt16() const
{
sal_Int16 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = sal_Int16(::rtl::OUString(m_aValue.m_pString).toInt32());
break;
case DataType::BIGINT:
nRet = sal_Int16(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = sal_Int16(getString().toInt32());
break;
case DataType::FLOAT:
nRet = sal_Int16(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int16(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getInt16() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = (sal_Int16)m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int32 ORowSetValue::getInt32() const
{
sal_Int32 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toInt32();
break;
case DataType::BIGINT:
nRet = sal_Int32(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toInt32();
break;
case DataType::FLOAT:
nRet = sal_Int32(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int32(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDays(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getInt32() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int64 ORowSetValue::getLong() const
{
sal_Int64 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toInt64();
break;
case DataType::BIGINT:
nRet = *(sal_Int64*)m_aValue.m_pValue;
break;
case DataType::LONGVARCHAR:
nRet = getString().toInt64();
break;
case DataType::FLOAT:
nRet = sal_Int64(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int64(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDays(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getInt32() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
float ORowSetValue::getFloat() const
{
float nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toFloat();
break;
case DataType::BIGINT:
nRet = float(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toFloat();
break;
case DataType::FLOAT:
nRet = *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = (float)*(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Time*)m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::DateTime*)m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getDouble() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = (float)m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
double ORowSetValue::getDouble() const
{
double nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toDouble();
break;
case DataType::BIGINT:
nRet = double(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toDouble();
break;
case DataType::FLOAT:
nRet = *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = *(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Time*)m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::DateTime*)m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("getDouble() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
void ORowSetValue::setFromDouble(const double& _rVal,sal_Int32 _nDatatype)
{
free();
m_bNull = sal_False;
switch(_nDatatype)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
{
::rtl::OUString aVal = ::rtl::OUString::valueOf(_rVal);
m_aValue.m_pString = aVal.pData;
rtl_uString_acquire(m_aValue.m_pString);
}
break;
case DataType::BIGINT:
m_aValue.m_pValue = new sal_Int64((sal_Int64)_rVal);
break;
case DataType::LONGVARCHAR:
{
::rtl::OUString aVal = ::rtl::OUString::valueOf(_rVal);
m_aValue.m_pValue = new Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(aVal.getStr()),sizeof(sal_Unicode)*aVal.getLength());
}
break;
case DataType::FLOAT:
m_aValue.m_pValue = new float((float)_rVal);
break;
case DataType::DOUBLE:
case DataType::REAL:
m_aValue.m_pValue = new double(_rVal);
break;
case DataType::DATE:
m_aValue.m_pValue = new Date(dbtools::DBTypeConversion::toDate(_rVal));
break;
case DataType::TIME:
m_aValue.m_pValue = new Time(dbtools::DBTypeConversion::toTime(_rVal));
break;
case DataType::TIMESTAMP:
m_aValue.m_pValue = new DateTime(dbtools::DBTypeConversion::toDateTime(_rVal));
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT("setFromDouble() for this type is not allowed!");
break;
case DataType::BIT:
m_aValue.m_bBool = _rVal != 0.0;
break;
case DataType::TINYINT:
m_aValue.m_nInt8 = sal_Int8(_rVal);
break;
case DataType::SMALLINT:
m_aValue.m_nInt16 = sal_Int16(_rVal);
break;
case DataType::INTEGER:
m_aValue.m_nInt32 = sal_Int32(_rVal);
break;
}
m_eTypeKind = _nDatatype;
}
// -----------------------------------------------------------------------------
Sequence<sal_Int8> ORowSetValue::getSequence() const
{
Sequence<sal_Int8> aSeq;
if (!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::OBJECT:
case DataType::CLOB:
case DataType::BLOB:
{
Reference<XInputStream> xStream;
Any aValue = getAny();
if(aValue.hasValue())
{
aValue >>= xStream;
if(xStream.is())
xStream->readBytes(aSeq,xStream->available());
}
}
break;
case DataType::VARCHAR:
{
::rtl::OUString sVal(m_aValue.m_pString);
aSeq = Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(sVal.getStr()),sizeof(sal_Unicode)*sVal.getLength());
}
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
aSeq = *(Sequence<sal_Int8>*)m_aValue.m_pValue;
break;
default:
;
}
}
return aSeq;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::Date ORowSetValue::getDate() const
{
::com::sun::star::util::Date aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toDate(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toDate((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toDate((double)*this);
break;
case DataType::DATE:
aValue = *(::com::sun::star::util::Date*)m_aValue.m_pValue;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::Time ORowSetValue::getTime() const
{
::com::sun::star::util::Time aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toTime(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toTime((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toTime((double)*this);
break;
case DataType::TIME:
aValue = *(::com::sun::star::util::Time*)m_aValue.m_pValue;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::DateTime ORowSetValue::getDateTime() const
{
::com::sun::star::util::DateTime aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toDateTime(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toDateTime((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toDateTime((double)*this);
break;
case DataType::TIMESTAMP:
aValue = *(::com::sun::star::util::DateTime*)m_aValue.m_pValue;
break;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
#92000# some type fixes
/*************************************************************************
*
* $RCSfile: FValue.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: oj $ $Date: 2001-10-08 04:53:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include "connectivity/FValue.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
using namespace connectivity;
using namespace dbtools;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::io;
namespace {
static sal_Bool isStorageCompatible(sal_Int32 _eType1, sal_Int32 _eType2)
{
sal_Bool bIsCompatible = sal_True;
if (_eType1 != _eType2)
{
switch (_eType1)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
bIsCompatible = (DataType::CHAR == _eType2)
|| (DataType::VARCHAR == _eType2)
|| (DataType::DECIMAL == _eType2)
|| (DataType::NUMERIC == _eType2);
break;
case DataType::DOUBLE:
case DataType::REAL:
bIsCompatible = (DataType::DOUBLE == _eType2)
|| (DataType::REAL == _eType2);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
bIsCompatible = (DataType::BINARY == _eType2)
|| (DataType::VARBINARY == _eType2)
|| (DataType::LONGVARBINARY == _eType2)
|| (DataType::LONGVARCHAR == _eType2);
break;
case DataType::INTEGER:
bIsCompatible = (DataType::SMALLINT == _eType2)
|| (DataType::TINYINT == _eType2)
|| (DataType::BIT == _eType2);
break;
case DataType::SMALLINT:
bIsCompatible = (DataType::TINYINT == _eType2)
|| (DataType::BIT == _eType2);
break;
case DataType::TINYINT:
bIsCompatible = (DataType::BIT == _eType2);
break;
default:
bIsCompatible = sal_False;
}
}
return bIsCompatible;
}
}
// -----------------------------------------------------------------------------
void ORowSetValue::setTypeKind(sal_Int32 _eType)
{
if (!m_bNull)
if (!isStorageCompatible(_eType, m_eTypeKind))
{
switch(_eType)
{
case DataType::VARCHAR:
case DataType::CHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
(*this) = getString();
break;
case DataType::BIGINT:
(*this) = getLong();
break;
case DataType::LONGVARCHAR:
(*this) = getSequence();
break;
case DataType::FLOAT:
(*this) = getFloat();
break;
case DataType::DOUBLE:
case DataType::REAL:
(*this) = getDouble();
break;
case DataType::TINYINT:
(*this) = getInt8();
break;
case DataType::SMALLINT:
(*this) = getInt16();
break;
case DataType::INTEGER:
(*this) = getInt32();
break;
case DataType::BIT:
(*this) = getBool();
break;
case DataType::DATE:
(*this) = getDate();
break;
case DataType::TIME:
(*this) = getTime();
break;
case DataType::TIMESTAMP:
(*this) = getDateTime();
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
(*this) = getSequence();
break;
default:
OSL_ENSURE(0,"ORowSetValue:operator==(): UNSPUPPORTED TYPE!");
}
}
m_eTypeKind = _eType;
}
// -----------------------------------------------------------------------------
void ORowSetValue::free()
{
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
OSL_ENSURE(m_aValue.m_pString,"String pointer is null!");
rtl_uString_release(m_aValue.m_pString);
m_aValue.m_pString = NULL;
break;
case DataType::BIGINT:
delete (sal_Int64*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::FLOAT:
delete (float*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::DOUBLE:
case DataType::REAL:
delete (double*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::DATE:
delete (::com::sun::star::util::Date*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::TIME:
delete (::com::sun::star::util::Time*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::TIMESTAMP:
delete (::com::sun::star::util::DateTime*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
delete (Sequence<sal_Int8>*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
case DataType::OBJECT:
delete (Any*)m_aValue.m_pValue;
m_aValue.m_pValue = NULL;
break;
}
m_bNull = sal_True;
}
}
// -----------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const ORowSetValue& _rRH)
{
if(&_rRH == this)
return *this;
if(m_eTypeKind != _rRH.m_eTypeKind || _rRH.m_bNull)
free();
m_bBound = _rRH.m_bBound;
m_eTypeKind = _rRH.m_eTypeKind;
if(m_bNull && !_rRH.m_bNull)
{
switch(_rRH.m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
rtl_uString_acquire(_rRH.m_aValue.m_pString);
m_aValue.m_pString = _rRH.m_aValue.m_pString;
break;
case DataType::BIGINT:
m_aValue.m_pValue = new sal_Int64(*(sal_Int64*)_rRH.m_aValue.m_pValue);
break;
case DataType::FLOAT:
m_aValue.m_pValue = new float(*(float*)_rRH.m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
m_aValue.m_pValue = new double(*(double*)_rRH.m_aValue.m_pValue);
break;
case DataType::DATE:
m_aValue.m_pValue = new Date(*(Date*)_rRH.m_aValue.m_pValue);
break;
case DataType::TIME:
m_aValue.m_pValue = new Time(*(Time*)_rRH.m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
m_aValue.m_pValue = new DateTime(*(DateTime*)_rRH.m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
m_aValue.m_pValue = new Sequence<sal_Int8>(*(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue);
break;
case DataType::BIT:
m_aValue.m_bBool = _rRH.m_aValue.m_bBool;
break;
case DataType::TINYINT:
m_aValue.m_nInt8 = _rRH.m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
m_aValue.m_nInt16 = _rRH.m_aValue.m_nInt16;
break;
case DataType::INTEGER:
m_aValue.m_nInt32 = _rRH.m_aValue.m_nInt32;
break;
default:
m_aValue.m_pValue = new Any(*(Any*)_rRH.m_aValue.m_pValue);
}
}
else if(!_rRH.m_bNull)
{
switch(_rRH.m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
(*this) = ::rtl::OUString(_rRH.m_aValue.m_pString);
break;
case DataType::BIGINT:
(*this) = *(sal_Int64*)_rRH.m_aValue.m_pValue;
break;
case DataType::FLOAT:
(*this) = *(float*)_rRH.m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
(*this) = *(double*)_rRH.m_aValue.m_pValue;
break;
case DataType::DATE:
(*this) = *(Date*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIME:
(*this) = *(Time*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
(*this) = *(DateTime*)_rRH.m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
(*this) = *(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue;
break;
case DataType::BIT:
m_aValue.m_bBool = _rRH.m_aValue.m_bBool;
break;
case DataType::TINYINT:
m_aValue.m_nInt8 = _rRH.m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
m_aValue.m_nInt16 = _rRH.m_aValue.m_nInt16;
break;
case DataType::INTEGER:
m_aValue.m_nInt32 = _rRH.m_aValue.m_nInt32;
break;
default:
(*(Any*)m_aValue.m_pValue) = (*(Any*)_rRH.m_aValue.m_pValue);
}
}
m_bNull = _rRH.m_bNull;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Date& _rRH)
{
if(m_eTypeKind != DataType::DATE)
free();
if(m_bNull)
{
m_aValue.m_pValue = new Date(_rRH);
m_eTypeKind = DataType::DATE;
m_bNull = sal_False;
}
else
*(Date*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Time& _rRH)
{
if(m_eTypeKind != DataType::TIME)
free();
if(m_bNull)
{
m_aValue.m_pValue = new Time(_rRH);
m_eTypeKind = DataType::TIME;
m_bNull = sal_False;
}
else
*(Time*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const DateTime& _rRH)
{
if(m_eTypeKind != DataType::TIMESTAMP)
free();
if(m_bNull)
{
m_aValue.m_pValue = new DateTime(_rRH);
m_eTypeKind = DataType::TIMESTAMP;
m_bNull = sal_False;
}
else
*(DateTime*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const ::rtl::OUString& _rRH)
{
if(m_eTypeKind != DataType::VARCHAR || m_aValue.m_pString != _rRH.pData)
{
free();
m_bNull = sal_False;
m_aValue.m_pString = _rRH.pData;
rtl_uString_acquire(m_aValue.m_pString);
m_eTypeKind = DataType::VARCHAR;
}
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const double& _rRH)
{
if(m_eTypeKind != DataType::DOUBLE)
free();
if(m_bNull)
{
m_aValue.m_pValue = new double(_rRH);
m_eTypeKind = DataType::DOUBLE;
m_bNull = sal_False;
}
else
*(double*)m_aValue.m_pValue = _rRH;
return *this;
}
// -----------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const float& _rRH)
{
if(m_eTypeKind != DataType::FLOAT)
free();
if(m_bNull)
{
m_aValue.m_pValue = new float(_rRH);
m_eTypeKind = DataType::FLOAT;
m_bNull = sal_False;
}
else
*(double*)m_aValue.m_pValue = _rRH;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int8& _rRH)
{
if(m_eTypeKind != DataType::TINYINT)
free();
m_aValue.m_nInt8 = _rRH;
m_eTypeKind = DataType::TINYINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int16& _rRH)
{
if(m_eTypeKind != DataType::SMALLINT)
free();
m_aValue.m_nInt16 = _rRH;
m_eTypeKind = DataType::SMALLINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int32& _rRH)
{
if(m_eTypeKind != DataType::INTEGER)
free();
m_aValue.m_nInt32 = _rRH;
m_eTypeKind = DataType::INTEGER;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Bool _rRH)
{
if(m_eTypeKind != DataType::BIT)
free();
m_aValue.m_bBool = _rRH;
m_eTypeKind = DataType::BIT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const sal_Int64& _rRH)
{
if (DataType::BIGINT != m_eTypeKind)
free();
if(m_bNull)
m_aValue.m_pValue = new sal_Int64(_rRH);
else
*static_cast<sal_Int64*>(m_aValue.m_pValue) = _rRH;
m_eTypeKind = DataType::BIGINT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Sequence<sal_Int8>& _rRH)
{
if (!isStorageCompatible(DataType::LONGVARCHAR,m_eTypeKind))
free();
if (m_bNull)
m_aValue.m_pValue = new Sequence<sal_Int8>(_rRH);
else
*static_cast< Sequence< sal_Int8 >* >(m_aValue.m_pValue) = _rRH;
m_eTypeKind = DataType::LONGVARCHAR;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
ORowSetValue& ORowSetValue::operator=(const Any& _rAny)
{
if (DataType::OBJECT != m_eTypeKind && !m_bNull)
free();
if(m_bNull)
m_aValue.m_pValue = new Any(_rAny);
else
*static_cast<Any*>(m_aValue.m_pValue) = _rAny;
m_eTypeKind = DataType::OBJECT;
m_bNull = sal_False;
return *this;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const Date& _rLH,const Date& _rRH)
{
return _rLH.Day == _rRH.Day && _rLH.Month == _rRH.Month && _rLH.Year == _rRH.Year;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const Time& _rLH,const Time& _rRH)
{
return _rLH.Minutes == _rRH.Minutes && _rLH.Hours == _rRH.Hours && _rLH.Seconds == _rRH.Seconds && _rLH.HundredthSeconds == _rRH.HundredthSeconds;
}
// -------------------------------------------------------------------------
sal_Bool operator==(const DateTime& _rLH,const DateTime& _rRH)
{
return _rLH.Day == _rRH.Day && _rLH.Month == _rRH.Month && _rLH.Year == _rRH.Year &&
_rLH.Minutes == _rRH.Minutes && _rLH.Hours == _rRH.Hours && _rLH.Seconds == _rRH.Seconds && _rLH.HundredthSeconds == _rRH.HundredthSeconds;
}
// -------------------------------------------------------------------------
ORowSetValue::operator==(const ORowSetValue& _rRH) const
{
if(m_eTypeKind != _rRH.m_eTypeKind)
return sal_False;
if(m_bNull != _rRH.isNull())
return sal_False;
if(m_bNull && _rRH.isNull())
return sal_True;
sal_Bool bRet = sal_False;
OSL_ENSURE(!m_bNull,"SHould not be null!");
switch(m_eTypeKind)
{
case DataType::VARCHAR:
case DataType::CHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
{
::rtl::OUString aVal1(m_aValue.m_pString);
::rtl::OUString aVal2(_rRH.m_aValue.m_pString);
bRet = aVal1 == aVal2;
break;
}
case DataType::BIGINT:
bRet = *(sal_Int64*)m_aValue.m_pValue == *(sal_Int64*)_rRH.m_aValue.m_pValue;
break;
case DataType::LONGVARCHAR:
bRet = *(Sequence<sal_Int8>*)m_aValue.m_pValue == *(Sequence<sal_Int8>*)_rRH.m_aValue.m_pValue;
break;
case DataType::FLOAT:
bRet = *(float*)m_aValue.m_pValue == *(float*)_rRH.m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
bRet = *(double*)m_aValue.m_pValue == *(double*)_rRH.m_aValue.m_pValue;
break;
case DataType::TINYINT:
bRet = m_aValue.m_nInt8 == _rRH.m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
bRet = m_aValue.m_nInt16 == _rRH.m_aValue.m_nInt16;
break;
case DataType::INTEGER:
bRet = m_aValue.m_nInt32 == _rRH.m_aValue.m_nInt32;
break;
case DataType::BIT:
bRet = m_aValue.m_bBool == _rRH.m_aValue.m_bBool;
break;
case DataType::DATE:
bRet = *(Date*)m_aValue.m_pValue == *(Date*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIME:
bRet = *(Time*)m_aValue.m_pValue == *(Time*)_rRH.m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
bRet = *(DateTime*)m_aValue.m_pValue == *(DateTime*)_rRH.m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
bRet = sal_False;
break;
default:
OSL_ENSURE(0,"ORowSetValue::operator==(): UNSPUPPORTED TYPE!");
}
return bRet;
}
// -------------------------------------------------------------------------
Any ORowSetValue::makeAny() const
{
Any rValue;
if(isBound() && !isNull())
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
OSL_ENSURE(m_aValue.m_pString,"Value is null!");
rValue <<= (::rtl::OUString)m_aValue.m_pString;
break;
case DataType::BIGINT:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(sal_Int64*)m_aValue.m_pValue;
break;
case DataType::FLOAT:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Date*)m_aValue.m_pValue;
break;
case DataType::TIME:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Time*)m_aValue.m_pValue;
break;
case DataType::TIMESTAMP:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(DateTime*)m_aValue.m_pValue;
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
OSL_ENSURE(m_aValue.m_pValue,"Value is null!");
rValue <<= *(Sequence<sal_Int8>*)m_aValue.m_pValue;
break;
case DataType::OBJECT:
rValue = getAny();
break;
case DataType::BIT:
rValue.setValue( &m_aValue.m_bBool, ::getCppuBooleanType() );
break;
case DataType::TINYINT:
rValue <<= m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
rValue <<= m_aValue.m_nInt16;
break;
case DataType::INTEGER:
rValue <<= m_aValue.m_nInt32;
break;
default:
OSL_ENSURE(0,"ORowSetValue::makeAny(): UNSPUPPORTED TYPE!");
}
}
return rValue;
}
// -------------------------------------------------------------------------
::rtl::OUString ORowSetValue::getString( ) const
{
::rtl::OUString aRet;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
aRet = m_aValue.m_pString;
break;
case DataType::BIGINT:
aRet = ::rtl::OUString::valueOf((sal_Int64)*this);
break;
case DataType::LONGVARCHAR:
{
Sequence<sal_Int8> aSeq(getSequence());
if(aSeq.getLength())
aRet = ::rtl::OUString(reinterpret_cast<const sal_Unicode*>(aSeq.getConstArray()),aSeq.getLength()/sizeof(sal_Unicode));
}
break;
case DataType::FLOAT:
aRet = ::rtl::OUString::valueOf((float)*this);
break;
case DataType::DOUBLE:
case DataType::REAL:
aRet = ::rtl::OUString::valueOf((double)*this);
break;
case DataType::DATE:
aRet = connectivity::toDateString(*this);
break;
case DataType::TIME:
aRet = connectivity::toTimeString(*this);
break;
case DataType::TIMESTAMP:
aRet = connectivity::toDateTimeString(*this);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
{
aRet = ::rtl::OUString::createFromAscii("0x");
Sequence<sal_Int8> aSeq(getSequence());
const sal_Int8* pBegin = aSeq.getConstArray();
const sal_Int8* pEnd = pBegin + aSeq.getLength();
for(;pBegin != pEnd;++pBegin)
aRet += ::rtl::OUString::valueOf((sal_Int32)*pBegin,16);
}
break;
case DataType::BIT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Bool)*this);
break;
case DataType::TINYINT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Int8)*this);
break;
case DataType::SMALLINT:
aRet = ::rtl::OUString::valueOf((sal_Int32)(sal_Int16)*this);
break;
case DataType::INTEGER:
aRet = ::rtl::OUString::valueOf((sal_Int32)*this);
break;
}
}
return aRet;
}
// -------------------------------------------------------------------------
sal_Bool ORowSetValue::getBool() const
{
sal_Bool bRet = sal_False;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
bRet = ::rtl::OUString(m_aValue.m_pString).toInt32() != 0;
break;
case DataType::BIGINT:
bRet = *(sal_Int64*)m_aValue.m_pValue != 0.0;
break;
case DataType::LONGVARCHAR:
bRet = getString().toInt32() != 0;
break;
case DataType::FLOAT:
bRet = *(float*)m_aValue.m_pValue != 0.0;
break;
case DataType::DOUBLE:
case DataType::REAL:
bRet = *(double*)m_aValue.m_pValue != 0.0;
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getBool() for this type is not allowed!");
break;
case DataType::BIT:
bRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
bRet = m_aValue.m_nInt8 != 0;
break;
case DataType::SMALLINT:
bRet = m_aValue.m_nInt16 != 0;
break;
case DataType::INTEGER:
bRet = m_aValue.m_nInt32 != 0;
break;
}
}
return bRet;
}
// -------------------------------------------------------------------------
sal_Int8 ORowSetValue::getInt8() const
{
sal_Int8 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = sal_Int8(::rtl::OUString(m_aValue.m_pString).toInt32());
break;
case DataType::BIGINT:
nRet = sal_Int8(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = sal_Int8(getString().toInt32());
break;
case DataType::FLOAT:
nRet = sal_Int8(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int8(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getInt8() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = sal_Int8(m_aValue.m_nInt16);
break;
case DataType::INTEGER:
nRet = sal_Int8(m_aValue.m_nInt32);
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int16 ORowSetValue::getInt16() const
{
sal_Int16 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = sal_Int16(::rtl::OUString(m_aValue.m_pString).toInt32());
break;
case DataType::BIGINT:
nRet = sal_Int16(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = sal_Int16(getString().toInt32());
break;
case DataType::FLOAT:
nRet = sal_Int16(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int16(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getInt16() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = (sal_Int16)m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int32 ORowSetValue::getInt32() const
{
sal_Int32 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toInt32();
break;
case DataType::BIGINT:
nRet = sal_Int32(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toInt32();
break;
case DataType::FLOAT:
nRet = sal_Int32(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int32(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDays(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getInt32() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
sal_Int64 ORowSetValue::getLong() const
{
sal_Int64 nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toInt64();
break;
case DataType::BIGINT:
nRet = *(sal_Int64*)m_aValue.m_pValue;
break;
case DataType::LONGVARCHAR:
nRet = getString().toInt64();
break;
case DataType::FLOAT:
nRet = sal_Int64(*(float*)m_aValue.m_pValue);
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = sal_Int64(*(double*)m_aValue.m_pValue);
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDays(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
case DataType::TIMESTAMP:
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getInt32() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
float ORowSetValue::getFloat() const
{
float nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toFloat();
break;
case DataType::BIGINT:
nRet = float(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toFloat();
break;
case DataType::FLOAT:
nRet = *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = (float)*(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Time*)m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
nRet = (float)dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::DateTime*)m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getDouble() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = (float)m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
double ORowSetValue::getDouble() const
{
double nRet = 0;
if(!m_bNull)
{
switch(getTypeKind())
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
nRet = ::rtl::OUString(m_aValue.m_pString).toDouble();
break;
case DataType::BIGINT:
nRet = double(*(sal_Int64*)m_aValue.m_pValue);
break;
case DataType::LONGVARCHAR:
nRet = getString().toDouble();
break;
case DataType::FLOAT:
nRet = *(float*)m_aValue.m_pValue;
break;
case DataType::DOUBLE:
case DataType::REAL:
nRet = *(double*)m_aValue.m_pValue;
break;
case DataType::DATE:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Date*)m_aValue.m_pValue);
break;
case DataType::TIME:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::Time*)m_aValue.m_pValue);
break;
case DataType::TIMESTAMP:
nRet = dbtools::DBTypeConversion::toDouble(*(::com::sun::star::util::DateTime*)m_aValue.m_pValue);
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"getDouble() for this type is not allowed!");
break;
case DataType::BIT:
nRet = m_aValue.m_bBool;
break;
case DataType::TINYINT:
nRet = m_aValue.m_nInt8;
break;
case DataType::SMALLINT:
nRet = m_aValue.m_nInt16;
break;
case DataType::INTEGER:
nRet = m_aValue.m_nInt32;
break;
}
}
return nRet;
}
// -------------------------------------------------------------------------
void ORowSetValue::setFromDouble(const double& _rVal,sal_Int32 _nDatatype)
{
free();
m_bNull = sal_False;
switch(_nDatatype)
{
case DataType::CHAR:
case DataType::VARCHAR:
case DataType::DECIMAL:
case DataType::NUMERIC:
{
::rtl::OUString aVal = ::rtl::OUString::valueOf(_rVal);
m_aValue.m_pString = aVal.pData;
rtl_uString_acquire(m_aValue.m_pString);
}
break;
case DataType::BIGINT:
m_aValue.m_pValue = new sal_Int64((sal_Int64)_rVal);
break;
case DataType::LONGVARCHAR:
{
::rtl::OUString aVal = ::rtl::OUString::valueOf(_rVal);
m_aValue.m_pValue = new Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(aVal.getStr()),sizeof(sal_Unicode)*aVal.getLength());
}
break;
case DataType::FLOAT:
m_aValue.m_pValue = new float((float)_rVal);
break;
case DataType::DOUBLE:
case DataType::REAL:
m_aValue.m_pValue = new double(_rVal);
break;
case DataType::DATE:
m_aValue.m_pValue = new Date(dbtools::DBTypeConversion::toDate(_rVal));
break;
case DataType::TIME:
m_aValue.m_pValue = new Time(dbtools::DBTypeConversion::toTime(_rVal));
break;
case DataType::TIMESTAMP:
m_aValue.m_pValue = new DateTime(dbtools::DBTypeConversion::toDateTime(_rVal));
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
OSL_ASSERT(!"setFromDouble() for this type is not allowed!");
break;
case DataType::BIT:
m_aValue.m_bBool = _rVal != 0.0;
break;
case DataType::TINYINT:
m_aValue.m_nInt8 = sal_Int8(_rVal);
break;
case DataType::SMALLINT:
m_aValue.m_nInt16 = sal_Int16(_rVal);
break;
case DataType::INTEGER:
m_aValue.m_nInt32 = sal_Int32(_rVal);
break;
}
m_eTypeKind = _nDatatype;
}
// -----------------------------------------------------------------------------
Sequence<sal_Int8> ORowSetValue::getSequence() const
{
Sequence<sal_Int8> aSeq;
if (!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::OBJECT:
case DataType::CLOB:
case DataType::BLOB:
{
Reference<XInputStream> xStream;
Any aValue = getAny();
if(aValue.hasValue())
{
aValue >>= xStream;
if(xStream.is())
xStream->readBytes(aSeq,xStream->available());
}
}
break;
case DataType::VARCHAR:
{
::rtl::OUString sVal(m_aValue.m_pString);
aSeq = Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(sVal.getStr()),sizeof(sal_Unicode)*sVal.getLength());
}
break;
case DataType::BINARY:
case DataType::VARBINARY:
case DataType::LONGVARBINARY:
case DataType::LONGVARCHAR:
aSeq = *(Sequence<sal_Int8>*)m_aValue.m_pValue;
break;
default:
;
}
}
return aSeq;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::Date ORowSetValue::getDate() const
{
::com::sun::star::util::Date aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toDate(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toDate((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toDate((double)*this);
break;
case DataType::DATE:
aValue = *(::com::sun::star::util::Date*)m_aValue.m_pValue;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::Time ORowSetValue::getTime() const
{
::com::sun::star::util::Time aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toTime(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toTime((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toTime((double)*this);
break;
case DataType::TIME:
aValue = *(::com::sun::star::util::Time*)m_aValue.m_pValue;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
::com::sun::star::util::DateTime ORowSetValue::getDateTime() const
{
::com::sun::star::util::DateTime aValue;
if(!m_bNull)
{
switch(m_eTypeKind)
{
case DataType::CHAR:
case DataType::VARCHAR:
aValue = DBTypeConversion::toDateTime(getString());
break;
case DataType::DECIMAL:
case DataType::NUMERIC:
aValue = DBTypeConversion::toDateTime((double)*this);
break;
case DataType::FLOAT:
case DataType::DOUBLE:
case DataType::REAL:
aValue = DBTypeConversion::toDateTime((double)*this);
break;
case DataType::TIMESTAMP:
aValue = *(::com::sun::star::util::DateTime*)m_aValue.m_pValue;
break;
}
}
return aValue;
}
// -----------------------------------------------------------------------------
|
/*************************************************************************
*
* $RCSfile: Class.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: oj $ $Date: 2001-08-14 07:21:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************
jclass java_lang_Class::theClass = 0;
java_lang_Class::~java_lang_Class()
{}
jclass java_lang_Class::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_lang_Class::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_ASCII_US);
sClassName = sClassName.replace('.','/');
out = t.pEnv->FindClass(sClassName);
ThrowSQLException(t.pEnv,0);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}
sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
jboolean out;
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/Class;)Z";
char * cMethodName = "isAssignableFrom";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jvalue args[1];
// Parameter konvertieren
args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
ThrowSQLException(t.pEnv,0);
// und aufraeumen
} //mID
} //t.pEnv
return out;
}
java_lang_Object * java_lang_Class::newInstance()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/Object;";
char * cMethodName = "newInstance";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}
jobject java_lang_Class::newInstanceObject()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/Object;";
char * cMethodName = "newInstance";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out;
}
::rtl::OUString java_lang_Class::getName()
{
jstring out = (jstring)NULL;
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/String;";
char * cMethodName = "getName";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = (jstring)t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
if(out)
aStr = JavaString2String(t.pEnv, (jstring)out );
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
INTEGRATION: CWS mav4 (1.7.80); FILE MERGED
2003/04/15 12:22:06 oj 1.7.80.1: #108943# merge from apps61beta2 and statement fix, concurrency
/*************************************************************************
*
* $RCSfile: Class.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2003-04-24 13:19:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************
jclass java_lang_Class::theClass = 0;
java_lang_Class::~java_lang_Class()
{}
jclass java_lang_Class::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_lang_Class::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_ASCII_US);
sClassName = sClassName.replace('.','/');
out = t.pEnv->FindClass(sClassName);
ThrowSQLException(t.pEnv,0);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}
sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
jboolean out;
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/Class;)Z";
char * cMethodName = "isAssignableFrom";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jvalue args[1];
// Parameter konvertieren
args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
ThrowSQLException(t.pEnv,0);
// und aufraeumen
} //mID
} //t.pEnv
return out;
}
java_lang_Object * java_lang_Class::newInstance()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/Object;";
char * cMethodName = "newInstance";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}
jobject java_lang_Class::newInstanceObject()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/Object;";
char * cMethodName = "newInstance";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out;
}
::rtl::OUString java_lang_Class::getName()
{
jstring out = (jstring)NULL;
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()Ljava/lang/String;";
char * cMethodName = "getName";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = (jstring)t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
if(out)
aStr = JavaString2String(t.pEnv, (jstring)out );
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
|
/*************************************************************************
*
* $RCSfile: tools.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: obo $ $Date: 2004-03-15 12:48:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <cstdarg>
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_
#include "java/lang/String.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef CONNECTIVITY_java_util_Properties
#include "java/util/Property.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value)
{
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
jobject out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,key);
args[1].l = convertwchar_tToJavaString(t.pEnv,value);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
char * cMethodName = "setProperty";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID )
{
out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
ThrowSQLException(t.pEnv,NULL);
}
t.pEnv->DeleteLocalRef((jstring)args[1].l);
t.pEnv->DeleteLocalRef((jstring)args[0].l);
ThrowSQLException(t.pEnv,0);
if(out)
t.pEnv->DeleteLocalRef(out);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}
jclass java_util_Properties::theClass = 0;
java_util_Properties::~java_util_Properties()
{}
jclass java_util_Properties::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass( "java/util/Properties" );
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_util_Properties::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
//--------------------------------------------------------------------------
java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "()V";
jobject tempObj;
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->NewObject( getMyClass(), mID);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
}
// --------------------------------------------------------------------------------
jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp)
{
jstring pStr = NULL;
if (pEnv)
{
pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
pEnv->ExceptionClear();
OSL_ENSURE(pStr,"Could not create a jsstring object!");
}
return pStr;
}
// --------------------------------------------------------------------------------
java_util_Properties* connectivity::createStringPropertyArray(JNIEnv *pEnv,const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
java_util_Properties* pProps = new java_util_Properties();
const PropertyValue* pBegin = info.getConstArray();
const PropertyValue* pEnd = pBegin + info.getLength();
for(;pBegin != pEnd;++pBegin)
{
// this is a special property to find the jdbc driver
if( pBegin->Name.compareToAscii("JavaDriverClass") &&
pBegin->Name.compareToAscii("CharSet") &&
pBegin->Name.compareToAscii("AppendTableAlias") &&
pBegin->Name.compareToAscii("ParameterNameSubstitution") &&
pBegin->Name.compareToAscii("IsPasswordRequired") &&
pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") &&
pBegin->Name.compareToAscii("AutoRetrievingStatement") &&
pBegin->Name.compareToAscii("AutoIncrementCreation") &&
pBegin->Name.compareToAscii("Extension") &&
pBegin->Name.compareToAscii("NoNameLengthLimit") &&
pBegin->Name.compareToAscii("EnableSQL92Check") &&
pBegin->Name.compareToAscii("EnableOuterJoinEscape") &&
pBegin->Name.compareToAscii("BooleanComparisonMode"))
{
::rtl::OUString aStr;
pBegin->Value >>= aStr;
pProps->setProperty(pBegin->Name,aStr);
}
}
return pProps;
}
// --------------------------------------------------------------------------------
::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
::rtl::OUString aStr;
if(_Str)
{
jboolean bCopy(sal_True);
const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
jsize len = pEnv->GetStringLength(_Str);
aStr = ::rtl::OUString(pChar,len);
if(bCopy)
pEnv->ReleaseStringChars(_Str,pChar);
pEnv->DeleteLocalRef(_Str);
}
return aStr;
}
// --------------------------------------------------------------------------------
jobject connectivity::XNameAccess2Map(JNIEnv *pEnv,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSeq = _rMap->getElementNames();
const ::rtl::OUString *pBegin = aSeq.getConstArray();
const ::rtl::OUString *pEnd = pBegin + aSeq.getLength();
for(;pBegin != pEnd;++pBegin)
{
}
return 0;
}
// -----------------------------------------------------------------------------
sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear)
{
if ( !pEnv )
return sal_False;
jthrowable pThrowable = pEnv->ExceptionOccurred();
sal_Bool bRet = pThrowable != NULL;
if ( pThrowable )
{
if ( _bClear )
pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass()))
{
java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
::rtl::OUString sError = pException->getMessage();
delete pException;
}
#else
pEnv->DeleteLocalRef(pThrowable);
#endif
}
return bRet;
}
INTEGRATION: CWS insight01 (1.15.14); FILE MERGED
2004/05/28 11:17:25 oj 1.15.14.2: RESYNC: (1.15-1.16); FILE MERGED
2004/04/23 06:25:48 oj 1.15.14.1: new switch to disable catalog and schema
/*************************************************************************
*
* $RCSfile: tools.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2004-08-02 17:05:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <cstdarg>
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_
#include "java/lang/String.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef CONNECTIVITY_java_util_Properties
#include "java/util/Property.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value)
{
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
jobject out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,key);
args[1].l = convertwchar_tToJavaString(t.pEnv,value);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
char * cMethodName = "setProperty";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID )
{
out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
ThrowSQLException(t.pEnv,NULL);
}
t.pEnv->DeleteLocalRef((jstring)args[1].l);
t.pEnv->DeleteLocalRef((jstring)args[0].l);
ThrowSQLException(t.pEnv,0);
if(out)
t.pEnv->DeleteLocalRef(out);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}
jclass java_util_Properties::theClass = 0;
java_util_Properties::~java_util_Properties()
{}
jclass java_util_Properties::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass( "java/util/Properties" );
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_util_Properties::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
//--------------------------------------------------------------------------
java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "()V";
jobject tempObj;
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->NewObject( getMyClass(), mID);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
}
// --------------------------------------------------------------------------------
jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp)
{
jstring pStr = NULL;
if (pEnv)
{
pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
pEnv->ExceptionClear();
OSL_ENSURE(pStr,"Could not create a jsstring object!");
}
return pStr;
}
// --------------------------------------------------------------------------------
java_util_Properties* connectivity::createStringPropertyArray(JNIEnv *pEnv,const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
java_util_Properties* pProps = new java_util_Properties();
const PropertyValue* pBegin = info.getConstArray();
const PropertyValue* pEnd = pBegin + info.getLength();
for(;pBegin != pEnd;++pBegin)
{
// this is a special property to find the jdbc driver
if( pBegin->Name.compareToAscii("JavaDriverClass") &&
pBegin->Name.compareToAscii("CharSet") &&
pBegin->Name.compareToAscii("AppendTableAlias") &&
pBegin->Name.compareToAscii("ParameterNameSubstitution") &&
pBegin->Name.compareToAscii("IsPasswordRequired") &&
pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") &&
pBegin->Name.compareToAscii("AutoRetrievingStatement") &&
pBegin->Name.compareToAscii("UseCatalogInSelect") &&
pBegin->Name.compareToAscii("UseSchemaInSelect") &&
pBegin->Name.compareToAscii("AutoIncrementCreation") &&
pBegin->Name.compareToAscii("Extension") &&
pBegin->Name.compareToAscii("NoNameLengthLimit") &&
pBegin->Name.compareToAscii("EnableSQL92Check") &&
pBegin->Name.compareToAscii("EnableOuterJoinEscape") &&
pBegin->Name.compareToAscii("BooleanComparisonMode"))
{
::rtl::OUString aStr;
pBegin->Value >>= aStr;
pProps->setProperty(pBegin->Name,aStr);
}
}
return pProps;
}
// --------------------------------------------------------------------------------
::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
::rtl::OUString aStr;
if(_Str)
{
jboolean bCopy(sal_True);
const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
jsize len = pEnv->GetStringLength(_Str);
aStr = ::rtl::OUString(pChar,len);
if(bCopy)
pEnv->ReleaseStringChars(_Str,pChar);
pEnv->DeleteLocalRef(_Str);
}
return aStr;
}
// --------------------------------------------------------------------------------
jobject connectivity::XNameAccess2Map(JNIEnv *pEnv,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSeq = _rMap->getElementNames();
const ::rtl::OUString *pBegin = aSeq.getConstArray();
const ::rtl::OUString *pEnd = pBegin + aSeq.getLength();
for(;pBegin != pEnd;++pBegin)
{
}
return 0;
}
// -----------------------------------------------------------------------------
sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear)
{
if ( !pEnv )
return sal_False;
jthrowable pThrowable = pEnv->ExceptionOccurred();
sal_Bool bRet = pThrowable != NULL;
if ( pThrowable )
{
if ( _bClear )
pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass()))
{
java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
::rtl::OUString sError = pException->getMessage();
delete pException;
}
#else
pEnv->DeleteLocalRef(pThrowable);
#endif
}
return bRet;
}
|
/*************************************************************************
*
* $RCSfile: DCatalog.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:14:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
namespace connectivity
{
namespace dbase
{
class ODbaseConnection;
class ODbaseCatalog : public file::OFileCatalog
{
public:
virtual void refreshTables();
public:
ODbaseCatalog(ODbaseConnection* _pCon);
};
}
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_
INTEGRATION: CWS ooo19126 (1.1.1.1.364); FILE MERGED
2005/09/05 17:25:13 rt 1.1.1.1.364.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DCatalog.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:01:16 $
*
* 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 _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
namespace connectivity
{
namespace dbase
{
class ODbaseConnection;
class ODbaseCatalog : public file::OFileCatalog
{
public:
virtual void refreshTables();
public:
ODbaseCatalog(ODbaseConnection* _pCon);
};
}
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_
|
// 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 "remoting/host/plugin/daemon_controller.h"
#include <objbase.h>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string16.h"
#include "base/stringize_macros.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/timer.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "remoting/base/scoped_sc_handle_win.h"
#include "remoting/host/branding.h"
#include "remoting/host/daemon_controller_common_win.h"
#include "remoting/host/plugin/daemon_installer_win.h"
// MIDL-generated declarations and definitions.
#include "remoting/host/elevated_controller.h"
using base::win::ScopedBstr;
using base::win::ScopedComPtr;
namespace remoting {
namespace {
// The COM elevation moniker for the Elevated Controller.
const char16 kDaemonControllerElevationMoniker[] =
TO_L_STRING("Elevation:Administrator!new:")
TO_L_STRING("ChromotingElevatedController.ElevatedController");
// Name of the Daemon Controller's worker thread.
const char kDaemonControllerThreadName[] = "Daemon Controller thread";
// The maximum interval between showing UAC prompts.
const int kUacTimeoutSec = 15 * 60;
// A base::Thread implementation that initializes COM on the new thread.
class ComThread : public base::Thread {
public:
explicit ComThread(const char* name);
// Activates an elevated instance of the controller and returns the pointer
// to the control interface in |control_out|. This class keeps the ownership
// of the pointer so the caller should not call call AddRef() or Release().
HRESULT ActivateElevatedController(HWND window_handle,
IDaemonControl** control_out);
bool Start();
protected:
virtual void Init() OVERRIDE;
virtual void CleanUp() OVERRIDE;
void ReleaseElevatedController();
ScopedComPtr<IDaemonControl> control_;
// This timer is used to release |control_| after a timeout.
base::OneShotTimer<ComThread> release_timer_;
DISALLOW_COPY_AND_ASSIGN(ComThread);
};
class DaemonControllerWin : public remoting::DaemonController {
public:
DaemonControllerWin();
virtual ~DaemonControllerWin();
virtual State GetState() OVERRIDE;
virtual void GetConfig(const GetConfigCallback& callback) OVERRIDE;
virtual void SetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) OVERRIDE;
virtual void UpdateConfig(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) OVERRIDE;
virtual void Stop(const CompletionCallback& done_callback) OVERRIDE;
virtual void SetWindow(void* window_handle) OVERRIDE;
private:
// Converts a Windows service status code to a Daemon state.
static State ConvertToDaemonState(DWORD service_state);
// Converts HRESULT to the AsyncResult.
static AsyncResult HResultToAsyncResult(HRESULT hr);
// Procedes with the daemon configuration if the installation succeeded,
// otherwise reports the error.
void OnInstallationComplete(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback,
HRESULT result);
// Opens the Chromoting service returning its handle in |service_out|.
DWORD OpenService(ScopedScHandle* service_out);
// The functions that actually do the work. They should be called in
// the context of |worker_thread_|;
void DoGetConfig(const GetConfigCallback& callback);
void DoInstallAsNeededAndStart(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoSetConfigAndStart(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoUpdateConfig(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoStop(const CompletionCallback& done_callback);
void DoSetWindow(void* window_handle);
// Handle of the plugin window.
HWND window_handle_;
// The worker thread used for servicing long running operations.
ComThread worker_thread_;
scoped_ptr<DaemonInstallerWin> installer_;
DISALLOW_COPY_AND_ASSIGN(DaemonControllerWin);
};
ComThread::ComThread(const char* name) : base::Thread(name), control_(NULL) {
}
HRESULT ComThread::ActivateElevatedController(
HWND window_handle,
IDaemonControl** control_out) {
// Cache an instance of the Elevated Controller to prevent a UAC prompt on
// every operation.
if (control_.get() == NULL) {
BIND_OPTS3 bind_options;
memset(&bind_options, 0, sizeof(bind_options));
bind_options.cbStruct = sizeof(bind_options);
bind_options.hwnd = GetTopLevelWindow(window_handle);
bind_options.dwClassContext = CLSCTX_LOCAL_SERVER;
HRESULT hr = ::CoGetObject(
kDaemonControllerElevationMoniker,
&bind_options,
IID_IDaemonControl,
control_.ReceiveVoid());
if (FAILED(hr)) {
return hr;
}
// Release |control_| upon expiration of the timeout.
release_timer_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(kUacTimeoutSec),
this, &ComThread::ReleaseElevatedController);
}
*control_out = control_.get();
return S_OK;
}
bool ComThread::Start() {
// N.B. The single threaded COM apartment must be run on a UI message loop.
base::Thread::Options thread_options(MessageLoop::TYPE_UI, 0);
return StartWithOptions(thread_options);
}
void ComThread::Init() {
CoInitialize(NULL);
}
void ComThread::CleanUp() {
ReleaseElevatedController();
CoUninitialize();
}
void ComThread::ReleaseElevatedController() {
control_.Release();
}
DaemonControllerWin::DaemonControllerWin()
: window_handle_(NULL),
worker_thread_(kDaemonControllerThreadName) {
if (!worker_thread_.Start()) {
LOG(FATAL) << "Failed to start the Daemon Controller worker thread.";
}
}
DaemonControllerWin::~DaemonControllerWin() {
worker_thread_.Stop();
}
remoting::DaemonController::State DaemonControllerWin::GetState() {
// TODO(alexeypa): Make the thread alertable, so we can switch to APC
// notifications rather than polling.
ScopedScHandle service;
DWORD error = OpenService(&service);
switch (error) {
case ERROR_SUCCESS: {
SERVICE_STATUS status;
if (::QueryServiceStatus(service, &status)) {
return ConvertToDaemonState(status.dwCurrentState);
} else {
LOG_GETLASTERROR(ERROR)
<< "Failed to query the state of the '" << kWindowsServiceName
<< "' service";
return STATE_UNKNOWN;
}
break;
}
case ERROR_SERVICE_DOES_NOT_EXIST:
return STATE_NOT_INSTALLED;
default:
return STATE_UNKNOWN;
}
}
void DaemonControllerWin::GetConfig(const GetConfigCallback& callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE,
base::Bind(&DaemonControllerWin::DoGetConfig,
base::Unretained(this), callback));
}
void DaemonControllerWin::SetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoInstallAsNeededAndStart,
base::Unretained(this), base::Passed(&config), done_callback));
}
void DaemonControllerWin::UpdateConfig(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoUpdateConfig,
base::Unretained(this), base::Passed(&config), done_callback));
}
void DaemonControllerWin::Stop(const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoStop, base::Unretained(this),
done_callback));
}
void DaemonControllerWin::SetWindow(void* window_handle) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoSetWindow, base::Unretained(this),
window_handle));
}
// static
remoting::DaemonController::State DaemonControllerWin::ConvertToDaemonState(
DWORD service_state) {
switch (service_state) {
case SERVICE_RUNNING:
return STATE_STARTED;
case SERVICE_CONTINUE_PENDING:
case SERVICE_START_PENDING:
return STATE_STARTING;
break;
case SERVICE_PAUSE_PENDING:
case SERVICE_STOP_PENDING:
return STATE_STOPPING;
break;
case SERVICE_PAUSED:
case SERVICE_STOPPED:
return STATE_STOPPED;
break;
default:
NOTREACHED();
return STATE_UNKNOWN;
}
}
// static
DaemonController::AsyncResult DaemonControllerWin::HResultToAsyncResult(
HRESULT hr) {
// TODO(sergeyu): Report other errors to the webapp once it knows
// how to handle them.
return FAILED(hr) ? RESULT_FAILED : RESULT_OK;
}
void DaemonControllerWin::OnInstallationComplete(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback,
HRESULT result) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
if (SUCCEEDED(result)) {
DoSetConfigAndStart(config.Pass(), done_callback);
} else {
LOG(ERROR) << "Failed to install the Chromoting Host "
<< "(error: 0x" << std::hex << result << std::dec << ").";
done_callback.Run(HResultToAsyncResult(result));
}
DCHECK(installer_.get() != NULL);
installer_.reset();
}
DWORD DaemonControllerWin::OpenService(ScopedScHandle* service_out) {
// Open the service and query its current state.
ScopedScHandle scmanager(
::OpenSCManagerW(NULL, SERVICES_ACTIVE_DATABASE,
SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE));
if (!scmanager.IsValid()) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to connect to the service control manager";
return error;
}
ScopedScHandle service(
::OpenServiceW(scmanager, kWindowsServiceName, SERVICE_QUERY_STATUS));
if (!service.IsValid()) {
DWORD error = GetLastError();
if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
LOG_GETLASTERROR(ERROR)
<< "Failed to open to the '" << kWindowsServiceName << "' service";
}
return error;
}
service_out->Set(service.Take());
return ERROR_SUCCESS;
}
void DaemonControllerWin::DoGetConfig(const GetConfigCallback& callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
scoped_ptr<base::DictionaryValue> dictionary_null(NULL);
// Get the name of the configuration file.
FilePath dir = remoting::GetConfigDir();
FilePath filename = dir.Append(kUnprivilegedConfigFileName);
// Read raw data from the configuration file.
base::win::ScopedHandle file(
CreateFileW(filename.value().c_str(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL));
if (!file.IsValid()) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to open '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
scoped_array<char> buffer(new char[kMaxConfigFileSize]);
DWORD size = kMaxConfigFileSize;
if (!::ReadFile(file, &buffer[0], size, &size, NULL)) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to read '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
// Parse the JSON configuration, expecting it to contain a dictionary.
std::string file_content(buffer.get(), size);
scoped_ptr<base::Value> value(
base::JSONReader::Read(file_content, base::JSON_ALLOW_TRAILING_COMMAS));
base::DictionaryValue* dictionary = NULL;
if (value.get() == NULL || !value->GetAsDictionary(&dictionary)) {
LOG(ERROR) << "Failed to read '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
// Release value, because dictionary points to the same object.
value.release();
callback.Run(scoped_ptr<base::DictionaryValue>(dictionary));
}
void DaemonControllerWin::DoInstallAsNeededAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
// Just configure and start the Daemon Controller if it is installed already.
if (SUCCEEDED(hr)) {
DoSetConfigAndStart(config.Pass(), done_callback);
return;
}
// Otherwise, install it if its COM registration entry is missing.
if (hr == CO_E_CLASSSTRING) {
scoped_ptr<DaemonInstallerWin> installer = DaemonInstallerWin::Create(
window_handle_,
base::Bind(&DaemonControllerWin::OnInstallationComplete,
base::Unretained(this),
base::Passed(&config),
done_callback));
if (installer.get()) {
DCHECK(!installer_.get());
installer_ = installer.Pass();
installer_->Install();
}
} else {
LOG(ERROR) << "Failed to initiate the Chromoting Host installation "
<< "(error: 0x" << std::hex << hr << std::dec << ").";
done_callback.Run(HResultToAsyncResult(hr));
}
}
void DaemonControllerWin::DoSetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Store the configuration.
std::string file_content;
base::JSONWriter::Write(config.get(), &file_content);
ScopedBstr host_config(UTF8ToUTF16(file_content).c_str());
if (host_config == NULL) {
done_callback.Run(HResultToAsyncResult(E_OUTOFMEMORY));
return;
}
hr = control->SetConfig(host_config);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Start daemon.
hr = control->StartDaemon();
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoUpdateConfig(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
// TODO(simonmorris): Much of this code was copied from DoSetConfigAndStart().
// Refactor.
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Store the configuration.
std::string file_content;
base::JSONWriter::Write(config.get(), &file_content);
ScopedBstr host_config(UTF8ToUTF16(file_content).c_str());
if (host_config == NULL) {
done_callback.Run(HResultToAsyncResult(E_OUTOFMEMORY));
return;
}
hr = control->UpdateConfig(host_config);
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoStop(const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
hr = control->StopDaemon();
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoSetWindow(void* window_handle) {
window_handle_ = reinterpret_cast<HWND>(window_handle);
}
} // namespace
scoped_ptr<DaemonController> remoting::DaemonController::Create() {
return scoped_ptr<DaemonController>(new DaemonControllerWin());
}
} // namespace remoting
[Chromoting] Factor duplicated code out of the Windows daemon controller.
Review URL: http://codereview.chromium.org/10228019
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@134322 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "remoting/host/plugin/daemon_controller.h"
#include <objbase.h>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string16.h"
#include "base/stringize_macros.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/timer.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "remoting/base/scoped_sc_handle_win.h"
#include "remoting/host/branding.h"
#include "remoting/host/daemon_controller_common_win.h"
#include "remoting/host/plugin/daemon_installer_win.h"
// MIDL-generated declarations and definitions.
#include "remoting/host/elevated_controller.h"
using base::win::ScopedBstr;
using base::win::ScopedComPtr;
namespace remoting {
namespace {
// The COM elevation moniker for the Elevated Controller.
const char16 kDaemonControllerElevationMoniker[] =
TO_L_STRING("Elevation:Administrator!new:")
TO_L_STRING("ChromotingElevatedController.ElevatedController");
// Name of the Daemon Controller's worker thread.
const char kDaemonControllerThreadName[] = "Daemon Controller thread";
// The maximum interval between showing UAC prompts.
const int kUacTimeoutSec = 15 * 60;
// A base::Thread implementation that initializes COM on the new thread.
class ComThread : public base::Thread {
public:
explicit ComThread(const char* name);
// Activates an elevated instance of the controller and returns the pointer
// to the control interface in |control_out|. This class keeps the ownership
// of the pointer so the caller should not call call AddRef() or Release().
HRESULT ActivateElevatedController(HWND window_handle,
IDaemonControl** control_out);
bool Start();
protected:
virtual void Init() OVERRIDE;
virtual void CleanUp() OVERRIDE;
void ReleaseElevatedController();
ScopedComPtr<IDaemonControl> control_;
// This timer is used to release |control_| after a timeout.
base::OneShotTimer<ComThread> release_timer_;
DISALLOW_COPY_AND_ASSIGN(ComThread);
};
class DaemonControllerWin : public remoting::DaemonController {
public:
DaemonControllerWin();
virtual ~DaemonControllerWin();
virtual State GetState() OVERRIDE;
virtual void GetConfig(const GetConfigCallback& callback) OVERRIDE;
virtual void SetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) OVERRIDE;
virtual void UpdateConfig(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) OVERRIDE;
virtual void Stop(const CompletionCallback& done_callback) OVERRIDE;
virtual void SetWindow(void* window_handle) OVERRIDE;
private:
// Converts a Windows service status code to a Daemon state.
static State ConvertToDaemonState(DWORD service_state);
// Converts HRESULT to the AsyncResult.
static AsyncResult HResultToAsyncResult(HRESULT hr);
// Procedes with the daemon configuration if the installation succeeded,
// otherwise reports the error.
void OnInstallationComplete(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback,
HRESULT result);
// Opens the Chromoting service returning its handle in |service_out|.
DWORD OpenService(ScopedScHandle* service_out);
// Converts a config dictionary to a scoped BSTR.
static void ConfigToString(const base::DictionaryValue& config,
ScopedBstr* out);
// The functions that actually do the work. They should be called in
// the context of |worker_thread_|;
void DoGetConfig(const GetConfigCallback& callback);
void DoInstallAsNeededAndStart(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoSetConfigAndStart(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoUpdateConfig(scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback);
void DoStop(const CompletionCallback& done_callback);
void DoSetWindow(void* window_handle);
// Handle of the plugin window.
HWND window_handle_;
// The worker thread used for servicing long running operations.
ComThread worker_thread_;
scoped_ptr<DaemonInstallerWin> installer_;
DISALLOW_COPY_AND_ASSIGN(DaemonControllerWin);
};
ComThread::ComThread(const char* name) : base::Thread(name), control_(NULL) {
}
HRESULT ComThread::ActivateElevatedController(
HWND window_handle,
IDaemonControl** control_out) {
// Cache an instance of the Elevated Controller to prevent a UAC prompt on
// every operation.
if (control_.get() == NULL) {
BIND_OPTS3 bind_options;
memset(&bind_options, 0, sizeof(bind_options));
bind_options.cbStruct = sizeof(bind_options);
bind_options.hwnd = GetTopLevelWindow(window_handle);
bind_options.dwClassContext = CLSCTX_LOCAL_SERVER;
HRESULT hr = ::CoGetObject(
kDaemonControllerElevationMoniker,
&bind_options,
IID_IDaemonControl,
control_.ReceiveVoid());
if (FAILED(hr)) {
return hr;
}
// Release |control_| upon expiration of the timeout.
release_timer_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(kUacTimeoutSec),
this, &ComThread::ReleaseElevatedController);
}
*control_out = control_.get();
return S_OK;
}
bool ComThread::Start() {
// N.B. The single threaded COM apartment must be run on a UI message loop.
base::Thread::Options thread_options(MessageLoop::TYPE_UI, 0);
return StartWithOptions(thread_options);
}
void ComThread::Init() {
CoInitialize(NULL);
}
void ComThread::CleanUp() {
ReleaseElevatedController();
CoUninitialize();
}
void ComThread::ReleaseElevatedController() {
control_.Release();
}
DaemonControllerWin::DaemonControllerWin()
: window_handle_(NULL),
worker_thread_(kDaemonControllerThreadName) {
if (!worker_thread_.Start()) {
LOG(FATAL) << "Failed to start the Daemon Controller worker thread.";
}
}
DaemonControllerWin::~DaemonControllerWin() {
worker_thread_.Stop();
}
remoting::DaemonController::State DaemonControllerWin::GetState() {
// TODO(alexeypa): Make the thread alertable, so we can switch to APC
// notifications rather than polling.
ScopedScHandle service;
DWORD error = OpenService(&service);
switch (error) {
case ERROR_SUCCESS: {
SERVICE_STATUS status;
if (::QueryServiceStatus(service, &status)) {
return ConvertToDaemonState(status.dwCurrentState);
} else {
LOG_GETLASTERROR(ERROR)
<< "Failed to query the state of the '" << kWindowsServiceName
<< "' service";
return STATE_UNKNOWN;
}
break;
}
case ERROR_SERVICE_DOES_NOT_EXIST:
return STATE_NOT_INSTALLED;
default:
return STATE_UNKNOWN;
}
}
void DaemonControllerWin::GetConfig(const GetConfigCallback& callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE,
base::Bind(&DaemonControllerWin::DoGetConfig,
base::Unretained(this), callback));
}
void DaemonControllerWin::SetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoInstallAsNeededAndStart,
base::Unretained(this), base::Passed(&config), done_callback));
}
void DaemonControllerWin::UpdateConfig(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoUpdateConfig,
base::Unretained(this), base::Passed(&config), done_callback));
}
void DaemonControllerWin::Stop(const CompletionCallback& done_callback) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoStop, base::Unretained(this),
done_callback));
}
void DaemonControllerWin::SetWindow(void* window_handle) {
worker_thread_.message_loop_proxy()->PostTask(
FROM_HERE, base::Bind(
&DaemonControllerWin::DoSetWindow, base::Unretained(this),
window_handle));
}
// static
remoting::DaemonController::State DaemonControllerWin::ConvertToDaemonState(
DWORD service_state) {
switch (service_state) {
case SERVICE_RUNNING:
return STATE_STARTED;
case SERVICE_CONTINUE_PENDING:
case SERVICE_START_PENDING:
return STATE_STARTING;
break;
case SERVICE_PAUSE_PENDING:
case SERVICE_STOP_PENDING:
return STATE_STOPPING;
break;
case SERVICE_PAUSED:
case SERVICE_STOPPED:
return STATE_STOPPED;
break;
default:
NOTREACHED();
return STATE_UNKNOWN;
}
}
// static
DaemonController::AsyncResult DaemonControllerWin::HResultToAsyncResult(
HRESULT hr) {
// TODO(sergeyu): Report other errors to the webapp once it knows
// how to handle them.
return FAILED(hr) ? RESULT_FAILED : RESULT_OK;
}
void DaemonControllerWin::OnInstallationComplete(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback,
HRESULT result) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
if (SUCCEEDED(result)) {
DoSetConfigAndStart(config.Pass(), done_callback);
} else {
LOG(ERROR) << "Failed to install the Chromoting Host "
<< "(error: 0x" << std::hex << result << std::dec << ").";
done_callback.Run(HResultToAsyncResult(result));
}
DCHECK(installer_.get() != NULL);
installer_.reset();
}
DWORD DaemonControllerWin::OpenService(ScopedScHandle* service_out) {
// Open the service and query its current state.
ScopedScHandle scmanager(
::OpenSCManagerW(NULL, SERVICES_ACTIVE_DATABASE,
SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE));
if (!scmanager.IsValid()) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to connect to the service control manager";
return error;
}
ScopedScHandle service(
::OpenServiceW(scmanager, kWindowsServiceName, SERVICE_QUERY_STATUS));
if (!service.IsValid()) {
DWORD error = GetLastError();
if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
LOG_GETLASTERROR(ERROR)
<< "Failed to open to the '" << kWindowsServiceName << "' service";
}
return error;
}
service_out->Set(service.Take());
return ERROR_SUCCESS;
}
void DaemonControllerWin::ConfigToString(const base::DictionaryValue& config,
ScopedBstr* out) {
std::string config_str;
base::JSONWriter::Write(&config, &config_str);
ScopedBstr config_scoped_bstr(UTF8ToUTF16(config_str).c_str());
out->Swap(config_scoped_bstr);
}
void DaemonControllerWin::DoGetConfig(const GetConfigCallback& callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
scoped_ptr<base::DictionaryValue> dictionary_null(NULL);
// Get the name of the configuration file.
FilePath dir = remoting::GetConfigDir();
FilePath filename = dir.Append(kUnprivilegedConfigFileName);
// Read raw data from the configuration file.
base::win::ScopedHandle file(
CreateFileW(filename.value().c_str(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL));
if (!file.IsValid()) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to open '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
scoped_array<char> buffer(new char[kMaxConfigFileSize]);
DWORD size = kMaxConfigFileSize;
if (!::ReadFile(file, &buffer[0], size, &size, NULL)) {
DWORD error = GetLastError();
LOG_GETLASTERROR(ERROR)
<< "Failed to read '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
// Parse the JSON configuration, expecting it to contain a dictionary.
std::string file_content(buffer.get(), size);
scoped_ptr<base::Value> value(
base::JSONReader::Read(file_content, base::JSON_ALLOW_TRAILING_COMMAS));
base::DictionaryValue* dictionary = NULL;
if (value.get() == NULL || !value->GetAsDictionary(&dictionary)) {
LOG(ERROR) << "Failed to read '" << filename.value() << "'";
callback.Run(dictionary_null.Pass());
return;
}
// Release value, because dictionary points to the same object.
value.release();
callback.Run(scoped_ptr<base::DictionaryValue>(dictionary));
}
void DaemonControllerWin::DoInstallAsNeededAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
// Just configure and start the Daemon Controller if it is installed already.
if (SUCCEEDED(hr)) {
DoSetConfigAndStart(config.Pass(), done_callback);
return;
}
// Otherwise, install it if its COM registration entry is missing.
if (hr == CO_E_CLASSSTRING) {
scoped_ptr<DaemonInstallerWin> installer = DaemonInstallerWin::Create(
window_handle_,
base::Bind(&DaemonControllerWin::OnInstallationComplete,
base::Unretained(this),
base::Passed(&config),
done_callback));
if (installer.get()) {
DCHECK(!installer_.get());
installer_ = installer.Pass();
installer_->Install();
}
} else {
LOG(ERROR) << "Failed to initiate the Chromoting Host installation "
<< "(error: 0x" << std::hex << hr << std::dec << ").";
done_callback.Run(HResultToAsyncResult(hr));
}
}
void DaemonControllerWin::DoSetConfigAndStart(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Set the configuration.
ScopedBstr config_str(NULL);
ConfigToString(*config, &config_str);
if (config_str == NULL) {
done_callback.Run(HResultToAsyncResult(E_OUTOFMEMORY));
return;
}
hr = control->SetConfig(config_str);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Start daemon.
hr = control->StartDaemon();
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoUpdateConfig(
scoped_ptr<base::DictionaryValue> config,
const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
// Update the configuration.
ScopedBstr config_str(NULL);
ConfigToString(*config, &config_str);
if (config_str == NULL) {
done_callback.Run(HResultToAsyncResult(E_OUTOFMEMORY));
return;
}
hr = control->UpdateConfig(config_str);
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoStop(const CompletionCallback& done_callback) {
DCHECK(worker_thread_.message_loop_proxy()->BelongsToCurrentThread());
IDaemonControl* control = NULL;
HRESULT hr = worker_thread_.ActivateElevatedController(window_handle_,
&control);
if (FAILED(hr)) {
done_callback.Run(HResultToAsyncResult(hr));
return;
}
hr = control->StopDaemon();
done_callback.Run(HResultToAsyncResult(hr));
}
void DaemonControllerWin::DoSetWindow(void* window_handle) {
window_handle_ = reinterpret_cast<HWND>(window_handle);
}
} // namespace
scoped_ptr<DaemonController> remoting::DaemonController::Create() {
return scoped_ptr<DaemonController>(new DaemonControllerWin());
}
} // namespace remoting
|
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE 0
#include <string.h> // because Borland's STL is braindead, we have to include <string.h> _before_ <string> in order to get memcpy
#include "test.hpp"
#include "writer_string.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#ifndef PUGIXML_NO_EXCEPTIONS
# include <stdexcept>
#endif
#ifdef __MINGW32__
# include <io.h> // for unlink in C++0x mode
#endif
#if defined(__CELLOS_LV2__) || defined(ANDROID) || defined(_GLIBCXX_HAVE_UNISTD_H) || defined(__APPLE__)
# include <unistd.h> // for unlink
#endif
using namespace pugi;
static bool load_file_in_memory(const char* path, char*& data, size_t& size)
{
FILE* file = fopen(path, "rb");
if (!file) return false;
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
CHECK(length >= 0);
size = static_cast<size_t>(length);
data = new char[size];
CHECK(fread(data, 1, size, file) == size);
fclose(file);
return true;
}
static bool test_file_contents(const char* path, const char* data, size_t size)
{
char* fdata;
size_t fsize;
if (!load_file_in_memory(path, fdata, fsize)) return false;
bool result = (size == fsize && memcmp(data, fdata, size) == 0);
delete[] fdata;
return result;
}
TEST(document_create_empty)
{
xml_document doc;
CHECK_NODE(doc, STR(""));
}
TEST(document_create)
{
xml_document doc;
doc.append_child().set_name(STR("node"));
CHECK_NODE(doc, STR("<node/>"));
}
#ifndef PUGIXML_NO_STL
TEST(document_load_stream)
{
xml_document doc;
std::istringstream iss("<node/>");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_offset)
{
xml_document doc;
std::istringstream iss("<foobar> <node/>");
std::string s;
iss >> s;
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_text)
{
xml_document doc;
std::ifstream iss("tests/data/multiline.xml");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node1/><node2/><node3/>"));
}
TEST(document_load_stream_error)
{
xml_document doc;
std::ifstream fs("filedoesnotexist");
CHECK(doc.load(fs).status == status_io_error);
}
TEST(document_load_stream_out_of_memory)
{
xml_document doc;
std::istringstream iss("<node/>");
test_runner::_memory_fail_threshold = 1;
CHECK_ALLOC_FAIL(CHECK(doc.load(iss).status == status_out_of_memory));
}
TEST(document_load_stream_wide_out_of_memory)
{
xml_document doc;
std::basic_istringstream<wchar_t> iss(L"<node/>");
test_runner::_memory_fail_threshold = 1;
CHECK_ALLOC_FAIL(CHECK(doc.load(iss).status == status_out_of_memory));
}
TEST(document_load_stream_empty)
{
std::istringstream iss;
xml_document doc;
doc.load(iss); // parse result depends on STL implementation
CHECK(!doc.first_child());
}
TEST(document_load_stream_wide)
{
xml_document doc;
std::basic_istringstream<wchar_t> iss(L"<node/>");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
#ifndef PUGIXML_NO_EXCEPTIONS
TEST(document_load_stream_exceptions)
{
xml_document doc;
// Windows has newline translation for text-mode files, so reading from this stream reaches eof and sets fail|eof bits.
// This test does not cause stream to throw an exception on Linux - I have no idea how to get read() to fail except
// newline translation.
std::ifstream iss("tests/data/multiline.xml");
iss.exceptions(std::ios::eofbit | std::ios::badbit | std::ios::failbit);
try
{
doc.load(iss);
CHECK(iss.good()); // if the exception was not thrown, stream reading should succeed without errors
}
catch (const std::ios_base::failure&)
{
CHECK(!doc.first_child());
}
}
#endif
TEST(document_load_stream_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
std::ifstream fs1("filedoesnotexist");
CHECK(doc.load(fs1).status == status_io_error);
CHECK(!doc.first_child());
}
TEST(document_load_stream_wide_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
std::basic_ifstream<wchar_t> fs1("filedoesnotexist");
CHECK(doc.load(fs1).status == status_io_error);
CHECK(!doc.first_child());
}
template <typename T> class char_array_buffer: public std::basic_streambuf<T>
{
public:
char_array_buffer(T* begin, T* end)
{
this->setg(begin, begin, end);
}
};
TEST(document_load_stream_nonseekable)
{
char contents[] = "<node />";
char_array_buffer<char> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::istream in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_wide_nonseekable)
{
wchar_t contents[] = L"<node />";
char_array_buffer<wchar_t> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_nonseekable_large)
{
std::basic_string<char_t> str;
str += STR("<node>");
for (int i = 0; i < 10000; ++i) str += STR("<node/>");
str += STR("</node>");
char_array_buffer<char_t> buffer(&str[0], &str[0] + str.length());
std::basic_istream<char_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, str.c_str());
}
TEST(document_load_stream_nonseekable_out_of_memory)
{
char contents[] = "<node />";
char_array_buffer<char> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::istream in(&buffer);
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_wide_nonseekable_out_of_memory)
{
wchar_t contents[] = L"<node />";
char_array_buffer<wchar_t> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::basic_istream<wchar_t> in(&buffer);
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_nonseekable_out_of_memory_large)
{
std::basic_string<char> str;
str += "<node>";
for (int i = 0; i < 10000; ++i) str += "<node />";
str += "</node>";
char_array_buffer<char> buffer(&str[0], &str[0] + str.length());
std::basic_istream<char> in(&buffer);
test_runner::_memory_fail_threshold = 32768 * 3 + 4096;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_wide_nonseekable_out_of_memory_large)
{
std::basic_string<wchar_t> str;
str += L"<node>";
for (int i = 0; i < 10000; ++i) str += L"<node />";
str += L"</node>";
char_array_buffer<wchar_t> buffer(&str[0], &str[0] + str.length());
std::basic_istream<wchar_t> in(&buffer);
test_runner::_memory_fail_threshold = 32768 * 3 * sizeof(wchar_t) + 4096;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
template <typename T> class seek_fail_buffer: public std::basic_streambuf<T>
{
public:
int seeks;
seek_fail_buffer(): seeks(0)
{
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type, std::ios_base::seekdir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
seeks++;
// pretend that our buffer is seekable (this is called by tellg)
return seeks == 1 ? 0 : -1;
}
};
TEST(document_load_stream_seekable_fail_seek)
{
seek_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_seek)
{
seek_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
template <typename T> class tell_fail_buffer: public std::basic_streambuf<T>
{
public:
int seeks;
tell_fail_buffer(): seeks(0)
{
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type, std::ios_base::seekdir dir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
seeks++;
return seeks > 1 && dir == std::ios_base::cur ? -1 : 0;
}
typename std::basic_streambuf<T>::pos_type seekpos(typename std::basic_streambuf<T>::pos_type, std::ios_base::openmode) PUGIXML_OVERRIDE
{
return 0;
}
};
TEST(document_load_stream_seekable_fail_tell)
{
tell_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_tell)
{
tell_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
#ifndef PUGIXML_NO_EXCEPTIONS
template <typename T> class read_fail_buffer: public std::basic_streambuf<T>
{
public:
typename std::basic_streambuf<T>::int_type underflow() PUGIXML_OVERRIDE
{
throw std::runtime_error("underflow failed");
#ifdef __DMC__
return 0;
#endif
}
};
TEST(document_load_stream_nonseekable_fail_read)
{
read_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_nonseekable_fail_read)
{
read_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
template <typename T> class read_fail_seekable_buffer: public std::basic_streambuf<T>
{
public:
typename std::basic_streambuf<T>::pos_type offset;
read_fail_seekable_buffer(): offset(0)
{
}
typename std::basic_streambuf<T>::int_type underflow() PUGIXML_OVERRIDE
{
throw std::runtime_error("underflow failed");
#ifdef __DMC__
return 0;
#endif
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type off, std::ios_base::seekdir dir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
switch (dir)
{
case std::ios_base::beg: offset = off; break;
case std::ios_base::cur: offset += off; break;
case std::ios_base::end: offset = 16 + off; break;
default: ;
}
return offset;
}
typename std::basic_streambuf<T>::pos_type seekpos(typename std::basic_streambuf<T>::pos_type pos, std::ios_base::openmode) PUGIXML_OVERRIDE
{
offset = pos;
return pos;
}
};
TEST(document_load_stream_seekable_fail_read)
{
read_fail_seekable_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_read)
{
read_fail_seekable_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
#endif
#endif
TEST(document_load_string)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file)
{
xml_document doc;
CHECK(doc.load_file("tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_empty)
{
xml_document doc;
CHECK(doc.load_file("tests/data/empty.xml").status == status_no_document_element);
CHECK(!doc.first_child());
}
TEST(document_load_file_large)
{
xml_document doc;
CHECK(doc.load_file("tests/data/large.xml"));
std::basic_string<char_t> str;
str += STR("<node>");
for (int i = 0; i < 10000; ++i) str += STR("<node/>");
str += STR("</node>");
CHECK_NODE(doc, str.c_str());
}
TEST(document_load_file_error)
{
xml_document doc;
CHECK(doc.load_file("filedoesnotexist").status == status_file_not_found);
}
TEST(document_load_file_out_of_memory)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load_file("tests/data/small.xml").status == status_out_of_memory));
}
TEST(document_load_file_out_of_memory_file_leak)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
for (int i = 0; i < 256; ++i)
CHECK_ALLOC_FAIL(CHECK(doc.load_file("tests/data/small.xml").status == status_out_of_memory));
test_runner::_memory_fail_threshold = 0;
CHECK(doc.load_file("tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_wide_out_of_memory_file_leak)
{
test_runner::_memory_fail_threshold = 256;
xml_document doc;
for (int i = 0; i < 256; ++i)
CHECK_ALLOC_FAIL(CHECK(doc.load_file(L"tests/data/small.xml").status == status_out_of_memory));
test_runner::_memory_fail_threshold = 0;
CHECK(doc.load_file(L"tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
CHECK(doc.load_file("filedoesnotexist").status == status_file_not_found);
CHECK(!doc.first_child());
}
TEST(document_load_file_wide_ascii)
{
xml_document doc;
CHECK(doc.load_file(L"tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
#if !defined(__DMC__) && !defined(__MWERKS__) && !(defined(__MINGW32__) && defined(__STRICT_ANSI__) && !defined(__MINGW64_VERSION_MAJOR)) && !defined(__BORLANDC__)
TEST(document_load_file_wide_unicode)
{
xml_document doc;
CHECK(doc.load_file(L"tests/data/\x0442\x0435\x0441\x0442.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
#endif
TEST(document_load_file_wide_out_of_memory)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
xml_parse_result result;
result.status = status_out_of_memory;
CHECK_ALLOC_FAIL(result = doc.load_file(L"tests/data/small.xml"));
CHECK(result.status == status_out_of_memory || result.status == status_file_not_found);
}
#if defined(__APPLE__)
TEST(document_load_file_special_folder)
{
xml_document doc;
xml_parse_result result = doc.load_file(".");
CHECK(result.status == status_io_error);
}
#endif
#if defined(__linux__)
TEST(document_load_file_special_device)
{
xml_document doc;
xml_parse_result result = doc.load_file("/dev/tty");
CHECK(result.status == status_file_not_found || result.status == status_io_error);
}
#endif
TEST_XML(document_save, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_no_declaration | format_raw, get_native_encoding());
CHECK(writer.as_string() == STR("<node/>"));
}
#ifndef PUGIXML_NO_STL
TEST_XML(document_save_stream, "<node/>")
{
std::ostringstream oss;
doc.save(oss, STR(""), format_no_declaration | format_raw);
CHECK(oss.str() == "<node/>");
}
TEST_XML(document_save_stream_wide, "<node/>")
{
std::basic_ostringstream<wchar_t> oss;
doc.save(oss, STR(""), format_no_declaration | format_raw);
CHECK(oss.str() == L"<node/>");
}
#endif
TEST_XML(document_save_bom, "<n/>")
{
unsigned int flags = format_no_declaration | format_raw | format_write_bom;
// specific encodings
CHECK(test_save_narrow(doc, flags, encoding_utf8, "\xef\xbb\xbf<n/>", 7));
CHECK(test_save_narrow(doc, flags, encoding_utf16_be, "\xfe\xff\x00<\x00n\x00/\x00>", 10));
CHECK(test_save_narrow(doc, flags, encoding_utf16_le, "\xff\xfe<\x00n\x00/\x00>\x00", 10));
CHECK(test_save_narrow(doc, flags, encoding_utf32_be, "\x00\x00\xfe\xff\x00\x00\x00<\x00\x00\x00n\x00\x00\x00/\x00\x00\x00>", 20));
CHECK(test_save_narrow(doc, flags, encoding_utf32_le, "\xff\xfe\x00\x00<\x00\x00\x00n\x00\x00\x00/\x00\x00\x00>\x00\x00\x00", 20));
CHECK(test_save_narrow(doc, flags, encoding_latin1, "<n/>", 4));
// encodings synonyms
CHECK(save_narrow(doc, flags, encoding_utf16) == save_narrow(doc, flags, (is_little_endian() ? encoding_utf16_le : encoding_utf16_be)));
CHECK(save_narrow(doc, flags, encoding_utf32) == save_narrow(doc, flags, (is_little_endian() ? encoding_utf32_le : encoding_utf32_be)));
size_t wcharsize = sizeof(wchar_t);
CHECK(save_narrow(doc, flags, encoding_wchar) == save_narrow(doc, flags, (wcharsize == 2 ? encoding_utf16 : encoding_utf32)));
}
TEST_XML(document_save_declaration, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n<node />\n"));
}
TEST(document_save_declaration_empty)
{
xml_document doc;
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n"));
}
TEST_XML(document_save_declaration_present_first, "<node/>")
{
doc.insert_child_before(node_declaration, doc.first_child()).append_attribute(STR("encoding")) = STR("utf8");
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml encoding=\"utf8\"?>\n<node />\n"));
}
TEST_XML(document_save_declaration_present_second, "<node/>")
{
doc.insert_child_before(node_declaration, doc.first_child()).append_attribute(STR("encoding")) = STR("utf8");
doc.insert_child_before(node_comment, doc.first_child()).set_value(STR("text"));
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<!--text-->\n<?xml encoding=\"utf8\"?>\n<node />\n"));
}
TEST_XML(document_save_declaration_present_last, "<node/>")
{
doc.append_child(node_declaration).append_attribute(STR("encoding")) = STR("utf8");
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
// node writer only looks for declaration before the first element child
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n<node />\n<?xml encoding=\"utf8\"?>\n"));
}
TEST_XML(document_save_declaration_latin1, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_default, encoding_latin1);
CHECK(writer.as_narrow() == "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<node />\n");
}
TEST_XML(document_save_declaration_raw, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_raw, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?><node/>"));
}
struct temp_file
{
char path[512];
temp_file()
{
static int index = 0;
sprintf(path, "%stempfile%d", test_runner::_temp_path, index++);
}
~temp_file()
{
#ifndef _WIN32_WCE
CHECK(unlink(path) == 0);
#endif
}
};
TEST_XML(document_save_file, "<node/>")
{
temp_file f;
CHECK(doc.save_file(f.path));
CHECK(doc.load_file(f.path, parse_default | parse_declaration));
CHECK_NODE(doc, STR("<?xml version=\"1.0\"?><node/>"));
}
TEST_XML(document_save_file_wide, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
CHECK(doc.save_file(wpath));
CHECK(doc.load_file(f.path, parse_default | parse_declaration));
CHECK_NODE(doc, STR("<?xml version=\"1.0\"?><node/>"));
}
TEST_XML(document_save_file_error, "<node/>")
{
CHECK(!doc.save_file("tests/data/unknown/output.xml"));
}
TEST_XML(document_save_file_text, "<node/>")
{
temp_file f;
CHECK(doc.save_file(f.path, STR(""), format_no_declaration | format_save_file_text));
CHECK(test_file_contents(f.path, "<node />\n", 9) || test_file_contents(f.path, "<node />\r\n", 10));
CHECK(doc.save_file(f.path, STR(""), format_no_declaration));
CHECK(test_file_contents(f.path, "<node />\n", 9));
}
TEST_XML(document_save_file_wide_text, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
CHECK(doc.save_file(wpath, STR(""), format_no_declaration | format_save_file_text));
CHECK(test_file_contents(f.path, "<node />\n", 9) || test_file_contents(f.path, "<node />\r\n", 10));
CHECK(doc.save_file(wpath, STR(""), format_no_declaration));
CHECK(test_file_contents(f.path, "<node />\n", 9));
}
TEST_XML(document_save_file_leak, "<node/>")
{
temp_file f;
for (int i = 0; i < 256; ++i)
CHECK(doc.save_file(f.path));
}
TEST_XML(document_save_file_wide_leak, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
for (int i = 0; i < 256; ++i)
CHECK(doc.save_file(wpath));
}
TEST(document_load_buffer)
{
const char_t text[] = STR("<?xml?><node/>");
xml_document doc;
CHECK(doc.load_buffer(text, sizeof(text)));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_buffer_inplace)
{
char_t text[] = STR("<?xml?><node/>");
xml_document doc;
CHECK(doc.load_buffer_inplace(text, sizeof(text)));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_buffer_inplace_own)
{
allocation_function alloc = get_memory_allocation_function();
size_t size = strlen("<?xml?><node/>") * sizeof(char_t);
char_t* text = static_cast<char_t*>(alloc(size));
CHECK(text);
memcpy(text, STR("<?xml?><node/>"), size);
xml_document doc;
CHECK(doc.load_buffer_inplace_own(text, size));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_parse_result_bool)
{
xml_parse_result result;
result.status = status_ok;
CHECK(result);
CHECK(!!result);
CHECK(result == true);
for (int i = 1; i < 20; ++i)
{
result.status = static_cast<xml_parse_status>(i);
CHECK(!result);
CHECK(result == false);
}
}
TEST(document_parse_result_description)
{
xml_parse_result result;
for (int i = 0; i < 20; ++i)
{
result.status = static_cast<xml_parse_status>(i);
CHECK(result.description() != 0);
CHECK(result.description()[0] != 0);
}
}
TEST(document_load_fail)
{
xml_document doc;
CHECK(!doc.load_string(STR("<foo><bar/>")));
CHECK(doc.child(STR("foo")).child(STR("bar")));
}
inline void check_utftest_document(const xml_document& doc)
{
// ascii text
CHECK_STRING(doc.last_child().first_child().name(), STR("English"));
// check that we have parsed some non-ascii text
CHECK(static_cast<unsigned int>(doc.last_child().last_child().name()[0]) >= 0x80);
// check magic string
const char_t* v = doc.last_child().child(STR("Heavy")).previous_sibling().child_value();
#ifdef PUGIXML_WCHAR_MODE
CHECK(v[0] == 0x4e16 && v[1] == 0x754c && v[2] == 0x6709 && v[3] == 0x5f88 && v[4] == 0x591a && v[5] == wchar_cast(0x8bed) && v[6] == wchar_cast(0x8a00));
// last character is a surrogate pair
size_t wcharsize = sizeof(wchar_t);
CHECK(wcharsize == 2 ? (v[7] == wchar_cast(0xd852) && v[8] == wchar_cast(0xdf62)) : (v[7] == wchar_cast(0x24b62)));
#else
// unicode string
CHECK_STRING(v, "\xe4\xb8\x96\xe7\x95\x8c\xe6\x9c\x89\xe5\xbe\x88\xe5\xa4\x9a\xe8\xaf\xad\xe8\xa8\x80\xf0\xa4\xad\xa2");
#endif
}
TEST(document_load_file_convert_auto)
{
const char* files[] =
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
"tests/data/utftest_utf8.xml",
"tests/data/utftest_utf8_bom.xml",
"tests/data/utftest_utf8_nodecl.xml"
};
xml_encoding encodings[] =
{
encoding_utf16_be, encoding_utf16_be, encoding_utf16_be,
encoding_utf16_le, encoding_utf16_le, encoding_utf16_le,
encoding_utf32_be, encoding_utf32_be, encoding_utf32_be,
encoding_utf32_le, encoding_utf32_le, encoding_utf32_le,
encoding_utf8, encoding_utf8, encoding_utf8
};
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
xml_document doc;
xml_parse_result res = doc.load_file(files[i]);
CHECK(res);
CHECK(res.encoding == encodings[i]);
check_utftest_document(doc);
}
}
TEST(document_load_file_convert_specific)
{
const char* files[] =
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
"tests/data/utftest_utf8.xml",
"tests/data/utftest_utf8_bom.xml",
"tests/data/utftest_utf8_nodecl.xml"
};
xml_encoding encodings[] =
{
encoding_utf16_be, encoding_utf16_be, encoding_utf16_be,
encoding_utf16_le, encoding_utf16_le, encoding_utf16_le,
encoding_utf32_be, encoding_utf32_be, encoding_utf32_be,
encoding_utf32_le, encoding_utf32_le, encoding_utf32_le,
encoding_utf8, encoding_utf8, encoding_utf8
};
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
xml_encoding encoding = encodings[j];
xml_document doc;
xml_parse_result res = doc.load_file(files[i], parse_default, encoding);
if (encoding == encodings[i])
{
CHECK(res);
CHECK(res.encoding == encoding);
check_utftest_document(doc);
}
else
{
// should not get past first tag
CHECK(!doc.first_child());
}
}
}
}
TEST(document_load_file_convert_native_endianness)
{
const char* files[2][6] =
{
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
},
{
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
}
};
xml_encoding encodings[] =
{
encoding_utf16, encoding_utf16, encoding_utf16,
encoding_utf32, encoding_utf32, encoding_utf32
};
for (unsigned int i = 0; i < sizeof(files[0]) / sizeof(files[0][0]); ++i)
{
const char* right_file = files[is_little_endian()][i];
const char* wrong_file = files[!is_little_endian()][i];
for (unsigned int j = 0; j < sizeof(encodings) / sizeof(encodings[0]); ++j)
{
xml_encoding encoding = encodings[j];
// check file with right endianness
{
xml_document doc;
xml_parse_result res = doc.load_file(right_file, parse_default, encoding);
if (encoding == encodings[i])
{
CHECK(res);
check_utftest_document(doc);
}
else
{
// should not get past first tag
CHECK(!doc.first_child());
}
}
// check file with wrong endianness
{
xml_document doc;
doc.load_file(wrong_file, parse_default, encoding);
CHECK(!doc.first_child());
}
}
}
}
struct file_data_t
{
const char* path;
xml_encoding encoding;
char* data;
size_t size;
};
TEST(document_contents_preserve)
{
file_data_t files[] =
{
{"tests/data/utftest_utf16_be_clean.xml", encoding_utf16_be, 0, 0},
{"tests/data/utftest_utf16_le_clean.xml", encoding_utf16_le, 0, 0},
{"tests/data/utftest_utf32_be_clean.xml", encoding_utf32_be, 0, 0},
{"tests/data/utftest_utf32_le_clean.xml", encoding_utf32_le, 0, 0},
{"tests/data/utftest_utf8_clean.xml", encoding_utf8, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// convert each file to each format and compare bitwise
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
for (unsigned int dst = 0; dst < sizeof(files) / sizeof(files[0]); ++dst)
{
// parse into document (preserve comments, declaration and whitespace pcdata)
xml_document doc;
CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default | parse_ws_pcdata | parse_declaration | parse_comments));
// compare saved document with the original (raw formatting, without extra declaration, write bom if it was in original file)
CHECK(test_save_narrow(doc, format_raw | format_no_declaration | format_write_bom, files[dst].encoding, files[dst].data, files[dst].size));
}
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
TEST(document_contents_preserve_latin1)
{
file_data_t files[] =
{
{"tests/data/latintest_utf8.xml", encoding_utf8, 0, 0},
{"tests/data/latintest_latin1.xml", encoding_latin1, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// convert each file to each format and compare bitwise
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
for (unsigned int dst = 0; dst < sizeof(files) / sizeof(files[0]); ++dst)
{
// parse into document (preserve comments, declaration and whitespace pcdata)
xml_document doc;
CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default | parse_ws_pcdata | parse_declaration | parse_comments));
// compare saved document with the original (raw formatting, without extra declaration, write bom if it was in original file)
CHECK(test_save_narrow(doc, format_raw | format_no_declaration | format_write_bom, files[dst].encoding, files[dst].data, files[dst].size));
}
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
static bool test_parse_fail(const void* buffer, size_t size, xml_encoding encoding = encoding_utf8)
{
// copy buffer to heap (to enable out-of-bounds checks)
void* temp = malloc(size);
memcpy(temp, buffer, size);
// check that this parses without buffer overflows (yielding an error)
xml_document doc;
bool result = doc.load_buffer_inplace(temp, size, parse_default, encoding);
free(temp);
return !result;
}
TEST(document_convert_invalid_utf8)
{
// invalid 1-byte input
CHECK(test_parse_fail("<\xb0", 2));
// invalid 2-byte input
CHECK(test_parse_fail("<\xc0", 2));
CHECK(test_parse_fail("<\xd0", 2));
// invalid 3-byte input
CHECK(test_parse_fail("<\xe2\x80", 3));
CHECK(test_parse_fail("<\xe2", 2));
// invalid 4-byte input
CHECK(test_parse_fail("<\xf2\x97\x98", 4));
CHECK(test_parse_fail("<\xf2\x97", 3));
CHECK(test_parse_fail("<\xf2", 2));
// invalid 5-byte input
CHECK(test_parse_fail("<\xf8", 2));
}
TEST(document_convert_invalid_utf16)
{
// check non-terminated degenerate handling
CHECK(test_parse_fail("\x00<\xda\x1d", 4, encoding_utf16_be));
CHECK(test_parse_fail("<\x00\x1d\xda", 4, encoding_utf16_le));
// check incorrect leading code
CHECK(test_parse_fail("\x00<\xde\x24", 4, encoding_utf16_be));
CHECK(test_parse_fail("<\x00\x24\xde", 4, encoding_utf16_le));
}
TEST(document_load_buffer_empty)
{
xml_encoding encodings[] =
{
encoding_auto,
encoding_utf8,
encoding_utf16_le,
encoding_utf16_be,
encoding_utf16,
encoding_utf32_le,
encoding_utf32_be,
encoding_utf32,
encoding_wchar,
encoding_latin1
};
char buffer[1];
for (unsigned int i = 0; i < sizeof(encodings) / sizeof(encodings[0]); ++i)
{
xml_encoding encoding = encodings[i];
xml_document doc;
CHECK(doc.load_buffer(buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace(buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
void* own_buffer = get_memory_allocation_function()(1);
CHECK(doc.load_buffer_inplace_own(own_buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
}
}
TEST(document_load_buffer_empty_fragment)
{
xml_encoding encodings[] =
{
encoding_auto,
encoding_utf8,
encoding_utf16_le,
encoding_utf16_be,
encoding_utf16,
encoding_utf32_le,
encoding_utf32_be,
encoding_utf32,
encoding_wchar,
encoding_latin1
};
char buffer[1];
for (unsigned int i = 0; i < sizeof(encodings) / sizeof(encodings[0]); ++i)
{
xml_encoding encoding = encodings[i];
xml_document doc;
CHECK(doc.load_buffer(buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace(buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 0, parse_fragment, encoding) && !doc.first_child());
void* own_buffer = get_memory_allocation_function()(1);
CHECK(doc.load_buffer_inplace_own(own_buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 0, parse_fragment, encoding) && !doc.first_child());
}
}
TEST(document_load_buffer_null)
{
xml_document doc;
CHECK(doc.load_buffer(0, 12).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer(0, 12, parse_fragment).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 12).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 12).status == status_io_error && !doc.first_child());
}
TEST(document_progressive_truncation)
{
char* original_data;
size_t original_size;
CHECK(load_file_in_memory("tests/data/truncation.xml", original_data, original_size));
char* buffer = new char[original_size];
for (size_t i = 1; i <= original_size; ++i)
{
char* truncated_data = buffer + original_size - i;
// default flags
{
memcpy(truncated_data, original_data, i);
xml_document doc;
bool result = doc.load_buffer_inplace(truncated_data, i);
// only eof is parseable
CHECK((i == original_size) ? result : !result);
}
// fragment mode
{
memcpy(truncated_data, original_data, i);
xml_document doc;
bool result = doc.load_buffer_inplace(truncated_data, i, parse_default | parse_fragment);
// some truncate locations are parseable - those that come after declaration, declaration + doctype, declaration + doctype + comment and eof
CHECK(((i >= 21 && i <= 23) || (i >= 66 && i <= 68) || (i >= 95 && i <= 97) || i == original_size) ? result : !result);
}
}
delete[] buffer;
delete[] original_data;
}
TEST(document_load_buffer_short)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer(data, 4).status == status_no_document_element);
CHECK(doc.load_buffer(data + 1, 3).status == status_no_document_element);
CHECK(doc.load_buffer(data + 2, 2).status == status_no_document_element);
CHECK(doc.load_buffer(data + 3, 1).status == status_no_document_element);
CHECK(doc.load_buffer(data + 4, 0).status == status_no_document_element);
CHECK(doc.load_buffer(0, 0).status == status_no_document_element);
delete[] data;
}
TEST(document_load_buffer_short_fragment)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer(data, 4, parse_fragment) && test_string_equal(doc.text().get(), STR("abcd")));
CHECK(doc.load_buffer(data + 1, 3, parse_fragment) && test_string_equal(doc.text().get(), STR("bcd")));
CHECK(doc.load_buffer(data + 2, 2, parse_fragment) && test_string_equal(doc.text().get(), STR("cd")));
CHECK(doc.load_buffer(data + 3, 1, parse_fragment) && test_string_equal(doc.text().get(), STR("d")));
CHECK(doc.load_buffer(data + 4, 0, parse_fragment) && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_fragment) && !doc.first_child());
delete[] data;
}
TEST(document_load_buffer_inplace_short)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer_inplace(data, 4).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 1, 3).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 2, 2).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 3, 1).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 4, 0).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(0, 0).status == status_no_document_element);
delete[] data;
}
#ifndef PUGIXML_NO_EXCEPTIONS
TEST(document_load_exceptions)
{
bool thrown = false;
try
{
xml_document doc;
if (!doc.load_string(STR("<node attribute='value"))) throw std::bad_alloc();
CHECK_FORCE_FAIL("Expected parsing failure");
}
catch (const std::bad_alloc&)
{
thrown = true;
}
CHECK(thrown);
}
#endif
TEST_XML_FLAGS(document_element, "<?xml version='1.0'?><node><child/></node><!---->", parse_default | parse_declaration | parse_comments)
{
CHECK(doc.document_element() == doc.child(STR("node")));
}
TEST_XML_FLAGS(document_element_absent, "<!---->", parse_comments | parse_fragment)
{
CHECK(doc.document_element() == xml_node());
}
TEST_XML(document_reset, "<node><child/></node>")
{
CHECK(doc.first_child());
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
CHECK_NODE(doc, STR("<node/>"));
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST(document_reset_empty)
{
xml_document doc;
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST_XML(document_reset_copy, "<node><child/></node>")
{
xml_document doc2;
CHECK_NODE(doc2, STR(""));
doc2.reset(doc);
CHECK_NODE(doc2, STR("<node><child/></node>"));
CHECK(doc.first_child() != doc2.first_child());
doc.reset(doc2);
CHECK_NODE(doc, STR("<node><child/></node>"));
CHECK(doc.first_child() != doc2.first_child());
CHECK(doc.first_child().offset_debug() == -1);
}
TEST_XML(document_reset_copy_self, "<node><child/></node>")
{
CHECK_NODE(doc, STR("<node><child/></node>"));
doc.reset(doc);
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST(document_load_buffer_utf_truncated)
{
const unsigned char utf8[] = {'<', 0xe2, 0x82, 0xac, '/', '>'};
const unsigned char utf16_be[] = {0, '<', 0x20, 0xac, 0, '/', 0, '>'};
const unsigned char utf16_le[] = {'<', 0, 0xac, 0x20, '/', 0, '>', 0};
const unsigned char utf32_be[] = {0, 0, 0, '<', 0, 0, 0x20, 0xac, 0, 0, 0, '/', 0, 0, 0, '>'};
const unsigned char utf32_le[] = {'<', 0, 0, 0, 0xac, 0x20, 0, 0, '/', 0, 0, 0, '>', 0, 0, 0};
struct document_data_t
{
xml_encoding encoding;
const unsigned char* data;
size_t size;
};
const document_data_t data[] =
{
{ encoding_utf8, utf8, sizeof(utf8) },
{ encoding_utf16_be, utf16_be, sizeof(utf16_be) },
{ encoding_utf16_le, utf16_le, sizeof(utf16_le) },
{ encoding_utf32_be, utf32_be, sizeof(utf32_be) },
{ encoding_utf32_le, utf32_le, sizeof(utf32_le) },
};
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); ++i)
{
const document_data_t& d = data[i];
for (size_t j = 0; j <= d.size; ++j)
{
char* buffer = new char[j];
memcpy(buffer, d.data, j);
xml_document doc;
xml_parse_result res = doc.load_buffer(buffer, j, parse_default, d.encoding);
if (j == d.size)
{
CHECK(res);
const char_t* name = doc.first_child().name();
#ifdef PUGIXML_WCHAR_MODE
CHECK(name[0] == 0x20ac && name[1] == 0);
#else
CHECK_STRING(name, "\xe2\x82\xac");
#endif
}
else
{
CHECK(!res || !doc.first_child());
}
delete[] buffer;
}
}
}
#ifndef PUGIXML_NO_STL
TEST(document_load_stream_truncated)
{
const unsigned char utf32_be[] = {0, 0, 0, '<', 0, 0, 0x20, 0xac, 0, 0, 0, '/', 0, 0, 0, '>'};
for (size_t i = 0; i <= sizeof(utf32_be); ++i)
{
std::string prefix(reinterpret_cast<const char*>(utf32_be), i);
std::istringstream iss(prefix);
xml_document doc;
xml_parse_result res = doc.load(iss);
if (i == sizeof(utf32_be))
{
CHECK(res);
}
else
{
CHECK(!res || !doc.first_child());
if (i < 8)
{
CHECK(!doc.first_child());
}
else
{
const char_t* name = doc.first_child().name();
#ifdef PUGIXML_WCHAR_MODE
CHECK(name[0] == 0x20ac && name[1] == 0);
#else
CHECK_STRING(name, "\xe2\x82\xac");
#endif
}
}
}
}
#endif
TEST(document_alignment)
{
char buf[256 + sizeof(xml_document)];
for (size_t offset = 0; offset < 256; offset += sizeof(void*))
{
xml_document* doc = new (buf + offset) xml_document;
CHECK(doc->load_string(STR("<node />")));
CHECK_NODE(*doc, STR("<node/>"));
doc->~xml_document();
}
}
TEST(document_convert_out_of_memory)
{
file_data_t files[] =
{
{"tests/data/utftest_utf16_be_clean.xml", encoding_utf16_be, 0, 0},
{"tests/data/utftest_utf16_le_clean.xml", encoding_utf16_le, 0, 0},
{"tests/data/utftest_utf32_be_clean.xml", encoding_utf32_be, 0, 0},
{"tests/data/utftest_utf32_le_clean.xml", encoding_utf32_le, 0, 0},
{"tests/data/utftest_utf8_clean.xml", encoding_utf8, 0, 0},
{"tests/data/latintest_latin1.xml", encoding_latin1, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// disallow allocations
test_runner::_memory_fail_threshold = 1;
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default, files[src].encoding).status == status_out_of_memory));
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
#ifdef PUGIXML_HAS_MOVE
TEST_XML(document_move_ctor, "<node1/><node2/>")
{
xml_document other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST_XML(document_move_assign, "<node1/><node2/>")
{
xml_document other;
CHECK(other.load_string(STR("<node3/>")));
other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST_XML(document_move_zero_alloc, "<node1/><node2/>")
{
test_runner::_memory_fail_threshold = 1;
xml_document other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST(document_move_append_buffer)
{
xml_document* doc = new xml_document();
CHECK(doc->load_string(STR("<node1 attr1='value1'><node2/></node1>")));
CHECK(doc->child(STR("node1")).append_buffer("<node3/>", 8));
CHECK(doc->child(STR("node1")).append_buffer("<node4/>", 8));
xml_document other = std::move(*doc);
delete doc;
CHECK(other.child(STR("node1")).append_buffer("<node5/>", 8));
CHECK(other.child(STR("node1")).append_buffer("<node6/>", 8));
CHECK_NODE(other, STR("<node1 attr1=\"value1\"><node2/><node3/><node4/><node5/><node6/></node1>"));
}
TEST(document_move_append_child)
{
xml_document* doc = new xml_document();
CHECK(doc->load_string(STR("<node1 attr1='value1'><node2/></node1>")));
xml_document other = std::move(*doc);
delete doc;
for (int i = 0; i < 3000; ++i)
other.child(STR("node1")).append_child(STR("node"));
for (int i = 0; i < 3000; ++i)
other.child(STR("node1")).remove_child(other.child(STR("node1")).last_child());
CHECK_NODE(other, STR("<node1 attr1=\"value1\"><node2/></node1>"));
other.remove_child(other.first_child());
CHECK(!other.first_child());
}
TEST(document_move_empty)
{
xml_document* doc = new xml_document();
xml_document other = std::move(*doc);
delete doc;
}
TEST(document_move_large)
{
xml_document* doc = new xml_document();
xml_node dn = doc->append_child(STR("node"));
for (int i = 0; i < 3000; ++i)
dn.append_child(STR("child"));
xml_document other = std::move(*doc);
delete doc;
xml_node on = other.child(STR("node"));
for (int i = 0; i < 3000; ++i)
CHECK(on.remove_child(on.first_child()));
CHECK(!on.first_child());
}
TEST_XML(document_move_buffer, "<node1/><node2/>")
{
CHECK(doc.child(STR("node2")).offset_debug() == 9);
xml_document other = std::move(doc);
CHECK(other.child(STR("node2")).offset_debug() == 9);
}
TEST_XML(document_move_append_child_zero_alloc, "<node1/><node2/>")
{
test_runner::_memory_fail_threshold = 1;
xml_document other = std::move(doc);
CHECK(other.append_child(STR("node3")));
CHECK_NODE(other, STR("<node1/><node2/><node3/>"));
}
TEST(document_move_empty_zero_alloc)
{
xml_document* docs = new xml_document[32];
test_runner::_memory_fail_threshold = 1;
for (int i = 1; i < 32; ++i)
docs[i] = std::move(docs[i-1]);
delete[] docs;
}
#ifndef PUGIXML_COMPACT
TEST(document_move_repeated_zero_alloc)
{
xml_document docs[32];
CHECK(docs[0].load_string(STR("<node><child/></node>")));
test_runner::_memory_fail_threshold = 1;
for (int i = 1; i < 32; ++i)
docs[i] = std::move(docs[i-1]);
for (int i = 0; i < 31; ++i)
CHECK(!docs[i].first_child());
CHECK_NODE(docs[31], STR("<node><child/></node>"));
}
#endif
#ifdef PUGIXML_COMPACT
TEST(document_move_compact_fail)
{
xml_document docs[32];
CHECK(docs[0].load_string(STR("<node><child/></node>")));
test_runner::_memory_fail_threshold = 1;
int safe_count = 21;
for (int i = 1; i <= safe_count; ++i)
docs[i] = std::move(docs[i-1]);
CHECK_ALLOC_FAIL(docs[safe_count+1] = std::move(docs[safe_count]));
for (int i = 0; i < safe_count; ++i)
CHECK(!docs[i].first_child());
CHECK_NODE(docs[safe_count], STR("<node><child/></node>"));
CHECK(!docs[safe_count+1].first_child());
}
#endif
TEST(document_move_assign_empty)
{
xml_document doc;
doc.append_child(STR("node"));
doc = xml_document();
doc.append_child(STR("node2"));
CHECK_NODE(doc, STR("<node2/>"));
}
#endif
Fix include in test_document.cpp when building against libc++
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE 0
#include <string.h> // because Borland's STL is braindead, we have to include <string.h> _before_ <string> in order to get memcpy
#include "test.hpp"
#include "writer_string.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#ifndef PUGIXML_NO_EXCEPTIONS
# include <stdexcept>
#endif
// for unlink
#ifdef _WIN32
# include <io.h>
#else
# include <unistd.h>
#endif
using namespace pugi;
static bool load_file_in_memory(const char* path, char*& data, size_t& size)
{
FILE* file = fopen(path, "rb");
if (!file) return false;
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
CHECK(length >= 0);
size = static_cast<size_t>(length);
data = new char[size];
CHECK(fread(data, 1, size, file) == size);
fclose(file);
return true;
}
static bool test_file_contents(const char* path, const char* data, size_t size)
{
char* fdata;
size_t fsize;
if (!load_file_in_memory(path, fdata, fsize)) return false;
bool result = (size == fsize && memcmp(data, fdata, size) == 0);
delete[] fdata;
return result;
}
TEST(document_create_empty)
{
xml_document doc;
CHECK_NODE(doc, STR(""));
}
TEST(document_create)
{
xml_document doc;
doc.append_child().set_name(STR("node"));
CHECK_NODE(doc, STR("<node/>"));
}
#ifndef PUGIXML_NO_STL
TEST(document_load_stream)
{
xml_document doc;
std::istringstream iss("<node/>");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_offset)
{
xml_document doc;
std::istringstream iss("<foobar> <node/>");
std::string s;
iss >> s;
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_text)
{
xml_document doc;
std::ifstream iss("tests/data/multiline.xml");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node1/><node2/><node3/>"));
}
TEST(document_load_stream_error)
{
xml_document doc;
std::ifstream fs("filedoesnotexist");
CHECK(doc.load(fs).status == status_io_error);
}
TEST(document_load_stream_out_of_memory)
{
xml_document doc;
std::istringstream iss("<node/>");
test_runner::_memory_fail_threshold = 1;
CHECK_ALLOC_FAIL(CHECK(doc.load(iss).status == status_out_of_memory));
}
TEST(document_load_stream_wide_out_of_memory)
{
xml_document doc;
std::basic_istringstream<wchar_t> iss(L"<node/>");
test_runner::_memory_fail_threshold = 1;
CHECK_ALLOC_FAIL(CHECK(doc.load(iss).status == status_out_of_memory));
}
TEST(document_load_stream_empty)
{
std::istringstream iss;
xml_document doc;
doc.load(iss); // parse result depends on STL implementation
CHECK(!doc.first_child());
}
TEST(document_load_stream_wide)
{
xml_document doc;
std::basic_istringstream<wchar_t> iss(L"<node/>");
CHECK(doc.load(iss));
CHECK_NODE(doc, STR("<node/>"));
}
#ifndef PUGIXML_NO_EXCEPTIONS
TEST(document_load_stream_exceptions)
{
xml_document doc;
// Windows has newline translation for text-mode files, so reading from this stream reaches eof and sets fail|eof bits.
// This test does not cause stream to throw an exception on Linux - I have no idea how to get read() to fail except
// newline translation.
std::ifstream iss("tests/data/multiline.xml");
iss.exceptions(std::ios::eofbit | std::ios::badbit | std::ios::failbit);
try
{
doc.load(iss);
CHECK(iss.good()); // if the exception was not thrown, stream reading should succeed without errors
}
catch (const std::ios_base::failure&)
{
CHECK(!doc.first_child());
}
}
#endif
TEST(document_load_stream_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
std::ifstream fs1("filedoesnotexist");
CHECK(doc.load(fs1).status == status_io_error);
CHECK(!doc.first_child());
}
TEST(document_load_stream_wide_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
std::basic_ifstream<wchar_t> fs1("filedoesnotexist");
CHECK(doc.load(fs1).status == status_io_error);
CHECK(!doc.first_child());
}
template <typename T> class char_array_buffer: public std::basic_streambuf<T>
{
public:
char_array_buffer(T* begin, T* end)
{
this->setg(begin, begin, end);
}
};
TEST(document_load_stream_nonseekable)
{
char contents[] = "<node />";
char_array_buffer<char> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::istream in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_wide_nonseekable)
{
wchar_t contents[] = L"<node />";
char_array_buffer<wchar_t> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_stream_nonseekable_large)
{
std::basic_string<char_t> str;
str += STR("<node>");
for (int i = 0; i < 10000; ++i) str += STR("<node/>");
str += STR("</node>");
char_array_buffer<char_t> buffer(&str[0], &str[0] + str.length());
std::basic_istream<char_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in));
CHECK_NODE(doc, str.c_str());
}
TEST(document_load_stream_nonseekable_out_of_memory)
{
char contents[] = "<node />";
char_array_buffer<char> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::istream in(&buffer);
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_wide_nonseekable_out_of_memory)
{
wchar_t contents[] = L"<node />";
char_array_buffer<wchar_t> buffer(contents, contents + sizeof(contents) / sizeof(contents[0]));
std::basic_istream<wchar_t> in(&buffer);
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_nonseekable_out_of_memory_large)
{
std::basic_string<char> str;
str += "<node>";
for (int i = 0; i < 10000; ++i) str += "<node />";
str += "</node>";
char_array_buffer<char> buffer(&str[0], &str[0] + str.length());
std::basic_istream<char> in(&buffer);
test_runner::_memory_fail_threshold = 32768 * 3 + 4096;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
TEST(document_load_stream_wide_nonseekable_out_of_memory_large)
{
std::basic_string<wchar_t> str;
str += L"<node>";
for (int i = 0; i < 10000; ++i) str += L"<node />";
str += L"</node>";
char_array_buffer<wchar_t> buffer(&str[0], &str[0] + str.length());
std::basic_istream<wchar_t> in(&buffer);
test_runner::_memory_fail_threshold = 32768 * 3 * sizeof(wchar_t) + 4096;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load(in).status == status_out_of_memory));
}
template <typename T> class seek_fail_buffer: public std::basic_streambuf<T>
{
public:
int seeks;
seek_fail_buffer(): seeks(0)
{
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type, std::ios_base::seekdir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
seeks++;
// pretend that our buffer is seekable (this is called by tellg)
return seeks == 1 ? 0 : -1;
}
};
TEST(document_load_stream_seekable_fail_seek)
{
seek_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_seek)
{
seek_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
template <typename T> class tell_fail_buffer: public std::basic_streambuf<T>
{
public:
int seeks;
tell_fail_buffer(): seeks(0)
{
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type, std::ios_base::seekdir dir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
seeks++;
return seeks > 1 && dir == std::ios_base::cur ? -1 : 0;
}
typename std::basic_streambuf<T>::pos_type seekpos(typename std::basic_streambuf<T>::pos_type, std::ios_base::openmode) PUGIXML_OVERRIDE
{
return 0;
}
};
TEST(document_load_stream_seekable_fail_tell)
{
tell_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_tell)
{
tell_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
#ifndef PUGIXML_NO_EXCEPTIONS
template <typename T> class read_fail_buffer: public std::basic_streambuf<T>
{
public:
typename std::basic_streambuf<T>::int_type underflow() PUGIXML_OVERRIDE
{
throw std::runtime_error("underflow failed");
#ifdef __DMC__
return 0;
#endif
}
};
TEST(document_load_stream_nonseekable_fail_read)
{
read_fail_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_nonseekable_fail_read)
{
read_fail_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
template <typename T> class read_fail_seekable_buffer: public std::basic_streambuf<T>
{
public:
typename std::basic_streambuf<T>::pos_type offset;
read_fail_seekable_buffer(): offset(0)
{
}
typename std::basic_streambuf<T>::int_type underflow() PUGIXML_OVERRIDE
{
throw std::runtime_error("underflow failed");
#ifdef __DMC__
return 0;
#endif
}
typename std::basic_streambuf<T>::pos_type seekoff(typename std::basic_streambuf<T>::off_type off, std::ios_base::seekdir dir, std::ios_base::openmode) PUGIXML_OVERRIDE
{
switch (dir)
{
case std::ios_base::beg: offset = off; break;
case std::ios_base::cur: offset += off; break;
case std::ios_base::end: offset = 16 + off; break;
default: ;
}
return offset;
}
typename std::basic_streambuf<T>::pos_type seekpos(typename std::basic_streambuf<T>::pos_type pos, std::ios_base::openmode) PUGIXML_OVERRIDE
{
offset = pos;
return pos;
}
};
TEST(document_load_stream_seekable_fail_read)
{
read_fail_seekable_buffer<char> buffer;
std::basic_istream<char> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
TEST(document_load_stream_wide_seekable_fail_read)
{
read_fail_seekable_buffer<wchar_t> buffer;
std::basic_istream<wchar_t> in(&buffer);
xml_document doc;
CHECK(doc.load(in).status == status_io_error);
}
#endif
#endif
TEST(document_load_string)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file)
{
xml_document doc;
CHECK(doc.load_file("tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_empty)
{
xml_document doc;
CHECK(doc.load_file("tests/data/empty.xml").status == status_no_document_element);
CHECK(!doc.first_child());
}
TEST(document_load_file_large)
{
xml_document doc;
CHECK(doc.load_file("tests/data/large.xml"));
std::basic_string<char_t> str;
str += STR("<node>");
for (int i = 0; i < 10000; ++i) str += STR("<node/>");
str += STR("</node>");
CHECK_NODE(doc, str.c_str());
}
TEST(document_load_file_error)
{
xml_document doc;
CHECK(doc.load_file("filedoesnotexist").status == status_file_not_found);
}
TEST(document_load_file_out_of_memory)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load_file("tests/data/small.xml").status == status_out_of_memory));
}
TEST(document_load_file_out_of_memory_file_leak)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
for (int i = 0; i < 256; ++i)
CHECK_ALLOC_FAIL(CHECK(doc.load_file("tests/data/small.xml").status == status_out_of_memory));
test_runner::_memory_fail_threshold = 0;
CHECK(doc.load_file("tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_wide_out_of_memory_file_leak)
{
test_runner::_memory_fail_threshold = 256;
xml_document doc;
for (int i = 0; i < 256; ++i)
CHECK_ALLOC_FAIL(CHECK(doc.load_file(L"tests/data/small.xml").status == status_out_of_memory));
test_runner::_memory_fail_threshold = 0;
CHECK(doc.load_file(L"tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_file_error_previous)
{
xml_document doc;
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
CHECK(doc.load_file("filedoesnotexist").status == status_file_not_found);
CHECK(!doc.first_child());
}
TEST(document_load_file_wide_ascii)
{
xml_document doc;
CHECK(doc.load_file(L"tests/data/small.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
#if !defined(__DMC__) && !defined(__MWERKS__) && !(defined(__MINGW32__) && defined(__STRICT_ANSI__) && !defined(__MINGW64_VERSION_MAJOR)) && !defined(__BORLANDC__)
TEST(document_load_file_wide_unicode)
{
xml_document doc;
CHECK(doc.load_file(L"tests/data/\x0442\x0435\x0441\x0442.xml"));
CHECK_NODE(doc, STR("<node/>"));
}
#endif
TEST(document_load_file_wide_out_of_memory)
{
test_runner::_memory_fail_threshold = 1;
xml_document doc;
xml_parse_result result;
result.status = status_out_of_memory;
CHECK_ALLOC_FAIL(result = doc.load_file(L"tests/data/small.xml"));
CHECK(result.status == status_out_of_memory || result.status == status_file_not_found);
}
#if defined(__APPLE__)
TEST(document_load_file_special_folder)
{
xml_document doc;
xml_parse_result result = doc.load_file(".");
CHECK(result.status == status_io_error);
}
#endif
#if defined(__linux__)
TEST(document_load_file_special_device)
{
xml_document doc;
xml_parse_result result = doc.load_file("/dev/tty");
CHECK(result.status == status_file_not_found || result.status == status_io_error);
}
#endif
TEST_XML(document_save, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_no_declaration | format_raw, get_native_encoding());
CHECK(writer.as_string() == STR("<node/>"));
}
#ifndef PUGIXML_NO_STL
TEST_XML(document_save_stream, "<node/>")
{
std::ostringstream oss;
doc.save(oss, STR(""), format_no_declaration | format_raw);
CHECK(oss.str() == "<node/>");
}
TEST_XML(document_save_stream_wide, "<node/>")
{
std::basic_ostringstream<wchar_t> oss;
doc.save(oss, STR(""), format_no_declaration | format_raw);
CHECK(oss.str() == L"<node/>");
}
#endif
TEST_XML(document_save_bom, "<n/>")
{
unsigned int flags = format_no_declaration | format_raw | format_write_bom;
// specific encodings
CHECK(test_save_narrow(doc, flags, encoding_utf8, "\xef\xbb\xbf<n/>", 7));
CHECK(test_save_narrow(doc, flags, encoding_utf16_be, "\xfe\xff\x00<\x00n\x00/\x00>", 10));
CHECK(test_save_narrow(doc, flags, encoding_utf16_le, "\xff\xfe<\x00n\x00/\x00>\x00", 10));
CHECK(test_save_narrow(doc, flags, encoding_utf32_be, "\x00\x00\xfe\xff\x00\x00\x00<\x00\x00\x00n\x00\x00\x00/\x00\x00\x00>", 20));
CHECK(test_save_narrow(doc, flags, encoding_utf32_le, "\xff\xfe\x00\x00<\x00\x00\x00n\x00\x00\x00/\x00\x00\x00>\x00\x00\x00", 20));
CHECK(test_save_narrow(doc, flags, encoding_latin1, "<n/>", 4));
// encodings synonyms
CHECK(save_narrow(doc, flags, encoding_utf16) == save_narrow(doc, flags, (is_little_endian() ? encoding_utf16_le : encoding_utf16_be)));
CHECK(save_narrow(doc, flags, encoding_utf32) == save_narrow(doc, flags, (is_little_endian() ? encoding_utf32_le : encoding_utf32_be)));
size_t wcharsize = sizeof(wchar_t);
CHECK(save_narrow(doc, flags, encoding_wchar) == save_narrow(doc, flags, (wcharsize == 2 ? encoding_utf16 : encoding_utf32)));
}
TEST_XML(document_save_declaration, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n<node />\n"));
}
TEST(document_save_declaration_empty)
{
xml_document doc;
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n"));
}
TEST_XML(document_save_declaration_present_first, "<node/>")
{
doc.insert_child_before(node_declaration, doc.first_child()).append_attribute(STR("encoding")) = STR("utf8");
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml encoding=\"utf8\"?>\n<node />\n"));
}
TEST_XML(document_save_declaration_present_second, "<node/>")
{
doc.insert_child_before(node_declaration, doc.first_child()).append_attribute(STR("encoding")) = STR("utf8");
doc.insert_child_before(node_comment, doc.first_child()).set_value(STR("text"));
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
CHECK(writer.as_string() == STR("<!--text-->\n<?xml encoding=\"utf8\"?>\n<node />\n"));
}
TEST_XML(document_save_declaration_present_last, "<node/>")
{
doc.append_child(node_declaration).append_attribute(STR("encoding")) = STR("utf8");
xml_writer_string writer;
doc.save(writer, STR(""), format_default, get_native_encoding());
// node writer only looks for declaration before the first element child
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?>\n<node />\n<?xml encoding=\"utf8\"?>\n"));
}
TEST_XML(document_save_declaration_latin1, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_default, encoding_latin1);
CHECK(writer.as_narrow() == "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<node />\n");
}
TEST_XML(document_save_declaration_raw, "<node/>")
{
xml_writer_string writer;
doc.save(writer, STR(""), format_raw, get_native_encoding());
CHECK(writer.as_string() == STR("<?xml version=\"1.0\"?><node/>"));
}
struct temp_file
{
char path[512];
temp_file()
{
static int index = 0;
sprintf(path, "%stempfile%d", test_runner::_temp_path, index++);
}
~temp_file()
{
#ifndef _WIN32_WCE
CHECK(unlink(path) == 0);
#endif
}
};
TEST_XML(document_save_file, "<node/>")
{
temp_file f;
CHECK(doc.save_file(f.path));
CHECK(doc.load_file(f.path, parse_default | parse_declaration));
CHECK_NODE(doc, STR("<?xml version=\"1.0\"?><node/>"));
}
TEST_XML(document_save_file_wide, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
CHECK(doc.save_file(wpath));
CHECK(doc.load_file(f.path, parse_default | parse_declaration));
CHECK_NODE(doc, STR("<?xml version=\"1.0\"?><node/>"));
}
TEST_XML(document_save_file_error, "<node/>")
{
CHECK(!doc.save_file("tests/data/unknown/output.xml"));
}
TEST_XML(document_save_file_text, "<node/>")
{
temp_file f;
CHECK(doc.save_file(f.path, STR(""), format_no_declaration | format_save_file_text));
CHECK(test_file_contents(f.path, "<node />\n", 9) || test_file_contents(f.path, "<node />\r\n", 10));
CHECK(doc.save_file(f.path, STR(""), format_no_declaration));
CHECK(test_file_contents(f.path, "<node />\n", 9));
}
TEST_XML(document_save_file_wide_text, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
CHECK(doc.save_file(wpath, STR(""), format_no_declaration | format_save_file_text));
CHECK(test_file_contents(f.path, "<node />\n", 9) || test_file_contents(f.path, "<node />\r\n", 10));
CHECK(doc.save_file(wpath, STR(""), format_no_declaration));
CHECK(test_file_contents(f.path, "<node />\n", 9));
}
TEST_XML(document_save_file_leak, "<node/>")
{
temp_file f;
for (int i = 0; i < 256; ++i)
CHECK(doc.save_file(f.path));
}
TEST_XML(document_save_file_wide_leak, "<node/>")
{
temp_file f;
// widen the path
wchar_t wpath[sizeof(f.path)];
std::copy(f.path, f.path + strlen(f.path) + 1, wpath + 0);
for (int i = 0; i < 256; ++i)
CHECK(doc.save_file(wpath));
}
TEST(document_load_buffer)
{
const char_t text[] = STR("<?xml?><node/>");
xml_document doc;
CHECK(doc.load_buffer(text, sizeof(text)));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_buffer_inplace)
{
char_t text[] = STR("<?xml?><node/>");
xml_document doc;
CHECK(doc.load_buffer_inplace(text, sizeof(text)));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_load_buffer_inplace_own)
{
allocation_function alloc = get_memory_allocation_function();
size_t size = strlen("<?xml?><node/>") * sizeof(char_t);
char_t* text = static_cast<char_t*>(alloc(size));
CHECK(text);
memcpy(text, STR("<?xml?><node/>"), size);
xml_document doc;
CHECK(doc.load_buffer_inplace_own(text, size));
CHECK_NODE(doc, STR("<node/>"));
}
TEST(document_parse_result_bool)
{
xml_parse_result result;
result.status = status_ok;
CHECK(result);
CHECK(!!result);
CHECK(result == true);
for (int i = 1; i < 20; ++i)
{
result.status = static_cast<xml_parse_status>(i);
CHECK(!result);
CHECK(result == false);
}
}
TEST(document_parse_result_description)
{
xml_parse_result result;
for (int i = 0; i < 20; ++i)
{
result.status = static_cast<xml_parse_status>(i);
CHECK(result.description() != 0);
CHECK(result.description()[0] != 0);
}
}
TEST(document_load_fail)
{
xml_document doc;
CHECK(!doc.load_string(STR("<foo><bar/>")));
CHECK(doc.child(STR("foo")).child(STR("bar")));
}
inline void check_utftest_document(const xml_document& doc)
{
// ascii text
CHECK_STRING(doc.last_child().first_child().name(), STR("English"));
// check that we have parsed some non-ascii text
CHECK(static_cast<unsigned int>(doc.last_child().last_child().name()[0]) >= 0x80);
// check magic string
const char_t* v = doc.last_child().child(STR("Heavy")).previous_sibling().child_value();
#ifdef PUGIXML_WCHAR_MODE
CHECK(v[0] == 0x4e16 && v[1] == 0x754c && v[2] == 0x6709 && v[3] == 0x5f88 && v[4] == 0x591a && v[5] == wchar_cast(0x8bed) && v[6] == wchar_cast(0x8a00));
// last character is a surrogate pair
size_t wcharsize = sizeof(wchar_t);
CHECK(wcharsize == 2 ? (v[7] == wchar_cast(0xd852) && v[8] == wchar_cast(0xdf62)) : (v[7] == wchar_cast(0x24b62)));
#else
// unicode string
CHECK_STRING(v, "\xe4\xb8\x96\xe7\x95\x8c\xe6\x9c\x89\xe5\xbe\x88\xe5\xa4\x9a\xe8\xaf\xad\xe8\xa8\x80\xf0\xa4\xad\xa2");
#endif
}
TEST(document_load_file_convert_auto)
{
const char* files[] =
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
"tests/data/utftest_utf8.xml",
"tests/data/utftest_utf8_bom.xml",
"tests/data/utftest_utf8_nodecl.xml"
};
xml_encoding encodings[] =
{
encoding_utf16_be, encoding_utf16_be, encoding_utf16_be,
encoding_utf16_le, encoding_utf16_le, encoding_utf16_le,
encoding_utf32_be, encoding_utf32_be, encoding_utf32_be,
encoding_utf32_le, encoding_utf32_le, encoding_utf32_le,
encoding_utf8, encoding_utf8, encoding_utf8
};
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
xml_document doc;
xml_parse_result res = doc.load_file(files[i]);
CHECK(res);
CHECK(res.encoding == encodings[i]);
check_utftest_document(doc);
}
}
TEST(document_load_file_convert_specific)
{
const char* files[] =
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
"tests/data/utftest_utf8.xml",
"tests/data/utftest_utf8_bom.xml",
"tests/data/utftest_utf8_nodecl.xml"
};
xml_encoding encodings[] =
{
encoding_utf16_be, encoding_utf16_be, encoding_utf16_be,
encoding_utf16_le, encoding_utf16_le, encoding_utf16_le,
encoding_utf32_be, encoding_utf32_be, encoding_utf32_be,
encoding_utf32_le, encoding_utf32_le, encoding_utf32_le,
encoding_utf8, encoding_utf8, encoding_utf8
};
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
xml_encoding encoding = encodings[j];
xml_document doc;
xml_parse_result res = doc.load_file(files[i], parse_default, encoding);
if (encoding == encodings[i])
{
CHECK(res);
CHECK(res.encoding == encoding);
check_utftest_document(doc);
}
else
{
// should not get past first tag
CHECK(!doc.first_child());
}
}
}
}
TEST(document_load_file_convert_native_endianness)
{
const char* files[2][6] =
{
{
"tests/data/utftest_utf16_be.xml",
"tests/data/utftest_utf16_be_bom.xml",
"tests/data/utftest_utf16_be_nodecl.xml",
"tests/data/utftest_utf32_be.xml",
"tests/data/utftest_utf32_be_bom.xml",
"tests/data/utftest_utf32_be_nodecl.xml",
},
{
"tests/data/utftest_utf16_le.xml",
"tests/data/utftest_utf16_le_bom.xml",
"tests/data/utftest_utf16_le_nodecl.xml",
"tests/data/utftest_utf32_le.xml",
"tests/data/utftest_utf32_le_bom.xml",
"tests/data/utftest_utf32_le_nodecl.xml",
}
};
xml_encoding encodings[] =
{
encoding_utf16, encoding_utf16, encoding_utf16,
encoding_utf32, encoding_utf32, encoding_utf32
};
for (unsigned int i = 0; i < sizeof(files[0]) / sizeof(files[0][0]); ++i)
{
const char* right_file = files[is_little_endian()][i];
const char* wrong_file = files[!is_little_endian()][i];
for (unsigned int j = 0; j < sizeof(encodings) / sizeof(encodings[0]); ++j)
{
xml_encoding encoding = encodings[j];
// check file with right endianness
{
xml_document doc;
xml_parse_result res = doc.load_file(right_file, parse_default, encoding);
if (encoding == encodings[i])
{
CHECK(res);
check_utftest_document(doc);
}
else
{
// should not get past first tag
CHECK(!doc.first_child());
}
}
// check file with wrong endianness
{
xml_document doc;
doc.load_file(wrong_file, parse_default, encoding);
CHECK(!doc.first_child());
}
}
}
}
struct file_data_t
{
const char* path;
xml_encoding encoding;
char* data;
size_t size;
};
TEST(document_contents_preserve)
{
file_data_t files[] =
{
{"tests/data/utftest_utf16_be_clean.xml", encoding_utf16_be, 0, 0},
{"tests/data/utftest_utf16_le_clean.xml", encoding_utf16_le, 0, 0},
{"tests/data/utftest_utf32_be_clean.xml", encoding_utf32_be, 0, 0},
{"tests/data/utftest_utf32_le_clean.xml", encoding_utf32_le, 0, 0},
{"tests/data/utftest_utf8_clean.xml", encoding_utf8, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// convert each file to each format and compare bitwise
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
for (unsigned int dst = 0; dst < sizeof(files) / sizeof(files[0]); ++dst)
{
// parse into document (preserve comments, declaration and whitespace pcdata)
xml_document doc;
CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default | parse_ws_pcdata | parse_declaration | parse_comments));
// compare saved document with the original (raw formatting, without extra declaration, write bom if it was in original file)
CHECK(test_save_narrow(doc, format_raw | format_no_declaration | format_write_bom, files[dst].encoding, files[dst].data, files[dst].size));
}
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
TEST(document_contents_preserve_latin1)
{
file_data_t files[] =
{
{"tests/data/latintest_utf8.xml", encoding_utf8, 0, 0},
{"tests/data/latintest_latin1.xml", encoding_latin1, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// convert each file to each format and compare bitwise
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
for (unsigned int dst = 0; dst < sizeof(files) / sizeof(files[0]); ++dst)
{
// parse into document (preserve comments, declaration and whitespace pcdata)
xml_document doc;
CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default | parse_ws_pcdata | parse_declaration | parse_comments));
// compare saved document with the original (raw formatting, without extra declaration, write bom if it was in original file)
CHECK(test_save_narrow(doc, format_raw | format_no_declaration | format_write_bom, files[dst].encoding, files[dst].data, files[dst].size));
}
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
static bool test_parse_fail(const void* buffer, size_t size, xml_encoding encoding = encoding_utf8)
{
// copy buffer to heap (to enable out-of-bounds checks)
void* temp = malloc(size);
memcpy(temp, buffer, size);
// check that this parses without buffer overflows (yielding an error)
xml_document doc;
bool result = doc.load_buffer_inplace(temp, size, parse_default, encoding);
free(temp);
return !result;
}
TEST(document_convert_invalid_utf8)
{
// invalid 1-byte input
CHECK(test_parse_fail("<\xb0", 2));
// invalid 2-byte input
CHECK(test_parse_fail("<\xc0", 2));
CHECK(test_parse_fail("<\xd0", 2));
// invalid 3-byte input
CHECK(test_parse_fail("<\xe2\x80", 3));
CHECK(test_parse_fail("<\xe2", 2));
// invalid 4-byte input
CHECK(test_parse_fail("<\xf2\x97\x98", 4));
CHECK(test_parse_fail("<\xf2\x97", 3));
CHECK(test_parse_fail("<\xf2", 2));
// invalid 5-byte input
CHECK(test_parse_fail("<\xf8", 2));
}
TEST(document_convert_invalid_utf16)
{
// check non-terminated degenerate handling
CHECK(test_parse_fail("\x00<\xda\x1d", 4, encoding_utf16_be));
CHECK(test_parse_fail("<\x00\x1d\xda", 4, encoding_utf16_le));
// check incorrect leading code
CHECK(test_parse_fail("\x00<\xde\x24", 4, encoding_utf16_be));
CHECK(test_parse_fail("<\x00\x24\xde", 4, encoding_utf16_le));
}
TEST(document_load_buffer_empty)
{
xml_encoding encodings[] =
{
encoding_auto,
encoding_utf8,
encoding_utf16_le,
encoding_utf16_be,
encoding_utf16,
encoding_utf32_le,
encoding_utf32_be,
encoding_utf32,
encoding_wchar,
encoding_latin1
};
char buffer[1];
for (unsigned int i = 0; i < sizeof(encodings) / sizeof(encodings[0]); ++i)
{
xml_encoding encoding = encodings[i];
xml_document doc;
CHECK(doc.load_buffer(buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace(buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
void* own_buffer = get_memory_allocation_function()(1);
CHECK(doc.load_buffer_inplace_own(own_buffer, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 0, parse_default, encoding).status == status_no_document_element && !doc.first_child());
}
}
TEST(document_load_buffer_empty_fragment)
{
xml_encoding encodings[] =
{
encoding_auto,
encoding_utf8,
encoding_utf16_le,
encoding_utf16_be,
encoding_utf16,
encoding_utf32_le,
encoding_utf32_be,
encoding_utf32,
encoding_wchar,
encoding_latin1
};
char buffer[1];
for (unsigned int i = 0; i < sizeof(encodings) / sizeof(encodings[0]); ++i)
{
xml_encoding encoding = encodings[i];
xml_document doc;
CHECK(doc.load_buffer(buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace(buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 0, parse_fragment, encoding) && !doc.first_child());
void* own_buffer = get_memory_allocation_function()(1);
CHECK(doc.load_buffer_inplace_own(own_buffer, 0, parse_fragment, encoding) && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 0, parse_fragment, encoding) && !doc.first_child());
}
}
TEST(document_load_buffer_null)
{
xml_document doc;
CHECK(doc.load_buffer(0, 12).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer(0, 12, parse_fragment).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer_inplace(0, 12).status == status_io_error && !doc.first_child());
CHECK(doc.load_buffer_inplace_own(0, 12).status == status_io_error && !doc.first_child());
}
TEST(document_progressive_truncation)
{
char* original_data;
size_t original_size;
CHECK(load_file_in_memory("tests/data/truncation.xml", original_data, original_size));
char* buffer = new char[original_size];
for (size_t i = 1; i <= original_size; ++i)
{
char* truncated_data = buffer + original_size - i;
// default flags
{
memcpy(truncated_data, original_data, i);
xml_document doc;
bool result = doc.load_buffer_inplace(truncated_data, i);
// only eof is parseable
CHECK((i == original_size) ? result : !result);
}
// fragment mode
{
memcpy(truncated_data, original_data, i);
xml_document doc;
bool result = doc.load_buffer_inplace(truncated_data, i, parse_default | parse_fragment);
// some truncate locations are parseable - those that come after declaration, declaration + doctype, declaration + doctype + comment and eof
CHECK(((i >= 21 && i <= 23) || (i >= 66 && i <= 68) || (i >= 95 && i <= 97) || i == original_size) ? result : !result);
}
}
delete[] buffer;
delete[] original_data;
}
TEST(document_load_buffer_short)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer(data, 4).status == status_no_document_element);
CHECK(doc.load_buffer(data + 1, 3).status == status_no_document_element);
CHECK(doc.load_buffer(data + 2, 2).status == status_no_document_element);
CHECK(doc.load_buffer(data + 3, 1).status == status_no_document_element);
CHECK(doc.load_buffer(data + 4, 0).status == status_no_document_element);
CHECK(doc.load_buffer(0, 0).status == status_no_document_element);
delete[] data;
}
TEST(document_load_buffer_short_fragment)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer(data, 4, parse_fragment) && test_string_equal(doc.text().get(), STR("abcd")));
CHECK(doc.load_buffer(data + 1, 3, parse_fragment) && test_string_equal(doc.text().get(), STR("bcd")));
CHECK(doc.load_buffer(data + 2, 2, parse_fragment) && test_string_equal(doc.text().get(), STR("cd")));
CHECK(doc.load_buffer(data + 3, 1, parse_fragment) && test_string_equal(doc.text().get(), STR("d")));
CHECK(doc.load_buffer(data + 4, 0, parse_fragment) && !doc.first_child());
CHECK(doc.load_buffer(0, 0, parse_fragment) && !doc.first_child());
delete[] data;
}
TEST(document_load_buffer_inplace_short)
{
char* data = new char[4];
memcpy(data, "abcd", 4);
xml_document doc;
CHECK(doc.load_buffer_inplace(data, 4).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 1, 3).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 2, 2).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 3, 1).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(data + 4, 0).status == status_no_document_element);
CHECK(doc.load_buffer_inplace(0, 0).status == status_no_document_element);
delete[] data;
}
#ifndef PUGIXML_NO_EXCEPTIONS
TEST(document_load_exceptions)
{
bool thrown = false;
try
{
xml_document doc;
if (!doc.load_string(STR("<node attribute='value"))) throw std::bad_alloc();
CHECK_FORCE_FAIL("Expected parsing failure");
}
catch (const std::bad_alloc&)
{
thrown = true;
}
CHECK(thrown);
}
#endif
TEST_XML_FLAGS(document_element, "<?xml version='1.0'?><node><child/></node><!---->", parse_default | parse_declaration | parse_comments)
{
CHECK(doc.document_element() == doc.child(STR("node")));
}
TEST_XML_FLAGS(document_element_absent, "<!---->", parse_comments | parse_fragment)
{
CHECK(doc.document_element() == xml_node());
}
TEST_XML(document_reset, "<node><child/></node>")
{
CHECK(doc.first_child());
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
CHECK(doc.load_string(STR("<node/>")));
CHECK(doc.first_child());
CHECK_NODE(doc, STR("<node/>"));
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST(document_reset_empty)
{
xml_document doc;
doc.reset();
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST_XML(document_reset_copy, "<node><child/></node>")
{
xml_document doc2;
CHECK_NODE(doc2, STR(""));
doc2.reset(doc);
CHECK_NODE(doc2, STR("<node><child/></node>"));
CHECK(doc.first_child() != doc2.first_child());
doc.reset(doc2);
CHECK_NODE(doc, STR("<node><child/></node>"));
CHECK(doc.first_child() != doc2.first_child());
CHECK(doc.first_child().offset_debug() == -1);
}
TEST_XML(document_reset_copy_self, "<node><child/></node>")
{
CHECK_NODE(doc, STR("<node><child/></node>"));
doc.reset(doc);
CHECK(!doc.first_child());
CHECK_NODE(doc, STR(""));
}
TEST(document_load_buffer_utf_truncated)
{
const unsigned char utf8[] = {'<', 0xe2, 0x82, 0xac, '/', '>'};
const unsigned char utf16_be[] = {0, '<', 0x20, 0xac, 0, '/', 0, '>'};
const unsigned char utf16_le[] = {'<', 0, 0xac, 0x20, '/', 0, '>', 0};
const unsigned char utf32_be[] = {0, 0, 0, '<', 0, 0, 0x20, 0xac, 0, 0, 0, '/', 0, 0, 0, '>'};
const unsigned char utf32_le[] = {'<', 0, 0, 0, 0xac, 0x20, 0, 0, '/', 0, 0, 0, '>', 0, 0, 0};
struct document_data_t
{
xml_encoding encoding;
const unsigned char* data;
size_t size;
};
const document_data_t data[] =
{
{ encoding_utf8, utf8, sizeof(utf8) },
{ encoding_utf16_be, utf16_be, sizeof(utf16_be) },
{ encoding_utf16_le, utf16_le, sizeof(utf16_le) },
{ encoding_utf32_be, utf32_be, sizeof(utf32_be) },
{ encoding_utf32_le, utf32_le, sizeof(utf32_le) },
};
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); ++i)
{
const document_data_t& d = data[i];
for (size_t j = 0; j <= d.size; ++j)
{
char* buffer = new char[j];
memcpy(buffer, d.data, j);
xml_document doc;
xml_parse_result res = doc.load_buffer(buffer, j, parse_default, d.encoding);
if (j == d.size)
{
CHECK(res);
const char_t* name = doc.first_child().name();
#ifdef PUGIXML_WCHAR_MODE
CHECK(name[0] == 0x20ac && name[1] == 0);
#else
CHECK_STRING(name, "\xe2\x82\xac");
#endif
}
else
{
CHECK(!res || !doc.first_child());
}
delete[] buffer;
}
}
}
#ifndef PUGIXML_NO_STL
TEST(document_load_stream_truncated)
{
const unsigned char utf32_be[] = {0, 0, 0, '<', 0, 0, 0x20, 0xac, 0, 0, 0, '/', 0, 0, 0, '>'};
for (size_t i = 0; i <= sizeof(utf32_be); ++i)
{
std::string prefix(reinterpret_cast<const char*>(utf32_be), i);
std::istringstream iss(prefix);
xml_document doc;
xml_parse_result res = doc.load(iss);
if (i == sizeof(utf32_be))
{
CHECK(res);
}
else
{
CHECK(!res || !doc.first_child());
if (i < 8)
{
CHECK(!doc.first_child());
}
else
{
const char_t* name = doc.first_child().name();
#ifdef PUGIXML_WCHAR_MODE
CHECK(name[0] == 0x20ac && name[1] == 0);
#else
CHECK_STRING(name, "\xe2\x82\xac");
#endif
}
}
}
}
#endif
TEST(document_alignment)
{
char buf[256 + sizeof(xml_document)];
for (size_t offset = 0; offset < 256; offset += sizeof(void*))
{
xml_document* doc = new (buf + offset) xml_document;
CHECK(doc->load_string(STR("<node />")));
CHECK_NODE(*doc, STR("<node/>"));
doc->~xml_document();
}
}
TEST(document_convert_out_of_memory)
{
file_data_t files[] =
{
{"tests/data/utftest_utf16_be_clean.xml", encoding_utf16_be, 0, 0},
{"tests/data/utftest_utf16_le_clean.xml", encoding_utf16_le, 0, 0},
{"tests/data/utftest_utf32_be_clean.xml", encoding_utf32_be, 0, 0},
{"tests/data/utftest_utf32_le_clean.xml", encoding_utf32_le, 0, 0},
{"tests/data/utftest_utf8_clean.xml", encoding_utf8, 0, 0},
{"tests/data/latintest_latin1.xml", encoding_latin1, 0, 0}
};
// load files in memory
for (unsigned int i = 0; i < sizeof(files) / sizeof(files[0]); ++i)
{
CHECK(load_file_in_memory(files[i].path, files[i].data, files[i].size));
}
// disallow allocations
test_runner::_memory_fail_threshold = 1;
for (unsigned int src = 0; src < sizeof(files) / sizeof(files[0]); ++src)
{
xml_document doc;
CHECK_ALLOC_FAIL(CHECK(doc.load_buffer(files[src].data, files[src].size, parse_default, files[src].encoding).status == status_out_of_memory));
}
// cleanup
for (unsigned int j = 0; j < sizeof(files) / sizeof(files[0]); ++j)
{
delete[] files[j].data;
}
}
#ifdef PUGIXML_HAS_MOVE
TEST_XML(document_move_ctor, "<node1/><node2/>")
{
xml_document other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST_XML(document_move_assign, "<node1/><node2/>")
{
xml_document other;
CHECK(other.load_string(STR("<node3/>")));
other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST_XML(document_move_zero_alloc, "<node1/><node2/>")
{
test_runner::_memory_fail_threshold = 1;
xml_document other = std::move(doc);
CHECK(doc.first_child().empty());
CHECK_STRING(other.first_child().name(), STR("node1"));
CHECK(other.first_child().parent() == other);
CHECK_STRING(other.last_child().name(), STR("node2"));
CHECK(other.last_child().parent() == other);
}
TEST(document_move_append_buffer)
{
xml_document* doc = new xml_document();
CHECK(doc->load_string(STR("<node1 attr1='value1'><node2/></node1>")));
CHECK(doc->child(STR("node1")).append_buffer("<node3/>", 8));
CHECK(doc->child(STR("node1")).append_buffer("<node4/>", 8));
xml_document other = std::move(*doc);
delete doc;
CHECK(other.child(STR("node1")).append_buffer("<node5/>", 8));
CHECK(other.child(STR("node1")).append_buffer("<node6/>", 8));
CHECK_NODE(other, STR("<node1 attr1=\"value1\"><node2/><node3/><node4/><node5/><node6/></node1>"));
}
TEST(document_move_append_child)
{
xml_document* doc = new xml_document();
CHECK(doc->load_string(STR("<node1 attr1='value1'><node2/></node1>")));
xml_document other = std::move(*doc);
delete doc;
for (int i = 0; i < 3000; ++i)
other.child(STR("node1")).append_child(STR("node"));
for (int i = 0; i < 3000; ++i)
other.child(STR("node1")).remove_child(other.child(STR("node1")).last_child());
CHECK_NODE(other, STR("<node1 attr1=\"value1\"><node2/></node1>"));
other.remove_child(other.first_child());
CHECK(!other.first_child());
}
TEST(document_move_empty)
{
xml_document* doc = new xml_document();
xml_document other = std::move(*doc);
delete doc;
}
TEST(document_move_large)
{
xml_document* doc = new xml_document();
xml_node dn = doc->append_child(STR("node"));
for (int i = 0; i < 3000; ++i)
dn.append_child(STR("child"));
xml_document other = std::move(*doc);
delete doc;
xml_node on = other.child(STR("node"));
for (int i = 0; i < 3000; ++i)
CHECK(on.remove_child(on.first_child()));
CHECK(!on.first_child());
}
TEST_XML(document_move_buffer, "<node1/><node2/>")
{
CHECK(doc.child(STR("node2")).offset_debug() == 9);
xml_document other = std::move(doc);
CHECK(other.child(STR("node2")).offset_debug() == 9);
}
TEST_XML(document_move_append_child_zero_alloc, "<node1/><node2/>")
{
test_runner::_memory_fail_threshold = 1;
xml_document other = std::move(doc);
CHECK(other.append_child(STR("node3")));
CHECK_NODE(other, STR("<node1/><node2/><node3/>"));
}
TEST(document_move_empty_zero_alloc)
{
xml_document* docs = new xml_document[32];
test_runner::_memory_fail_threshold = 1;
for (int i = 1; i < 32; ++i)
docs[i] = std::move(docs[i-1]);
delete[] docs;
}
#ifndef PUGIXML_COMPACT
TEST(document_move_repeated_zero_alloc)
{
xml_document docs[32];
CHECK(docs[0].load_string(STR("<node><child/></node>")));
test_runner::_memory_fail_threshold = 1;
for (int i = 1; i < 32; ++i)
docs[i] = std::move(docs[i-1]);
for (int i = 0; i < 31; ++i)
CHECK(!docs[i].first_child());
CHECK_NODE(docs[31], STR("<node><child/></node>"));
}
#endif
#ifdef PUGIXML_COMPACT
TEST(document_move_compact_fail)
{
xml_document docs[32];
CHECK(docs[0].load_string(STR("<node><child/></node>")));
test_runner::_memory_fail_threshold = 1;
int safe_count = 21;
for (int i = 1; i <= safe_count; ++i)
docs[i] = std::move(docs[i-1]);
CHECK_ALLOC_FAIL(docs[safe_count+1] = std::move(docs[safe_count]));
for (int i = 0; i < safe_count; ++i)
CHECK(!docs[i].first_child());
CHECK_NODE(docs[safe_count], STR("<node><child/></node>"));
CHECK(!docs[safe_count+1].first_child());
}
#endif
TEST(document_move_assign_empty)
{
xml_document doc;
doc.append_child(STR("node"));
doc = xml_document();
doc.append_child(STR("node2"));
CHECK_NODE(doc, STR("<node2/>"));
}
#endif
|
#include <iostream>
#include <cstdio>
#include <vector>
#define SEQAN_TEST
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/align.h>
using namespace std;
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////
template <typename TSource, typename TSpec>
void TestGapsBase()
{
typedef Gaps<TSource, TSpec> TGaps;
TGaps gaps1; //default ctor
TSource src1 = "hello";
setSource(gaps1, src1); //setSource
SEQAN_TASSERT(source(gaps1) == src1)
SEQAN_TASSERT(id(source(gaps1)) == id(src1))
SEQAN_TASSERT(id(source(gaps1)) == id(gaps1)) //id
assignSource(gaps1, "blabla"); //assignSource
SEQAN_TASSERT(source(gaps1) == "blabla")
SEQAN_TASSERT(src1 == "blabla")
assignSource(gaps1, "abcdef", 1, 5); //assignSource
SEQAN_TASSERT(source(gaps1) == "abcdef")
SEQAN_TASSERT(sourceSegment(gaps1) == "bcde") //sourceSegment
moveSource(gaps1, "hullahulla"); //moveSource
SEQAN_TASSERT(source(gaps1) == "hullahulla")
moveSource(gaps1, "abcdef", 1, 5); //moveSource
SEQAN_TASSERT(source(gaps1) == "abcdef") //???Sollte das anders sein?
SEQAN_TASSERT(sourceSegment(gaps1) == "bcde")
detach(gaps1); //detach, createSource
SEQAN_TASSERT(source(gaps1) == src1)
SEQAN_TASSERT(id(gaps1) != id(src1))
TGaps gaps2(gaps1); //copy ctor
// it is a real copy
// SEQAN_TASSERT(id(gaps1) == id(gaps2)) //(its not a real copy)
//____________________________________________________________________________
setSource(gaps1, src1);
src1 = "hello";
SEQAN_TASSERT(id(gaps1) != id(gaps2))
gaps2 = gaps1; //operator =
SEQAN_TASSERT(id(gaps1) == id(gaps2))
SEQAN_TASSERT(id(gaps2) == id(src1))
TGaps gaps3(src1); //ctor with source
TGaps const & c_gaps3 = gaps3; //const version
SEQAN_TASSERT(id(gaps3) == id(src1))
SEQAN_TASSERT(id(c_gaps3) == id(src1))
SEQAN_TASSERT(dependentSource(gaps3)) //dependentSource
SEQAN_TASSERT(dependentSource(c_gaps3))
SEQAN_TASSERT(length(gaps3) == length(src1)) //length
SEQAN_TASSERT(sourceLength(gaps3) == length(src1)) //sourceLength
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 0) //sourceBeginPosition
SEQAN_TASSERT(sourceBegin(gaps3) == begin(source(gaps3))) //sourceBegin
SEQAN_TASSERT(sourceBegin(gaps3, Rooted()) == begin(source(gaps3), Rooted()))
SEQAN_TASSERT(sourceEndPosition(gaps3) == length(src1)) //sourceEndPosition
SEQAN_TASSERT(sourceEnd(gaps3) == end(source(gaps3))) //sourceEnd
SEQAN_TASSERT(sourceEnd(gaps3, Rooted()) == end(source(gaps3), Rooted()))
SEQAN_TASSERT(*(--end(gaps3)) == 'o') //end
SEQAN_TASSERT(*(--end(c_gaps3)) == 'o') //end
setSourceBeginPosition(gaps3, 3); //"---lo" //setSourceBeginPosition
SEQAN_TASSERT(gaps3 == "lo");
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 3) //sourceBeginPosition
SEQAN_TASSERT(beginPosition(gaps3) == 3) //beginPosition
SEQAN_TASSERT(length(gaps3) == 2) //length
setSourceBeginPosition(gaps3, 1); //"-ello" //setSourceBeginPosition
SEQAN_TASSERT(gaps3 == "ello");
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 1) //sourceBeginPosition
SEQAN_TASSERT(beginPosition(gaps3) == 1) //beginPosition
SEQAN_TASSERT(length(gaps3) == 4) //length
SEQAN_TASSERT(isGap(gaps3, 0)) //isGap
SEQAN_TASSERT(gaps3[1] == 'e')
SEQAN_TASSERT(c_gaps3[1] == 'e')
SEQAN_TASSERT(getValue(gaps3, 1) == 'e'); //getValue
SEQAN_TASSERT(getValue(c_gaps3, 1) == 'e');
setSourceEndPosition(gaps3, 3); //"-el" //setSourceEndPosition
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(sourceEndPosition(gaps3) == 3) //sourceEndPosition
SEQAN_TASSERT(endPosition(gaps3) == 3) //endPosition
SEQAN_TASSERT(length(gaps3) == 2)
setBeginPosition(gaps3, 0); //"el" //setBeginPosition
SEQAN_TASSERT(gaps3[0] == 'e')
SEQAN_TASSERT(beginPosition(gaps3) == 0)
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 1)
SEQAN_TASSERT(endPosition(gaps3) == 2)
SEQAN_TASSERT(sourceEndPosition(gaps3) == 3)
//____________________________________________________________________________
clear(gaps3); //clear
SEQAN_TASSERT(length(gaps3) == 0);
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 0)
SEQAN_TASSERT(sourceEndPosition(gaps3) == 0)
setSourceEndPosition(gaps3, length(source(gaps3))); //reactivate after clear
SEQAN_TASSERT(gaps3 == "hello")
insertGaps(gaps3, 2, 3);
setBeginPosition(gaps3, 2);
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
//toSourcePosition
SEQAN_TASSERT(toSourcePosition(gaps3, 0) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 1) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 2) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 3) == 1)
SEQAN_TASSERT(toSourcePosition(gaps3, 4) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 5) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 6) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 7) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 8) == 3)
SEQAN_TASSERT(toSourcePosition(gaps3, 9) == 4)
SEQAN_TASSERT(toSourcePosition(gaps3, 10) == 5)
SEQAN_TASSERT(toSourcePosition(gaps3, 11) == 5)
//toViewPosition
SEQAN_TASSERT(toViewPosition(gaps3, 0) == 2)
SEQAN_TASSERT(toViewPosition(gaps3, 1) == 3)
SEQAN_TASSERT(toViewPosition(gaps3, 2) == 7)
SEQAN_TASSERT(toViewPosition(gaps3, 3) == 8)
SEQAN_TASSERT(toViewPosition(gaps3, 4) == 9)
SEQAN_TASSERT(toViewPosition(gaps3, 5) == 10)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "he--llo") //"-he--llo"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "hello") //"-hello"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3);
SEQAN_TASSERT(gaps3 == "hello") //"hello"
SEQAN_TASSERT(beginPosition(gaps3) == 0)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "hello") //"hello"
setSourceBeginPosition(gaps3, 1);
setSourceEndPosition(gaps3, 3); //"el"
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(sourceSegment(gaps3) == "el") //sourceSegment
SEQAN_TASSERT(sourceSegment(c_gaps3) == "el")
//____________________________________________________________________________
// Comparison Functions
SEQAN_TASSERT(gaps3 == "el") //"hello"
SEQAN_TASSERT(gaps3 != "ello")
SEQAN_TASSERT(gaps3 <= "el")
SEQAN_TASSERT(gaps3 < "ello")
SEQAN_TASSERT(gaps3 > "a")
SEQAN_TASSERT(gaps3 >= "el")
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
// Iterator Functions
template <typename TSource, typename TSpec>
void TestGapsIterator()
{
//____________________________________________________________________________
typedef Gaps<TSource, TSpec> TGaps;
typedef typename Iterator<TGaps, Rooted>::Type TIterator;
TSource src1 = "hello";
TGaps gaps4(src1);
TIterator it1 = begin(gaps4); //begin
TIterator const & c_it1 = it1; //const version
SEQAN_TASSERT(*it1 == 'h'); //operator *
SEQAN_TASSERT(source(it1) == begin(src1)) //source
SEQAN_TASSERT(source(c_it1) == begin(src1))
SEQAN_TASSERT(atBegin(c_it1)) //atBegin
++it1; //operator ++
SEQAN_TASSERT(*it1 == 'e');
--it1; //operator --
SEQAN_TASSERT(*it1 == 'h');
TIterator it2 = end(gaps4); //end
SEQAN_TASSERT(atEnd(it2)) //atEnd
--it2;
SEQAN_TASSERT(*it2 == 'o');
//____________________________________________________________________________
TIterator it3; //default ctor
TIterator it4 = it1; //copy ctor
TIterator const & c_it4 = it4;
SEQAN_TASSERT(container(it4) == container(it1))
SEQAN_TASSERT(*it4 == *it1)
SEQAN_TASSERT(it4 == it1) //operator ==
SEQAN_TASSERT(it4 == c_it1)
SEQAN_TASSERT(c_it4 == it1)
SEQAN_TASSERT(c_it4 == c_it1)
++it1;
SEQAN_TASSERT(it4 != it1) //operator !=
SEQAN_TASSERT(it4 != c_it1)
SEQAN_TASSERT(c_it4 != it1)
SEQAN_TASSERT(c_it4 != c_it1)
it4 = it2; //operator =
SEQAN_TASSERT(*it4 == *it2)
TIterator it5(gaps4, 1, 1); //special ctor
//____________________________________________________________________________
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
// Manipulation of Gaps
template <typename TSource, typename TSpec>
void TestGapManipulation()
{
//____________________________________________________________________________
typedef Gaps<TSource, TSpec> TGaps;
//inserting gaps
TSource src1 = "hello";
TGaps gaps5(src1);
insertGaps(gaps5, 1, 2); //insert gap somewhere
SEQAN_TASSERT(gaps5 != "hello");
SEQAN_TASSERT(gaps5 == "h--ello");
insertGaps(gaps5, 1, 1); //insert blank at the beginning of a gap
SEQAN_TASSERT(gaps5 == "h---ello");
insertGaps(gaps5, 4, 1); //insert blank at the end of a gap
SEQAN_TASSERT(gaps5 == "h----ello");
insertGap(gaps5, 8); //insert second gap
SEQAN_TASSERT(gaps5 == "h----ell-o");
insertGaps(gaps5, 0, 2); //insert at position 0
SEQAN_TASSERT(gaps5 == "h----ell-o"); //note: leading and trailing gaps are not displayed
SEQAN_TASSERT(beginPosition(gaps5) == 2);
insertGaps(gaps5, 8, 2); //insert gap with beginPosition == 2
SEQAN_TASSERT(gaps5 == "h----e--ll-o");
SEQAN_TASSERT(length(gaps5) == 12);
insertGaps(gaps5, 14, 1); //insert gap behind end. Nothing happens
SEQAN_TASSERT(gaps5 == "h----e--ll-o");
SEQAN_TASSERT(length(gaps5) == 12);
//counting gaps
SEQAN_TASSERT(gaps5 == "h----e--ll-o"); // "--h----e--ll-o"
SEQAN_TASSERT(beginPosition(gaps5) == 2);
SEQAN_TASSERT(countGaps(gaps5, 0) == 2);
SEQAN_TASSERT(countGaps(gaps5, 2) == 0);
SEQAN_TASSERT(countGaps(gaps5, 3) == 4);
SEQAN_TASSERT(countGaps(gaps5, 4) == 3);
SEQAN_TASSERT(countGaps(gaps5, 6) == 1);
SEQAN_TASSERT(countGaps(gaps5, 8) == 2);
SEQAN_TASSERT(countGaps(gaps5, 20) == 0);
//removing gaps
SEQAN_TASSERT(gaps5 == "h----e--ll-o"); // "--h----e--ll-o"
SEQAN_TASSERT(beginPosition(gaps5) == 2);
removeGap(gaps5, 4); //remove gap somewhere in gap area
SEQAN_TASSERT(gaps5 == "h---e--ll-o");
removeGaps(gaps5, 6, 1); //try to remove gap in non-gap area. Nothing happens
SEQAN_TASSERT("h---e--ll-o" == gaps5);
removeGaps(gaps5, 7, 2); //remove gap region completely
SEQAN_TASSERT(gaps5 == "h---ell-o");
removeGaps(gaps5, 4, 10); //remove rest of gap region
SEQAN_TASSERT(gaps5 == "h-ell-o");
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
template <typename TSource, typename TSpec>
void TestSequenceGapsBase()
{
typedef Gaps<TSource, TSpec> TGaps;
TGaps gaps3;
assignSource(gaps3, "hello");
insertGaps(gaps3, 2, 3);
setBeginPosition(gaps3, 2);
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
//toSourcePosition
SEQAN_TASSERT(toSourcePosition(gaps3, 0) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 1) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 2) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 3) == 1)
SEQAN_TASSERT(toSourcePosition(gaps3, 4) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 5) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 6) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 7) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 8) == 3)
SEQAN_TASSERT(toSourcePosition(gaps3, 9) == 4)
SEQAN_TASSERT(toSourcePosition(gaps3, 10) == 5)
SEQAN_TASSERT(toSourcePosition(gaps3, 11) == 5)
//toViewPosition
SEQAN_TASSERT(toViewPosition(gaps3, 0) == 2)
SEQAN_TASSERT(toViewPosition(gaps3, 1) == 3)
SEQAN_TASSERT(toViewPosition(gaps3, 2) == 7)
SEQAN_TASSERT(toViewPosition(gaps3, 3) == 8)
SEQAN_TASSERT(toViewPosition(gaps3, 4) == 9)
SEQAN_TASSERT(toViewPosition(gaps3, 5) == 10)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "he--llo") //"-he--llo"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "hello") //"-hello"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3);
SEQAN_TASSERT(gaps3 == "hello") //"hello"
SEQAN_TASSERT(beginPosition(gaps3) == 0)
assign(gaps3, "el");
SEQAN_TASSERT(gaps3 == "el") //"el"
//____________________________________________________________________________
// Comparison Functions
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(gaps3 != "ello")
SEQAN_TASSERT(gaps3 <= "el")
SEQAN_TASSERT(gaps3 < "ello")
SEQAN_TASSERT(gaps3 > "a")
SEQAN_TASSERT(gaps3 >= "el")
}
//////////////////////////////////////////////////////////////////////////////
SEQAN_DEFINE_TEST(test_align_gaps_base_char_string_array_gaps) {
TestGapsBase<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_base_char_string_sumlist_gaps) {
TestGapsBase<String<char>, SumlistGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gaps_iterator) {
TestGapsIterator<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gap_manipulation_char_string_array_gaps) {
TestGapManipulation<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gap_manipulation_char_string_sumlist_gaps) {
TestGapManipulation<String<char>, SumlistGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_sequence_gaps_base) {
TestSequenceGapsBase<String<char>, SequenceGaps>();
}
added test methods for trailing gaps and countCharacters used by ArrayGaps
git-svn-id: a7f2a8f7432d210e972fb03898013d213e2b549b@7560 e6417c60-b987-48fd-844e-b20f0fcc1017
#include <iostream>
#include <cstdio>
#include <vector>
#define SEQAN_TEST
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/align.h>
using namespace std;
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////
template <typename TSource, typename TSpec>
void TestGapsBase()
{
typedef Gaps<TSource, TSpec> TGaps;
TGaps gaps1; //default ctor
TSource src1 = "hello";
setSource(gaps1, src1); //setSource
SEQAN_TASSERT(source(gaps1) == src1)
SEQAN_TASSERT(id(source(gaps1)) == id(src1))
SEQAN_TASSERT(id(source(gaps1)) == id(gaps1)) //id
assignSource(gaps1, "blabla"); //assignSource
SEQAN_TASSERT(source(gaps1) == "blabla")
SEQAN_TASSERT(src1 == "blabla")
assignSource(gaps1, "abcdef", 1, 5); //assignSource
SEQAN_TASSERT(source(gaps1) == "abcdef")
SEQAN_TASSERT(sourceSegment(gaps1) == "bcde") //sourceSegment
moveSource(gaps1, "hullahulla"); //moveSource
SEQAN_TASSERT(source(gaps1) == "hullahulla")
moveSource(gaps1, "abcdef", 1, 5); //moveSource
SEQAN_TASSERT(source(gaps1) == "abcdef") //???Sollte das anders sein?
SEQAN_TASSERT(sourceSegment(gaps1) == "bcde")
detach(gaps1); //detach, createSource
SEQAN_TASSERT(source(gaps1) == src1)
SEQAN_TASSERT(id(gaps1) != id(src1))
TGaps gaps2(gaps1); //copy ctor
// it is a real copy
// SEQAN_TASSERT(id(gaps1) == id(gaps2)) //(its not a real copy)
//____________________________________________________________________________
setSource(gaps1, src1);
src1 = "hello";
SEQAN_TASSERT(id(gaps1) != id(gaps2))
gaps2 = gaps1; //operator =
SEQAN_TASSERT(id(gaps1) == id(gaps2))
SEQAN_TASSERT(id(gaps2) == id(src1))
TGaps gaps3(src1); //ctor with source
TGaps const & c_gaps3 = gaps3; //const version
SEQAN_TASSERT(id(gaps3) == id(src1))
SEQAN_TASSERT(id(c_gaps3) == id(src1))
SEQAN_TASSERT(dependentSource(gaps3)) //dependentSource
SEQAN_TASSERT(dependentSource(c_gaps3))
SEQAN_TASSERT(length(gaps3) == length(src1)) //length
SEQAN_TASSERT(sourceLength(gaps3) == length(src1)) //sourceLength
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 0) //sourceBeginPosition
SEQAN_TASSERT(sourceBegin(gaps3) == begin(source(gaps3))) //sourceBegin
SEQAN_TASSERT(sourceBegin(gaps3, Rooted()) == begin(source(gaps3), Rooted()))
SEQAN_TASSERT(sourceEndPosition(gaps3) == length(src1)) //sourceEndPosition
SEQAN_TASSERT(sourceEnd(gaps3) == end(source(gaps3))) //sourceEnd
SEQAN_TASSERT(sourceEnd(gaps3, Rooted()) == end(source(gaps3), Rooted()))
SEQAN_TASSERT(*(--end(gaps3)) == 'o') //end
SEQAN_TASSERT(*(--end(c_gaps3)) == 'o') //end
setSourceBeginPosition(gaps3, 3); //"---lo" //setSourceBeginPosition
SEQAN_TASSERT(gaps3 == "lo");
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 3) //sourceBeginPosition
SEQAN_TASSERT(beginPosition(gaps3) == 3) //beginPosition
SEQAN_TASSERT(length(gaps3) == 2) //length
setSourceBeginPosition(gaps3, 1); //"-ello" //setSourceBeginPosition
SEQAN_TASSERT(gaps3 == "ello");
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 1) //sourceBeginPosition
SEQAN_TASSERT(beginPosition(gaps3) == 1) //beginPosition
SEQAN_TASSERT(length(gaps3) == 4) //length
SEQAN_TASSERT(isGap(gaps3, 0)) //isGap
SEQAN_TASSERT(gaps3[1] == 'e')
SEQAN_TASSERT(c_gaps3[1] == 'e')
SEQAN_TASSERT(getValue(gaps3, 1) == 'e'); //getValue
SEQAN_TASSERT(getValue(c_gaps3, 1) == 'e');
setSourceEndPosition(gaps3, 3); //"-el" //setSourceEndPosition
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(sourceEndPosition(gaps3) == 3) //sourceEndPosition
SEQAN_TASSERT(endPosition(gaps3) == 3) //endPosition
SEQAN_TASSERT(length(gaps3) == 2)
setBeginPosition(gaps3, 0); //"el" //setBeginPosition
SEQAN_TASSERT(gaps3[0] == 'e')
SEQAN_TASSERT(beginPosition(gaps3) == 0)
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 1)
SEQAN_TASSERT(endPosition(gaps3) == 2)
SEQAN_TASSERT(sourceEndPosition(gaps3) == 3)
//____________________________________________________________________________
clear(gaps3); //clear
SEQAN_TASSERT(length(gaps3) == 0);
SEQAN_TASSERT(sourceBeginPosition(gaps3) == 0)
SEQAN_TASSERT(sourceEndPosition(gaps3) == 0)
setSourceEndPosition(gaps3, length(source(gaps3))); //reactivate after clear
SEQAN_TASSERT(gaps3 == "hello")
insertGaps(gaps3, 2, 3);
setBeginPosition(gaps3, 2);
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
//toSourcePosition
SEQAN_TASSERT(toSourcePosition(gaps3, 0) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 1) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 2) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 3) == 1)
SEQAN_TASSERT(toSourcePosition(gaps3, 4) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 5) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 6) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 7) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 8) == 3)
SEQAN_TASSERT(toSourcePosition(gaps3, 9) == 4)
SEQAN_TASSERT(toSourcePosition(gaps3, 10) == 5)
SEQAN_TASSERT(toSourcePosition(gaps3, 11) == 5)
//toViewPosition
SEQAN_TASSERT(toViewPosition(gaps3, 0) == 2)
SEQAN_TASSERT(toViewPosition(gaps3, 1) == 3)
SEQAN_TASSERT(toViewPosition(gaps3, 2) == 7)
SEQAN_TASSERT(toViewPosition(gaps3, 3) == 8)
SEQAN_TASSERT(toViewPosition(gaps3, 4) == 9)
SEQAN_TASSERT(toViewPosition(gaps3, 5) == 10)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "he--llo") //"-he--llo"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "hello") //"-hello"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3);
SEQAN_TASSERT(gaps3 == "hello") //"hello"
SEQAN_TASSERT(beginPosition(gaps3) == 0)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "hello") //"hello"
setSourceBeginPosition(gaps3, 1);
setSourceEndPosition(gaps3, 3); //"el"
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(sourceSegment(gaps3) == "el") //sourceSegment
SEQAN_TASSERT(sourceSegment(c_gaps3) == "el")
//____________________________________________________________________________
// Comparison Functions
SEQAN_TASSERT(gaps3 == "el") //"hello"
SEQAN_TASSERT(gaps3 != "ello")
SEQAN_TASSERT(gaps3 <= "el")
SEQAN_TASSERT(gaps3 < "ello")
SEQAN_TASSERT(gaps3 > "a")
SEQAN_TASSERT(gaps3 >= "el")
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
// Iterator Functions
template <typename TSource, typename TSpec>
void TestGapsIterator()
{
//____________________________________________________________________________
typedef Gaps<TSource, TSpec> TGaps;
typedef typename Iterator<TGaps, Rooted>::Type TIterator;
TSource src1 = "hello";
TGaps gaps4(src1);
TIterator it1 = begin(gaps4); //begin
TIterator const & c_it1 = it1; //const version
SEQAN_TASSERT(*it1 == 'h'); //operator *
SEQAN_TASSERT(source(it1) == begin(src1)) //source
SEQAN_TASSERT(source(c_it1) == begin(src1))
SEQAN_TASSERT(atBegin(c_it1)) //atBegin
++it1; //operator ++
SEQAN_TASSERT(*it1 == 'e');
--it1; //operator --
SEQAN_TASSERT(*it1 == 'h');
TIterator it2 = end(gaps4); //end
SEQAN_TASSERT(atEnd(it2)) //atEnd
--it2;
SEQAN_TASSERT(*it2 == 'o');
//____________________________________________________________________________
TIterator it3; //default ctor
TIterator it4 = it1; //copy ctor
TIterator const & c_it4 = it4;
SEQAN_TASSERT(container(it4) == container(it1))
SEQAN_TASSERT(*it4 == *it1)
SEQAN_TASSERT(it4 == it1) //operator ==
SEQAN_TASSERT(it4 == c_it1)
SEQAN_TASSERT(c_it4 == it1)
SEQAN_TASSERT(c_it4 == c_it1)
++it1;
SEQAN_TASSERT(it4 != it1) //operator !=
SEQAN_TASSERT(it4 != c_it1)
SEQAN_TASSERT(c_it4 != it1)
SEQAN_TASSERT(c_it4 != c_it1)
it4 = it2; //operator =
SEQAN_TASSERT(*it4 == *it2)
TIterator it5(gaps4, 1, 1); //special ctor
//____________________________________________________________________________
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
// Manipulation of Gaps
template <typename TSource, typename TSpec>
void TestGapManipulation()
{
//____________________________________________________________________________
typedef Gaps<TSource, TSpec> TGaps;
//inserting gaps
TSource src1 = "hello";
TGaps gaps5(src1);
insertGaps(gaps5, 1, 2); //insert gap somewhere
SEQAN_TASSERT(gaps5 != "hello");
SEQAN_TASSERT(gaps5 == "h--ello");
insertGaps(gaps5, 1, 1); //insert blank at the beginning of a gap
SEQAN_TASSERT(gaps5 == "h---ello");
insertGaps(gaps5, 4, 1); //insert blank at the end of a gap
SEQAN_TASSERT(gaps5 == "h----ello");
insertGap(gaps5, 8); //insert second gap
SEQAN_TASSERT(gaps5 == "h----ell-o");
insertGaps(gaps5, 0, 2); //insert at position 0
SEQAN_TASSERT(gaps5 == "h----ell-o"); //note: leading and trailing gaps are not displayed
SEQAN_TASSERT(beginPosition(gaps5) == 2);
insertGaps(gaps5, 8, 2); //insert gap with beginPosition == 2
SEQAN_TASSERT(gaps5 == "h----e--ll-o");
SEQAN_TASSERT(length(gaps5) == 12);
insertGaps(gaps5, 14, 1); //insert gap behind end. Nothing happens
SEQAN_TASSERT(gaps5 == "h----e--ll-o");
SEQAN_TASSERT(length(gaps5) == 12);
//counting gaps
SEQAN_TASSERT(gaps5 == "h----e--ll-o"); // "--h----e--ll-o"
SEQAN_TASSERT(beginPosition(gaps5) == 2);
SEQAN_TASSERT(countGaps(gaps5, 0) == 2);
SEQAN_TASSERT(countGaps(gaps5, 2) == 0);
SEQAN_TASSERT(countGaps(gaps5, 3) == 4);
SEQAN_TASSERT(countGaps(gaps5, 4) == 3);
SEQAN_TASSERT(countGaps(gaps5, 6) == 1);
SEQAN_TASSERT(countGaps(gaps5, 8) == 2);
SEQAN_TASSERT(countGaps(gaps5, 20) == 0);
//removing gaps
SEQAN_TASSERT(gaps5 == "h----e--ll-o"); // "--h----e--ll-o"
SEQAN_TASSERT(beginPosition(gaps5) == 2);
removeGap(gaps5, 4); //remove gap somewhere in gap area
SEQAN_TASSERT(gaps5 == "h---e--ll-o");
removeGaps(gaps5, 6, 1); //try to remove gap in non-gap area. Nothing happens
SEQAN_TASSERT("h---e--ll-o" == gaps5);
removeGaps(gaps5, 7, 2); //remove gap region completely
SEQAN_TASSERT(gaps5 == "h---ell-o");
removeGaps(gaps5, 4, 10); //remove rest of gap region
SEQAN_TASSERT(gaps5 == "h-ell-o");
//____________________________________________________________________________
}
//////////////////////////////////////////////////////////////////////////////
template <typename TSource, typename TSpec>
void TestSequenceGapsBase()
{
typedef Gaps<TSource, TSpec> TGaps;
TGaps gaps3;
assignSource(gaps3, "hello");
insertGaps(gaps3, 2, 3);
setBeginPosition(gaps3, 2);
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
//toSourcePosition
SEQAN_TASSERT(toSourcePosition(gaps3, 0) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 1) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 2) == 0)
SEQAN_TASSERT(toSourcePosition(gaps3, 3) == 1)
SEQAN_TASSERT(toSourcePosition(gaps3, 4) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 5) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 6) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 7) == 2)
SEQAN_TASSERT(toSourcePosition(gaps3, 8) == 3)
SEQAN_TASSERT(toSourcePosition(gaps3, 9) == 4)
SEQAN_TASSERT(toSourcePosition(gaps3, 10) == 5)
SEQAN_TASSERT(toSourcePosition(gaps3, 11) == 5)
//toViewPosition
SEQAN_TASSERT(toViewPosition(gaps3, 0) == 2)
SEQAN_TASSERT(toViewPosition(gaps3, 1) == 3)
SEQAN_TASSERT(toViewPosition(gaps3, 2) == 7)
SEQAN_TASSERT(toViewPosition(gaps3, 3) == 8)
SEQAN_TASSERT(toViewPosition(gaps3, 4) == 9)
SEQAN_TASSERT(toViewPosition(gaps3, 5) == 10)
//____________________________________________________________________________
SEQAN_TASSERT(gaps3 == "he---llo") //"--he---llo"
SEQAN_TASSERT(beginPosition(gaps3) == 2)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "he--llo") //"-he--llo"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3, 1, 5);
SEQAN_TASSERT(gaps3 == "hello") //"-hello"
SEQAN_TASSERT(beginPosition(gaps3) == 1)
clearGaps(gaps3);
SEQAN_TASSERT(gaps3 == "hello") //"hello"
SEQAN_TASSERT(beginPosition(gaps3) == 0)
assign(gaps3, "el");
SEQAN_TASSERT(gaps3 == "el") //"el"
//____________________________________________________________________________
// Comparison Functions
SEQAN_TASSERT(gaps3 == "el")
SEQAN_TASSERT(gaps3 != "ello")
SEQAN_TASSERT(gaps3 <= "el")
SEQAN_TASSERT(gaps3 < "ello")
SEQAN_TASSERT(gaps3 > "a")
SEQAN_TASSERT(gaps3 >= "el")
}
//____________________________________________________________________________
template <typename TSource, typename TSpec>
void TestTrailingGaps()
{
typedef Gaps<TSource, TSpec> TGaps;
//inserting gaps
TSource src1 = "hello";
TGaps gaps6(src1);
SEQAN_TASSERT(gaps6 == "hello");
insertGaps(gaps6, 10, 2);//somewhere behind the last char
SEQAN_TASSERT(gaps6 == "hello"); //nothing changes
SEQAN_TASSERT(countGaps(gaps6, 5) == 0);
SEQAN_TASSERT(countGaps(gaps6, 10) == 0);
insertGaps(gaps6, 5, 3); //directly behind the last char: append intended trailing gap
SEQAN_TASSERT(gaps6 == "hello"); //"hello---"
SEQAN_TASSERT(countGaps(gaps6,5) == 3);
SEQAN_TASSERT(countGaps(gaps6,6) == 2);
insertGap(gaps6, 8);//expand trailing gaps
SEQAN_TASSERT(gaps6 == "hello"); //"hello----"
SEQAN_TASSERT(countGaps(gaps6,5) == 4);
SEQAN_TASSERT(countGaps(gaps6,6) == 3);
SEQAN_TASSERT(countGaps(gaps6,7) == 2);
SEQAN_TASSERT(countGaps(gaps6,8) == 1);
SEQAN_TASSERT(countGaps(gaps6,9) == 0);
SEQAN_TASSERT(countGaps(gaps6,10) == 0);
SEQAN_TASSERT(countGaps(gaps6,20) == 0);
insertGaps(gaps6, 9, 2);//expand trailing gaps on last position
SEQAN_TASSERT(gaps6 == "hello") //"hello------"
SEQAN_TASSERT(countGaps(gaps6,5) == 6);
//removing gaps
SEQAN_TASSERT(gaps6 == "hello"); // "hello------"
SEQAN_TASSERT(beginPosition(gaps6) == 0);
removeGap(gaps6, 7); //remove gap somewhere in gap area
SEQAN_TASSERT(gaps6 == "hello");//"hello-----"
SEQAN_TASSERT(countGaps(gaps6, 5) == 5);
SEQAN_TASSERT(countGaps(gaps6, 7) == 3);
SEQAN_TASSERT(countGaps(gaps6, 9) == 1);
SEQAN_TASSERT(countGaps(gaps6, 10) == 0);
removeGaps(gaps6, 8, 15); //remove rest of gap region
SEQAN_TASSERT(gaps6 == "hello"); //"hello---"
SEQAN_TASSERT(countGaps(gaps6, 5) == 3);
SEQAN_TASSERT(countGaps(gaps6, 7) == 1);
SEQAN_TASSERT(countGaps(gaps6, 8) == 0);
removeGaps(gaps6, 5, 3); //remove gap region completely
SEQAN_TASSERT(gaps6 == "hello"); //"hello"
SEQAN_TASSERT(countGaps(gaps6, 5) == 0);
insertGaps(gaps6, 5, 6);
SEQAN_TASSERT(countGaps(gaps6,5) == 6);
assignSource(gaps6, "new"); //clear trailing gaps when assign new source
SEQAN_TASSERT(gaps6 == "new") //"new"
SEQAN_TASSERT(countGaps(gaps6, 3) == 0);
insertGaps(gaps6, 3, 10);
SEQAN_TASSERT(countGaps(gaps6, 3) == 10);
TSource src2 = "hello";
setSource(gaps6, src2); //clear trailing gaps when set new source
SEQAN_TASSERT(gaps6 == "hello") //"re"
SEQAN_TASSERT(countGaps(gaps6, 5) == 0);
insertGaps(gaps6, 5, 10);
SEQAN_TASSERT(countGaps(gaps6, 5) == 10);
TGaps gaps6a(gaps6); //copy all trailing gaps
SEQAN_TASSERT(gaps6a == "hello");
SEQAN_TASSERT(countGaps(gaps6a, 5) == 10);
TGaps gaps6b = gaps6a; //assign the trailing gaps
insertGaps(gaps6b, 10, 5);
SEQAN_TASSERT(gaps6b == "hello");
SEQAN_TASSERT(countGaps(gaps6a, 5) == 10);
SEQAN_TASSERT(countGaps(gaps6b, 5) == 15);
clearGaps(gaps6a); //remove all trailing gaps
SEQAN_TASSERT(countGaps(gaps6a, 5) == 0);
SEQAN_TASSERT(countGaps(gaps6b, 5) == 15);
}
template <typename TSource, typename TGapSpec>
inline void
TestCountCharacters() {
typedef Gaps<TSource, TGapSpec> TGap;
TSource seq = "hello";
TGap gap7(seq);
SEQAN_TASSERT(gap7 == "hello");
SEQAN_TASSERT(length(gap7) == 5);
SEQAN_TASSERT(countCharacters(gap7, 0) == 5);
SEQAN_TASSERT(countCharacters(gap7, 1) == 4);
SEQAN_TASSERT(countCharacters(gap7, 0) == 5);
SEQAN_TASSERT(countCharacters(gap7, 3) == 2);
SEQAN_TASSERT(countCharacters(gap7, 5) == 0);
insertGaps(gap7, 0, 2);
SEQAN_TASSERT(gap7 == "hello"); //"--hello"
SEQAN_TASSERT(length(gap7) == 5);
SEQAN_TASSERT(countCharacters(gap7, 0) == 0);
SEQAN_TASSERT(countCharacters(gap7, 2) == 5);
insertGap(gap7, 4);
SEQAN_TASSERT(gap7 == "he-llo"); //"--he-llo"
SEQAN_TASSERT(length(gap7) == 6);
SEQAN_TASSERT(countCharacters(gap7, 0) == 0);
SEQAN_TASSERT(countCharacters(gap7, 2) == 2);
SEQAN_TASSERT(countCharacters(gap7, 3) == 1);
SEQAN_TASSERT(countCharacters(gap7, 4) == 0);
SEQAN_TASSERT(countCharacters(gap7, 5) == 3);
SEQAN_TASSERT(countCharacters(gap7, 6) == 2);
SEQAN_TASSERT(countCharacters(gap7, 7) == 1);
SEQAN_TASSERT(countCharacters(gap7, 8) == 0);
insertGaps(gap7, 6, 3);
SEQAN_TASSERT(gap7 == "he-l---lo"); //"--he-l---lo"
SEQAN_TASSERT(length(gap7) == 9);
SEQAN_TASSERT(countCharacters(gap7, 0) == 0);
SEQAN_TASSERT(countCharacters(gap7, 2) == 2);
SEQAN_TASSERT(countCharacters(gap7, 3) == 1);
SEQAN_TASSERT(countCharacters(gap7, 4) == 0);
SEQAN_TASSERT(countCharacters(gap7, 5) == 1);
SEQAN_TASSERT(countCharacters(gap7, 6) == 0);
SEQAN_TASSERT(countCharacters(gap7, 7) == 0);
SEQAN_TASSERT(countCharacters(gap7, 8) == 0);
SEQAN_TASSERT(countCharacters(gap7, 9) == 2);
SEQAN_TASSERT(countCharacters(gap7, 10) == 1);
insertGaps(gap7, 11, 5);
SEQAN_TASSERT(gap7 == "he-l---lo"); //"--he-l---lo-----"
SEQAN_TASSERT(length(gap7) == 9);
SEQAN_TASSERT(countCharacters(gap7, 11) == 0);
SEQAN_TASSERT(countCharacters(gap7, 12) == 0);
SEQAN_TASSERT(countCharacters(gap7, 30) == 0);
}
//////////////////////////////////////////////////////////////////////////////
SEQAN_DEFINE_TEST(test_align_gaps_base_char_string_array_gaps) {
TestGapsBase<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_base_char_string_sumlist_gaps) {
TestGapsBase<String<char>, SumlistGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gaps_iterator) {
TestGapsIterator<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gap_manipulation_char_string_array_gaps) {
TestGapManipulation<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_gap_manipulation_char_string_sumlist_gaps) {
TestGapManipulation<String<char>, SumlistGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_sequence_gaps_base) {
TestSequenceGapsBase<String<char>, SequenceGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_trailing_gaps_char_string_array_gaps) {
TestTrailingGaps<String<char>, ArrayGaps>();
}
SEQAN_DEFINE_TEST(test_align_gaps_test_count_characters_char_string_array_gaps) {
TestCountCharacters<String<char>, ArrayGaps >();
}
|
/* Copyright 2013-present Barefoot Networks, Inc.
*
* 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.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <gtest/gtest.h>
#include <bm/bm_sim/queueing.h>
#include <thread>
#include <memory>
#include <array>
#include <vector>
#include <algorithm> // for std::count, std::max
using std::unique_ptr;
using std::thread;
using bm::QueueingLogic;
using bm::QueueingLogicRL;
using bm::QueueingLogicPriRL;
struct WorkerMapper {
WorkerMapper(size_t nb_workers)
: nb_workers(nb_workers) { }
size_t operator()(size_t queue_id) const {
return queue_id % nb_workers;
}
size_t nb_workers;
};
struct RndInput {
size_t queue_id;
int v;
};
template <class QType>
class QueueingTest : public ::testing::Test {
protected:
static constexpr size_t nb_queues = 3u;
static constexpr size_t nb_workers = 2u;
static constexpr size_t capacity = 128u;
static constexpr size_t iterations = 200000;
// QueueingLogic<T, WorkerMapper> queue;
QType queue;
std::vector<RndInput> values;
QueueingTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand()};
}
}
public:
void produce();
// virtual void TearDown() {}
};
typedef std::unique_ptr<int> QEm;
template <typename QType>
void QueueingTest<QType>::produce() {
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id,
unique_ptr<int>(new int(values[i].v)));
}
}
namespace {
template <typename Q>
void produce_if_dropping(Q &queue, size_t iterations, size_t capacity,
const std::vector<RndInput> &values) {
for (size_t i = 0; i < iterations; i++) {
size_t queue_id = values[i].queue_id;
// this is to avoid drops
// kind of makes me question if using type parameterization is really useful
// for this
while (queue.size(queue_id) > capacity / 2) {
// originally, I just had an empty loop, but Valgrind was running forever
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
queue.push_front(queue_id, unique_ptr<int>(new int(values[i].v)));
}
}
} // namespace
template <>
void QueueingTest<QueueingLogicRL<QEm, WorkerMapper> >::produce() {
produce_if_dropping(queue, iterations, capacity, values);
}
template <>
void QueueingTest<QueueingLogicPriRL<QEm, WorkerMapper> >::produce() {
produce_if_dropping(queue, iterations, capacity, values);
}
using testing::Types;
typedef Types<QueueingLogic<QEm, WorkerMapper>,
QueueingLogicRL<QEm, WorkerMapper>,
QueueingLogicPriRL<QEm, WorkerMapper> > QueueingTypes;
TYPED_TEST_CASE(QueueingTest, QueueingTypes);
TYPED_TEST(QueueingTest, ProducerConsummer) {
thread producer_thread(&QueueingTest<TypeParam>::produce, this);
WorkerMapper mapper(this->nb_workers);
for (size_t i = 0; i < this->iterations; i++) {
size_t queue_id;
size_t expected_queue_id = this->values[i].queue_id;
unique_ptr<int> v;
size_t worker_id = mapper(expected_queue_id);
this->queue.pop_back(worker_id, &queue_id, &v);
ASSERT_EQ(expected_queue_id, queue_id);
ASSERT_EQ(this->values[i].v, *v);
}
producer_thread.join();
}
class QueueingRLTest : public ::testing::Test {
protected:
typedef std::unique_ptr<int> T;
static constexpr size_t nb_queues = 1u;
static constexpr size_t nb_workers = 1u;
static constexpr size_t capacity = 1024u;
static constexpr size_t iterations = 512u;
static constexpr uint64_t pps = 100u;
QueueingLogicRL<T, WorkerMapper> queue;
std::vector<RndInput> values;
static_assert(capacity >= iterations,
"for RL test, capacity needs to be greater or equal to # pkts");
QueueingRLTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand()};
}
queue.set_rate(0u, pps);
}
public:
void produce() {
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id,
unique_ptr<int>(new int(values[i].v)));
}
}
// virtual void TearDown() {}
};
TEST_F(QueueingRLTest, RateLimiter) {
thread producer_thread(&QueueingRLTest::produce, this);
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using clock = std::chrono::high_resolution_clock;
std::vector<int> times;
times.reserve(iterations);
auto start = clock::now();
for (size_t i = 0; i < iterations; i++) {
size_t queue_id;
unique_ptr<int> v;
this->queue.pop_back(0u, &queue_id, &v);
ASSERT_EQ(0u, queue_id);
ASSERT_EQ(values[i].v, *v);
auto now = clock::now();
times.push_back(duration_cast<milliseconds>(now - start).count());
}
producer_thread.join();
int elapsed = times.back();
int expected = (iterations * 1000) / pps;
ASSERT_GT(elapsed, expected * 0.9);
ASSERT_LT(elapsed, expected * 1.1);
// TODO(antonin): better check of times vector?
}
struct RndInputPri {
size_t queue_id;
int v;
size_t priority;
};
class QueueingPriRLTest : public ::testing::Test {
protected:
typedef std::unique_ptr<int> T;
static constexpr size_t nb_queues = 1u;
static constexpr size_t nb_workers = 1u;
static constexpr size_t nb_priorities = 2u;
static constexpr size_t capacity = 200u;
static constexpr size_t iterations = 1000u;
static constexpr uint64_t consummer_pps = 50u;
static constexpr uint64_t producer_pps = 100u;
QueueingLogicPriRL<T, WorkerMapper> queue;
std::vector<RndInputPri> values;
QueueingPriRLTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers),
nb_priorities),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand(), rand() % nb_priorities};
}
}
std::vector<size_t> receive_all() {
using std::chrono::duration;
std::vector<size_t> priorities;
priorities.reserve(iterations);
while (priorities.size() < capacity || queue.size(0u) > 0) {
size_t queue_id, priority;
unique_ptr<int> v;
this->queue.pop_back(0u, &queue_id, &priority, &v);
std::this_thread::sleep_for(duration<double>(1. / consummer_pps));
priorities.push_back(priority);
}
return priorities;
}
public:
void produce() {
using std::chrono::duration;
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id, values[i].priority,
unique_ptr<int>(new int(values[i].v)));
std::this_thread::sleep_for(duration<double>(1. / producer_pps));
}
}
// virtual void TearDown() {}
};
TEST_F(QueueingPriRLTest, Pri) {
thread producer_thread(&QueueingPriRLTest::produce, this);
auto priorities = receive_all();
producer_thread.join();
size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
size_t priority_1 = priorities.size() - priority_0;
// if removed, g++ complains that capacity was not defined
const size_t c = capacity;
// we have to receive at least capacity P1 elements (they are buffered and
// dequeued at the end...)
ASSERT_LT(c, priority_1);
// most elements should be P0
// was originally 10%, but replaced it with 20% as the test would fail from
// time to time
ASSERT_GT(0.2, (priority_1 - c) / static_cast<double>(priority_0));
}
TEST_F(QueueingPriRLTest, PriRateLimiter) {
static constexpr size_t rate_pps = consummer_pps / 2u;
queue.set_rate(0u, rate_pps);
thread producer_thread(&QueueingPriRLTest::produce, this);
auto priorities = receive_all();
producer_thread.join();
size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
size_t priority_1 = priorities.size() - priority_0;
size_t diff;
if (priority_0 < priority_1)
diff = priority_1 - priority_0;
else
diff = priority_0 - priority_1;
ASSERT_LT(diff, std::max(priority_0, priority_1) * 0.1);
}
Increase tolerance margin in queueing unit test (#248)
The test is PriRateLimiter. Related to issue #247.
/* Copyright 2013-present Barefoot Networks, Inc.
*
* 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.
*/
/*
* Antonin Bas (antonin@barefootnetworks.com)
*
*/
#include <gtest/gtest.h>
#include <bm/bm_sim/queueing.h>
#include <thread>
#include <memory>
#include <array>
#include <vector>
#include <algorithm> // for std::count, std::max
using std::unique_ptr;
using std::thread;
using bm::QueueingLogic;
using bm::QueueingLogicRL;
using bm::QueueingLogicPriRL;
struct WorkerMapper {
WorkerMapper(size_t nb_workers)
: nb_workers(nb_workers) { }
size_t operator()(size_t queue_id) const {
return queue_id % nb_workers;
}
size_t nb_workers;
};
struct RndInput {
size_t queue_id;
int v;
};
template <class QType>
class QueueingTest : public ::testing::Test {
protected:
static constexpr size_t nb_queues = 3u;
static constexpr size_t nb_workers = 2u;
static constexpr size_t capacity = 128u;
static constexpr size_t iterations = 200000;
// QueueingLogic<T, WorkerMapper> queue;
QType queue;
std::vector<RndInput> values;
QueueingTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand()};
}
}
public:
void produce();
// virtual void TearDown() {}
};
typedef std::unique_ptr<int> QEm;
template <typename QType>
void QueueingTest<QType>::produce() {
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id,
unique_ptr<int>(new int(values[i].v)));
}
}
namespace {
template <typename Q>
void produce_if_dropping(Q &queue, size_t iterations, size_t capacity,
const std::vector<RndInput> &values) {
for (size_t i = 0; i < iterations; i++) {
size_t queue_id = values[i].queue_id;
// this is to avoid drops
// kind of makes me question if using type parameterization is really useful
// for this
while (queue.size(queue_id) > capacity / 2) {
// originally, I just had an empty loop, but Valgrind was running forever
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
queue.push_front(queue_id, unique_ptr<int>(new int(values[i].v)));
}
}
} // namespace
template <>
void QueueingTest<QueueingLogicRL<QEm, WorkerMapper> >::produce() {
produce_if_dropping(queue, iterations, capacity, values);
}
template <>
void QueueingTest<QueueingLogicPriRL<QEm, WorkerMapper> >::produce() {
produce_if_dropping(queue, iterations, capacity, values);
}
using testing::Types;
typedef Types<QueueingLogic<QEm, WorkerMapper>,
QueueingLogicRL<QEm, WorkerMapper>,
QueueingLogicPriRL<QEm, WorkerMapper> > QueueingTypes;
TYPED_TEST_CASE(QueueingTest, QueueingTypes);
TYPED_TEST(QueueingTest, ProducerConsummer) {
thread producer_thread(&QueueingTest<TypeParam>::produce, this);
WorkerMapper mapper(this->nb_workers);
for (size_t i = 0; i < this->iterations; i++) {
size_t queue_id;
size_t expected_queue_id = this->values[i].queue_id;
unique_ptr<int> v;
size_t worker_id = mapper(expected_queue_id);
this->queue.pop_back(worker_id, &queue_id, &v);
ASSERT_EQ(expected_queue_id, queue_id);
ASSERT_EQ(this->values[i].v, *v);
}
producer_thread.join();
}
class QueueingRLTest : public ::testing::Test {
protected:
typedef std::unique_ptr<int> T;
static constexpr size_t nb_queues = 1u;
static constexpr size_t nb_workers = 1u;
static constexpr size_t capacity = 1024u;
static constexpr size_t iterations = 512u;
static constexpr uint64_t pps = 100u;
QueueingLogicRL<T, WorkerMapper> queue;
std::vector<RndInput> values;
static_assert(capacity >= iterations,
"for RL test, capacity needs to be greater or equal to # pkts");
QueueingRLTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand()};
}
queue.set_rate(0u, pps);
}
public:
void produce() {
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id,
unique_ptr<int>(new int(values[i].v)));
}
}
// virtual void TearDown() {}
};
TEST_F(QueueingRLTest, RateLimiter) {
thread producer_thread(&QueueingRLTest::produce, this);
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using clock = std::chrono::high_resolution_clock;
std::vector<int> times;
times.reserve(iterations);
auto start = clock::now();
for (size_t i = 0; i < iterations; i++) {
size_t queue_id;
unique_ptr<int> v;
this->queue.pop_back(0u, &queue_id, &v);
ASSERT_EQ(0u, queue_id);
ASSERT_EQ(values[i].v, *v);
auto now = clock::now();
times.push_back(duration_cast<milliseconds>(now - start).count());
}
producer_thread.join();
int elapsed = times.back();
int expected = (iterations * 1000) / pps;
ASSERT_GT(elapsed, expected * 0.9);
ASSERT_LT(elapsed, expected * 1.1);
// TODO(antonin): better check of times vector?
}
struct RndInputPri {
size_t queue_id;
int v;
size_t priority;
};
class QueueingPriRLTest : public ::testing::Test {
protected:
typedef std::unique_ptr<int> T;
static constexpr size_t nb_queues = 1u;
static constexpr size_t nb_workers = 1u;
static constexpr size_t nb_priorities = 2u;
static constexpr size_t capacity = 200u;
static constexpr size_t iterations = 1000u;
static constexpr uint64_t consummer_pps = 50u;
static constexpr uint64_t producer_pps = 100u;
QueueingLogicPriRL<T, WorkerMapper> queue;
std::vector<RndInputPri> values;
QueueingPriRLTest()
: queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers),
nb_priorities),
values(iterations) { }
virtual void SetUp() {
for (size_t i = 0; i < iterations; i++) {
values[i] = {rand() % nb_queues, rand(), rand() % nb_priorities};
}
}
std::vector<size_t> receive_all() {
using std::chrono::duration;
std::vector<size_t> priorities;
priorities.reserve(iterations);
while (priorities.size() < capacity || queue.size(0u) > 0) {
size_t queue_id, priority;
unique_ptr<int> v;
this->queue.pop_back(0u, &queue_id, &priority, &v);
std::this_thread::sleep_for(duration<double>(1. / consummer_pps));
priorities.push_back(priority);
}
return priorities;
}
public:
void produce() {
using std::chrono::duration;
for (size_t i = 0; i < iterations; i++) {
queue.push_front(values[i].queue_id, values[i].priority,
unique_ptr<int>(new int(values[i].v)));
std::this_thread::sleep_for(duration<double>(1. / producer_pps));
}
}
// virtual void TearDown() {}
};
TEST_F(QueueingPriRLTest, Pri) {
thread producer_thread(&QueueingPriRLTest::produce, this);
auto priorities = receive_all();
producer_thread.join();
size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
size_t priority_1 = priorities.size() - priority_0;
// if removed, g++ complains that capacity was not defined
const size_t c = capacity;
// we have to receive at least capacity P1 elements (they are buffered and
// dequeued at the end...)
ASSERT_LT(c, priority_1);
// most elements should be P0
// was originally 10%, but replaced it with 20% as the test would fail from
// time to time
ASSERT_GT(0.2, (priority_1 - c) / static_cast<double>(priority_0));
}
TEST_F(QueueingPriRLTest, PriRateLimiter) {
static constexpr size_t rate_pps = consummer_pps / 2u;
queue.set_rate(0u, rate_pps);
thread producer_thread(&QueueingPriRLTest::produce, this);
auto priorities = receive_all();
producer_thread.join();
size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
size_t priority_1 = priorities.size() - priority_0;
size_t diff;
if (priority_0 < priority_1)
diff = priority_1 - priority_0;
else
diff = priority_0 - priority_1;
// was originally 10%, but replaced it with 25% as the test would fail from
// time to time (on slower machines?)
ASSERT_LT(diff, std::max(priority_0, priority_1) * 0.25);
}
|
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
class ResMgr;
typedef ::cppu::WeakComponentImplHelper3<
::com::sun::star::lang::XInitialization,
::com::sun::star::frame::XTerminateListener,
::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;
class ShutdownIcon : public ShutdownIconServiceBase
{
::osl::Mutex m_aMutex;
bool m_bVeto;
ResMgr *m_pResMgr;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
static ShutdownIcon *pShutdownIcon; // one instance
#ifdef WNT
void initSystray();
void deInitSystray();
static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate );
static bool GetAutostartW32( const ::rtl::OUString& aShortcutName );
static void EnterModalMode();
static void LeaveModalMode();
friend class SfxNotificationListener_Impl;
#endif
public:
ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );
virtual ~ShutdownIcon();
SFX_DECL_XSERVICEINFO
static ShutdownIcon* getInstance();
static void terminateDesktop();
static void addTerminateListener();
static void FileOpen();
static void OpenURL( const ::rtl::OUString& aURL, const ::rtl::OUString& rTarget, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& =
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >( 0 ) );
static void FromTemplate();
static void SetAutostart( bool bActivate );
static bool GetAutostart();
static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
static ::rtl::OUString GetImplementationName_static();
::rtl::OUString GetResString( int id );
::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );
void SetVeto( bool bVeto ) { m_bVeto = bVeto;}
bool GetVeto() { return m_bVeto; }
#ifdef WNT
static bool IsQuickstarterInstalled();
#endif
// Component Helper - force override
virtual void SAL_CALL disposing();
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw(::com::sun::star::uno::RuntimeException);
// XTerminateListener
virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw( ::com::sun::star::uno::Exception );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;
};
#endif
INTEGRATION: CWS gtkquickstart (1.18.430); FILE MERGED
2006/08/07 13:45:00 mmeeks 1.18.430.2: Issue number: i#57872#
Submitted by: mmeeks
Fix a number of Win32 build / re-factoring issues in the initial work.
2006/08/01 10:57:04 mmeeks 1.18.430.1: #i57872#
gtk systray quickstarter
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include <sfx2/dllapi.h>
#endif
class ResMgr;
typedef ::cppu::WeakComponentImplHelper3<
::com::sun::star::lang::XInitialization,
::com::sun::star::frame::XTerminateListener,
::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;
#if defined(USE_APP_SHORTCUTS)
#define WRITER_URL "private:factory/swriter"
#define CALC_URL "private:factory/scalc"
#define IMPRESS_URL "private:factory/simpress"
#define IMPRESS_WIZARD_URL "private:factory/simpress?slot=10425"
#define DRAW_URL "private:factory/sdraw"
#define MATH_URL "private:factory/smath"
#define BASE_URL "private:factory/sdatabase?Interactive"
#endif
class SFX2_DLLPUBLIC ShutdownIcon : public ShutdownIconServiceBase
{
::osl::Mutex m_aMutex;
bool m_bVeto;
ResMgr *m_pResMgr;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
static ShutdownIcon *pShutdownIcon; // one instance
void (*m_pInitSystray) ();
void (*m_pDeInitSystray) ();
::osl::Module *m_pPlugin;
void initSystray();
void deInitSystray();
static void EnterModalMode();
static void LeaveModalMode();
static rtl::OUString getShortcutName();
friend class SfxNotificationListener_Impl;
public:
ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );
virtual ~ShutdownIcon();
SFX_DECL_XSERVICEINFO
static ShutdownIcon* getInstance();
static void terminateDesktop();
static void addTerminateListener();
static void FileOpen();
static void OpenURL( const ::rtl::OUString& aURL, const ::rtl::OUString& rTarget, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& =
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >( 0 ) );
static void FromTemplate();
static void SetAutostart( bool bActivate );
static bool GetAutostart();
static bool bModalMode;
static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
static ::rtl::OUString GetImplementationName_static();
::rtl::OUString GetResString( int id );
::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );
void SetVeto( bool bVeto ) { m_bVeto = bVeto;}
bool GetVeto() { return m_bVeto; }
static bool IsQuickstarterInstalled();
// Component Helper - force override
virtual void SAL_CALL disposing();
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
throw(::com::sun::star::uno::RuntimeException);
// XTerminateListener
virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
throw(::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw( ::com::sun::star::uno::Exception );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;
#ifdef WNT
static void EnableAutostartW32( const rtl::OUString &aShortcutName );
static rtl::OUString GetAutostartFolderNameW32();
#endif
};
extern "C" {
# ifdef WNT
// builtin win32 systray
void win32_init_sys_tray();
void win32_shutdown_sys_tray();
# endif
// external plugin systray impl.
void plugin_init_sys_tray();
void plugin_shutdown_sys_tray();
}
#endif
|
#ifndef SILICIUM_MEMORY_SOURCE_HPP
#define SILICIUM_MEMORY_SOURCE_HPP
#include <silicium/source/source.hpp>
#include <vector>
#include <string>
#include <array>
namespace Si
{
template <class Element>
struct memory_source SILICIUM_FINAL : source<Element>
{
memory_source()
{
}
explicit memory_source(iterator_range<Element const *> elements)
: m_elements(std::move(elements))
{
}
virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
{
(void)size;
return m_elements;
}
virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
{
while (!m_elements.empty() && !destination.empty())
{
destination.front() = m_elements.front();
destination.pop_front();
m_elements.pop_front();
}
return destination.begin();
}
private:
iterator_range<Element const *> m_elements;
};
template <class Element>
memory_source<Element> make_container_source(std::vector<Element> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element, std::size_t N>
memory_source<Element> make_container_source(std::array<Element, N> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element>
memory_source<Element> make_container_source(std::basic_string<Element> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element>
memory_source<Element> make_c_str_source(Element const *c_str)
{
return memory_source<Element>(make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
}
}
#endif
begin to add sources that move the elements
#ifndef SILICIUM_MEMORY_SOURCE_HPP
#define SILICIUM_MEMORY_SOURCE_HPP
#include <silicium/source/source.hpp>
#include <vector>
#include <string>
#include <array>
namespace Si
{
template <class Element>
struct memory_source SILICIUM_FINAL : source<Element>
{
memory_source()
{
}
explicit memory_source(iterator_range<Element const *> elements)
: m_elements(std::move(elements))
{
}
virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
{
(void)size;
return m_elements;
}
virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
{
while (!m_elements.empty() && !destination.empty())
{
destination.front() = m_elements.front();
destination.pop_front();
m_elements.pop_front();
}
return destination.begin();
}
private:
iterator_range<Element const *> m_elements;
};
template <class Element>
struct mutable_memory_source SILICIUM_FINAL : source<Element>
{
mutable_memory_source()
{
}
explicit mutable_memory_source(iterator_range<Element *> elements)
: m_elements(std::move(elements))
{
}
virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
{
boost::ignore_unused_variable_warning(size);
return {};
}
virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
{
while (!m_elements.empty() && !destination.empty())
{
destination.front() = std::move(m_elements.front());
destination.pop_front();
m_elements.pop_front();
}
return destination.begin();
}
private:
iterator_range<Element *> m_elements;
};
template <class Element>
memory_source<Element> make_container_source(std::vector<Element> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element, std::size_t N>
memory_source<Element> make_container_source(std::array<Element, N> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element, std::size_t N>
mutable_memory_source<Element> make_container_source(std::array<Element, N> &&container)
{
return mutable_memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element>
memory_source<Element> make_container_source(std::basic_string<Element> const &container)
{
return memory_source<Element>({container.data(), container.data() + container.size()});
}
template <class Element>
memory_source<Element> make_c_str_source(Element const *c_str)
{
return memory_source<Element>(make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
}
}
#endif
|
/*=========================================================================
Program: KWSys - Kitware System Library
Module: Registry.cxx
Copyright (c) Kitware, Inc., Insight Consortium. 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 notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Registry.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/map)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
#include KWSYS_HEADER(ios/sstream)
#include <ctype.h> // for isspace
#include <stdio.h>
#ifdef _WIN32
# include <windows.h>
#endif
namespace KWSYS_NAMESPACE
{
class RegistryHelper {
public:
RegistryHelper(Registry::RegistryType registryType);
virtual ~RegistryHelper();
// Read a value from the registry.
virtual bool ReadValue(const char *key, const char **value);
// Delete a key from the registry.
virtual bool DeleteKey(const char *key);
// Delete a value from a given key.
virtual bool DeleteValue(const char *key);
// Set value in a given key.
virtual bool SetValue(const char *key,
const char *value);
// Open the registry at toplevel/subkey.
virtual bool Open(const char *toplevel, const char *subkey,
int readonly);
// Close the registry.
virtual bool Close();
// Set the value of changed
void SetChanged(bool b) { m_Changed = b; }
void SetTopLevel(const char* tl);
const char* GetTopLevel() { return m_TopLevel.c_str(); }
//! Read from local or global scope. On Windows this mean from local machine
// or local user. On unix this will read from $HOME/.Projectrc or
// /etc/Project
void SetGlobalScope(bool b);
bool GetGlobalScope();
kwsys_stl::string EncodeKey(const char* str);
kwsys_stl::string EncodeValue(const char* str);
kwsys_stl::string DecodeValue(const char* str);
protected:
bool m_Changed;
kwsys_stl::string m_TopLevel;
bool m_GlobalScope;
#ifdef _WIN32
HKEY HKey;
#endif
// Strip trailing and ending spaces.
char *Strip(char *str);
void SetSubKey(const char* sk);
kwsys_stl::string CreateKey(const char *key);
typedef kwsys_stl::map<kwsys_stl::string, kwsys_stl::string> StringToStringMap;
StringToStringMap EntriesMap;
kwsys_stl::string m_SubKey;
bool m_Empty;
bool m_SubKeySpecified;
kwsys_stl::string m_HomeDirectory;
Registry::RegistryType m_RegistryType;
};
//----------------------------------------------------------------------------
#define Registry_BUFFER_SIZE 8192
//----------------------------------------------------------------------------
Registry::Registry(Registry::RegistryType registryType)
{
m_Opened = false;
m_Locked = false;
this->Helper = 0;
this->Helper = new RegistryHelper(registryType);
}
//----------------------------------------------------------------------------
Registry::~Registry()
{
if ( m_Opened )
{
kwsys_ios::cerr << "Registry::Close should be "
"called here. The registry is not closed."
<< kwsys_ios::endl;
}
delete this->Helper;
}
//----------------------------------------------------------------------------
void Registry::SetGlobalScope(bool b)
{
this->Helper->SetGlobalScope(b);
}
//----------------------------------------------------------------------------
bool Registry::GetGlobalScope()
{
return this->Helper->GetGlobalScope();
}
//----------------------------------------------------------------------------
bool Registry::Open(const char *toplevel,
const char *subkey, int readonly)
{
bool res = false;
if ( m_Locked )
{
return 0;
}
if ( m_Opened )
{
if ( !this->Close() )
{
return false;
}
}
if ( !toplevel || !*toplevel )
{
kwsys_ios::cerr << "Registry::Opened() Toplevel not defined" << kwsys_ios::endl;
return false;
}
if ( isspace(toplevel[0]) ||
isspace(toplevel[strlen(toplevel)-1]) )
{
kwsys_ios::cerr << "Toplevel has to start with letter or number and end"
" with one" << kwsys_ios::endl;
return 0;
}
res = this->Helper->Open(toplevel, subkey, readonly);
if ( readonly != Registry::READONLY )
{
m_Locked = true;
}
if ( res )
{
m_Opened = true;
this->Helper->SetTopLevel(toplevel);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::Close()
{
bool res = false;
if ( m_Opened )
{
res = this->Helper->Close();
}
if ( res )
{
m_Opened = false;
m_Locked = false;
this->Helper->SetChanged(false);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::ReadValue(const char *subkey,
const char *key,
const char **value)
{
*value = 0;
bool res = true;
bool open = false;
if ( ! value )
{
return false;
}
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READONLY) )
{
return false;
}
open = true;
}
res = this->Helper->ReadValue(key, value);
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteKey(const char *subkey, const char *key)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->DeleteKey(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteValue(const char *subkey, const char *key)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->DeleteValue(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::SetValue(const char *subkey, const char *key,
const char *value)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->SetValue( key, value );
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
const char* Registry::GetTopLevel()
{
return this->Helper->GetTopLevel();
}
//----------------------------------------------------------------------------
void Registry::SetTopLevel(const char* tl)
{
this->Helper->SetTopLevel(tl);
}
//----------------------------------------------------------------------------
void RegistryHelper::SetTopLevel(const char* tl)
{
if ( tl )
{
m_TopLevel = tl;
}
else
{
m_TopLevel = "";
}
}
//----------------------------------------------------------------------------
RegistryHelper::RegistryHelper(Registry::RegistryType registryType)
{
m_Changed = false;
m_TopLevel = "";
m_SubKey = "";
m_SubKeySpecified = false;
m_Empty = true;
m_GlobalScope = false;
m_RegistryType = registryType;
}
//----------------------------------------------------------------------------
RegistryHelper::~RegistryHelper()
{
}
//----------------------------------------------------------------------------
bool RegistryHelper::Open(const char *toplevel, const char *subkey,
int readonly)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
HKEY scope = HKEY_CURRENT_USER;
if ( this->GetGlobalScope() )
{
scope = HKEY_LOCAL_MACHINE;
}
int res = 0;
kwsys_ios::ostringstream str;
DWORD dwDummy;
str << "Software\\Kitware\\" << toplevel << "\\" << subkey;
if ( readonly == Registry::READONLY )
{
res = ( RegOpenKeyEx(scope, str.str().c_str(),
0, KEY_READ, &this->HKey) == ERROR_SUCCESS );
}
else
{
res = ( RegCreateKeyEx(scope, str.str().c_str(),
0, "", REG_OPTION_NON_VOLATILE, KEY_READ|KEY_WRITE,
NULL, &this->HKey, &dwDummy) == ERROR_SUCCESS );
}
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
int cc;
kwsys_ios::ostringstream str;
const char* homeDirectory;
if ( (homeDirectory = getenv("HOME")) == 0 )
{
if ( (homeDirectory = getenv("USERPROFILE")) == 0 )
{
return false;
}
}
m_HomeDirectory = homeDirectory;
str << m_HomeDirectory << "/." << toplevel << "rc";
if ( readonly == Registry::READWRITE )
{
kwsys_ios::ofstream ofs( str.str().c_str(), kwsys_ios::ios::out|kwsys_ios::ios::app );
if ( ofs.fail() )
{
return false;
}
ofs.close();
}
kwsys_ios::ifstream *ifs = new kwsys_ios::ifstream(str.str().c_str(), kwsys_ios::ios::in
#ifndef KWSYS_IOS_USE_ANSI
| kwsys_ios::ios::nocreate
#endif
);
if ( !ifs )
{
return false;
}
if ( ifs->fail())
{
delete ifs;
return false;
}
res = true;
char buffer[Registry_BUFFER_SIZE];
while( !ifs->fail() )
{
int found = 0;
ifs->getline(buffer, Registry_BUFFER_SIZE);
if ( ifs->fail() || ifs->eof() )
{
break;
}
char *line = this->Strip(buffer);
if ( *line == '#' || *line == 0 )
{
// Comment
continue;
}
int linelen = static_cast<int>(strlen(line));
for ( cc = 0; cc < linelen; cc++ )
{
if ( line[cc] == '=' )
{
char *key = new char[ cc+1 ];
strncpy( key, line, cc );
key[cc] = 0;
char *value = line + cc + 1;
char *nkey = this->Strip(key);
char *nvalue = this->Strip(value);
this->EntriesMap[nkey] = this->DecodeValue(nvalue);
m_Empty = 0;
delete [] key;
found = 1;
break;
}
}
}
ifs->close();
this->SetSubKey( subkey );
delete ifs;
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::Close()
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res;
res = ( RegCloseKey(this->HKey) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
if ( !m_Changed )
{
this->EntriesMap.erase(
this->EntriesMap.begin(),
this->EntriesMap.end());
m_Empty = 1;
this->SetSubKey(0);
return true;
}
kwsys_ios::ostringstream str;
str << m_HomeDirectory << "/." << this->GetTopLevel() << "rc";
kwsys_ios::ofstream *ofs = new kwsys_ios::ofstream(str.str().c_str(), kwsys_ios::ios::out);
if ( !ofs )
{
return false;
}
if ( ofs->fail())
{
delete ofs;
return false;
}
*ofs << "# This file is automatically generated by the application" << kwsys_ios::endl
<< "# If you change any lines or add new lines, note that all" << kwsys_ios::endl
<< "# comments and empty lines will be deleted. Every line has" << kwsys_ios::endl
<< "# to be in format: " << kwsys_ios::endl
<< "# key = value" << kwsys_ios::endl
<< "#" << kwsys_ios::endl;
if ( !this->EntriesMap.empty() )
{
RegistryHelper::StringToStringMap::iterator it;
for ( it = this->EntriesMap.begin();
it != this->EntriesMap.end();
++ it )
{
*ofs << it->first.c_str() << " = " << this->EncodeValue(it->second.c_str()).c_str() << kwsys_ios::endl;
}
}
this->EntriesMap.erase(
this->EntriesMap.begin(),
this->EntriesMap.end());
ofs->close();
delete ofs;
this->SetSubKey(0);
m_Empty = 1;
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::ReadValue(const char *skey, const char **value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
int res = 1;
DWORD dwType, dwSize;
dwType = REG_SZ;
dwSize = Registry_BUFFER_SIZE;
char buffer[1024]; // Replace with RegQueryInfoKey
res = ( RegQueryValueEx(this->HKey, skey, NULL, &dwType,
(BYTE *)buffer, &dwSize) == ERROR_SUCCESS );
if ( !res )
{
return false;
}
this->EntriesMap[key] = buffer;
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
*value = it->second.c_str();
return true;
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
if ( it != this->EntriesMap.end() )
{
*value = it->second.c_str();
res = true;
}
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteKey(const char* skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
res = ( RegDeleteKey( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteValue(const char *skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
res = ( RegDeleteValue( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::SetValue(const char *skey, const char *value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
DWORD len = (DWORD)(value ? strlen(value) : 0);
res = ( RegSetValueEx(this->HKey, skey, 0, REG_SZ,
(CONST BYTE *)(const char *)value,
len+1) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return 0;
}
this->EntriesMap[key] = value;
return 1;
}
return false;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::CreateKey( const char *key )
{
if ( !m_SubKeySpecified || m_SubKey.empty() || !key )
{
return "";
}
kwsys_ios::ostringstream ostr;
ostr << this->EncodeKey(this->m_SubKey.c_str()) << "\\" << this->EncodeKey(key);
return ostr.str();
}
//----------------------------------------------------------------------------
void RegistryHelper::SetSubKey(const char* sk)
{
if ( !sk )
{
m_SubKey = "";
m_SubKeySpecified = false;
}
else
{
m_SubKey = sk;
m_SubKeySpecified = true;
}
}
//----------------------------------------------------------------------------
char *RegistryHelper::Strip(char *str)
{
int cc;
int len;
char *nstr;
if ( !str )
{
return NULL;
}
len = strlen(str);
nstr = str;
for( cc=0; cc<len; cc++ )
{
if ( !isspace( *nstr ) )
{
break;
}
nstr ++;
}
for( cc=(strlen(nstr)-1); cc>=0; cc-- )
{
if ( !isspace( nstr[cc] ) )
{
nstr[cc+1] = 0;
break;
}
}
return nstr;
}
//----------------------------------------------------------------------------
void RegistryHelper::SetGlobalScope(bool b)
{
m_GlobalScope = b;
}
//----------------------------------------------------------------------------
bool RegistryHelper::GetGlobalScope()
{
return m_GlobalScope;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeKey(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::DecodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
int val;
switch ( *str )
{
case '%':
if ( *(str+1) && *(str+2) && sscanf(str+1, "%x", &val) == 1 )
{
ostr << (char)val;
str += 2;
}
else
{
ostr << *str;
}
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
} // namespace KWSYS_NAMESPACE
COMP: Remove unused variable
/*=========================================================================
Program: KWSys - Kitware System Library
Module: Registry.cxx
Copyright (c) Kitware, Inc., Insight Consortium. 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 notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Registry.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/map)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
#include KWSYS_HEADER(ios/sstream)
#include <ctype.h> // for isspace
#include <stdio.h>
#ifdef _WIN32
# include <windows.h>
#endif
namespace KWSYS_NAMESPACE
{
class RegistryHelper {
public:
RegistryHelper(Registry::RegistryType registryType);
virtual ~RegistryHelper();
// Read a value from the registry.
virtual bool ReadValue(const char *key, const char **value);
// Delete a key from the registry.
virtual bool DeleteKey(const char *key);
// Delete a value from a given key.
virtual bool DeleteValue(const char *key);
// Set value in a given key.
virtual bool SetValue(const char *key,
const char *value);
// Open the registry at toplevel/subkey.
virtual bool Open(const char *toplevel, const char *subkey,
int readonly);
// Close the registry.
virtual bool Close();
// Set the value of changed
void SetChanged(bool b) { m_Changed = b; }
void SetTopLevel(const char* tl);
const char* GetTopLevel() { return m_TopLevel.c_str(); }
//! Read from local or global scope. On Windows this mean from local machine
// or local user. On unix this will read from $HOME/.Projectrc or
// /etc/Project
void SetGlobalScope(bool b);
bool GetGlobalScope();
kwsys_stl::string EncodeKey(const char* str);
kwsys_stl::string EncodeValue(const char* str);
kwsys_stl::string DecodeValue(const char* str);
protected:
bool m_Changed;
kwsys_stl::string m_TopLevel;
bool m_GlobalScope;
#ifdef _WIN32
HKEY HKey;
#endif
// Strip trailing and ending spaces.
char *Strip(char *str);
void SetSubKey(const char* sk);
kwsys_stl::string CreateKey(const char *key);
typedef kwsys_stl::map<kwsys_stl::string, kwsys_stl::string> StringToStringMap;
StringToStringMap EntriesMap;
kwsys_stl::string m_SubKey;
bool m_Empty;
bool m_SubKeySpecified;
kwsys_stl::string m_HomeDirectory;
Registry::RegistryType m_RegistryType;
};
//----------------------------------------------------------------------------
#define Registry_BUFFER_SIZE 8192
//----------------------------------------------------------------------------
Registry::Registry(Registry::RegistryType registryType)
{
m_Opened = false;
m_Locked = false;
this->Helper = 0;
this->Helper = new RegistryHelper(registryType);
}
//----------------------------------------------------------------------------
Registry::~Registry()
{
if ( m_Opened )
{
kwsys_ios::cerr << "Registry::Close should be "
"called here. The registry is not closed."
<< kwsys_ios::endl;
}
delete this->Helper;
}
//----------------------------------------------------------------------------
void Registry::SetGlobalScope(bool b)
{
this->Helper->SetGlobalScope(b);
}
//----------------------------------------------------------------------------
bool Registry::GetGlobalScope()
{
return this->Helper->GetGlobalScope();
}
//----------------------------------------------------------------------------
bool Registry::Open(const char *toplevel,
const char *subkey, int readonly)
{
bool res = false;
if ( m_Locked )
{
return 0;
}
if ( m_Opened )
{
if ( !this->Close() )
{
return false;
}
}
if ( !toplevel || !*toplevel )
{
kwsys_ios::cerr << "Registry::Opened() Toplevel not defined" << kwsys_ios::endl;
return false;
}
if ( isspace(toplevel[0]) ||
isspace(toplevel[strlen(toplevel)-1]) )
{
kwsys_ios::cerr << "Toplevel has to start with letter or number and end"
" with one" << kwsys_ios::endl;
return 0;
}
res = this->Helper->Open(toplevel, subkey, readonly);
if ( readonly != Registry::READONLY )
{
m_Locked = true;
}
if ( res )
{
m_Opened = true;
this->Helper->SetTopLevel(toplevel);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::Close()
{
bool res = false;
if ( m_Opened )
{
res = this->Helper->Close();
}
if ( res )
{
m_Opened = false;
m_Locked = false;
this->Helper->SetChanged(false);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::ReadValue(const char *subkey,
const char *key,
const char **value)
{
*value = 0;
bool res = true;
bool open = false;
if ( ! value )
{
return false;
}
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READONLY) )
{
return false;
}
open = true;
}
res = this->Helper->ReadValue(key, value);
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteKey(const char *subkey, const char *key)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->DeleteKey(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteValue(const char *subkey, const char *key)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->DeleteValue(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::SetValue(const char *subkey, const char *key,
const char *value)
{
bool res = true;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return false;
}
open = true;
}
res = this->Helper->SetValue( key, value );
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
const char* Registry::GetTopLevel()
{
return this->Helper->GetTopLevel();
}
//----------------------------------------------------------------------------
void Registry::SetTopLevel(const char* tl)
{
this->Helper->SetTopLevel(tl);
}
//----------------------------------------------------------------------------
void RegistryHelper::SetTopLevel(const char* tl)
{
if ( tl )
{
m_TopLevel = tl;
}
else
{
m_TopLevel = "";
}
}
//----------------------------------------------------------------------------
RegistryHelper::RegistryHelper(Registry::RegistryType registryType)
{
m_Changed = false;
m_TopLevel = "";
m_SubKey = "";
m_SubKeySpecified = false;
m_Empty = true;
m_GlobalScope = false;
m_RegistryType = registryType;
}
//----------------------------------------------------------------------------
RegistryHelper::~RegistryHelper()
{
}
//----------------------------------------------------------------------------
bool RegistryHelper::Open(const char *toplevel, const char *subkey,
int readonly)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
HKEY scope = HKEY_CURRENT_USER;
if ( this->GetGlobalScope() )
{
scope = HKEY_LOCAL_MACHINE;
}
int res = 0;
kwsys_ios::ostringstream str;
DWORD dwDummy;
str << "Software\\Kitware\\" << toplevel << "\\" << subkey;
if ( readonly == Registry::READONLY )
{
res = ( RegOpenKeyEx(scope, str.str().c_str(),
0, KEY_READ, &this->HKey) == ERROR_SUCCESS );
}
else
{
res = ( RegCreateKeyEx(scope, str.str().c_str(),
0, "", REG_OPTION_NON_VOLATILE, KEY_READ|KEY_WRITE,
NULL, &this->HKey, &dwDummy) == ERROR_SUCCESS );
}
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
int cc;
kwsys_ios::ostringstream str;
const char* homeDirectory;
if ( (homeDirectory = getenv("HOME")) == 0 )
{
if ( (homeDirectory = getenv("USERPROFILE")) == 0 )
{
return false;
}
}
m_HomeDirectory = homeDirectory;
str << m_HomeDirectory << "/." << toplevel << "rc";
if ( readonly == Registry::READWRITE )
{
kwsys_ios::ofstream ofs( str.str().c_str(), kwsys_ios::ios::out|kwsys_ios::ios::app );
if ( ofs.fail() )
{
return false;
}
ofs.close();
}
kwsys_ios::ifstream *ifs = new kwsys_ios::ifstream(str.str().c_str(), kwsys_ios::ios::in
#ifndef KWSYS_IOS_USE_ANSI
| kwsys_ios::ios::nocreate
#endif
);
if ( !ifs )
{
return false;
}
if ( ifs->fail())
{
delete ifs;
return false;
}
res = true;
char buffer[Registry_BUFFER_SIZE];
while( !ifs->fail() )
{
ifs->getline(buffer, Registry_BUFFER_SIZE);
if ( ifs->fail() || ifs->eof() )
{
break;
}
char *line = this->Strip(buffer);
if ( *line == '#' || *line == 0 )
{
// Comment
continue;
}
int linelen = static_cast<int>(strlen(line));
for ( cc = 0; cc < linelen; cc++ )
{
if ( line[cc] == '=' )
{
char *key = new char[ cc+1 ];
strncpy( key, line, cc );
key[cc] = 0;
char *value = line + cc + 1;
char *nkey = this->Strip(key);
char *nvalue = this->Strip(value);
this->EntriesMap[nkey] = this->DecodeValue(nvalue);
m_Empty = 0;
delete [] key;
break;
}
}
}
ifs->close();
this->SetSubKey( subkey );
delete ifs;
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::Close()
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res;
res = ( RegCloseKey(this->HKey) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
if ( !m_Changed )
{
this->EntriesMap.erase(
this->EntriesMap.begin(),
this->EntriesMap.end());
m_Empty = 1;
this->SetSubKey(0);
return true;
}
kwsys_ios::ostringstream str;
str << m_HomeDirectory << "/." << this->GetTopLevel() << "rc";
kwsys_ios::ofstream *ofs = new kwsys_ios::ofstream(str.str().c_str(), kwsys_ios::ios::out);
if ( !ofs )
{
return false;
}
if ( ofs->fail())
{
delete ofs;
return false;
}
*ofs << "# This file is automatically generated by the application" << kwsys_ios::endl
<< "# If you change any lines or add new lines, note that all" << kwsys_ios::endl
<< "# comments and empty lines will be deleted. Every line has" << kwsys_ios::endl
<< "# to be in format: " << kwsys_ios::endl
<< "# key = value" << kwsys_ios::endl
<< "#" << kwsys_ios::endl;
if ( !this->EntriesMap.empty() )
{
RegistryHelper::StringToStringMap::iterator it;
for ( it = this->EntriesMap.begin();
it != this->EntriesMap.end();
++ it )
{
*ofs << it->first.c_str() << " = " << this->EncodeValue(it->second.c_str()).c_str() << kwsys_ios::endl;
}
}
this->EntriesMap.erase(
this->EntriesMap.begin(),
this->EntriesMap.end());
ofs->close();
delete ofs;
this->SetSubKey(0);
m_Empty = 1;
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::ReadValue(const char *skey, const char **value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
int res = 1;
DWORD dwType, dwSize;
dwType = REG_SZ;
dwSize = Registry_BUFFER_SIZE;
char buffer[1024]; // Replace with RegQueryInfoKey
res = ( RegQueryValueEx(this->HKey, skey, NULL, &dwType,
(BYTE *)buffer, &dwSize) == ERROR_SUCCESS );
if ( !res )
{
return false;
}
this->EntriesMap[key] = buffer;
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
*value = it->second.c_str();
return true;
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
if ( it != this->EntriesMap.end() )
{
*value = it->second.c_str();
res = true;
}
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteKey(const char* skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
res = ( RegDeleteKey( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteValue(const char *skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
res = ( RegDeleteValue( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::SetValue(const char *skey, const char *value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = 1;
DWORD len = (DWORD)(value ? strlen(value) : 0);
res = ( RegSetValueEx(this->HKey, skey, 0, REG_SZ,
(CONST BYTE *)(const char *)value,
len+1) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return 0;
}
this->EntriesMap[key] = value;
return 1;
}
return false;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::CreateKey( const char *key )
{
if ( !m_SubKeySpecified || m_SubKey.empty() || !key )
{
return "";
}
kwsys_ios::ostringstream ostr;
ostr << this->EncodeKey(this->m_SubKey.c_str()) << "\\" << this->EncodeKey(key);
return ostr.str();
}
//----------------------------------------------------------------------------
void RegistryHelper::SetSubKey(const char* sk)
{
if ( !sk )
{
m_SubKey = "";
m_SubKeySpecified = false;
}
else
{
m_SubKey = sk;
m_SubKeySpecified = true;
}
}
//----------------------------------------------------------------------------
char *RegistryHelper::Strip(char *str)
{
int cc;
int len;
char *nstr;
if ( !str )
{
return NULL;
}
len = strlen(str);
nstr = str;
for( cc=0; cc<len; cc++ )
{
if ( !isspace( *nstr ) )
{
break;
}
nstr ++;
}
for( cc=(strlen(nstr)-1); cc>=0; cc-- )
{
if ( !isspace( nstr[cc] ) )
{
nstr[cc+1] = 0;
break;
}
}
return nstr;
}
//----------------------------------------------------------------------------
void RegistryHelper::SetGlobalScope(bool b)
{
m_GlobalScope = b;
}
//----------------------------------------------------------------------------
bool RegistryHelper::GetGlobalScope()
{
return m_GlobalScope;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeKey(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::DecodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
int val;
switch ( *str )
{
case '%':
if ( *(str+1) && *(str+2) && sscanf(str+1, "%x", &val) == 1 )
{
ostr << (char)val;
str += 2;
}
else
{
ostr << *str;
}
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
} // namespace KWSYS_NAMESPACE
|
#include "project.h"
/**
* @brief Project::Project
* @param id
* @param name
*/
Project::Project(ID id, std::string name)
{
this->files = new ProjFiles();
this->m_name = name;
this->m_id = id;
this->m_videos.clear();
this->saved = false;
}
/**
* @brief Project::Project
*/
Project::Project(){
this->files = new ProjFiles();
this->m_name = "";
this->m_id = -1;
this->m_videos.clear();
}
/**
* @brief Project::add_video
* @param vid
* add given video to project
*/
void Project::add_video(Video* vid)
{
this->m_videos.push_back(vid);
}
/**
* UNSFINISHED
* @brief operator >>
* @param is
* @param proj
* @return stringstream containing project information
*/
ProjectStream& operator>>(ProjectStream& ps, Project& proj){
//write files
//Read project id and name
ps.projFile >> proj.m_name;
// read videos
int vidCounter = 0;
std::vector<Video*> temp; // used to preserve order ov videos, important for == operator
ps.videos >> vidCounter;
if( vidCounter < 0) return ps; // if negative number of videos, loop below will
// be infinite. This is unlikely to happen. but just in case!
while(vidCounter--){
Video* v = new Video();
ps.videos >> *v;
temp.push_back(v);
}
for (auto vidIt = temp.rbegin(); vidIt < temp.rend(); ++vidIt) { // to preserve order we add videos in reverse
proj.add_video(*vidIt);
}
return ps;
}
/**
* @brief operator <<
* @param os
* @param proj
* @return stream
* used for writing videos to file
*/
ProjectStream& operator<<(ProjectStream &ps, const Project& proj){
//write name and id;
ps.projFile << proj.m_name.c_str() << " ";
//write videos
int vidcounter = proj.m_videos.size();
ps.videos << vidcounter << " ";
for(auto vid = proj.m_videos.rbegin(); vid != proj.m_videos.rend(); ++vid){
Video* v = *vid;
ps.videos << *v << " ";
vidcounter++;
}
return ps;
}
/**
* @brief operator ==
* @param proj
* @param proj2
* @return if projects are same TRUE else False
*/
bool operator==(Project proj, Project proj2){
bool videoEquals = std::equal(proj.m_videos.begin(), proj.m_videos.end(),
proj2.m_videos.begin(),
[](const Video* v, const Video* v2){return *v == *v2;}); // lambda function comparing using video==
// by dereferencing pointers in vector
return *proj.files == *proj2.files && //probably unnecessary as projfiles have projname followed by default suffix
proj.m_name == proj2.m_name &&
videoEquals;
}
/**
* @brief operator ==
* @param pf
* @param pf2
* @retur
* may not be needed but works as intended,
*/
bool operator==(ProjFiles pf, ProjFiles pf2){
return true;pf.dir == pf2.dir &&
pf.f_proj == pf2.f_proj &&
pf.f_videos == pf2.f_videos &&
// Not used in current implementation
pf.f_analysis == pf2.f_analysis &&
pf.f_drawings == pf2.f_drawings;
}
/**
* @brief operator <<
* @param ps
* @param pf
* @return ps
* Writes a projectfile object to projectstream
* @deprecated
* Shouldnt be needed, ids useless and filenames are standard.
*/
ProjectStream& operator<<(ProjectStream &ps,const ProjFiles& pf){
// ps.projFile << pf.f_analysis << " ";
// ps.projFile << pf.f_drawings << " ";
// ps.projFile << pf.f_videos << " ";
return ps;
}
/**
* @brief operator >>
* @param ps
* @param pf
* @return ps
* Reads files from a ProjFiles struct to a ProjectStream
*/
ProjectStream& operator>>(ProjectStream &ps, ProjFiles& pf){
std::string dummy;
ps.projFile >> pf.f_proj;
ps.projFile >> pf.dir;
ps.projFile >> pf.f_analysis;
ps.projFile >> pf.f_drawings;
ps.projFile >> pf.f_videos;
return ps;
}
uncommented code and added commment explaining its (non-use)
#include "project.h"
/**
* @brief Project::Project
* @param id
* @param name
*/
Project::Project(ID id, std::string name)
{
this->files = new ProjFiles();
this->m_name = name;
this->m_id = id;
this->m_videos.clear();
this->saved = false;
}
/**
* @brief Project::Project
*/
Project::Project(){
this->files = new ProjFiles();
this->m_name = "";
this->m_id = -1;
this->m_videos.clear();
}
/**
* @brief Project::add_video
* @param vid
* add given video to project
*/
void Project::add_video(Video* vid)
{
this->m_videos.push_back(vid);
}
/**
* UNSFINISHED
* @brief operator >>
* @param is
* @param proj
* @return stringstream containing project information
*/
ProjectStream& operator>>(ProjectStream& ps, Project& proj){
//write files
//Read project id and name
ps.projFile >> proj.m_name;
// read videos
int vidCounter = 0;
std::vector<Video*> temp; // used to preserve order ov videos, important for == operator
ps.videos >> vidCounter;
if( vidCounter < 0) return ps; // if negative number of videos, loop below will
// be infinite. This is unlikely to happen. but just in case!
while(vidCounter--){
Video* v = new Video();
ps.videos >> *v;
temp.push_back(v);
}
for (auto vidIt = temp.rbegin(); vidIt < temp.rend(); ++vidIt) { // to preserve order we add videos in reverse
proj.add_video(*vidIt);
}
return ps;
}
/**
* @brief operator <<
* @param os
* @param proj
* @return stream
* used for writing videos to file
*/
ProjectStream& operator<<(ProjectStream &ps, const Project& proj){
//write name and id;
ps.projFile << proj.m_name.c_str() << " ";
//write videos
int vidcounter = proj.m_videos.size();
ps.videos << vidcounter << " ";
for(auto vid = proj.m_videos.rbegin(); vid != proj.m_videos.rend(); ++vid){
Video* v = *vid;
ps.videos << *v << " ";
vidcounter++;
}
return ps;
}
/**
* @brief operator ==
* @param proj
* @param proj2
* @return if projects are same TRUE else False
*/
bool operator==(Project proj, Project proj2){
bool videoEquals = std::equal(proj.m_videos.begin(), proj.m_videos.end(),
proj2.m_videos.begin(),
[](const Video* v, const Video* v2){return *v == *v2;}); // lambda function comparing using video==
// by dereferencing pointers in vector
return *proj.files == *proj2.files && //probably unnecessary as projfiles have projname followed by default suffix
proj.m_name == proj2.m_name &&
videoEquals;
}
/**
* @brief operator ==
* @param pf
* @param pf2
* @retur
* may not be needed but works as intended,
*/
bool operator==(ProjFiles pf, ProjFiles pf2){
return pf.dir == pf2.dir &&
pf.f_proj == pf2.f_proj &&
pf.f_videos == pf2.f_videos &&
// Not used in current implementation
pf.f_analysis == pf2.f_analysis &&
pf.f_drawings == pf2.f_drawings;
}
/**
* @brief operator <<
* @param ps
* @param pf
* @return ps
* Writes a projectfile object to projectstream
* @deprecated
* Shouldnt be needed, ids useless and filenames are standard.
* isnt currently used but works as intended.
* kept just in case.
*/
ProjectStream& operator<<(ProjectStream &ps,const ProjFiles& pf){
ps.projFile << pf.f_analysis << " ";
ps.projFile << pf.f_drawings << " ";
ps.projFile << pf.f_videos << " ";
return ps;
}
/**
* @brief operator >>
* @param ps
* @param pf
* @return ps
* Reads files from a ProjFiles struct to a ProjectStream
* Shouldnt be needed, ids useless and filenames are standard.
* isnt currently used but works as intended.
* kept just in case.
*/
ProjectStream& operator>>(ProjectStream &ps, ProjFiles& pf){
std::string dummy;
ps.projFile >> pf.f_analysis;
ps.projFile >> pf.f_drawings;
ps.projFile >> pf.f_videos;
return ps;
}
|
#include <librealsense/rs2.hpp>
#include "example.hpp"
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <imgui.h>
#include "imgui_impl_glfw.h"
#include <cstdarg>
#include <thread>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <sstream>
#include <array>
#include <mutex>
#pragma comment(lib, "opengl32.lib")
#define WHITE_SPACES std::string(" ")
using namespace rs2;
class subdevice_model;
class option_model
{
public:
rs2_option opt;
option_range range;
device endpoint;
bool* invalidate_flag;
bool supported = false;
bool read_only = false;
float value = 0.0f;
std::string label = "";
std::string id = "";
subdevice_model* dev;
void draw(std::string& error_message)
{
if (supported)
{
auto desc = endpoint.get_option_description(opt);
if (is_checkbox())
{
auto bool_value = value > 0.0f;
if (ImGui::Checkbox(label.c_str(), &bool_value))
{
value = bool_value ? 1.0f : 0.0f;
try
{
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
if (ImGui::IsItemHovered() && desc)
{
ImGui::SetTooltip("%s", desc);
}
}
else
{
std::string txt = to_string() << rs2_option_to_string(opt) << ":";
ImGui::Text("%s", txt.c_str());
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Text, { 0.5f, 0.5f, 0.5f, 1.f });
ImGui::Text("(?)");
ImGui::PopStyleColor();
if (ImGui::IsItemHovered() && desc)
{
ImGui::SetTooltip("%s", desc);
}
ImGui::PushItemWidth(-1);
try
{
if (read_only)
{
ImVec2 vec{0, 14};
ImGui::ProgressBar(value/100.f, vec, std::to_string((int)value).c_str());
}
else if (is_enum())
{
std::vector<const char*> labels;
auto selected = 0, counter = 0;
for (auto i = range.min; i <= range.max; i += range.step, counter++)
{
if (abs(i - value) < 0.001f) selected = counter;
labels.push_back(endpoint.get_option_value_description(opt, i));
}
if (ImGui::Combo(id.c_str(), &selected, labels.data(),
static_cast<int>(labels.size())))
{
value = range.min + range.step * selected;
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
else if (is_all_integers())
{
auto int_value = static_cast<int>(value);
if (ImGui::SliderInt(id.c_str(), &int_value,
static_cast<int>(range.min),
static_cast<int>(range.max)))
{
// TODO: Round to step?
value = static_cast<float>(int_value);
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
else
{
if (ImGui::SliderFloat(id.c_str(), &value,
range.min, range.max, "%.4f"))
{
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
ImGui::PopItemWidth();
}
}
}
void update_supported(std::string& error_message)
{
try
{
supported = endpoint.supports(opt);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
void update_read_only(std::string& error_message)
{
try
{
read_only = endpoint.is_option_read_only(opt);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
void update_all(std::string& error_message)
{
try
{
if (supported = endpoint.supports(opt))
{
value = endpoint.get_option(opt);
range = endpoint.get_option_range(opt);
read_only = endpoint.is_option_read_only(opt);
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
private:
bool is_all_integers() const
{
return is_integer(range.min) && is_integer(range.max) &&
is_integer(range.def) && is_integer(range.step);
}
bool is_enum() const
{
if (range.step < 0.001f) return false;
for (auto i = range.min; i <= range.max; i += range.step)
{
if (endpoint.get_option_value_description(opt, i) == nullptr)
return false;
}
return true;
}
bool is_checkbox() const
{
return range.max == 1.0f &&
range.min == 0.0f &&
range.step == 1.0f;
}
};
template<class T>
void push_back_if_not_exists(std::vector<T>& vec, T value)
{
auto it = std::find(vec.begin(), vec.end(), value);
if (it == vec.end()) vec.push_back(value);
}
std::vector<const char*> get_string_pointers(const std::vector<std::string>& vec)
{
std::vector<const char*> res;
for (auto&& s : vec) res.push_back(s.c_str());
return res;
}
struct mouse_info
{
float2 cursor;
bool mouse_down = false;
};
class subdevice_model
{
public:
subdevice_model(device dev, std::string& error_message)
: dev(dev), streaming(false), queues(RS2_STREAM_COUNT),
selected_shared_fps_id(0)
{
for (auto& elem : queues)
{
elem = std::unique_ptr<frame_queue>(new frame_queue(5));
}
try
{
if (dev.supports(RS2_OPTION_ENABLE_AUTO_EXPOSURE))
auto_exposure_enabled = dev.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE) > 0;
}
catch(...)
{
}
try
{
if (dev.supports(RS2_OPTION_DEPTH_UNITS))
depth_units = dev.get_option(RS2_OPTION_DEPTH_UNITS);
}
catch(...)
{
}
for (auto i = 0; i < RS2_OPTION_COUNT; i++)
{
option_model metadata;
auto opt = static_cast<rs2_option>(i);
std::stringstream ss;
ss << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< "/" << dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< "/" << rs2_option_to_string(opt);
metadata.id = ss.str();
metadata.opt = opt;
metadata.endpoint = dev;
metadata.label = rs2_option_to_string(opt) + WHITE_SPACES + ss.str();
metadata.invalidate_flag = &options_invalidated;
metadata.dev = this;
metadata.supported = dev.supports(opt);
if (metadata.supported)
{
try
{
metadata.range = dev.get_option_range(opt);
metadata.read_only = dev.is_option_read_only(opt);
if (!metadata.read_only)
metadata.value = dev.get_option(opt);
}
catch (const error& e)
{
metadata.range = { 0, 1, 0, 0 };
metadata.value = 0;
error_message = error_to_string(e);
}
}
options_metadata[opt] = metadata;
}
try
{
auto uvc_profiles = dev.get_stream_modes();
std::reverse(std::begin(uvc_profiles), std::end(uvc_profiles));
for (auto&& profile : uvc_profiles)
{
std::stringstream res;
res << profile.width << " x " << profile.height;
push_back_if_not_exists(res_values, std::pair<int, int>(profile.width, profile.height));
push_back_if_not_exists(resolutions, res.str());
std::stringstream fps;
fps << profile.fps;
push_back_if_not_exists(fps_values_per_stream[profile.stream], profile.fps);
push_back_if_not_exists(shared_fps_values, profile.fps);
push_back_if_not_exists(fpses_per_stream[profile.stream], fps.str());
push_back_if_not_exists(shared_fpses, fps.str());
std::string format = rs2_format_to_string(profile.format);
push_back_if_not_exists(formats[profile.stream], format);
push_back_if_not_exists(format_values[profile.stream], profile.format);
auto any_stream_enabled = false;
for (auto it : stream_enabled)
{
if (it.second)
{
any_stream_enabled = true;
break;
}
}
if (!any_stream_enabled)
{
stream_enabled[profile.stream] = true;
}
profiles.push_back(profile);
}
show_single_fps_list = is_there_common_fps();
// set default selections
int selection_index;
get_default_selection_index(res_values, std::pair<int,int>(640,480), &selection_index);
selected_res_id = selection_index;
if (!show_single_fps_list)
{
for (auto fps_array : fps_values_per_stream)
{
if (get_default_selection_index(fps_array.second, 30, &selection_index))
{
selected_fps_id[fps_array.first] = selection_index;
break;
}
}
}
else
{
if (get_default_selection_index(shared_fps_values, 30, &selection_index))
selected_shared_fps_id = selection_index;
}
for (auto format_array : format_values)
{
for (auto format : { rs2_format::RS2_FORMAT_RGB8,
rs2_format::RS2_FORMAT_Z16,
rs2_format::RS2_FORMAT_Y8,
rs2_format::RS2_FORMAT_MOTION_XYZ32F } )
{
if (get_default_selection_index(format_array.second, format, &selection_index))
{
selected_format_id[format_array.first] = selection_index;
break;
}
}
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
bool is_there_common_fps()
{
std::vector<int> first_fps_group;
auto group_index = 0;
for (; group_index < fps_values_per_stream.size() ; ++group_index)
{
if (!fps_values_per_stream[(rs2_stream)group_index].empty())
{
first_fps_group = fps_values_per_stream[(rs2_stream)group_index];
break;
}
}
for (int i = group_index + 1 ; i < fps_values_per_stream.size() ; ++i)
{
auto fps_group = fps_values_per_stream[(rs2_stream)i];
if (fps_group.empty())
continue;
for (auto& fps1 : first_fps_group)
{
auto it = std::find_if(std::begin(fps_group),
std::end(fps_group),
[&](const int& fps2)
{
return fps2 == fps1;
});
if (it != std::end(fps_group))
{
break;
}
return false;
}
}
return true;
}
void draw_stream_selection()
{
// Draw combo-box with all resolution options for this device
auto res_chars = get_string_pointers(resolutions);
ImGui::PushItemWidth(-1);
ImGui::Text("Resolution:");
ImGui::SameLine();
std::string label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME) << " resolution";
if (streaming)
ImGui::Text("%s", res_chars[selected_res_id]);
else
{
ImGui::Combo(label.c_str(), &selected_res_id, res_chars.data(),
static_cast<int>(res_chars.size()));
}
ImGui::PopItemWidth();
// FPS
if (show_single_fps_list)
{
auto fps_chars = get_string_pointers(shared_fpses);
ImGui::Text("FPS: ");
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME) << " fps";
ImGui::SameLine();
ImGui::PushItemWidth(-1);
if (streaming)
{
ImGui::Text("%s", fps_chars[selected_shared_fps_id]);
}
else
{
ImGui::Combo(label.c_str(), &selected_shared_fps_id, fps_chars.data(),
static_cast<int>(fps_chars.size()));
}
ImGui::PopItemWidth();
}
// Check which streams are live in current device
auto live_streams = 0;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (formats[stream].size() > 0)
live_streams++;
}
// Draw combo-box with all format options for current device
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
// Format
if (formats[stream].size() == 0)
continue;
ImGui::PushItemWidth(-1);
auto formats_chars = get_string_pointers(formats[stream]);
if (!streaming || (streaming && stream_enabled[stream]))
{
if (live_streams > 1)
{
label = to_string() << rs2_stream_to_string(stream);
if (!show_single_fps_list)
label += " stream:";
if (streaming)
ImGui::Text("%s", label.c_str());
else
ImGui::Checkbox(label.c_str(), &stream_enabled[stream]);
}
}
if (stream_enabled[stream])
{
if (show_single_fps_list) ImGui::SameLine();
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< " " << rs2_stream_to_string(stream) << " format";
if (!show_single_fps_list)
{
ImGui::Text("Format: ");
ImGui::SameLine();
}
if (streaming)
{
ImGui::Text("%s", formats_chars[selected_format_id[stream]]);
}
else
{
ImGui::Combo(label.c_str(), &selected_format_id[stream], formats_chars.data(),
static_cast<int>(formats_chars.size()));
}
// FPS
// Draw combo-box with all FPS options for this device
if (!show_single_fps_list && !fpses_per_stream[stream].empty() && stream_enabled[stream])
{
auto fps_chars = get_string_pointers(fpses_per_stream[stream]);
ImGui::Text("FPS: ");
ImGui::SameLine();
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< rs2_stream_to_string(stream) << " fps";
if (streaming)
{
ImGui::Text("%s", fps_chars[selected_fps_id[stream]]);
}
else
{
ImGui::Combo(label.c_str(), &selected_fps_id[stream], fps_chars.data(),
static_cast<int>(fps_chars.size()));
}
}
}
ImGui::PopItemWidth();
}
}
bool is_selected_combination_supported()
{
std::vector<stream_profile> results;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (stream_enabled[stream])
{
auto width = res_values[selected_res_id].first;
auto height = res_values[selected_res_id].second;
auto fps = 0;
if (show_single_fps_list)
fps = shared_fps_values[selected_shared_fps_id];
else
fps = fps_values_per_stream[stream][selected_fps_id[stream]];
auto format = format_values[stream][selected_format_id[stream]];
for (auto&& p : profiles)
{
if (p.width == width && p.height == height && p.fps == fps && p.format == format)
results.push_back(p);
}
}
}
return results.size() > 0;
}
std::vector<stream_profile> get_selected_profiles()
{
std::vector<stream_profile> results;
std::stringstream error_message;
error_message << "The profile ";
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (stream_enabled[stream])
{
auto width = res_values[selected_res_id].first;
auto height = res_values[selected_res_id].second;
auto format = format_values[stream][selected_format_id[stream]];
auto fps = 0;
if (show_single_fps_list)
fps = shared_fps_values[selected_shared_fps_id];
else
fps = fps_values_per_stream[stream][selected_fps_id[stream]];
error_message << "\n{" << rs2_stream_to_string(stream) << ","
<< width << "x" << height << " at " << fps << "Hz, "
<< rs2_format_to_string(format) << "} ";
for (auto&& p : profiles)
{
if (p.width == width &&
p.height == height &&
p.fps == fps &&
p.format == format &&
p.stream == stream)
results.push_back(p);
}
}
}
if (results.size() == 0)
{
error_message << " is unsupported!";
throw std::runtime_error(error_message.str());
}
return results;
}
void stop()
{
streaming = false;
for (auto& elem : queues)
elem->flush();
dev.stop();
dev.close();
}
void play(const std::vector<stream_profile>& profiles)
{
dev.open(profiles);
try {
dev.start([&](frame f){
auto stream_type = f.get_stream_type();
queues[(int)stream_type]->enqueue(std::move(f));
});
}
catch (...)
{
dev.close();
throw;
}
streaming = true;
}
void update(std::string& error_message)
{
if (options_invalidated)
{
next_option = 0;
options_invalidated = false;
}
if (next_option < RS2_OPTION_COUNT)
{
auto& opt_md = options_metadata[static_cast<rs2_option>(next_option)];
opt_md.update_all(error_message);
if (next_option == RS2_OPTION_ENABLE_AUTO_EXPOSURE)
{
auto old_ae_enabled = auto_exposure_enabled;
auto_exposure_enabled = opt_md.value > 0;
if (!old_ae_enabled && auto_exposure_enabled)
{
try
{
auto roi = dev.get_region_of_interest();
roi_rect.x = roi.min_x;
roi_rect.y = roi.min_y;
roi_rect.w = roi.max_x - roi.min_x;
roi_rect.h = roi.max_y - roi.min_y;
}
catch (...)
{
auto_exposure_enabled = false;
}
}
}
if (next_option == RS2_OPTION_DEPTH_UNITS)
{
opt_md.dev->depth_units = opt_md.value;
}
next_option++;
}
}
template<typename T>
bool get_default_selection_index(const std::vector<T>& values, const T & def, int* index)
{
auto max_default = values.begin();
for (auto it = values.begin(); it != values.end(); it++)
{
if (*it == def)
{
*index = (int)(it - values.begin());
return true;
}
if (*max_default < *it)
{
max_default = it;
}
}
*index = (int)(max_default - values.begin());
return false;
}
device dev;
std::map<rs2_option, option_model> options_metadata;
std::vector<std::string> resolutions;
std::map<rs2_stream, std::vector<std::string>> fpses_per_stream;
std::vector<std::string> shared_fpses;
std::map<rs2_stream, std::vector<std::string>> formats;
std::map<rs2_stream, bool> stream_enabled;
int selected_res_id = 0;
std::map<rs2_stream, int> selected_fps_id;
int selected_shared_fps_id = 0;
std::map<rs2_stream, int> selected_format_id;
std::vector<std::pair<int, int>> res_values;
std::map<rs2_stream, std::vector<int>> fps_values_per_stream;
std::vector<int> shared_fps_values;
bool show_single_fps_list = false;
std::map<rs2_stream, std::vector<rs2_format>> format_values;
std::vector<stream_profile> profiles;
std::vector<std::unique_ptr<frame_queue>> queues;
bool options_invalidated = false;
int next_option = RS2_OPTION_COUNT;
bool streaming = false;
rect roi_rect;
bool auto_exposure_enabled = false;
float depth_units = 1.f;
};
class fps_calc
{
public:
fps_calc()
: _counter(0),
_delta(0),
_last_timestamp(0),
_num_of_frames(0)
{}
fps_calc(const fps_calc& other)
{
std::lock_guard<std::mutex> lock(other._mtx);
_counter = other._counter;
_delta = other._delta;
_num_of_frames = other._num_of_frames;
_last_timestamp = other._last_timestamp;
}
void add_timestamp(double timestamp, unsigned long long frame_counter)
{
std::lock_guard<std::mutex> lock(_mtx);
if (++_counter >= _skip_frames)
{
if (_last_timestamp != 0)
{
_delta = timestamp - _last_timestamp;
_num_of_frames = frame_counter - _last_frame_counter;
}
_last_frame_counter = frame_counter;
_last_timestamp = timestamp;
_counter = 0;
}
}
double get_fps() const
{
std::lock_guard<std::mutex> lock(_mtx);
if (_delta == 0)
return 0;
return (static_cast<double>(_numerator) * _num_of_frames)/_delta;
}
private:
static const int _numerator = 1000;
static const int _skip_frames = 5;
unsigned long long _num_of_frames;
int _counter;
double _delta;
double _last_timestamp;
unsigned long long _last_frame_counter;
mutable std::mutex _mtx;
};
typedef std::map<rs2_stream, rect> streams_layout;
struct frame_metadata
{
std::array<std::pair<bool,rs2_metadata_t>,RS2_FRAME_METADATA_COUNT> md_attributes{};
};
class stream_model
{
public:
rect layout;
std::unique_ptr<texture_buffer> texture;
float2 size;
rs2_stream stream;
rs2_format format;
std::chrono::high_resolution_clock::time_point last_frame;
double timestamp;
unsigned long long frame_number;
rs2_timestamp_domain timestamp_domain;
fps_calc fps;
rect roi_display_rect{};
frame_metadata frame_md;
bool metadata_displayed = false;
bool roi_supported = false; // supported by device in its current state
bool roi_checked = false; // actively selected by user
bool capturing_roi = false; // active modification of roi
std::shared_ptr<subdevice_model> dev;
stream_model()
:texture ( std::unique_ptr<texture_buffer>(new texture_buffer()))
{}
void upload_frame(frame&& f)
{
last_frame = std::chrono::high_resolution_clock::now();
auto is_motion = ((f.get_format() == RS2_FORMAT_MOTION_RAW) || (f.get_format() == RS2_FORMAT_MOTION_XYZ32F));
auto width = (is_motion) ? 640.f : f.get_width();
auto height = (is_motion) ? 480.f : f.get_height();
size = { static_cast<float>(width), static_cast<float>(height)};
stream = f.get_stream_type();
format = f.get_format();
frame_number = f.get_frame_number();
timestamp_domain = f.get_frame_timestamp_domain();
timestamp = f.get_timestamp();
fps.add_timestamp(f.get_timestamp(), f.get_frame_number());
// populate frame metadata attributes
for (auto i=0; i< RS2_FRAME_METADATA_COUNT; i++)
{
if (f.supports_frame_metadata((rs2_frame_metadata)i))
frame_md.md_attributes[i] = std::make_pair(true,f.get_frame_metadata((rs2_frame_metadata)i));
else
frame_md.md_attributes[i].first = false;
}
roi_supported = (dev.get() && dev->auto_exposure_enabled);
texture->upload(f);
}
void outline_rect(const rect& r)
{
glPushAttrib(GL_ENABLE_BIT);
glLineWidth(1);
glLineStipple(1, 0xAAAA);
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINE_STRIP);
glVertex2i(r.x, r.y);
glVertex2i(r.x, r.y + r.h);
glVertex2i(r.x + r.w, r.y + r.h);
glVertex2i(r.x + r.w, r.y);
glVertex2i(r.x, r.y);
glEnd();
glPopAttrib();
}
float get_stream_alpha()
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto diff = now - last_frame;
auto ms = duration_cast<milliseconds>(diff).count();
auto t = smoothstep(static_cast<float>(ms),
_min_timeout, _min_timeout + _frame_timeout);
return 1.0f - t;
}
bool is_stream_visible()
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto diff = now - last_frame;
auto ms = duration_cast<milliseconds>(diff).count();
return ms <= _frame_timeout + _min_timeout;
}
void update_ae_roi_rect(const rect& stream_rect, const mouse_info& mouse, std::string& error_message)
{
if (roi_checked)
{
// Case 1: Starting Dragging of the ROI rect
// Pre-condition: not capturing already + mouse is down + we are inside stream rect
if (!capturing_roi && mouse.mouse_down && stream_rect.contains(mouse.cursor))
{
// Initialize roi_display_rect with drag-start position
roi_display_rect.x = mouse.cursor.x;
roi_display_rect.y = mouse.cursor.y;
roi_display_rect.w = 0; // Still unknown, will be update later
roi_display_rect.h = 0;
capturing_roi = true; // Mark that we are in process of capturing the ROI rect
}
// Case 2: We are in the middle of dragging (capturing) ROI rect and we did not leave the stream boundaries
if (capturing_roi && stream_rect.contains(mouse.cursor))
{
// x,y remain the same, only update the width,height with new mouse position relative to starting mouse position
roi_display_rect.w = mouse.cursor.x - roi_display_rect.x;
roi_display_rect.h = mouse.cursor.y - roi_display_rect.y;
}
// Case 3: We are in middle of dragging (capturing) and mouse was released
if (!mouse.mouse_down && capturing_roi && stream_rect.contains(mouse.cursor))
{
// Update width,height one last time
roi_display_rect.w = mouse.cursor.x - roi_display_rect.x;
roi_display_rect.h = mouse.cursor.y - roi_display_rect.y;
capturing_roi = false; // Mark that we are no longer dragging
if (roi_display_rect) // If the rect is not empty?
{
// Convert from local (pixel) coordinate system to device coordinate system
auto r = roi_display_rect;
r.x = ((r.x - stream_rect.x) / stream_rect.w) * size.x;
r.y = ((r.y - stream_rect.y) / stream_rect.h) * size.y;
r.w = (r.w / stream_rect.w) * size.x;
r.h = (r.h / stream_rect.h) * size.y;
dev->roi_rect = r; // Store new rect in device coordinates into the subdevice object
// Send it to firmware:
// Step 1: get rid of negative width / height
region_of_interest roi;
roi.min_x = std::min(r.x, r.x + r.w);
roi.max_x = std::max(r.x, r.x + r.w);
roi.min_y = std::min(r.y, r.y + r.h);
roi.max_y = std::max(r.y, r.y + r.h);
try
{
// Step 2: send it to firmware
dev->dev.set_region_of_interest(roi);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
else // If the rect is empty
{
try
{
// To reset ROI, just set ROI to the entire frame
auto x_margin = (int)size.x / 8;
auto y_margin = (int)size.y / 8;
// Default ROI behaviour is center 3/4 of the screen:
dev->dev.set_region_of_interest({ x_margin, y_margin,
(int)size.x - x_margin - 1,
(int)size.y - y_margin - 1 });
roi_display_rect = { 0, 0, 0, 0 };
dev->roi_rect = { 0, 0, 0, 0 };
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
}
// If we left stream bounds while capturing, stop capturing
if (capturing_roi && !stream_rect.contains(mouse.cursor))
{
capturing_roi = false;
}
// When not capturing, just refresh the ROI rect in case the stream box moved
if (!capturing_roi)
{
auto r = dev->roi_rect; // Take the current from device, convert to local coordinates
r.x = ((r.x / size.x) * stream_rect.w) + stream_rect.x;
r.y = ((r.y / size.y) * stream_rect.h) + stream_rect.y;
r.w = (r.w / size.x) * stream_rect.w;
r.h = (r.h / size.y) * stream_rect.h;
roi_display_rect = r;
}
// Display ROI rect
glColor3f(1.0f, 1.0f, 1.0f);
outline_rect(roi_display_rect);
}
}
void show_frame(const rect& stream_rect, const mouse_info& g, std::string& error_message)
{
texture->show(stream_rect, get_stream_alpha());
update_ae_roi_rect(stream_rect, g, error_message);
}
void show_metadata(const mouse_info& g)
{
auto lines = RS2_FRAME_METADATA_COUNT;
auto flags = ImGuiWindowFlags_ShowBorders;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.3f, 0.3f, 0.3f, 0.5});
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.f, 0.25f, 0.3f, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.f, 0.3f, 0.8f, 1 });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 });
std::string label = to_string() << rs2_stream_to_string(stream) << " Stream Metadata #";
ImGui::Begin(label.c_str(), nullptr, flags);
// Print all available frame metadata attributes
for (size_t i=0; i < RS2_FRAME_METADATA_COUNT; i++ )
{
if (frame_md.md_attributes[i].first)
{
label = to_string() << rs2_frame_metadata_to_string((rs2_frame_metadata)i) << " = " << frame_md.md_attributes[i].second;
ImGui::Text("%s", label.c_str());
}
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
}
float _frame_timeout = 700.0f;
float _min_timeout = 167.0f;
};
class device_model
{
public:
device_model(){}
void reset()
{
subdevices.resize(0);
streams.clear();
}
explicit device_model(device& dev, std::string& error_message)
{
for (auto&& sub : dev.get_adjacent_devices())
{
auto model = std::make_shared<subdevice_model>(sub, error_message);
subdevices.push_back(model);
}
}
std::map<rs2_stream, rect> calc_layout(float x0, float y0, float width, float height)
{
std::vector<rs2_stream> active_streams;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (streams[stream].is_stream_visible())
{
active_streams.push_back(stream);
}
}
if (fullscreen)
{
auto it = std::find(begin(active_streams), end(active_streams), selected_stream);
if (it == end(active_streams)) fullscreen = false;
}
std::map<rs2_stream, rect> results;
if (fullscreen)
{
results[selected_stream] = { static_cast<float>(x0), static_cast<float>(y0), static_cast<float>(width), static_cast<float>(height) };
}
else
{
auto factor = ceil(sqrt(active_streams.size()));
auto complement = ceil(active_streams.size() / factor);
auto cell_width = static_cast<float>(width / factor);
auto cell_height = static_cast<float>(height / complement);
auto i = 0;
for (auto x = 0; x < factor; x++)
{
for (auto y = 0; y < complement; y++)
{
if (i == active_streams.size()) break;
rect r = { x0 + x * cell_width, y0 + y * cell_height,
cell_width, cell_height };
results[active_streams[i]] = r;
i++;
}
}
}
return get_interpolated_layout(results);
}
void upload_frame(frame&& f)
{
auto stream_type = f.get_stream_type();
streams[stream_type].upload_frame(std::move(f));
}
std::vector<std::shared_ptr<subdevice_model>> subdevices;
std::map<rs2_stream, stream_model> streams;
bool fullscreen = false;
bool metadata_supported = false;
rs2_stream selected_stream = RS2_STREAM_ANY;
private:
std::map<rs2_stream, rect> get_interpolated_layout(const std::map<rs2_stream, rect>& l)
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
if (l != _layout) // detect layout change
{
_transition_start_time = now;
_old_layout = _layout;
_layout = l;
}
//if (_old_layout.size() == 0 && l.size() == 1) return l;
auto diff = now - _transition_start_time;
auto ms = duration_cast<milliseconds>(diff).count();
auto t = smoothstep(static_cast<float>(ms), 0, 100);
std::map<rs2_stream, rect> results;
for (auto&& kvp : l)
{
auto stream = kvp.first;
if (_old_layout.find(stream) == _old_layout.end())
{
_old_layout[stream] = _layout[stream].center();
}
results[stream] = _old_layout[stream].lerp(t, _layout[stream]);
}
return results;
}
streams_layout _layout;
streams_layout _old_layout;
std::chrono::high_resolution_clock::time_point _transition_start_time;
};
struct user_data
{
GLFWwindow* curr_window = nullptr;
mouse_info* mouse = nullptr;
};
struct notification_data
{
notification_data( std::string description,
double timestamp,
rs2_log_severity severity,
rs2_notification_category category)
: _description(description),
_timestamp(timestamp),
_severity(severity),
_category(category){}
rs2_notification_category get_category() const
{
return _category;
}
std::string get_description() const
{
return _description;
}
double get_timestamp() const
{
return _timestamp;
}
rs2_log_severity get_severity() const
{
return _severity;
}
std::string _description;
double _timestamp;
rs2_log_severity _severity;
rs2_notification_category _category;
};
struct notification_model
{
static const int MAX_LIFETIME_MS = 10000;
notification_model()
{
message = "";
}
notification_model(const notification_data& n)
{
message = n.get_description();
timestamp = n.get_timestamp();
severity = n.get_severity();
created_time = std::chrono::high_resolution_clock::now();
}
int height = 60;
int index;
std::string message;
double timestamp;
rs2_log_severity severity;
std::chrono::high_resolution_clock::time_point created_time;
// TODO: Add more info
double get_age_in_ms()
{
auto age = std::chrono::high_resolution_clock::now() - created_time;
return std::chrono::duration_cast<std::chrono::milliseconds>(age).count();
}
void draw(int w, int y, notification_model& selected)
{
auto flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse;
auto ms = get_age_in_ms() / MAX_LIFETIME_MS;
auto t = smoothstep(static_cast<float>(ms), 0.7f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.3f, 0, 0, 1 - t });
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.5f, 0.2f, 0.2f, 1 - t });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.6f, 0.2f, 0.2f, 1 - t });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 - t });
auto lines = std::count(message.begin(), message.end(), '\n')+1;
ImGui::SetNextWindowPos({ float(w - 430), float(y) });
ImGui::SetNextWindowSize({ float(500), float(lines*50) });
height = lines*50 +10;
std::string label = to_string() << "Hardware Notification #" << index;
ImGui::Begin(label.c_str(), nullptr, flags);
ImGui::Text("%s", message.c_str());
if(lines == 1)
ImGui::SameLine();
ImGui::Text("(...)");
if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered())
{
selected = *this;
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
}
};
struct notifications_model
{
std::vector<notification_model> pending_notifications;
int index = 1;
const int MAX_SIZE = 6;
std::mutex m;
void add_notification(const notification_data& n)
{
std::lock_guard<std::mutex> lock(m); // need to protect the pending_notifications queue because the insertion of notifications
// done from the notifications callback and proccesing and removing of old notifications done from the main thread
notification_model m(n);
m.index = index++;
pending_notifications.push_back(m);
if (pending_notifications.size() > MAX_SIZE)
pending_notifications.erase(pending_notifications.begin());
}
void draw(int w, int h, notification_model& selected)
{
std::lock_guard<std::mutex> lock(m);
if (pending_notifications.size() > 0)
{
// loop over all notifications, remove "old" ones
pending_notifications.erase(std::remove_if(std::begin(pending_notifications),
std::end(pending_notifications),
[&](notification_model& n)
{
return (n.get_age_in_ms() > notification_model::MAX_LIFETIME_MS);
}), end(pending_notifications));
int idx = 0;
auto height = 30;
for (auto& noti : pending_notifications)
{
noti.draw(w, height, selected);
height += noti.height;
idx++;
}
}
auto flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoTitleBar;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::Begin("Notification parent window", nullptr, flags);
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.1f, 0, 0, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.3f, 0.1f, 0.1f, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.5f, 0.1f, 0.1f, 1 });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 });
if (selected.message != "")
ImGui::OpenPopup("Notification from Hardware");
if (ImGui::BeginPopupModal("Notification from Hardware", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("Received the following notification:");
std::stringstream s;
s<<"Timestamp: "<<std::fixed<<selected.timestamp<<"\n"<<"Severity: "<<selected.severity<<"\nDescription: "<<const_cast<char*>(selected.message.c_str());
ImGui::InputTextMultiline("notification", const_cast<char*>(s.str().c_str()),
selected.message.size() + 1, { 500,100 }, ImGuiInputTextFlags_AutoSelectAll);
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
selected.message = "";
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::End();
ImGui::PopStyleColor();
}
};
std::vector<std::string> get_device_info(const device& dev)
{
std::vector<std::string> res;
for (auto i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = static_cast<rs2_camera_info>(i);
if (dev.supports(info))
{
auto value = dev.get_camera_info(info);
res.push_back(value);
}
}
return res;
}
std::string get_device_name(device& dev)
{
std::string name = dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME); // retrieve device name
std::string serial = dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_SERIAL_NUMBER); // retrieve device serial number
std::string module = dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME); // retrieve device serial number
std::stringstream s;
s<< std::setw(25)<<std::left<< name << " " <<std::setw(10)<<std::left<< module<<" Sn#" << serial;
return s.str(); // push name and sn to list
}
std::vector<std::string> get_devices_names(const device_list& list)
{
std::vector<std::string> device_names;
for (uint32_t i = 0; i < list.size(); i++)
{
try
{
auto dev = list[i];
device_names.push_back(get_device_name(dev)); // push name and sn to list
}
catch (...)
{
device_names.push_back(to_string() << "Unknown Device #" << i);
}
}
return device_names;
}
int find_device_index(const device_list& list ,std::vector<std::string> device_info)
{
std::vector<std::vector<std::string>> devices_info;
for (auto l:list)
{
devices_info.push_back(get_device_info(l));
}
auto it = std::find(devices_info.begin(),devices_info.end(), device_info);
return std::distance(devices_info.begin(), it);
}
int main(int, char**) try
{
// activate logging to console
log_to_console(RS2_LOG_SEVERITY_WARN);
// Init GUI
if (!glfwInit())
exit(1);
// Create GUI Windows
auto window = glfwCreateWindow(1280, 720, "librealsense - config-ui", nullptr, nullptr);
glfwMakeContextCurrent(window);
ImGui_ImplGlfw_Init(window, true);
ImVec4 clear_color = ImColor(10, 0, 0);
// Create RealSense Context
context ctx;
auto refresh_device_list = true;
auto device_index = 0;
std::vector<std::string> device_names;
std::vector<const char*> device_names_chars;
notifications_model not_model;
std::string error_message = "";
notification_model selected_notification;
// Initialize list with each device name and serial number
std::string label;
mouse_info mouse;
user_data data;
data.curr_window = window;
data.mouse = &mouse;
glfwSetWindowUserPointer(window, &data);
glfwSetCursorPosCallback(window, [](GLFWwindow * w, double cx, double cy)
{
reinterpret_cast<user_data *>(glfwGetWindowUserPointer(w))->mouse->cursor = { (float)cx, (float)cy };
});
glfwSetMouseButtonCallback(window, [](GLFWwindow * w, int button, int action, int mods)
{
auto data = reinterpret_cast<user_data *>(glfwGetWindowUserPointer(w));
data->mouse->mouse_down = action != GLFW_RELEASE;
});
auto last_time_point = std::chrono::high_resolution_clock::now();
device dev;
device_model model;
device_list list;
device_list new_list;
std::vector<std::string> active_device_info;
auto dev_exist = false;
auto hw_reset_enable = true;
std::vector<device> devs;
std::mutex m;
auto timestamp = std::chrono::duration<double, std::milli>(std::chrono::system_clock::now().time_since_epoch()).count();
ctx.set_devices_changed_callback([&](event_information& info)
{
timestamp = std::chrono::duration<double, std::milli>(std::chrono::system_clock::now().time_since_epoch()).count();
std::lock_guard<std::mutex> lock(m);
for(auto dev:devs)
{
if(info.was_removed(dev))
{
not_model.add_notification({get_device_name(dev) + "\ndisconnected",
timestamp,
RS2_LOG_SEVERITY_INFO,
RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR});
}
}
if(info.was_removed(dev))
{
dev_exist = false;
}
for(auto dev:info.get_new_devices())
{
not_model.add_notification({get_device_name(dev) + "\nconnected",
timestamp,
RS2_LOG_SEVERITY_INFO,
RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR});
}
refresh_device_list = true;
});
// Closing the window
while (!glfwWindowShouldClose(window))
{
{
std::lock_guard<std::mutex> lock(m);
if(refresh_device_list)
{
refresh_device_list = false;
try
{
list = ctx.query_devices();
device_names = get_devices_names(list);
device_names_chars = get_string_pointers(device_names);
for(auto dev: devs)
{
dev = nullptr;
}
devs.clear();
if( !dev_exist)
{
device_index = 0;
dev = nullptr;
model.reset();
if(list.size()>0)
{
dev = list[device_index]; // Access first device
model = device_model(dev, error_message); // Initialize device model
active_device_info = get_device_info(dev);
dev_exist = true;
}
}
else
{
device_index = find_device_index(list, active_device_info);
}
for (auto&& sub : list)
{
devs.push_back(sub);
sub.set_notifications_callback([&](const notification& n)
{
not_model.add_notification({n.get_description(), n.get_timestamp(), n.get_severity(), n.get_category()});
});
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
catch (const std::exception& e)
{
error_message = e.what();
}
hw_reset_enable = true;
}
}
bool update_read_only_options = false;
auto now = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration<double, std::milli>(now - last_time_point).count();
if (duration >= 5000)
{
update_read_only_options = true;
last_time_point = now;
}
glfwPollEvents();
int w, h;
glfwGetWindowSize(window, &w, &h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ImGui_ImplGlfw_NewFrame();
// Flags for pop-up window - no window resize, move or collaps
auto flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse;
const float panel_size = 320;
// Set window position and size
ImGui::SetNextWindowPos({ 0, 0 });
ImGui::SetNextWindowSize({ panel_size, static_cast<float>(h) });
// *********************
// Creating window menus
// *********************
ImGui::Begin("Control Panel", nullptr, flags);
rs2_error* e = nullptr;
label = to_string() << "VERSION: " << api_version_to_string(rs2_get_api_version(&e));
ImGui::Text("%s", label.c_str());
if (list.size()==0 )
{
ImGui::Text("No device detected.");
}
// Device Details Menu - Elaborate details on connected devices
if (list.size()>0 && ImGui::CollapsingHeader("Device Details", nullptr, true, true))
{
// Draw a combo-box with the list of connected devices
ImGui::PushItemWidth(-1);
auto new_index = device_index;
if (ImGui::Combo("", &new_index, device_names_chars.data(),
static_cast<int>(device_names.size())))
{
for (auto&& sub : model.subdevices)
{
if (sub->streaming)
sub->stop();
}
try
{
dev = list[new_index];
device_index = new_index;
model = device_model(dev, error_message);
active_device_info = get_device_info(dev);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
catch (const std::exception& e)
{
error_message = e.what();
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip(device_names_chars[new_index]);
}
ImGui::PopItemWidth();
// Show all device details - name, module name, serial number, FW version and location
for (auto i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = static_cast<rs2_camera_info>(i);
if (dev.supports(info))
{
// retrieve info property
std::stringstream ss;
ss << rs2_camera_info_to_string(info) << ":";
auto line = ss.str();
ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 1.0f, 1.0f, 0.5f });
ImGui::Text("%s", line.c_str());
ImGui::PopStyleColor();
// retrieve property value
ImGui::SameLine();
auto value = dev.get_camera_info(info);
ImGui::Text("%s", value);
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", value);
}
}
}
}
// Streaming Menu - Allow user to play different streams
if (list.size()>0 && ImGui::CollapsingHeader("Streaming", nullptr, true, true))
{
if (model.subdevices.size() > 1)
{
try
{
const float stream_all_button_width = 290;
const float stream_all_button_height = 0;
auto anything_stream = false;
for (auto&& sub : model.subdevices)
{
if (sub->streaming) anything_stream = true;
}
if (!anything_stream)
{
label = to_string() << "Start All";
if (ImGui::Button(label.c_str(), { stream_all_button_width, stream_all_button_height }))
{
for (auto&& sub : model.subdevices)
{
if (sub->is_selected_combination_supported())
{
auto profiles = sub->get_selected_profiles();
sub->play(profiles);
for (auto&& profile : profiles)
{
model.streams[profile.stream].dev = sub;
}
}
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Start streaming from all subdevices");
}
}
else
{
label = to_string() << "Stop All";
if (ImGui::Button(label.c_str(), { stream_all_button_width, stream_all_button_height }))
{
for (auto&& sub : model.subdevices)
{
if (sub->streaming) sub->stop();
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Stop streaming from all subdevices");
}
}
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
}
// Draw menu foreach subdevice with its properties
for (auto&& sub : model.subdevices)
{
label = to_string() << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (ImGui::CollapsingHeader(label.c_str(), nullptr, true, true))
{
sub->draw_stream_selection();
try
{
if (!sub->streaming)
{
label = to_string() << "Start " << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (sub->is_selected_combination_supported())
{
if (ImGui::Button(label.c_str()))
{
auto profiles = sub->get_selected_profiles();
sub->play(profiles);
for (auto&& profile : profiles)
{
model.streams[profile.stream].dev = sub;
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Start streaming data from selected sub-device");
}
}
else
{
ImGui::TextDisabled("%s", label.c_str());
}
}
else
{
label = to_string() << "Stop " << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (ImGui::Button(label.c_str()))
{
sub->stop();
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Stop streaming data from selected sub-device");
}
}
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
for (auto i = 0; i < RS2_OPTION_COUNT; i++)
{
auto opt = static_cast<rs2_option>(i);
auto&& metadata = sub->options_metadata[opt];
if (update_read_only_options)
{
metadata.update_supported(error_message);
if (metadata.supported && sub->streaming)
{
metadata.update_read_only(error_message);
if (metadata.read_only)
{
metadata.update_all(error_message);
}
}
}
metadata.draw(error_message);
}
}
ImGui::Text("\n");
}
}
if (list.size()>0 && ImGui::CollapsingHeader("Hardware Commands", nullptr, true))
{
label = to_string() << "Hardware Reset";
const float hardware_reset_button_width = 290;
const float hardware_reset_button_height = 0;
if (ImGui::ButtonEx(label.c_str(), { hardware_reset_button_width, hardware_reset_button_height }, hw_reset_enable?0:ImGuiButtonFlags_Disabled))
{
try
{
dev.hardware_reset();
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
}
}
ImGui::Text("\n\n\n\n\n\n\n");
for (auto&& sub : model.subdevices)
{
sub->update(error_message);
}
if (error_message != "")
ImGui::OpenPopup("Oops, something went wrong!");
if (ImGui::BeginPopupModal("Oops, something went wrong!", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("RealSense error calling:");
ImGui::InputTextMultiline("error", const_cast<char*>(error_message.c_str()),
error_message.size() + 1, { 500,100 }, ImGuiInputTextFlags_AutoSelectAll);
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
error_message = "";
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::End();
not_model.draw(w, h, selected_notification);
// Fetch frames from queue
for (auto&& sub : model.subdevices)
{
for (auto& queue : sub->queues)
{
try
{
frame f;
if (queue->poll_for_frame(&f))
{
model.upload_frame(std::move(f));
}
}
catch(const error& e)
{
error_message = error_to_string(e);
sub->stop();
}
catch(const std::exception& e)
{
error_message = e.what();
sub->stop();
}
}
}
// Rendering
glViewport(0, 0,
static_cast<int>(ImGui::GetIO().DisplaySize.x),
static_cast<int>(ImGui::GetIO().DisplaySize.y));
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
glfwGetWindowSize(window, &w, &h);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, +1);
auto layout = model.calc_layout(panel_size, 0.f, w - panel_size, (float)h);
for (auto &&kvp : layout)
{
auto&& view_rect = kvp.second;
auto stream = kvp.first;
auto&& stream_size = model.streams[stream].size;
auto stream_rect = view_rect.adjust_ratio(stream_size);
model.streams[stream].show_frame(stream_rect, mouse, error_message);
flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoTitleBar;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::SetNextWindowPos({ stream_rect.x, stream_rect.y });
ImGui::SetNextWindowSize({ stream_rect.w, stream_rect.h });
label = to_string() << "Stream of " << rs2_stream_to_string(stream);
ImGui::Begin(label.c_str(), nullptr, flags);
label = to_string() << rs2_stream_to_string(stream) << " "
<< stream_size.x << "x" << stream_size.y << ", "
<< rs2_format_to_string(model.streams[stream].format) << ", "
<< "Frame# " << model.streams[stream].frame_number << ", "
<< "FPS:";
ImGui::Text("%s", label.c_str());
ImGui::SameLine();
label = to_string() << std::setprecision(2) << std::fixed << model.streams[stream].fps.get_fps();
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("FPS is calculated based on timestamps and not viewer time");
}
ImGui::SameLine((int)ImGui::GetWindowWidth() - 30);
if (!layout.empty() && !model.fullscreen)
{
if (ImGui::Button("[+]", { 26, 20 }))
{
model.fullscreen = true;
model.selected_stream = stream;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Maximize stream to full-screen");
}
}
else if (model.fullscreen)
{
if (ImGui::Button("[-]", { 26, 20 }))
{
model.fullscreen = false;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Minimize stream to tile-view");
}
}
if (!layout.empty())
{
if (model.streams[stream].roi_supported )
{
ImGui::SameLine((int)ImGui::GetWindowWidth() - 160);
ImGui::Checkbox("[ROI]", &model.streams[stream].roi_checked);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Auto Exposure Region-of-Interest Selection");
}
else
model.streams[stream].roi_checked = false;
}
// Control metadata overlay widget
ImGui::SameLine((int)ImGui::GetWindowWidth() - 90); // metadata GUI hint
if (!layout.empty())
{
ImGui::Checkbox("[MD]", &model.streams[stream].metadata_displayed);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Show per-frame metadata");
}
label = to_string() << "Timestamp: " << std::fixed << std::setprecision(3) << model.streams[stream].timestamp
<< ", Domain:";
ImGui::Text("%s", label.c_str());
ImGui::SameLine();
auto domain = model.streams[stream].timestamp_domain;
label = to_string() << rs2_timestamp_domain_to_string(domain);
if (domain == RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)
{
ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 0.0f, 0.0f, 1.0f });
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Hardware Timestamp unavailable! This is often an indication of inproperly applied Kernel patch.\nPlease refer to installation.md for mode information");
}
ImGui::PopStyleColor();
}
else
{
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Specifies the clock-domain for the timestamp (hardware-clock / system-time)");
}
}
ImGui::End();
ImGui::PopStyleColor();
if (stream_rect.contains(mouse.cursor))
{
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::SetNextWindowPos({ stream_rect.x, stream_rect.y + stream_rect.h - 25 });
ImGui::SetNextWindowSize({ stream_rect.w, 25 });
label = to_string() << "Footer for stream of " << rs2_stream_to_string(stream);
ImGui::Begin(label.c_str(), nullptr, flags);
std::stringstream ss;
auto x = ((mouse.cursor.x - stream_rect.x) / stream_rect.w) * stream_size.x;
auto y = ((mouse.cursor.y - stream_rect.y) / stream_rect.h) * stream_size.y;
ss << std::fixed << std::setprecision(0) << x << ", " << y;
float val;
if (model.streams[stream].texture->try_pick(x, y, &val))
{
ss << ", *p: 0x" << std::hex << val;
if (stream == RS2_STREAM_DEPTH && val > 0)
{
auto meters = (val * model.streams[stream].dev->depth_units);
ss << std::dec << ", ~"
<< std::setprecision(2) << meters << " meters";
}
}
label = ss.str();
ImGui::Text("%s", label.c_str());
ImGui::End();
ImGui::PopStyleColor();
}
}
// Metadata overlay windows shall be drawn after textures to preserve z-buffer functionality
for (auto &&kvp : layout)
{
if (model.streams[kvp.first].metadata_displayed)
model.streams[kvp.first].show_metadata(mouse);
}
ImGui::Render();
glfwSwapBuffers(window);
}
// Stop all subdevices
for (auto&& sub : model.subdevices)
{
if (sub->streaming)
sub->stop();
}
// Cleanup
ImGui_ImplGlfw_Shutdown();
glfwTerminate();
return EXIT_SUCCESS;
}
catch (const error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
Config-UI connect/disconnect events properly call dev.supports() before requesting camera_infos
Tracked On: DSO-4853
#include <librealsense/rs2.hpp>
#include "example.hpp"
#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <imgui.h>
#include "imgui_impl_glfw.h"
#include <cstdarg>
#include <thread>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <sstream>
#include <array>
#include <mutex>
#pragma comment(lib, "opengl32.lib")
#define WHITE_SPACES std::string(" ")
using namespace rs2;
class subdevice_model;
class option_model
{
public:
rs2_option opt;
option_range range;
device endpoint;
bool* invalidate_flag;
bool supported = false;
bool read_only = false;
float value = 0.0f;
std::string label = "";
std::string id = "";
subdevice_model* dev;
void draw(std::string& error_message)
{
if (supported)
{
auto desc = endpoint.get_option_description(opt);
if (is_checkbox())
{
auto bool_value = value > 0.0f;
if (ImGui::Checkbox(label.c_str(), &bool_value))
{
value = bool_value ? 1.0f : 0.0f;
try
{
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
if (ImGui::IsItemHovered() && desc)
{
ImGui::SetTooltip("%s", desc);
}
}
else
{
std::string txt = to_string() << rs2_option_to_string(opt) << ":";
ImGui::Text("%s", txt.c_str());
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Text, { 0.5f, 0.5f, 0.5f, 1.f });
ImGui::Text("(?)");
ImGui::PopStyleColor();
if (ImGui::IsItemHovered() && desc)
{
ImGui::SetTooltip("%s", desc);
}
ImGui::PushItemWidth(-1);
try
{
if (read_only)
{
ImVec2 vec{0, 14};
ImGui::ProgressBar(value/100.f, vec, std::to_string((int)value).c_str());
}
else if (is_enum())
{
std::vector<const char*> labels;
auto selected = 0, counter = 0;
for (auto i = range.min; i <= range.max; i += range.step, counter++)
{
if (abs(i - value) < 0.001f) selected = counter;
labels.push_back(endpoint.get_option_value_description(opt, i));
}
if (ImGui::Combo(id.c_str(), &selected, labels.data(),
static_cast<int>(labels.size())))
{
value = range.min + range.step * selected;
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
else if (is_all_integers())
{
auto int_value = static_cast<int>(value);
if (ImGui::SliderInt(id.c_str(), &int_value,
static_cast<int>(range.min),
static_cast<int>(range.max)))
{
// TODO: Round to step?
value = static_cast<float>(int_value);
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
else
{
if (ImGui::SliderFloat(id.c_str(), &value,
range.min, range.max, "%.4f"))
{
endpoint.set_option(opt, value);
*invalidate_flag = true;
}
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
ImGui::PopItemWidth();
}
}
}
void update_supported(std::string& error_message)
{
try
{
supported = endpoint.supports(opt);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
void update_read_only(std::string& error_message)
{
try
{
read_only = endpoint.is_option_read_only(opt);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
void update_all(std::string& error_message)
{
try
{
if (supported = endpoint.supports(opt))
{
value = endpoint.get_option(opt);
range = endpoint.get_option_range(opt);
read_only = endpoint.is_option_read_only(opt);
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
private:
bool is_all_integers() const
{
return is_integer(range.min) && is_integer(range.max) &&
is_integer(range.def) && is_integer(range.step);
}
bool is_enum() const
{
if (range.step < 0.001f) return false;
for (auto i = range.min; i <= range.max; i += range.step)
{
if (endpoint.get_option_value_description(opt, i) == nullptr)
return false;
}
return true;
}
bool is_checkbox() const
{
return range.max == 1.0f &&
range.min == 0.0f &&
range.step == 1.0f;
}
};
template<class T>
void push_back_if_not_exists(std::vector<T>& vec, T value)
{
auto it = std::find(vec.begin(), vec.end(), value);
if (it == vec.end()) vec.push_back(value);
}
std::vector<const char*> get_string_pointers(const std::vector<std::string>& vec)
{
std::vector<const char*> res;
for (auto&& s : vec) res.push_back(s.c_str());
return res;
}
struct mouse_info
{
float2 cursor;
bool mouse_down = false;
};
class subdevice_model
{
public:
subdevice_model(device dev, std::string& error_message)
: dev(dev), streaming(false), queues(RS2_STREAM_COUNT),
selected_shared_fps_id(0)
{
for (auto& elem : queues)
{
elem = std::unique_ptr<frame_queue>(new frame_queue(5));
}
try
{
if (dev.supports(RS2_OPTION_ENABLE_AUTO_EXPOSURE))
auto_exposure_enabled = dev.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE) > 0;
}
catch(...)
{
}
try
{
if (dev.supports(RS2_OPTION_DEPTH_UNITS))
depth_units = dev.get_option(RS2_OPTION_DEPTH_UNITS);
}
catch(...)
{
}
for (auto i = 0; i < RS2_OPTION_COUNT; i++)
{
option_model metadata;
auto opt = static_cast<rs2_option>(i);
std::stringstream ss;
ss << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< "/" << dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< "/" << rs2_option_to_string(opt);
metadata.id = ss.str();
metadata.opt = opt;
metadata.endpoint = dev;
metadata.label = rs2_option_to_string(opt) + WHITE_SPACES + ss.str();
metadata.invalidate_flag = &options_invalidated;
metadata.dev = this;
metadata.supported = dev.supports(opt);
if (metadata.supported)
{
try
{
metadata.range = dev.get_option_range(opt);
metadata.read_only = dev.is_option_read_only(opt);
if (!metadata.read_only)
metadata.value = dev.get_option(opt);
}
catch (const error& e)
{
metadata.range = { 0, 1, 0, 0 };
metadata.value = 0;
error_message = error_to_string(e);
}
}
options_metadata[opt] = metadata;
}
try
{
auto uvc_profiles = dev.get_stream_modes();
std::reverse(std::begin(uvc_profiles), std::end(uvc_profiles));
for (auto&& profile : uvc_profiles)
{
std::stringstream res;
res << profile.width << " x " << profile.height;
push_back_if_not_exists(res_values, std::pair<int, int>(profile.width, profile.height));
push_back_if_not_exists(resolutions, res.str());
std::stringstream fps;
fps << profile.fps;
push_back_if_not_exists(fps_values_per_stream[profile.stream], profile.fps);
push_back_if_not_exists(shared_fps_values, profile.fps);
push_back_if_not_exists(fpses_per_stream[profile.stream], fps.str());
push_back_if_not_exists(shared_fpses, fps.str());
std::string format = rs2_format_to_string(profile.format);
push_back_if_not_exists(formats[profile.stream], format);
push_back_if_not_exists(format_values[profile.stream], profile.format);
auto any_stream_enabled = false;
for (auto it : stream_enabled)
{
if (it.second)
{
any_stream_enabled = true;
break;
}
}
if (!any_stream_enabled)
{
stream_enabled[profile.stream] = true;
}
profiles.push_back(profile);
}
show_single_fps_list = is_there_common_fps();
// set default selections
int selection_index;
get_default_selection_index(res_values, std::pair<int,int>(640,480), &selection_index);
selected_res_id = selection_index;
if (!show_single_fps_list)
{
for (auto fps_array : fps_values_per_stream)
{
if (get_default_selection_index(fps_array.second, 30, &selection_index))
{
selected_fps_id[fps_array.first] = selection_index;
break;
}
}
}
else
{
if (get_default_selection_index(shared_fps_values, 30, &selection_index))
selected_shared_fps_id = selection_index;
}
for (auto format_array : format_values)
{
for (auto format : { rs2_format::RS2_FORMAT_RGB8,
rs2_format::RS2_FORMAT_Z16,
rs2_format::RS2_FORMAT_Y8,
rs2_format::RS2_FORMAT_MOTION_XYZ32F } )
{
if (get_default_selection_index(format_array.second, format, &selection_index))
{
selected_format_id[format_array.first] = selection_index;
break;
}
}
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
bool is_there_common_fps()
{
std::vector<int> first_fps_group;
auto group_index = 0;
for (; group_index < fps_values_per_stream.size() ; ++group_index)
{
if (!fps_values_per_stream[(rs2_stream)group_index].empty())
{
first_fps_group = fps_values_per_stream[(rs2_stream)group_index];
break;
}
}
for (int i = group_index + 1 ; i < fps_values_per_stream.size() ; ++i)
{
auto fps_group = fps_values_per_stream[(rs2_stream)i];
if (fps_group.empty())
continue;
for (auto& fps1 : first_fps_group)
{
auto it = std::find_if(std::begin(fps_group),
std::end(fps_group),
[&](const int& fps2)
{
return fps2 == fps1;
});
if (it != std::end(fps_group))
{
break;
}
return false;
}
}
return true;
}
void draw_stream_selection()
{
// Draw combo-box with all resolution options for this device
auto res_chars = get_string_pointers(resolutions);
ImGui::PushItemWidth(-1);
ImGui::Text("Resolution:");
ImGui::SameLine();
std::string label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME) << " resolution";
if (streaming)
ImGui::Text("%s", res_chars[selected_res_id]);
else
{
ImGui::Combo(label.c_str(), &selected_res_id, res_chars.data(),
static_cast<int>(res_chars.size()));
}
ImGui::PopItemWidth();
// FPS
if (show_single_fps_list)
{
auto fps_chars = get_string_pointers(shared_fpses);
ImGui::Text("FPS: ");
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME) << " fps";
ImGui::SameLine();
ImGui::PushItemWidth(-1);
if (streaming)
{
ImGui::Text("%s", fps_chars[selected_shared_fps_id]);
}
else
{
ImGui::Combo(label.c_str(), &selected_shared_fps_id, fps_chars.data(),
static_cast<int>(fps_chars.size()));
}
ImGui::PopItemWidth();
}
// Check which streams are live in current device
auto live_streams = 0;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (formats[stream].size() > 0)
live_streams++;
}
// Draw combo-box with all format options for current device
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
// Format
if (formats[stream].size() == 0)
continue;
ImGui::PushItemWidth(-1);
auto formats_chars = get_string_pointers(formats[stream]);
if (!streaming || (streaming && stream_enabled[stream]))
{
if (live_streams > 1)
{
label = to_string() << rs2_stream_to_string(stream);
if (!show_single_fps_list)
label += " stream:";
if (streaming)
ImGui::Text("%s", label.c_str());
else
ImGui::Checkbox(label.c_str(), &stream_enabled[stream]);
}
}
if (stream_enabled[stream])
{
if (show_single_fps_list) ImGui::SameLine();
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< " " << rs2_stream_to_string(stream) << " format";
if (!show_single_fps_list)
{
ImGui::Text("Format: ");
ImGui::SameLine();
}
if (streaming)
{
ImGui::Text("%s", formats_chars[selected_format_id[stream]]);
}
else
{
ImGui::Combo(label.c_str(), &selected_format_id[stream], formats_chars.data(),
static_cast<int>(formats_chars.size()));
}
// FPS
// Draw combo-box with all FPS options for this device
if (!show_single_fps_list && !fpses_per_stream[stream].empty() && stream_enabled[stream])
{
auto fps_chars = get_string_pointers(fpses_per_stream[stream]);
ImGui::Text("FPS: ");
ImGui::SameLine();
label = to_string() << dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME)
<< dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME)
<< rs2_stream_to_string(stream) << " fps";
if (streaming)
{
ImGui::Text("%s", fps_chars[selected_fps_id[stream]]);
}
else
{
ImGui::Combo(label.c_str(), &selected_fps_id[stream], fps_chars.data(),
static_cast<int>(fps_chars.size()));
}
}
}
ImGui::PopItemWidth();
}
}
bool is_selected_combination_supported()
{
std::vector<stream_profile> results;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (stream_enabled[stream])
{
auto width = res_values[selected_res_id].first;
auto height = res_values[selected_res_id].second;
auto fps = 0;
if (show_single_fps_list)
fps = shared_fps_values[selected_shared_fps_id];
else
fps = fps_values_per_stream[stream][selected_fps_id[stream]];
auto format = format_values[stream][selected_format_id[stream]];
for (auto&& p : profiles)
{
if (p.width == width && p.height == height && p.fps == fps && p.format == format)
results.push_back(p);
}
}
}
return results.size() > 0;
}
std::vector<stream_profile> get_selected_profiles()
{
std::vector<stream_profile> results;
std::stringstream error_message;
error_message << "The profile ";
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (stream_enabled[stream])
{
auto width = res_values[selected_res_id].first;
auto height = res_values[selected_res_id].second;
auto format = format_values[stream][selected_format_id[stream]];
auto fps = 0;
if (show_single_fps_list)
fps = shared_fps_values[selected_shared_fps_id];
else
fps = fps_values_per_stream[stream][selected_fps_id[stream]];
error_message << "\n{" << rs2_stream_to_string(stream) << ","
<< width << "x" << height << " at " << fps << "Hz, "
<< rs2_format_to_string(format) << "} ";
for (auto&& p : profiles)
{
if (p.width == width &&
p.height == height &&
p.fps == fps &&
p.format == format &&
p.stream == stream)
results.push_back(p);
}
}
}
if (results.size() == 0)
{
error_message << " is unsupported!";
throw std::runtime_error(error_message.str());
}
return results;
}
void stop()
{
streaming = false;
for (auto& elem : queues)
elem->flush();
dev.stop();
dev.close();
}
void play(const std::vector<stream_profile>& profiles)
{
dev.open(profiles);
try {
dev.start([&](frame f){
auto stream_type = f.get_stream_type();
queues[(int)stream_type]->enqueue(std::move(f));
});
}
catch (...)
{
dev.close();
throw;
}
streaming = true;
}
void update(std::string& error_message)
{
if (options_invalidated)
{
next_option = 0;
options_invalidated = false;
}
if (next_option < RS2_OPTION_COUNT)
{
auto& opt_md = options_metadata[static_cast<rs2_option>(next_option)];
opt_md.update_all(error_message);
if (next_option == RS2_OPTION_ENABLE_AUTO_EXPOSURE)
{
auto old_ae_enabled = auto_exposure_enabled;
auto_exposure_enabled = opt_md.value > 0;
if (!old_ae_enabled && auto_exposure_enabled)
{
try
{
auto roi = dev.get_region_of_interest();
roi_rect.x = roi.min_x;
roi_rect.y = roi.min_y;
roi_rect.w = roi.max_x - roi.min_x;
roi_rect.h = roi.max_y - roi.min_y;
}
catch (...)
{
auto_exposure_enabled = false;
}
}
}
if (next_option == RS2_OPTION_DEPTH_UNITS)
{
opt_md.dev->depth_units = opt_md.value;
}
next_option++;
}
}
template<typename T>
bool get_default_selection_index(const std::vector<T>& values, const T & def, int* index)
{
auto max_default = values.begin();
for (auto it = values.begin(); it != values.end(); it++)
{
if (*it == def)
{
*index = (int)(it - values.begin());
return true;
}
if (*max_default < *it)
{
max_default = it;
}
}
*index = (int)(max_default - values.begin());
return false;
}
device dev;
std::map<rs2_option, option_model> options_metadata;
std::vector<std::string> resolutions;
std::map<rs2_stream, std::vector<std::string>> fpses_per_stream;
std::vector<std::string> shared_fpses;
std::map<rs2_stream, std::vector<std::string>> formats;
std::map<rs2_stream, bool> stream_enabled;
int selected_res_id = 0;
std::map<rs2_stream, int> selected_fps_id;
int selected_shared_fps_id = 0;
std::map<rs2_stream, int> selected_format_id;
std::vector<std::pair<int, int>> res_values;
std::map<rs2_stream, std::vector<int>> fps_values_per_stream;
std::vector<int> shared_fps_values;
bool show_single_fps_list = false;
std::map<rs2_stream, std::vector<rs2_format>> format_values;
std::vector<stream_profile> profiles;
std::vector<std::unique_ptr<frame_queue>> queues;
bool options_invalidated = false;
int next_option = RS2_OPTION_COUNT;
bool streaming = false;
rect roi_rect;
bool auto_exposure_enabled = false;
float depth_units = 1.f;
};
class fps_calc
{
public:
fps_calc()
: _counter(0),
_delta(0),
_last_timestamp(0),
_num_of_frames(0)
{}
fps_calc(const fps_calc& other)
{
std::lock_guard<std::mutex> lock(other._mtx);
_counter = other._counter;
_delta = other._delta;
_num_of_frames = other._num_of_frames;
_last_timestamp = other._last_timestamp;
}
void add_timestamp(double timestamp, unsigned long long frame_counter)
{
std::lock_guard<std::mutex> lock(_mtx);
if (++_counter >= _skip_frames)
{
if (_last_timestamp != 0)
{
_delta = timestamp - _last_timestamp;
_num_of_frames = frame_counter - _last_frame_counter;
}
_last_frame_counter = frame_counter;
_last_timestamp = timestamp;
_counter = 0;
}
}
double get_fps() const
{
std::lock_guard<std::mutex> lock(_mtx);
if (_delta == 0)
return 0;
return (static_cast<double>(_numerator) * _num_of_frames)/_delta;
}
private:
static const int _numerator = 1000;
static const int _skip_frames = 5;
unsigned long long _num_of_frames;
int _counter;
double _delta;
double _last_timestamp;
unsigned long long _last_frame_counter;
mutable std::mutex _mtx;
};
typedef std::map<rs2_stream, rect> streams_layout;
struct frame_metadata
{
std::array<std::pair<bool,rs2_metadata_t>,RS2_FRAME_METADATA_COUNT> md_attributes{};
};
class stream_model
{
public:
rect layout;
std::unique_ptr<texture_buffer> texture;
float2 size;
rs2_stream stream;
rs2_format format;
std::chrono::high_resolution_clock::time_point last_frame;
double timestamp;
unsigned long long frame_number;
rs2_timestamp_domain timestamp_domain;
fps_calc fps;
rect roi_display_rect{};
frame_metadata frame_md;
bool metadata_displayed = false;
bool roi_supported = false; // supported by device in its current state
bool roi_checked = false; // actively selected by user
bool capturing_roi = false; // active modification of roi
std::shared_ptr<subdevice_model> dev;
stream_model()
:texture ( std::unique_ptr<texture_buffer>(new texture_buffer()))
{}
void upload_frame(frame&& f)
{
last_frame = std::chrono::high_resolution_clock::now();
auto is_motion = ((f.get_format() == RS2_FORMAT_MOTION_RAW) || (f.get_format() == RS2_FORMAT_MOTION_XYZ32F));
auto width = (is_motion) ? 640.f : f.get_width();
auto height = (is_motion) ? 480.f : f.get_height();
size = { static_cast<float>(width), static_cast<float>(height)};
stream = f.get_stream_type();
format = f.get_format();
frame_number = f.get_frame_number();
timestamp_domain = f.get_frame_timestamp_domain();
timestamp = f.get_timestamp();
fps.add_timestamp(f.get_timestamp(), f.get_frame_number());
// populate frame metadata attributes
for (auto i=0; i< RS2_FRAME_METADATA_COUNT; i++)
{
if (f.supports_frame_metadata((rs2_frame_metadata)i))
frame_md.md_attributes[i] = std::make_pair(true,f.get_frame_metadata((rs2_frame_metadata)i));
else
frame_md.md_attributes[i].first = false;
}
roi_supported = (dev.get() && dev->auto_exposure_enabled);
texture->upload(f);
}
void outline_rect(const rect& r)
{
glPushAttrib(GL_ENABLE_BIT);
glLineWidth(1);
glLineStipple(1, 0xAAAA);
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINE_STRIP);
glVertex2i(r.x, r.y);
glVertex2i(r.x, r.y + r.h);
glVertex2i(r.x + r.w, r.y + r.h);
glVertex2i(r.x + r.w, r.y);
glVertex2i(r.x, r.y);
glEnd();
glPopAttrib();
}
float get_stream_alpha()
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto diff = now - last_frame;
auto ms = duration_cast<milliseconds>(diff).count();
auto t = smoothstep(static_cast<float>(ms),
_min_timeout, _min_timeout + _frame_timeout);
return 1.0f - t;
}
bool is_stream_visible()
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
auto diff = now - last_frame;
auto ms = duration_cast<milliseconds>(diff).count();
return ms <= _frame_timeout + _min_timeout;
}
void update_ae_roi_rect(const rect& stream_rect, const mouse_info& mouse, std::string& error_message)
{
if (roi_checked)
{
// Case 1: Starting Dragging of the ROI rect
// Pre-condition: not capturing already + mouse is down + we are inside stream rect
if (!capturing_roi && mouse.mouse_down && stream_rect.contains(mouse.cursor))
{
// Initialize roi_display_rect with drag-start position
roi_display_rect.x = mouse.cursor.x;
roi_display_rect.y = mouse.cursor.y;
roi_display_rect.w = 0; // Still unknown, will be update later
roi_display_rect.h = 0;
capturing_roi = true; // Mark that we are in process of capturing the ROI rect
}
// Case 2: We are in the middle of dragging (capturing) ROI rect and we did not leave the stream boundaries
if (capturing_roi && stream_rect.contains(mouse.cursor))
{
// x,y remain the same, only update the width,height with new mouse position relative to starting mouse position
roi_display_rect.w = mouse.cursor.x - roi_display_rect.x;
roi_display_rect.h = mouse.cursor.y - roi_display_rect.y;
}
// Case 3: We are in middle of dragging (capturing) and mouse was released
if (!mouse.mouse_down && capturing_roi && stream_rect.contains(mouse.cursor))
{
// Update width,height one last time
roi_display_rect.w = mouse.cursor.x - roi_display_rect.x;
roi_display_rect.h = mouse.cursor.y - roi_display_rect.y;
capturing_roi = false; // Mark that we are no longer dragging
if (roi_display_rect) // If the rect is not empty?
{
// Convert from local (pixel) coordinate system to device coordinate system
auto r = roi_display_rect;
r.x = ((r.x - stream_rect.x) / stream_rect.w) * size.x;
r.y = ((r.y - stream_rect.y) / stream_rect.h) * size.y;
r.w = (r.w / stream_rect.w) * size.x;
r.h = (r.h / stream_rect.h) * size.y;
dev->roi_rect = r; // Store new rect in device coordinates into the subdevice object
// Send it to firmware:
// Step 1: get rid of negative width / height
region_of_interest roi;
roi.min_x = std::min(r.x, r.x + r.w);
roi.max_x = std::max(r.x, r.x + r.w);
roi.min_y = std::min(r.y, r.y + r.h);
roi.max_y = std::max(r.y, r.y + r.h);
try
{
// Step 2: send it to firmware
dev->dev.set_region_of_interest(roi);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
else // If the rect is empty
{
try
{
// To reset ROI, just set ROI to the entire frame
auto x_margin = (int)size.x / 8;
auto y_margin = (int)size.y / 8;
// Default ROI behaviour is center 3/4 of the screen:
dev->dev.set_region_of_interest({ x_margin, y_margin,
(int)size.x - x_margin - 1,
(int)size.y - y_margin - 1 });
roi_display_rect = { 0, 0, 0, 0 };
dev->roi_rect = { 0, 0, 0, 0 };
}
catch (const error& e)
{
error_message = error_to_string(e);
}
}
}
// If we left stream bounds while capturing, stop capturing
if (capturing_roi && !stream_rect.contains(mouse.cursor))
{
capturing_roi = false;
}
// When not capturing, just refresh the ROI rect in case the stream box moved
if (!capturing_roi)
{
auto r = dev->roi_rect; // Take the current from device, convert to local coordinates
r.x = ((r.x / size.x) * stream_rect.w) + stream_rect.x;
r.y = ((r.y / size.y) * stream_rect.h) + stream_rect.y;
r.w = (r.w / size.x) * stream_rect.w;
r.h = (r.h / size.y) * stream_rect.h;
roi_display_rect = r;
}
// Display ROI rect
glColor3f(1.0f, 1.0f, 1.0f);
outline_rect(roi_display_rect);
}
}
void show_frame(const rect& stream_rect, const mouse_info& g, std::string& error_message)
{
texture->show(stream_rect, get_stream_alpha());
update_ae_roi_rect(stream_rect, g, error_message);
}
void show_metadata(const mouse_info& g)
{
auto lines = RS2_FRAME_METADATA_COUNT;
auto flags = ImGuiWindowFlags_ShowBorders;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.3f, 0.3f, 0.3f, 0.5});
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.f, 0.25f, 0.3f, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.f, 0.3f, 0.8f, 1 });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 });
std::string label = to_string() << rs2_stream_to_string(stream) << " Stream Metadata #";
ImGui::Begin(label.c_str(), nullptr, flags);
// Print all available frame metadata attributes
for (size_t i=0; i < RS2_FRAME_METADATA_COUNT; i++ )
{
if (frame_md.md_attributes[i].first)
{
label = to_string() << rs2_frame_metadata_to_string((rs2_frame_metadata)i) << " = " << frame_md.md_attributes[i].second;
ImGui::Text("%s", label.c_str());
}
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
}
float _frame_timeout = 700.0f;
float _min_timeout = 167.0f;
};
class device_model
{
public:
device_model(){}
void reset()
{
subdevices.resize(0);
streams.clear();
}
explicit device_model(device& dev, std::string& error_message)
{
for (auto&& sub : dev.get_adjacent_devices())
{
auto model = std::make_shared<subdevice_model>(sub, error_message);
subdevices.push_back(model);
}
}
std::map<rs2_stream, rect> calc_layout(float x0, float y0, float width, float height)
{
std::vector<rs2_stream> active_streams;
for (auto i = 0; i < RS2_STREAM_COUNT; i++)
{
auto stream = static_cast<rs2_stream>(i);
if (streams[stream].is_stream_visible())
{
active_streams.push_back(stream);
}
}
if (fullscreen)
{
auto it = std::find(begin(active_streams), end(active_streams), selected_stream);
if (it == end(active_streams)) fullscreen = false;
}
std::map<rs2_stream, rect> results;
if (fullscreen)
{
results[selected_stream] = { static_cast<float>(x0), static_cast<float>(y0), static_cast<float>(width), static_cast<float>(height) };
}
else
{
auto factor = ceil(sqrt(active_streams.size()));
auto complement = ceil(active_streams.size() / factor);
auto cell_width = static_cast<float>(width / factor);
auto cell_height = static_cast<float>(height / complement);
auto i = 0;
for (auto x = 0; x < factor; x++)
{
for (auto y = 0; y < complement; y++)
{
if (i == active_streams.size()) break;
rect r = { x0 + x * cell_width, y0 + y * cell_height,
cell_width, cell_height };
results[active_streams[i]] = r;
i++;
}
}
}
return get_interpolated_layout(results);
}
void upload_frame(frame&& f)
{
auto stream_type = f.get_stream_type();
streams[stream_type].upload_frame(std::move(f));
}
std::vector<std::shared_ptr<subdevice_model>> subdevices;
std::map<rs2_stream, stream_model> streams;
bool fullscreen = false;
bool metadata_supported = false;
rs2_stream selected_stream = RS2_STREAM_ANY;
private:
std::map<rs2_stream, rect> get_interpolated_layout(const std::map<rs2_stream, rect>& l)
{
using namespace std::chrono;
auto now = high_resolution_clock::now();
if (l != _layout) // detect layout change
{
_transition_start_time = now;
_old_layout = _layout;
_layout = l;
}
//if (_old_layout.size() == 0 && l.size() == 1) return l;
auto diff = now - _transition_start_time;
auto ms = duration_cast<milliseconds>(diff).count();
auto t = smoothstep(static_cast<float>(ms), 0, 100);
std::map<rs2_stream, rect> results;
for (auto&& kvp : l)
{
auto stream = kvp.first;
if (_old_layout.find(stream) == _old_layout.end())
{
_old_layout[stream] = _layout[stream].center();
}
results[stream] = _old_layout[stream].lerp(t, _layout[stream]);
}
return results;
}
streams_layout _layout;
streams_layout _old_layout;
std::chrono::high_resolution_clock::time_point _transition_start_time;
};
struct user_data
{
GLFWwindow* curr_window = nullptr;
mouse_info* mouse = nullptr;
};
struct notification_data
{
notification_data( std::string description,
double timestamp,
rs2_log_severity severity,
rs2_notification_category category)
: _description(description),
_timestamp(timestamp),
_severity(severity),
_category(category){}
rs2_notification_category get_category() const
{
return _category;
}
std::string get_description() const
{
return _description;
}
double get_timestamp() const
{
return _timestamp;
}
rs2_log_severity get_severity() const
{
return _severity;
}
std::string _description;
double _timestamp;
rs2_log_severity _severity;
rs2_notification_category _category;
};
struct notification_model
{
static const int MAX_LIFETIME_MS = 10000;
notification_model()
{
message = "";
}
notification_model(const notification_data& n)
{
message = n.get_description();
timestamp = n.get_timestamp();
severity = n.get_severity();
created_time = std::chrono::high_resolution_clock::now();
}
int height = 60;
int index;
std::string message;
double timestamp;
rs2_log_severity severity;
std::chrono::high_resolution_clock::time_point created_time;
// TODO: Add more info
double get_age_in_ms()
{
auto age = std::chrono::high_resolution_clock::now() - created_time;
return std::chrono::duration_cast<std::chrono::milliseconds>(age).count();
}
void draw(int w, int y, notification_model& selected)
{
auto flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse;
auto ms = get_age_in_ms() / MAX_LIFETIME_MS;
auto t = smoothstep(static_cast<float>(ms), 0.7f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.3f, 0, 0, 1 - t });
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.5f, 0.2f, 0.2f, 1 - t });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.6f, 0.2f, 0.2f, 1 - t });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 - t });
auto lines = std::count(message.begin(), message.end(), '\n')+1;
ImGui::SetNextWindowPos({ float(w - 430), float(y) });
ImGui::SetNextWindowSize({ float(500), float(lines*50) });
height = lines*50 +10;
std::string label = to_string() << "Hardware Notification #" << index;
ImGui::Begin(label.c_str(), nullptr, flags);
ImGui::Text("%s", message.c_str());
if(lines == 1)
ImGui::SameLine();
ImGui::Text("(...)");
if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered())
{
selected = *this;
}
ImGui::End();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
}
};
struct notifications_model
{
std::vector<notification_model> pending_notifications;
int index = 1;
const int MAX_SIZE = 6;
std::mutex m;
void add_notification(const notification_data& n)
{
std::lock_guard<std::mutex> lock(m); // need to protect the pending_notifications queue because the insertion of notifications
// done from the notifications callback and proccesing and removing of old notifications done from the main thread
notification_model m(n);
m.index = index++;
pending_notifications.push_back(m);
if (pending_notifications.size() > MAX_SIZE)
pending_notifications.erase(pending_notifications.begin());
}
void draw(int w, int h, notification_model& selected)
{
std::lock_guard<std::mutex> lock(m);
if (pending_notifications.size() > 0)
{
// loop over all notifications, remove "old" ones
pending_notifications.erase(std::remove_if(std::begin(pending_notifications),
std::end(pending_notifications),
[&](notification_model& n)
{
return (n.get_age_in_ms() > notification_model::MAX_LIFETIME_MS);
}), end(pending_notifications));
int idx = 0;
auto height = 30;
for (auto& noti : pending_notifications)
{
noti.draw(w, height, selected);
height += noti.height;
idx++;
}
}
auto flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoTitleBar;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::Begin("Notification parent window", nullptr, flags);
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0.1f, 0, 0, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBg, { 0.3f, 0.1f, 0.1f, 1 });
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, { 0.5f, 0.1f, 0.1f, 1 });
ImGui::PushStyleColor(ImGuiCol_Text, { 1, 1, 1, 1 });
if (selected.message != "")
ImGui::OpenPopup("Notification from Hardware");
if (ImGui::BeginPopupModal("Notification from Hardware", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("Received the following notification:");
std::stringstream s;
s<<"Timestamp: "<<std::fixed<<selected.timestamp<<"\n"<<"Severity: "<<selected.severity<<"\nDescription: "<<const_cast<char*>(selected.message.c_str());
ImGui::InputTextMultiline("notification", const_cast<char*>(s.str().c_str()),
selected.message.size() + 1, { 500,100 }, ImGuiInputTextFlags_AutoSelectAll);
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
selected.message = "";
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::End();
ImGui::PopStyleColor();
}
};
std::vector<std::string> get_device_info(const device& dev)
{
std::vector<std::string> res;
for (auto i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = static_cast<rs2_camera_info>(i);
if (dev.supports(info))
{
auto value = dev.get_camera_info(info);
res.push_back(value);
}
}
return res;
}
std::string get_device_name(device& dev)
{
// retrieve device name
std::string name = (dev.supports(RS2_CAMERA_INFO_DEVICE_NAME))? dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_NAME):"Unknown";
// retrieve device serial number
std::string serial = (dev.supports(RS2_CAMERA_INFO_DEVICE_SERIAL_NUMBER))? dev.get_camera_info(RS2_CAMERA_INFO_DEVICE_SERIAL_NUMBER):"Unknown";
// retrieve device module name
std::string module = (dev.supports(RS2_CAMERA_INFO_MODULE_NAME))? dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME):"Unknown";
std::stringstream s;
s<< std::setw(25)<<std::left<< name << " " <<std::setw(10)<<std::left<< module<<" Sn#" << serial;
return s.str(); // push name and sn to list
}
std::vector<std::string> get_devices_names(const device_list& list)
{
std::vector<std::string> device_names;
for (uint32_t i = 0; i < list.size(); i++)
{
try
{
auto dev = list[i];
device_names.push_back(get_device_name(dev)); // push name and sn to list
}
catch (...)
{
device_names.push_back(to_string() << "Unknown Device #" << i);
}
}
return device_names;
}
int find_device_index(const device_list& list ,std::vector<std::string> device_info)
{
std::vector<std::vector<std::string>> devices_info;
for (auto l:list)
{
devices_info.push_back(get_device_info(l));
}
auto it = std::find(devices_info.begin(),devices_info.end(), device_info);
return std::distance(devices_info.begin(), it);
}
int main(int, char**) try
{
// activate logging to console
log_to_console(RS2_LOG_SEVERITY_WARN);
// Init GUI
if (!glfwInit())
exit(1);
// Create GUI Windows
auto window = glfwCreateWindow(1280, 720, "librealsense - config-ui", nullptr, nullptr);
glfwMakeContextCurrent(window);
ImGui_ImplGlfw_Init(window, true);
ImVec4 clear_color = ImColor(10, 0, 0);
// Create RealSense Context
context ctx;
auto refresh_device_list = true;
auto device_index = 0;
std::vector<std::string> device_names;
std::vector<const char*> device_names_chars;
notifications_model not_model;
std::string error_message = "";
notification_model selected_notification;
// Initialize list with each device name and serial number
std::string label;
mouse_info mouse;
user_data data;
data.curr_window = window;
data.mouse = &mouse;
glfwSetWindowUserPointer(window, &data);
glfwSetCursorPosCallback(window, [](GLFWwindow * w, double cx, double cy)
{
reinterpret_cast<user_data *>(glfwGetWindowUserPointer(w))->mouse->cursor = { (float)cx, (float)cy };
});
glfwSetMouseButtonCallback(window, [](GLFWwindow * w, int button, int action, int mods)
{
auto data = reinterpret_cast<user_data *>(glfwGetWindowUserPointer(w));
data->mouse->mouse_down = action != GLFW_RELEASE;
});
auto last_time_point = std::chrono::high_resolution_clock::now();
device dev;
device_model model;
device_list list;
device_list new_list;
std::vector<std::string> active_device_info;
auto dev_exist = false;
auto hw_reset_enable = true;
std::vector<device> devs;
std::mutex m;
auto timestamp = std::chrono::duration<double, std::milli>(std::chrono::system_clock::now().time_since_epoch()).count();
ctx.set_devices_changed_callback([&](event_information& info)
{
timestamp = std::chrono::duration<double, std::milli>(std::chrono::system_clock::now().time_since_epoch()).count();
std::lock_guard<std::mutex> lock(m);
for(auto dev:devs)
{
if(info.was_removed(dev))
{
not_model.add_notification({get_device_name(dev) + "\ndisconnected",
timestamp,
RS2_LOG_SEVERITY_INFO,
RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR});
}
}
if(info.was_removed(dev))
{
dev_exist = false;
}
for(auto dev:info.get_new_devices())
{
not_model.add_notification({get_device_name(dev) + "\nconnected",
timestamp,
RS2_LOG_SEVERITY_INFO,
RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR});
}
refresh_device_list = true;
});
// Closing the window
while (!glfwWindowShouldClose(window))
{
{
std::lock_guard<std::mutex> lock(m);
if(refresh_device_list)
{
refresh_device_list = false;
try
{
list = ctx.query_devices();
device_names = get_devices_names(list);
device_names_chars = get_string_pointers(device_names);
for(auto dev: devs)
{
dev = nullptr;
}
devs.clear();
if( !dev_exist)
{
device_index = 0;
dev = nullptr;
model.reset();
if(list.size()>0)
{
dev = list[device_index]; // Access first device
model = device_model(dev, error_message); // Initialize device model
active_device_info = get_device_info(dev);
dev_exist = true;
}
}
else
{
device_index = find_device_index(list, active_device_info);
}
for (auto&& sub : list)
{
devs.push_back(sub);
sub.set_notifications_callback([&](const notification& n)
{
not_model.add_notification({n.get_description(), n.get_timestamp(), n.get_severity(), n.get_category()});
});
}
}
catch (const error& e)
{
error_message = error_to_string(e);
}
catch (const std::exception& e)
{
error_message = e.what();
}
hw_reset_enable = true;
}
}
bool update_read_only_options = false;
auto now = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration<double, std::milli>(now - last_time_point).count();
if (duration >= 5000)
{
update_read_only_options = true;
last_time_point = now;
}
glfwPollEvents();
int w, h;
glfwGetWindowSize(window, &w, &h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ImGui_ImplGlfw_NewFrame();
// Flags for pop-up window - no window resize, move or collaps
auto flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse;
const float panel_size = 320;
// Set window position and size
ImGui::SetNextWindowPos({ 0, 0 });
ImGui::SetNextWindowSize({ panel_size, static_cast<float>(h) });
// *********************
// Creating window menus
// *********************
ImGui::Begin("Control Panel", nullptr, flags);
rs2_error* e = nullptr;
label = to_string() << "VERSION: " << api_version_to_string(rs2_get_api_version(&e));
ImGui::Text("%s", label.c_str());
if (list.size()==0 )
{
ImGui::Text("No device detected.");
}
// Device Details Menu - Elaborate details on connected devices
if (list.size()>0 && ImGui::CollapsingHeader("Device Details", nullptr, true, true))
{
// Draw a combo-box with the list of connected devices
ImGui::PushItemWidth(-1);
auto new_index = device_index;
if (ImGui::Combo("", &new_index, device_names_chars.data(),
static_cast<int>(device_names.size())))
{
for (auto&& sub : model.subdevices)
{
if (sub->streaming)
sub->stop();
}
try
{
dev = list[new_index];
device_index = new_index;
model = device_model(dev, error_message);
active_device_info = get_device_info(dev);
}
catch (const error& e)
{
error_message = error_to_string(e);
}
catch (const std::exception& e)
{
error_message = e.what();
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip(device_names_chars[new_index]);
}
ImGui::PopItemWidth();
// Show all device details - name, module name, serial number, FW version and location
for (auto i = 0; i < RS2_CAMERA_INFO_COUNT; i++)
{
auto info = static_cast<rs2_camera_info>(i);
if (dev.supports(info))
{
// retrieve info property
std::stringstream ss;
ss << rs2_camera_info_to_string(info) << ":";
auto line = ss.str();
ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 1.0f, 1.0f, 0.5f });
ImGui::Text("%s", line.c_str());
ImGui::PopStyleColor();
// retrieve property value
ImGui::SameLine();
auto value = dev.get_camera_info(info);
ImGui::Text("%s", value);
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", value);
}
}
}
}
// Streaming Menu - Allow user to play different streams
if (list.size()>0 && ImGui::CollapsingHeader("Streaming", nullptr, true, true))
{
if (model.subdevices.size() > 1)
{
try
{
const float stream_all_button_width = 290;
const float stream_all_button_height = 0;
auto anything_stream = false;
for (auto&& sub : model.subdevices)
{
if (sub->streaming) anything_stream = true;
}
if (!anything_stream)
{
label = to_string() << "Start All";
if (ImGui::Button(label.c_str(), { stream_all_button_width, stream_all_button_height }))
{
for (auto&& sub : model.subdevices)
{
if (sub->is_selected_combination_supported())
{
auto profiles = sub->get_selected_profiles();
sub->play(profiles);
for (auto&& profile : profiles)
{
model.streams[profile.stream].dev = sub;
}
}
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Start streaming from all subdevices");
}
}
else
{
label = to_string() << "Stop All";
if (ImGui::Button(label.c_str(), { stream_all_button_width, stream_all_button_height }))
{
for (auto&& sub : model.subdevices)
{
if (sub->streaming) sub->stop();
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Stop streaming from all subdevices");
}
}
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
}
// Draw menu foreach subdevice with its properties
for (auto&& sub : model.subdevices)
{
label = to_string() << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (ImGui::CollapsingHeader(label.c_str(), nullptr, true, true))
{
sub->draw_stream_selection();
try
{
if (!sub->streaming)
{
label = to_string() << "Start " << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (sub->is_selected_combination_supported())
{
if (ImGui::Button(label.c_str()))
{
auto profiles = sub->get_selected_profiles();
sub->play(profiles);
for (auto&& profile : profiles)
{
model.streams[profile.stream].dev = sub;
}
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Start streaming data from selected sub-device");
}
}
else
{
ImGui::TextDisabled("%s", label.c_str());
}
}
else
{
label = to_string() << "Stop " << sub->dev.get_camera_info(RS2_CAMERA_INFO_MODULE_NAME);
if (ImGui::Button(label.c_str()))
{
sub->stop();
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Stop streaming data from selected sub-device");
}
}
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
for (auto i = 0; i < RS2_OPTION_COUNT; i++)
{
auto opt = static_cast<rs2_option>(i);
auto&& metadata = sub->options_metadata[opt];
if (update_read_only_options)
{
metadata.update_supported(error_message);
if (metadata.supported && sub->streaming)
{
metadata.update_read_only(error_message);
if (metadata.read_only)
{
metadata.update_all(error_message);
}
}
}
metadata.draw(error_message);
}
}
ImGui::Text("\n");
}
}
if (list.size()>0 && ImGui::CollapsingHeader("Hardware Commands", nullptr, true))
{
label = to_string() << "Hardware Reset";
const float hardware_reset_button_width = 290;
const float hardware_reset_button_height = 0;
if (ImGui::ButtonEx(label.c_str(), { hardware_reset_button_width, hardware_reset_button_height }, hw_reset_enable?0:ImGuiButtonFlags_Disabled))
{
try
{
dev.hardware_reset();
}
catch(const error& e)
{
error_message = error_to_string(e);
}
catch(const std::exception& e)
{
error_message = e.what();
}
}
}
ImGui::Text("\n\n\n\n\n\n\n");
for (auto&& sub : model.subdevices)
{
sub->update(error_message);
}
if (error_message != "")
ImGui::OpenPopup("Oops, something went wrong!");
if (ImGui::BeginPopupModal("Oops, something went wrong!", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("RealSense error calling:");
ImGui::InputTextMultiline("error", const_cast<char*>(error_message.c_str()),
error_message.size() + 1, { 500,100 }, ImGuiInputTextFlags_AutoSelectAll);
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
error_message = "";
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::End();
not_model.draw(w, h, selected_notification);
// Fetch frames from queue
for (auto&& sub : model.subdevices)
{
for (auto& queue : sub->queues)
{
try
{
frame f;
if (queue->poll_for_frame(&f))
{
model.upload_frame(std::move(f));
}
}
catch(const error& e)
{
error_message = error_to_string(e);
sub->stop();
}
catch(const std::exception& e)
{
error_message = e.what();
sub->stop();
}
}
}
// Rendering
glViewport(0, 0,
static_cast<int>(ImGui::GetIO().DisplaySize.x),
static_cast<int>(ImGui::GetIO().DisplaySize.y));
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
glfwGetWindowSize(window, &w, &h);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, +1);
auto layout = model.calc_layout(panel_size, 0.f, w - panel_size, (float)h);
for (auto &&kvp : layout)
{
auto&& view_rect = kvp.second;
auto stream = kvp.first;
auto&& stream_size = model.streams[stream].size;
auto stream_rect = view_rect.adjust_ratio(stream_size);
model.streams[stream].show_frame(stream_rect, mouse, error_message);
flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoTitleBar;
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::SetNextWindowPos({ stream_rect.x, stream_rect.y });
ImGui::SetNextWindowSize({ stream_rect.w, stream_rect.h });
label = to_string() << "Stream of " << rs2_stream_to_string(stream);
ImGui::Begin(label.c_str(), nullptr, flags);
label = to_string() << rs2_stream_to_string(stream) << " "
<< stream_size.x << "x" << stream_size.y << ", "
<< rs2_format_to_string(model.streams[stream].format) << ", "
<< "Frame# " << model.streams[stream].frame_number << ", "
<< "FPS:";
ImGui::Text("%s", label.c_str());
ImGui::SameLine();
label = to_string() << std::setprecision(2) << std::fixed << model.streams[stream].fps.get_fps();
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("FPS is calculated based on timestamps and not viewer time");
}
ImGui::SameLine((int)ImGui::GetWindowWidth() - 30);
if (!layout.empty() && !model.fullscreen)
{
if (ImGui::Button("[+]", { 26, 20 }))
{
model.fullscreen = true;
model.selected_stream = stream;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Maximize stream to full-screen");
}
}
else if (model.fullscreen)
{
if (ImGui::Button("[-]", { 26, 20 }))
{
model.fullscreen = false;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Minimize stream to tile-view");
}
}
if (!layout.empty())
{
if (model.streams[stream].roi_supported )
{
ImGui::SameLine((int)ImGui::GetWindowWidth() - 160);
ImGui::Checkbox("[ROI]", &model.streams[stream].roi_checked);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Auto Exposure Region-of-Interest Selection");
}
else
model.streams[stream].roi_checked = false;
}
// Control metadata overlay widget
ImGui::SameLine((int)ImGui::GetWindowWidth() - 90); // metadata GUI hint
if (!layout.empty())
{
ImGui::Checkbox("[MD]", &model.streams[stream].metadata_displayed);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Show per-frame metadata");
}
label = to_string() << "Timestamp: " << std::fixed << std::setprecision(3) << model.streams[stream].timestamp
<< ", Domain:";
ImGui::Text("%s", label.c_str());
ImGui::SameLine();
auto domain = model.streams[stream].timestamp_domain;
label = to_string() << rs2_timestamp_domain_to_string(domain);
if (domain == RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME)
{
ImGui::PushStyleColor(ImGuiCol_Text, { 1.0f, 0.0f, 0.0f, 1.0f });
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Hardware Timestamp unavailable! This is often an indication of inproperly applied Kernel patch.\nPlease refer to installation.md for mode information");
}
ImGui::PopStyleColor();
}
else
{
ImGui::Text("%s", label.c_str());
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Specifies the clock-domain for the timestamp (hardware-clock / system-time)");
}
}
ImGui::End();
ImGui::PopStyleColor();
if (stream_rect.contains(mouse.cursor))
{
ImGui::PushStyleColor(ImGuiCol_WindowBg, { 0, 0, 0, 0 });
ImGui::SetNextWindowPos({ stream_rect.x, stream_rect.y + stream_rect.h - 25 });
ImGui::SetNextWindowSize({ stream_rect.w, 25 });
label = to_string() << "Footer for stream of " << rs2_stream_to_string(stream);
ImGui::Begin(label.c_str(), nullptr, flags);
std::stringstream ss;
auto x = ((mouse.cursor.x - stream_rect.x) / stream_rect.w) * stream_size.x;
auto y = ((mouse.cursor.y - stream_rect.y) / stream_rect.h) * stream_size.y;
ss << std::fixed << std::setprecision(0) << x << ", " << y;
float val;
if (model.streams[stream].texture->try_pick(x, y, &val))
{
ss << ", *p: 0x" << std::hex << val;
if (stream == RS2_STREAM_DEPTH && val > 0)
{
auto meters = (val * model.streams[stream].dev->depth_units);
ss << std::dec << ", ~"
<< std::setprecision(2) << meters << " meters";
}
}
label = ss.str();
ImGui::Text("%s", label.c_str());
ImGui::End();
ImGui::PopStyleColor();
}
}
// Metadata overlay windows shall be drawn after textures to preserve z-buffer functionality
for (auto &&kvp : layout)
{
if (model.streams[kvp.first].metadata_displayed)
model.streams[kvp.first].show_metadata(mouse);
}
ImGui::Render();
glfwSwapBuffers(window);
}
// Stop all subdevices
for (auto&& sub : model.subdevices)
{
if (sub->streaming)
sub->stop();
}
// Cleanup
ImGui_ImplGlfw_Shutdown();
glfwTerminate();
return EXIT_SUCCESS;
}
catch (const error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
|
#include "TensorData.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <SmurffCpp/ConstVMatrixExprIterator.hpp>
using namespace Eigen;
using namespace smurff;
//convert array of coordinates to [nnz x nmodes] matrix
MatrixXui32 toMatrixNew(const std::vector<std::uint32_t>& columns, std::uint64_t nnz, std::uint64_t nmodes)
{
MatrixXui32 idx(nnz, nmodes);
for (std::uint64_t row = 0; row < nnz; row++)
{
for (std::uint64_t col = 0; col < nmodes; col++)
{
idx(row, col) = columns[col * nnz + row];
}
}
return idx;
}
TensorData::TensorData(const smurff::TensorConfig& tc)
: m_dims(tc.getDims()),
m_nnz(tc.getNNZ()),
m_Y(std::make_shared<std::vector<std::shared_ptr<SparseMode> > >())
{
//combine coordinates into [nnz x nmodes] matrix
MatrixXui32 idx = toMatrixNew(tc.getColumns(), tc.getNNZ(), tc.getNModes());
for (std::uint64_t mode = 0; mode < tc.getNModes(); mode++)
{
m_Y->push_back(std::make_shared<SparseMode>(idx, tc.getValues(), mode, m_dims[mode]));
}
std::uint64_t totalSize = std::accumulate(m_dims.begin(), m_dims.end(), (std::uint64_t)1, std::multiplies<std::uint64_t>());
this->name = totalSize == m_nnz ? "TensorData [fully known]" : "TensorData [with NAs]";
}
std::shared_ptr<SparseMode> TensorData::Y(std::uint64_t mode) const
{
return m_Y->operator[](mode);
}
void TensorData::init_pre()
{
//no logic here
}
double TensorData::sum() const
{
double esum = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:esum)
for(std::uint64_t n = 0; n < sview->getNPlanes(); n++) //go through each hyperplane
{
for(std::uint64_t j = sview->beginPlane(n); j < sview->endPlane(n); j++) //go through each item in the plane
{
esum += sview->getValues()[j];
}
}
return esum;
}
std::uint64_t TensorData::nmode() const
{
return m_dims.size();
}
std::uint64_t TensorData::nnz() const
{
return m_nnz;
}
std::uint64_t TensorData::nna() const
{
return size() - this->nnz();
}
PVec<> TensorData::dim() const
{
std::vector<int> pvec_dims;
for(auto& d : m_dims)
pvec_dims.push_back(static_cast<int>(d));
return PVec<>(pvec_dims);
}
double TensorData::train_rmse(const SubModel& model) const
{
return std::sqrt(sumsq(model) / this->nnz());
}
//d is an index of column in U matrix
//this function selects d'th hyperplane from mode`th SparseMode
//it does j multiplications
//where each multiplication is a cwiseProduct of columns from each V matrix
void TensorData::getMuLambda(const SubModel& model, uint32_t mode, int d, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) const
{
std::shared_ptr<SparseMode> sview = Y(mode); //get tensor rotation for mode
auto V0 = model.CVbegin(mode); //get first V matrix
for (std::uint64_t j = sview->beginPlane(d); j < sview->endPlane(d); j++) //go through hyperplane in tensor rotation
{
VectorXd col = (*V0).col(sview->getIndices()(j, 0)); //create a copy of m'th column from V (m = 0)
auto V = model.CVbegin(mode); //get V matrices for mode
for (std::uint64_t m = 1; m < sview->getNCoords(); m++) //go through each coordinate of value
{
++V; //inc iterator prior to access since we are starting from m = 1
col.noalias() = col.cwiseProduct((*V).col(sview->getIndices()(j, m))); //multiply by m'th column from V
}
MM.triangularView<Eigen::Lower>() += noise()->getAlpha() * col * col.transpose(); // MM = MM + (col * colT) * alpha (where col = product of columns in each V)
auto pos = sview->pos(d, j);
double noisy_val = noise()->sample(model, pos, sview->getValues()[j]);
rr.noalias() += col * noisy_val; // rr = rr + (col * value) * alpha (where value = j'th value of Y)
}
}
void TensorData::update_pnm(const SubModel& model, uint32_t mode)
{
//do not need to cache VV here
}
double TensorData::sumsq(const SubModel& model) const
{
double sumsq = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)
for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
{
for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
{
auto item = sview->item(h, n);
double pred = model.predict(item.first);
sumsq += std::pow(pred - item.second, 2);
}
}
return sumsq;
}
double TensorData::var_total() const
{
double cwise_mean = this->sum() / this->nnz();
double se = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:se)
for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
{
for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
{
auto item = sview->item(h, n);
se += std::pow(item.second - cwise_mean, 2);
}
}
double var = se / this->nnz();
if (var <= 0.0 || std::isnan(var))
{
// if var cannot be computed using 1.0
var = 1.0;
}
return var;
}
std::pair<PVec<>, double> TensorData::item(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
if(mode >= m_Y->size())
{
THROWERROR("Invalid mode");
}
return m_Y->at(mode)->item(hyperplane, item);
}
PVec<> TensorData::pos(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
if(mode >= m_Y->size())
{
THROWERROR("Invalid mode");
}
return m_Y->at(mode)->pos(hyperplane, item);
}
std::ostream& TensorData::info(std::ostream& os, std::string indent)
{
Data::info(os, indent);
double train_fill_rate = 100. * nnz() / size();
os << indent << "Size: " << nnz() << " [";
for (std::size_t i = 0; i < m_dims.size() - 1; i++)
{
os << m_dims[i] << " x ";
}
os << m_dims.back() << "] (" << std::fixed << std::setprecision(2) << train_fill_rate << "%)\n";
return os;
}
fix bug in TensorData in getMuLambda.
previously - only lower triangle of MM matrix was calculated.
#include "TensorData.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <SmurffCpp/ConstVMatrixExprIterator.hpp>
using namespace Eigen;
using namespace smurff;
//convert array of coordinates to [nnz x nmodes] matrix
MatrixXui32 toMatrixNew(const std::vector<std::uint32_t>& columns, std::uint64_t nnz, std::uint64_t nmodes)
{
MatrixXui32 idx(nnz, nmodes);
for (std::uint64_t row = 0; row < nnz; row++)
{
for (std::uint64_t col = 0; col < nmodes; col++)
{
idx(row, col) = columns[col * nnz + row];
}
}
return idx;
}
TensorData::TensorData(const smurff::TensorConfig& tc)
: m_dims(tc.getDims()),
m_nnz(tc.getNNZ()),
m_Y(std::make_shared<std::vector<std::shared_ptr<SparseMode> > >())
{
//combine coordinates into [nnz x nmodes] matrix
MatrixXui32 idx = toMatrixNew(tc.getColumns(), tc.getNNZ(), tc.getNModes());
for (std::uint64_t mode = 0; mode < tc.getNModes(); mode++)
{
m_Y->push_back(std::make_shared<SparseMode>(idx, tc.getValues(), mode, m_dims[mode]));
}
std::uint64_t totalSize = std::accumulate(m_dims.begin(), m_dims.end(), (std::uint64_t)1, std::multiplies<std::uint64_t>());
this->name = totalSize == m_nnz ? "TensorData [fully known]" : "TensorData [with NAs]";
}
std::shared_ptr<SparseMode> TensorData::Y(std::uint64_t mode) const
{
return m_Y->operator[](mode);
}
void TensorData::init_pre()
{
//no logic here
}
double TensorData::sum() const
{
double esum = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:esum)
for(std::uint64_t n = 0; n < sview->getNPlanes(); n++) //go through each hyperplane
{
for(std::uint64_t j = sview->beginPlane(n); j < sview->endPlane(n); j++) //go through each item in the plane
{
esum += sview->getValues()[j];
}
}
return esum;
}
std::uint64_t TensorData::nmode() const
{
return m_dims.size();
}
std::uint64_t TensorData::nnz() const
{
return m_nnz;
}
std::uint64_t TensorData::nna() const
{
return size() - this->nnz();
}
PVec<> TensorData::dim() const
{
std::vector<int> pvec_dims;
for(auto& d : m_dims)
pvec_dims.push_back(static_cast<int>(d));
return PVec<>(pvec_dims);
}
double TensorData::train_rmse(const SubModel& model) const
{
return std::sqrt(sumsq(model) / this->nnz());
}
//d is an index of column in U matrix
//this function selects d'th hyperplane from mode`th SparseMode
//it does j multiplications
//where each multiplication is a cwiseProduct of columns from each V matrix
void TensorData::getMuLambda(const SubModel& model, uint32_t mode, int d, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) const
{
std::shared_ptr<SparseMode> sview = Y(mode); //get tensor rotation for mode
auto V0 = model.CVbegin(mode); //get first V matrix
for (std::uint64_t j = sview->beginPlane(d); j < sview->endPlane(d); j++) //go through hyperplane in tensor rotation
{
VectorXd col = (*V0).col(sview->getIndices()(j, 0)); //create a copy of m'th column from V (m = 0)
auto V = model.CVbegin(mode); //get V matrices for mode
for (std::uint64_t m = 1; m < sview->getNCoords(); m++) //go through each coordinate of value
{
++V; //inc iterator prior to access since we are starting from m = 1
col.noalias() = col.cwiseProduct((*V).col(sview->getIndices()(j, m))); //multiply by m'th column from V
}
MM.triangularView<Eigen::Lower>() += noise()->getAlpha() * col * col.transpose(); // MM = MM + (col * colT) * alpha (where col = product of columns in each V)
auto pos = sview->pos(d, j);
double noisy_val = noise()->sample(model, pos, sview->getValues()[j]);
rr.noalias() += col * noisy_val; // rr = rr + (col * value) * alpha (where value = j'th value of Y)
}
MM.triangularView<Upper>() = MM.transpose();
}
void TensorData::update_pnm(const SubModel& model, uint32_t mode)
{
//do not need to cache VV here
}
double TensorData::sumsq(const SubModel& model) const
{
double sumsq = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)
for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
{
for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
{
auto item = sview->item(h, n);
double pred = model.predict(item.first);
sumsq += std::pow(pred - item.second, 2);
}
}
return sumsq;
}
double TensorData::var_total() const
{
double cwise_mean = this->sum() / this->nnz();
double se = 0.0;
std::shared_ptr<SparseMode> sview = Y(0);
#pragma omp parallel for schedule(dynamic, 4) reduction(+:se)
for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
{
for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
{
auto item = sview->item(h, n);
se += std::pow(item.second - cwise_mean, 2);
}
}
double var = se / this->nnz();
if (var <= 0.0 || std::isnan(var))
{
// if var cannot be computed using 1.0
var = 1.0;
}
return var;
}
std::pair<PVec<>, double> TensorData::item(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
if(mode >= m_Y->size())
{
THROWERROR("Invalid mode");
}
return m_Y->at(mode)->item(hyperplane, item);
}
PVec<> TensorData::pos(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
if(mode >= m_Y->size())
{
THROWERROR("Invalid mode");
}
return m_Y->at(mode)->pos(hyperplane, item);
}
std::ostream& TensorData::info(std::ostream& os, std::string indent)
{
Data::info(os, indent);
double train_fill_rate = 100. * nnz() / size();
os << indent << "Size: " << nnz() << " [";
for (std::size_t i = 0; i < m_dims.size() - 1; i++)
{
os << m_dims[i] << " x ";
}
os << m_dims.back() << "] (" << std::fixed << std::setprecision(2) << train_fill_rate << "%)\n";
return os;
}
|
#include <KrisLibrary/Logger.h>
#include "PointCloud.h"
#include <iostream>
#include <KrisLibrary/math3d/AABB3D.h>
#include <KrisLibrary/math3d/rotation.h>
#include <KrisLibrary/utils/SimpleParser.h>
#include <KrisLibrary/utils/stringutils.h>
#include <KrisLibrary/utils/ioutils.h>
#include <KrisLibrary/Timer.h>
#include <errors.h>
#include <sstream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace Meshing;
const static Real one_over_255 = 1.0/255.0;
string IntToStr(int i)
{
stringstream ss;
ss<<i;
return ss.str();
}
class PCLParser : public SimpleParser
{
public:
enum {NORMAL, READING_FIELDS, READING_TYPES, READING_SIZES, READING_COUNTS };
PCLParser(istream& in,PointCloud3D& _pc)
:SimpleParser(in),pc(_pc),state(NORMAL),numPoints(-1)
{}
virtual bool IsComment(char c) const { return c=='#'; }
virtual bool IsToken(char c) const { return !IsSpace(c) && !IsComment(c); }
virtual bool IsPunct(char c) const { return !IsSpace(c) && !IsComment(c) && !IsToken(c); }
virtual Result InputToken(const string& word) {
if(state == READING_FIELDS) {
pc.propertyNames.push_back(word);
}
else if(state == READING_TYPES) {
if(word != "F" && word != "U" && word != "I") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD TYPE "<<word.c_str());
return Error;
}
types.push_back(word);
}
else if(state == READING_COUNTS) {
if(!IsValidInteger(word.c_str())) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD COUNT string "<<word.c_str()<<", must be integer");
return Error;
}
stringstream ss(word);
int count;
ss>>count;
if(ss.bad() || count <= 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD COUNT "<<word.c_str()<<", must be a positive integer");
return Error;
}
counts.push_back(count);
}
else if(state == READING_SIZES) {
if(!IsValidInteger(word.c_str())) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD SIZE string "<<word.c_str()<<", must be integer");
return Error;
}
stringstream ss(word);
int size;
ss>>size;
if(size <= 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD SIZE "<<word.c_str()<<" must be positive");
return Error;
}
sizes.push_back(size);
}
else {
if(word == "POINTS") {
string points;
ReadLine(points);
stringstream ss(points);
ss>>numPoints;
if(!ss) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Unable to read integer POINTS");
return Error;
}
}
else if(word == "FIELDS") {
state = READING_FIELDS;
}
else if(word == "COUNT") {
state = READING_COUNTS;
}
else if(word == "TYPE") {
state = READING_TYPES;
}
else if(word == "SIZE") {
state = READING_SIZES;
}
else if(word == "DATA") {
ConvertToSingleCounts();
/*
cout<<"property names, type, size"<<endl;
for(size_t i=0;i<pc.propertyNames.size();i++)
cout<<pc.propertyNames[i]<<", "<<types[i]<<", "<<sizes[i]<<endl;
*/
string datatype;
if(!ReadLine(datatype)) return Error;
datatype = Strip(datatype);
if(datatype == "binary") {
//pull in the endline
int c = in.get();
if(c != '\n') {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA binary not followed immediately by endline");
return Error;
}
//read in binary data
if(numPoints < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA specified before POINTS element");
return Error;
}
if(sizes.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid number of SIZE elements");
return Error;
}
if(types.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid number of TYPE elements");
return Error;
}
int pointsize = 0;
for(size_t i=0;i<sizes.size();i++)
pointsize += sizes[i];
streampos fcur = in.tellg();
in.seekg( 0, std::ios::end );
streampos fsize = in.tellg() - fcur;
in.seekg( fcur );
if(fsize-streampos(pointsize*numPoints) != 0) {
cout<<"Size of point "<<pointsize<<" x "<<numPoints<<" points"<<endl;
cout<<"Remaining bytes left: "<<fsize<<", we'll probably have "<<fsize-streampos(pointsize*numPoints)<<" left?"<<endl;
for(int i=0;i<int(fsize)-pointsize*numPoints;i++) {
if(in.peek() != 0) {
cout<<"Hmmm... what's this wasted space? stopped on "<<i<<endl;
}
in.get();
}
}
vector<char> buffer(pointsize);
for(int i=0;i<numPoints;i++) {
in.read(&buffer[0],pointsize);
if(!in) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Error reading data for point "<<i);
return Error;
}
//parse the point and add it
Vector v(pc.propertyNames.size());
int ofs = 0;
for(size_t j=0;j<sizes.size();j++) {
if(types[j] == "F") {
if(sizes[j] == 4) {
float f;
memcpy(&f,&buffer[ofs],sizes[j]);
v[j] = f;
/*
if(i % 10000 == 0)
printf("%s Buffer %x => float %f\n",pc.propertyNames[j].c_str(),*((unsigned int*)&buffer[ofs]),f);
*/
}
else if(sizes[j] == 8) {
double f;
memcpy(&f,&buffer[ofs],sizes[j]);
v[j] = f;
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid float size "<<sizes[j]);
return Error;
}
}
else if(types[j] == "U") {
if(sizes[j] > 4) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid unsigned int size "<<sizes[j]);
return Error;
}
unsigned i=0;
memcpy(&i,&buffer[ofs],sizes[j]);
v[j] = Real(i);
}
else if(types[j] == "I") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid int size "<<sizes[j]);
int i=0;
memcpy(&i,&buffer[ofs],sizes[j]);
v[j] = Real(i);
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid type "<<types[i].c_str());
return Error;
}
ofs += sizes[j];
}
pc.properties.push_back(v);
}
return Stop;
}
else if(datatype == "ascii") {
if(numPoints < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA specified before POINTS element");
return Error;
}
string line;
for(int i=0;i<numPoints;i++) {
int c = in.get();
assert(c=='\n' || c==EOF);
lineno++;
if(c==EOF) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Premature end of DATA element");
return Error;
}
if(!ReadLine(line)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Error reading point "<<i);
return Error;
}
vector<string> elements = Split(line," ");
if(elements.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA element "<<i<<" has length "<<elements.size()<<", but "<<pc.propertyNames.size());
return Error;
}
Vector v(elements.size());
for(size_t k=0;k<elements.size();k++) {
stringstream ss(elements[k]);
SafeInputFloat(ss,v[k]);
}
pc.properties.push_back(v);
}
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA is not spcified as ascii or binary");
return Error;
}
}
else {
string value;
if(!ReadLine(value)) return Error;
value = Strip(value);
if(word == "VERSION") {
if(value != "0.7" && value != ".7") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Warning, PCD version 0.7 expected, got \""<<value.c_str()<<"\"");
}
pc.settings["pcd_version"] = value;
}
else {
//LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: Read property \""<<word.c_str()<<"\" = \""<<pc.settings[word].c_str());
string key=word;
Lowercase(key);
pc.settings[key] = Strip(value);
}
}
}
return Continue;
}
virtual Result InputPunct(const string& punct) { return Continue; }
virtual Result InputEndLine()
{
if(state != NORMAL) state=NORMAL;
return Continue;
}
void ConvertToSingleCounts()
{
size_t i=0;
while(i < counts.size()) {
if(counts[i] > 1) {
int n=counts[i];
LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: converting element "<<pc.propertyNames[i]<<" into "<<counts[i]<<" sub-elements");
string basename = pc.propertyNames[i];
pc.propertyNames[i] = basename + '_' + IntToStr(0);
counts[i] = 1;
for(int j=1;j<n;j++) {
pc.propertyNames.insert(pc.propertyNames.begin()+i+1,basename + '_' + IntToStr(j));
types.insert(types.begin()+i+1,types[i]);
sizes.insert(sizes.begin()+i+1,sizes[i]);
counts.insert(counts.begin()+i+1,1);
}
i += n;
}
else
i++;
}
}
PointCloud3D& pc;
int state;
int numPoints;
//for binary data
vector<string> types;
vector<int> sizes;
vector<int> counts;
};
void PointCloud3D::Clear()
{
points.clear();
propertyNames.clear();
properties.clear();
settings.clear();
}
bool PointCloud3D::LoadPCL(const char* fn)
{
ifstream in(fn,ios::in);
if(!in) return false;
if(!LoadPCL(in)) return false;
settings["file"] = fn;
in.close();
return true;
}
bool PointCloud3D::SavePCL(const char* fn) const
{
ofstream out(fn,ios::out);
if(!out) return false;
if(!SavePCL(out)) return false;
out.close();
return true;
}
bool PointCloud3D::LoadPCL(istream& in)
{
PCLParser parser(in,*this);
if(!parser.Read()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Unable to parse PCD file");
return false;
}
int elemIndex[3] = {-1,-1,-1};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(elemIndex[0]<0 || elemIndex[1]<0 || elemIndex[2]<0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Warning, PCD file does not have x, y or z");
LOG4CXX_ERROR(KrisLibrary::logger()," Properties:");
for(size_t i=0;i<propertyNames.size();i++)
LOG4CXX_ERROR(KrisLibrary::logger()," \""<<propertyNames[i].c_str());
LOG4CXX_ERROR(KrisLibrary::logger(),"");
return true;
}
//HACK: for float RGB and RGBA elements, convert float bytes
//to integer via memory cast
Assert(propertyNames.size() == parser.types.size());
for(size_t k=0;k<propertyNames.size();k++) {
if(parser.types[k] == "F" && (propertyNames[k] == "rgb" || propertyNames[k] == "rgba")) {
bool docast = false;
for(size_t i=0;i<properties.size();i++) {
Vector& v = properties[i];
float f = float(v[k]);
if(f < 1.0 && f > 0.0) {
docast=true;
break;
}
}
if(docast) {
//LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud::LoadPCL: Warning, casting RGB colors to integers via direct memory cast");
for(size_t i=0;i<properties.size();i++) {
Vector& v = properties[i];
float f = float(v[k]);
int rgb = *((int*)&f);
v[k] = (Real)rgb;
}
}
}
}
//parse out the points
points.resize(properties.size());
for(size_t i=0;i<properties.size();i++) {
points[i].set(properties[i][elemIndex[0]],properties[i][elemIndex[1]],properties[i][elemIndex[2]]);
}
//LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: "<<points.size());
if(properties.size()==3 && elemIndex[0]==0 && elemIndex[1]==1 && elemIndex[2]==2) {
//x,y,z are the only properties, go ahead and take them out
propertyNames.resize(0);
properties.resize(0);
}
return true;
}
bool PointCloud3D::SavePCL(ostream& out) const
{
out<<"# .PCD v0.7 - Point Cloud Data file format"<<endl;
if(settings.find("pcd_version") != settings.end())
out<<"VERSION "<<settings.find("pcd_version")->second<<endl;
else
out<<"VERSION 0.7"<<endl;
bool addxyz = !HasXYZAsProperties();
out<<"FIELDS";
if(addxyz)
out<<" x y z";
for(size_t i=0;i<propertyNames.size();i++)
out<<" "<<propertyNames[i];
out;
out<<"TYPE";
if(addxyz)
out<<" F F F";
for(size_t i=0;i<propertyNames.size();i++)
out<<" F";
out;
if(!properties.empty())
out<<"POINTS "<<properties.size();
else
out<<"POINTS "<<points.size();
for(map<string,string>::const_iterator i=settings.begin();i!=settings.end();i++) {
if(i->first == "pcd_version" || i->first == "file") continue;
string key = i->first;
Uppercase(key);
out<<key<<" "<<i->second;
}
out<<"DATA ascii";
if(propertyNames.empty()) {
for(size_t i=0;i<points.size();i++)
out<<points[i];
}
else {
for(size_t i=0;i<properties.size();i++) {
if(addxyz)
out<<points[i]<<" ";
for(int j=0;j<properties[i].n;j++)
out<<properties[i][j]<<" ";
out;
}
}
return true;
}
void PointCloud3D::FromDepthImage(int w,int h,float wfov,float hfov,const std::vector<float>& depths,const std::vector<unsigned int>& rgb,float invalidDepth)
{
SetStructured(w,h);
Real xscale = Tan(wfov/2)*(2.0/w);
Real yscale = Tan(hfov/2)*(2.0/h);
Assert(depths.size()==points.size());
Real xc = Real(w)/2;
Real yc = Real(h)/2;
int k=0;
Real fi=0,fj=0;
for(int j=0;j<h;j++,fj+=1.0) {
fi = 0;
for(int i=0;i<w;i++,k++,fi+=1.0) {
if(depths[k] == invalidDepth)
points[k].setZero();
else {
Real x = (fi-xc)*xscale;
Real y = (fj-yc)*yscale;
points[k].x = depths[k]*x;
points[k].y = depths[k]*y;
points[k].z = depths[k];
}
}
}
if(!rgb.empty()) {
Assert(rgb.size()==depths.size());
propertyNames.resize(1);
propertyNames[0] = "rgb";
properties.resize(points.size());
for(size_t i=0;i<points.size();i++) {
properties[i].resize(1);
properties[i][0] = Real(rgb[i]);
}
}
}
void PointCloud3D::FromDepthImage(int w,int h,float wfov,float hfov,float depthscale,const std::vector<unsigned short>& depths,const std::vector<unsigned int>& rgb,unsigned short invalidDepth)
{
vector<float> fdepth(depths.size());
for(size_t i=0;i<depths.size();i++)
fdepth[i] = depths[i]*depthscale;
FromDepthImage(w,h,wfov,hfov,fdepth,rgb,invalidDepth*depthscale);
}
bool PointCloud3D::IsStructured() const
{
return GetStructuredWidth() >= 1 && GetStructuredHeight() > 1;
}
int PointCloud3D::GetStructuredWidth() const
{
return settings.getDefault("width",0);
}
int PointCloud3D::GetStructuredHeight() const
{
return settings.getDefault("height",0);
}
void PointCloud3D::SetStructured(int w,int h)
{
settings.set("width",w);
settings.set("height",h);
points.resize(w*h);
}
Vector3 PointCloud3D::GetOrigin() const
{
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) return Vector3(0.0);
stringstream ss(viewpoint);
Vector3 o;
ss>>o;
return o;
}
void PointCloud3D::SetOrigin(const Vector3& origin)
{
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) {
stringstream ss;
ss<<origin<<" 1 0 0 0";
settings.set("viewpoint",ss.str());
return;
}
stringstream ss(viewpoint);
Vector3 o;
Vector4 q;
ss>>o>>q;
stringstream ss2;
ss2<<origin<<" "<<q;
settings.set("viewpoint",ss2.str());
}
RigidTransform PointCloud3D::GetViewpoint() const
{
RigidTransform T;
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) {
T.setIdentity();
return T;
}
stringstream ss(viewpoint);
QuaternionRotation q;
ss>>T.t>>q;
q.getMatrix(T.R);
return T;
}
void PointCloud3D::SetViewpoint(const RigidTransform& T)
{
QuaternionRotation q;
q.setMatrix(T.R);
stringstream ss;
ss<<T.t<<" "<<q;
settings.set("viewpoint",ss.str());
}
void PointCloud3D::GetAABB(Vector3& bmin,Vector3& bmax) const
{
AABB3D bb;
bb.minimize();
for(size_t i=0;i<points.size();i++)
bb.expand(points[i]);
bmin = bb.bmin;
bmax = bb.bmax;
}
void PointCloud3D::Transform(const Matrix4& mat)
{
bool hasNormals = false;
//names of the normal properties in the PCD file
static const char* nxprop = "normal_x", *nyprop = "normal_y", *nzprop = "normal_z";
int nxind = -1, nyind = -1, nzind = -1;
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i] == nxprop) {
nxind = (int)i;
continue;
}
if(propertyNames[i] == nyprop) {
nyind = (int)i;
continue;
}
if(propertyNames[i] == nzprop) {
nzind = (int)i;
continue;
}
}
hasNormals = (nxind >= 0 && nyind >= 0 && nzind >= 0);
for(size_t i=0;i<points.size();i++) {
Vector3 temp=points[i];
mat.mulPoint(temp,points[i]);
//transform normals if this has them
if(hasNormals) {
Vector3 temp2;
temp.set(properties[i][nxind],properties[i][nyind],properties[i][nzind]);
mat.mulVector(temp,temp2);
temp2.get(properties[i][nxind],properties[i][nyind],properties[i][nzind]);
}
}
}
bool PointCloud3D::HasXYZAsProperties() const
{
if(points.empty()) return false;
int elemIndex[3] = {-1,-1,-1};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(elemIndex[0]<0 || elemIndex[1]<0 || elemIndex[2]<0)
return false;
return true;
}
void PointCloud3D::SetXYZAsProperties(bool isprop)
{
if(HasXYZAsProperties() == isprop) return;
int elemIndex[3] = {-1,-1,-1};
const char* elementNames[3] = {"x","y","z"};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(isprop) { //add
int numprops = propertyNames.size();
for(int i=0;i<3;i++)
if(elemIndex[i] < 0) {
propertyNames.push_back(elementNames[i]);
elemIndex[i] = numprops;
numprops++;
}
if(properties.empty())
properties.resize(points.size());
for(size_t i=0;i<points.size();i++) {
Vector oldprops = properties[i];
properties[i].resize(numprops);
properties[i].copySubVector(0,oldprops);
properties[i][elemIndex[0]] = points[i].x;
properties[i][elemIndex[1]] = points[i].y;
properties[i][elemIndex[2]] = points[i].z;
}
}
else {
//remove from properties
if(elemIndex[2] >= 0) RemoveProperty("z");
if(elemIndex[1] >= 0) RemoveProperty("y");
if(elemIndex[0] >= 0) RemoveProperty("x");
}
}
bool PointCloud3D::HasNormals() const
{
return HasProperty("normal_x") && HasProperty("normal_y") && HasProperty("normal_z") ;
}
bool PointCloud3D::GetNormals(vector<Vector3>& normals) const
{
int nx=PropertyIndex("normal_x"),ny=PropertyIndex("normal_y"),nz=PropertyIndex("normal_z");
if(nx < 0 || ny < 0 || nz < 0) return false;
normals.resize(properties.size());
for(size_t i=0;i<properties.size();i++)
normals[i].set(properties[i][nx],properties[i][ny],properties[i][nz]);
return true;
}
void PointCloud3D::SetNormals(const vector<Vector3>& normals)
{
int nx=PropertyIndex("normal_x"),ny=PropertyIndex("normal_y"),nz=PropertyIndex("normal_z");
if(nx < 0) {
vector<Real> items(points.size());
SetProperty("normal_x",items);
}
if(ny < 0) {
vector<Real> items(points.size());
SetProperty("normal_y",items);
}
if(nz < 0) {
vector<Real> items(points.size());
SetProperty("normal_z",items);
}
for(size_t i=0;i<properties.size();i++)
normals[i].get(properties[i][nx],properties[i][ny],properties[i][nz]);
}
bool PointCloud3D::HasColor() const
{
return HasProperty("c") || HasProperty("rgba") || HasProperty("rgb") || HasProperty("opacity") || (HasProperty("r") && HasProperty("g") && HasProperty("b"));
}
bool PointCloud3D::HasOpacity() const
{
return HasProperty("c") || HasProperty("opacity");
}
bool PointCloud3D::HasRGB() const
{
return HasProperty("rgb") || HasProperty("rgba") || (HasProperty("r") && HasProperty("g") && HasProperty("b"));
}
bool PointCloud3D::HasRGBA() const
{
return HasProperty("rgba") || (HasProperty("r") && HasProperty("g") && HasProperty("b") && HasProperty("a"));
}
bool PointCloud3D::UnpackColorChannels(bool alpha)
{
if(HasProperty("rgb")) {
vector<Real> r,g,b,a;
GetColors(r,g,b,a);
SetProperty("r",r);
SetProperty("g",g);
SetProperty("b",b);
if(alpha)
SetProperty("a",a);
RemoveProperty("rgb");
return true;
}
else if(HasProperty("rgba")) {
vector<Real> r,g,b,a;
GetColors(r,g,b,a);
SetProperty("r",r);
SetProperty("g",g);
SetProperty("b",b);
SetProperty("a",a);
RemoveProperty("rgba");
return true;
}
return false;
}
bool PointCloud3D::PackColorChannels(const char* fmt)
{
vector<Real> r,g,b,a;
if(!GetProperty("r",r)) return false;
if(!GetProperty("g",g)) return false;
if(!GetProperty("b",b)) return false;
if(0==strcmp(fmt,"rgb")) {
SetColors(r,g,b,false);
RemoveProperty("r");
RemoveProperty("g");
RemoveProperty("b");
if(HasProperty("a")) RemoveProperty("a");
return true;
}
else if(0==strcmp(fmt,"rgba")) {
if(!GetProperty("a",a)) {
a.resize(points.size());
fill(a.begin(),a.end(),1.0);
}
SetColors(r,g,b,a,true);
RemoveProperty("r");
RemoveProperty("g");
RemoveProperty("b");
RemoveProperty("a");
return true;
}
return false;
}
bool PointCloud3D::GetColors(vector<Vector4>& out) const
{
Timer timer;
vector<Real> rgb;
if(GetProperty("rgb",rgb)) {
//convert real to hex to GLcolor
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
unsigned int col = (unsigned int)rgb[i];
Real r=((col&0xff0000)>>16) *one_over_255;
Real g=((col&0xff00)>>8) *one_over_255;
Real b=(col&0xff) *one_over_255;
out[i].set(r,g,b,1.0);
}
return true;
}
else if(GetProperty("rgba",rgb)) {
//convert real to hex to GLcolor
//following PCD, this is actuall A-RGB
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
unsigned int col = (unsigned int)rgb[i];
Real r = ((col&0xff0000)>>16) *one_over_255;
Real g = ((col&0xff00)>>8) *one_over_255;
Real b = (col&0xff) *one_over_255;
Real a = ((col&0xff000000)>>24) *one_over_255;
out[i].set(r,g,b,a);
}
return true;
}
else if(GetProperty("opacity",rgb)) {
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
out[i].set(1,1,1,rgb[i]);
return true;
}
else if(GetProperty("c",rgb)) {
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
out[i].set(1,1,1,rgb[i]*one_over_255);
return true;
}
return false;
}
bool PointCloud3D::GetColors(vector<Real>& r,vector<Real>& g,vector<Real>& b,vector<Real>& a) const
{
vector<Real> rgb;
if(GetProperty("rgb",rgb)) {
//convert real to hex to GLcolor
r.resize(rgb.size());
g.resize(rgb.size());
b.resize(rgb.size());
a.resize(rgb.size());
fill(a.begin(),a.end(),1.0);
for(size_t i=0;i<rgb.size();i++) {
int col = (int)rgb[i];
r[i]=((col&0xff0000)>>16) *one_over_255;
g[i]=((col&0xff00)>>8) *one_over_255;
b[i]=(col&0xff) *one_over_255;
}
return true;
}
else if(GetProperty("rgba",rgb)) {
//convert real to hex to GLcolor
//following PCD, this is actuall A-RGB
r.resize(rgb.size());
g.resize(rgb.size());
b.resize(rgb.size());
a.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
int col = (int)rgb[i];
r[i] = ((col&0xff0000)>>16) * one_over_255;
g[i] = ((col&0xff00)>>8) * one_over_255;
b[i] = (col&0xff) * one_over_255;
a[i] = ((col&0xff000000)>>24) * one_over_255;
}
return true;
}
else if(GetProperty("opacity",rgb)) {
r.resize(rgb.size(),1.0);
g.resize(rgb.size(),1.0);
b.resize(rgb.size(),1.0);
a = rgb;
return true;
}
else if(GetProperty("c",rgb)) {
r.resize(rgb.size(),1.0);
g.resize(rgb.size(),1.0);
b.resize(rgb.size(),1.0);
a.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
a[i] = rgb[i]*one_over_255;
return true;
}
return false;
}
void PointCloud3D::SetColors(const vector<Real>& r,const vector<Real>& g,const vector<Real>& b,bool includeAlpha)
{
if(!includeAlpha) {
vector<Real> a;
SetColors(r,g,b,a,includeAlpha);
}
else {
vector<Real> a(points.size(),1.0);
SetColors(r,g,b,a,includeAlpha);
}
}
void PointCloud3D::SetColors(const vector<Real>& r,const vector<Real>& g,const vector<Real>& b,const vector<Real>& a,bool includeAlpha)
{
if(!includeAlpha) {
//pack it
vector<Real> rgb(r.size());
for(size_t i=0;i<r.size();i++) {
int col = ((int(r[i]*255.0) & 0xff) << 16) |
((int(g[i]*255.0) & 0xff) << 8) |
(int(b[i]*255.0) & 0xff);
rgb[i] = Real(col);
}
SetProperty("rgb",rgb);
}
else {
//pack it
vector<Real> rgba(r.size());
for(size_t i=0;i<r.size();i++) {
int col = ((int(a[i]*255.0) & 0xff) << 24) |
((int(r[i]*255.0) & 0xff) << 16) |
((int(g[i]*255.0) & 0xff) << 8) |
(int(b[i]*255.0) & 0xff);
rgba[i] = Real(col);
}
SetProperty("rgba",rgba);
}
}
void PointCloud3D::SetColors(const vector<Vector4>& rgba,bool includeAlpha)
{
Assert(points.size()==rgba.size());
Real r,g,b,a;
if(!includeAlpha) {
//pack it
vector<Real> packed(rgba.size());
for(size_t i=0;i<rgba.size();i++) {
rgba[i].get(r,g,b,a);
int col = ((int(r*255.0) & 0xff) << 16) |
((int(g*255.0) & 0xff) << 8) |
(int(b*255.0) & 0xff);
packed[i] = Real(col);
}
SetProperty("rgb",packed);
}
else {
//pack it
vector<Real> packed(rgba.size());
for(size_t i=0;i<rgba.size();i++) {
rgba[i].get(r,g,b,a);
int col = ((int(a*255.0) & 0xff) << 24) |
((int(r*255.0) & 0xff) << 16) |
((int(g*255.0) & 0xff) << 8) |
(int(b*255.0) & 0xff);
packed[i] = Real(col);
}
SetProperty("rgba",packed);
}
}
void PointCloud3D::SetUV(const vector<Vector2>& uvs)
{
Assert(points.size()==uvs.size());
vector<Real> u(uvs.size()),v(uvs.size());
for(size_t i=0;i<uvs.size();i++) {
uvs[i].get(u[i],v[i]);
}
SetProperty("u",u);
SetProperty("v",v);
}
bool PointCloud3D::GetUV(vector<Vector2>& uvs) const
{
vector<Real> u,v;
if(GetProperty("u",u) && GetProperty("v",v)) {
//convert real to hex to GLcolor
uvs.resize(u.size());
for(size_t i=0;i<uvs.size();i++) {
uvs[i].set(u[i],v[i]);
}
return true;
}
return false;
}
int PointCloud3D::PropertyIndex(const string& name) const
{
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i] == name) return (int)i;
}
return -1;
}
bool PointCloud3D::GetProperty(const string& name,vector<Real>& items) const
{
int i = PropertyIndex(name);
if(i < 0) return false;
items.resize(properties.size());
for(size_t k=0;k<properties.size();k++)
items[k] = properties[k][i];
return true;
}
void PointCloud3D::SetProperty(const string& name,const vector<Real>& items)
{
int i = PropertyIndex(name);
if(i >= 0) {
for(size_t k=0;k<properties.size();k++) {
properties[k][i] = items[k];
}
return;
}
else {
//add it
propertyNames.push_back(name);
for(size_t k=0;k<properties.size();k++) {
Vector oldval = properties[k];
properties[k].resize(propertyNames.size());
properties[k].copySubVector(0,oldval);
properties[k][propertyNames.size()-1] = items[k];
}
}
}
void PointCloud3D::RemoveProperty(const string& name)
{
int i = PropertyIndex(name);
if(i >= 0) {
for(size_t k=0;k<properties.size();k++) {
for(size_t j=i+1;j<propertyNames.size();j++)
properties[k][j-1] = properties[k][j];
properties[k].n--;
}
propertyNames.erase(propertyNames.begin()+i);
return;
}
else
LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud3D::RemoveProperty: warning, property "<<name.c_str());
}
void PointCloud3D::GetSubCloud(const Vector3& bmin,const Vector3& bmax,PointCloud3D& subcloud)
{
AABB3D bb(bmin,bmax);
subcloud.Clear();
subcloud.propertyNames = propertyNames;
subcloud.settings = settings;
for(size_t i=0;i<points.size();i++)
if(bb.contains(points[i])) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
void PointCloud3D::GetSubCloud(const string& property,Real value,PointCloud3D& subcloud)
{
GetSubCloud(property,value,value,subcloud);
}
void PointCloud3D::GetSubCloud(const string& property,Real minValue,Real maxValue,PointCloud3D& subcloud)
{
subcloud.Clear();
subcloud.propertyNames = propertyNames;
subcloud.settings = settings;
if(property == "x") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].x && points[i].x <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else if(property == "y") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].y && points[i].y <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else if(property == "z") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].z && points[i].z <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else {
int i=PropertyIndex(property);
if(i < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud3D::GetSubCloud: warning, property "<<property.c_str());
return;
}
for(size_t k=0;k<properties.size();k++)
if(minValue <= properties[k][i] && properties[k][i] <= maxValue) {
subcloud.points.push_back(points[k]);
subcloud.properties.push_back(properties[k]);
}
}
}
Fixed stupid problem with endlines in saving PCD files
#include <KrisLibrary/Logger.h>
#include "PointCloud.h"
#include <iostream>
#include <KrisLibrary/math3d/AABB3D.h>
#include <KrisLibrary/math3d/rotation.h>
#include <KrisLibrary/utils/SimpleParser.h>
#include <KrisLibrary/utils/stringutils.h>
#include <KrisLibrary/utils/ioutils.h>
#include <KrisLibrary/Timer.h>
#include <errors.h>
#include <sstream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace Meshing;
const static Real one_over_255 = 1.0/255.0;
string IntToStr(int i)
{
stringstream ss;
ss<<i;
return ss.str();
}
class PCLParser : public SimpleParser
{
public:
enum {NORMAL, READING_FIELDS, READING_TYPES, READING_SIZES, READING_COUNTS };
PCLParser(istream& in,PointCloud3D& _pc)
:SimpleParser(in),pc(_pc),state(NORMAL),numPoints(-1)
{}
virtual bool IsComment(char c) const { return c=='#'; }
virtual bool IsToken(char c) const { return !IsSpace(c) && !IsComment(c); }
virtual bool IsPunct(char c) const { return !IsSpace(c) && !IsComment(c) && !IsToken(c); }
virtual Result InputToken(const string& word) {
if(state == READING_FIELDS) {
pc.propertyNames.push_back(word);
}
else if(state == READING_TYPES) {
if(word != "F" && word != "U" && word != "I") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD TYPE "<<word.c_str());
return Error;
}
types.push_back(word);
}
else if(state == READING_COUNTS) {
if(!IsValidInteger(word.c_str())) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD COUNT string "<<word.c_str()<<", must be integer");
return Error;
}
stringstream ss(word);
int count;
ss>>count;
if(ss.bad() || count <= 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD COUNT "<<word.c_str()<<", must be a positive integer");
return Error;
}
counts.push_back(count);
}
else if(state == READING_SIZES) {
if(!IsValidInteger(word.c_str())) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD SIZE string "<<word.c_str()<<", must be integer");
return Error;
}
stringstream ss(word);
int size;
ss>>size;
if(size <= 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid PCD SIZE "<<word.c_str()<<" must be positive");
return Error;
}
sizes.push_back(size);
}
else {
if(word == "POINTS") {
string points;
ReadLine(points);
stringstream ss(points);
ss>>numPoints;
if(!ss) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Unable to read integer POINTS");
return Error;
}
}
else if(word == "FIELDS") {
state = READING_FIELDS;
}
else if(word == "COUNT") {
state = READING_COUNTS;
}
else if(word == "TYPE") {
state = READING_TYPES;
}
else if(word == "SIZE") {
state = READING_SIZES;
}
else if(word == "DATA") {
ConvertToSingleCounts();
/*
cout<<"property names, type, size"<<endl;
for(size_t i=0;i<pc.propertyNames.size();i++)
cout<<pc.propertyNames[i]<<", "<<types[i]<<", "<<sizes[i]<<endl;
*/
string datatype;
if(!ReadLine(datatype)) return Error;
datatype = Strip(datatype);
if(datatype == "binary") {
//pull in the endline
int c = in.get();
if(c != '\n') {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA binary not followed immediately by endline");
return Error;
}
//read in binary data
if(numPoints < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA specified before POINTS element");
return Error;
}
if(sizes.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid number of SIZE elements");
return Error;
}
if(types.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid number of TYPE elements");
return Error;
}
int pointsize = 0;
for(size_t i=0;i<sizes.size();i++)
pointsize += sizes[i];
streampos fcur = in.tellg();
in.seekg( 0, std::ios::end );
streampos fsize = in.tellg() - fcur;
in.seekg( fcur );
if(fsize-streampos(pointsize*numPoints) != 0) {
cout<<"Size of point "<<pointsize<<" x "<<numPoints<<" points"<<endl;
cout<<"Remaining bytes left: "<<fsize<<", we'll probably have "<<fsize-streampos(pointsize*numPoints)<<" left?"<<endl;
for(int i=0;i<int(fsize)-pointsize*numPoints;i++) {
if(in.peek() != 0) {
cout<<"Hmmm... what's this wasted space? stopped on "<<i<<endl;
}
in.get();
}
}
vector<char> buffer(pointsize);
for(int i=0;i<numPoints;i++) {
in.read(&buffer[0],pointsize);
if(!in) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Error reading data for point "<<i);
return Error;
}
//parse the point and add it
Vector v(pc.propertyNames.size());
int ofs = 0;
for(size_t j=0;j<sizes.size();j++) {
if(types[j] == "F") {
if(sizes[j] == 4) {
float f;
memcpy(&f,&buffer[ofs],sizes[j]);
v[j] = f;
/*
if(i % 10000 == 0)
printf("%s Buffer %x => float %f\n",pc.propertyNames[j].c_str(),*((unsigned int*)&buffer[ofs]),f);
*/
}
else if(sizes[j] == 8) {
double f;
memcpy(&f,&buffer[ofs],sizes[j]);
v[j] = f;
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid float size "<<sizes[j]);
return Error;
}
}
else if(types[j] == "U") {
if(sizes[j] > 4) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid unsigned int size "<<sizes[j]);
return Error;
}
unsigned i=0;
memcpy(&i,&buffer[ofs],sizes[j]);
v[j] = Real(i);
}
else if(types[j] == "I") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid int size "<<sizes[j]);
int i=0;
memcpy(&i,&buffer[ofs],sizes[j]);
v[j] = Real(i);
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Invalid type "<<types[i].c_str());
return Error;
}
ofs += sizes[j];
}
pc.properties.push_back(v);
}
return Stop;
}
else if(datatype == "ascii") {
if(numPoints < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA specified before POINTS element");
return Error;
}
string line;
for(int i=0;i<numPoints;i++) {
int c = in.get();
assert(c=='\n' || c==EOF);
lineno++;
if(c==EOF) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Premature end of DATA element");
return Error;
}
if(!ReadLine(line)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Error reading point "<<i);
return Error;
}
vector<string> elements = Split(line," ");
if(elements.size() != pc.propertyNames.size()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA element "<<i<<" has length "<<elements.size()<<", but "<<pc.propertyNames.size());
return Error;
}
Vector v(elements.size());
for(size_t k=0;k<elements.size();k++) {
stringstream ss(elements[k]);
SafeInputFloat(ss,v[k]);
}
pc.properties.push_back(v);
}
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: DATA is not spcified as ascii or binary");
return Error;
}
}
else {
string value;
if(!ReadLine(value)) return Error;
value = Strip(value);
if(word == "VERSION") {
if(value != "0.7" && value != ".7") {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Warning, PCD version 0.7 expected, got \""<<value.c_str()<<"\"");
}
pc.settings["pcd_version"] = value;
}
else {
//LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: Read property \""<<word.c_str()<<"\" = \""<<pc.settings[word].c_str());
string key=word;
Lowercase(key);
pc.settings[key] = Strip(value);
}
}
}
return Continue;
}
virtual Result InputPunct(const string& punct) { return Continue; }
virtual Result InputEndLine()
{
if(state != NORMAL) state=NORMAL;
return Continue;
}
void ConvertToSingleCounts()
{
size_t i=0;
while(i < counts.size()) {
if(counts[i] > 1) {
int n=counts[i];
LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: converting element "<<pc.propertyNames[i]<<" into "<<counts[i]<<" sub-elements");
string basename = pc.propertyNames[i];
pc.propertyNames[i] = basename + '_' + IntToStr(0);
counts[i] = 1;
for(int j=1;j<n;j++) {
pc.propertyNames.insert(pc.propertyNames.begin()+i+1,basename + '_' + IntToStr(j));
types.insert(types.begin()+i+1,types[i]);
sizes.insert(sizes.begin()+i+1,sizes[i]);
counts.insert(counts.begin()+i+1,1);
}
i += n;
}
else
i++;
}
}
PointCloud3D& pc;
int state;
int numPoints;
//for binary data
vector<string> types;
vector<int> sizes;
vector<int> counts;
};
void PointCloud3D::Clear()
{
points.clear();
propertyNames.clear();
properties.clear();
settings.clear();
}
bool PointCloud3D::LoadPCL(const char* fn)
{
ifstream in(fn,ios::in);
if(!in) return false;
if(!LoadPCL(in)) return false;
settings["file"] = fn;
in.close();
return true;
}
bool PointCloud3D::SavePCL(const char* fn) const
{
ofstream out(fn,ios::out);
if(!out) return false;
if(!SavePCL(out)) return false;
out.close();
return true;
}
bool PointCloud3D::LoadPCL(istream& in)
{
PCLParser parser(in,*this);
if(!parser.Read()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Unable to parse PCD file");
return false;
}
int elemIndex[3] = {-1,-1,-1};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(elemIndex[0]<0 || elemIndex[1]<0 || elemIndex[2]<0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PCD parser: Warning, PCD file does not have x, y or z");
LOG4CXX_ERROR(KrisLibrary::logger()," Properties:");
for(size_t i=0;i<propertyNames.size();i++)
LOG4CXX_ERROR(KrisLibrary::logger()," \""<<propertyNames[i].c_str());
LOG4CXX_ERROR(KrisLibrary::logger(),"");
return true;
}
//HACK: for float RGB and RGBA elements, convert float bytes
//to integer via memory cast
Assert(propertyNames.size() == parser.types.size());
for(size_t k=0;k<propertyNames.size();k++) {
if(parser.types[k] == "F" && (propertyNames[k] == "rgb" || propertyNames[k] == "rgba")) {
bool docast = false;
for(size_t i=0;i<properties.size();i++) {
Vector& v = properties[i];
float f = float(v[k]);
if(f < 1.0 && f > 0.0) {
docast=true;
break;
}
}
if(docast) {
//LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud::LoadPCL: Warning, casting RGB colors to integers via direct memory cast");
for(size_t i=0;i<properties.size();i++) {
Vector& v = properties[i];
float f = float(v[k]);
int rgb = *((int*)&f);
v[k] = (Real)rgb;
}
}
}
}
//parse out the points
points.resize(properties.size());
for(size_t i=0;i<properties.size();i++) {
points[i].set(properties[i][elemIndex[0]],properties[i][elemIndex[1]],properties[i][elemIndex[2]]);
}
//LOG4CXX_INFO(KrisLibrary::logger(),"PCD parser: "<<points.size());
if(properties.size()==3 && elemIndex[0]==0 && elemIndex[1]==1 && elemIndex[2]==2) {
//x,y,z are the only properties, go ahead and take them out
propertyNames.resize(0);
properties.resize(0);
}
return true;
}
bool PointCloud3D::SavePCL(ostream& out) const
{
out<<"# .PCD v0.7 - Point Cloud Data file format"<<endl;
if(settings.find("pcd_version") != settings.end())
out<<"VERSION "<<settings.find("pcd_version")->second<<endl;
else
out<<"VERSION 0.7"<<endl;
bool addxyz = !HasXYZAsProperties();
out<<"FIELDS";
if(addxyz)
out<<" x y z";
for(size_t i=0;i<propertyNames.size();i++)
out<<" "<<propertyNames[i];
out<<endl;
out<<"TYPE";
if(addxyz)
out<<" F F F";
for(size_t i=0;i<propertyNames.size();i++)
out<<" F";
out<<endl;
if(!properties.empty())
out<<"POINTS "<<properties.size();
else
out<<"POINTS "<<points.size();
for(map<string,string>::const_iterator i=settings.begin();i!=settings.end();i++) {
if(i->first == "pcd_version" || i->first == "file") continue;
string key = i->first;
Uppercase(key);
out<<key<<" "<<i->second;
}
out<<"DATA ascii";
if(propertyNames.empty()) {
for(size_t i=0;i<points.size();i++)
out<<points[i];
}
else {
for(size_t i=0;i<properties.size();i++) {
if(addxyz)
out<<points[i]<<" ";
for(int j=0;j<properties[i].n;j++)
out<<properties[i][j]<<" ";
out<<endl;
}
}
return true;
}
void PointCloud3D::FromDepthImage(int w,int h,float wfov,float hfov,const std::vector<float>& depths,const std::vector<unsigned int>& rgb,float invalidDepth)
{
SetStructured(w,h);
Real xscale = Tan(wfov/2)*(2.0/w);
Real yscale = Tan(hfov/2)*(2.0/h);
Assert(depths.size()==points.size());
Real xc = Real(w)/2;
Real yc = Real(h)/2;
int k=0;
Real fi=0,fj=0;
for(int j=0;j<h;j++,fj+=1.0) {
fi = 0;
for(int i=0;i<w;i++,k++,fi+=1.0) {
if(depths[k] == invalidDepth)
points[k].setZero();
else {
Real x = (fi-xc)*xscale;
Real y = (fj-yc)*yscale;
points[k].x = depths[k]*x;
points[k].y = depths[k]*y;
points[k].z = depths[k];
}
}
}
if(!rgb.empty()) {
Assert(rgb.size()==depths.size());
propertyNames.resize(1);
propertyNames[0] = "rgb";
properties.resize(points.size());
for(size_t i=0;i<points.size();i++) {
properties[i].resize(1);
properties[i][0] = Real(rgb[i]);
}
}
}
void PointCloud3D::FromDepthImage(int w,int h,float wfov,float hfov,float depthscale,const std::vector<unsigned short>& depths,const std::vector<unsigned int>& rgb,unsigned short invalidDepth)
{
vector<float> fdepth(depths.size());
for(size_t i=0;i<depths.size();i++)
fdepth[i] = depths[i]*depthscale;
FromDepthImage(w,h,wfov,hfov,fdepth,rgb,invalidDepth*depthscale);
}
bool PointCloud3D::IsStructured() const
{
return GetStructuredWidth() >= 1 && GetStructuredHeight() > 1;
}
int PointCloud3D::GetStructuredWidth() const
{
return settings.getDefault("width",0);
}
int PointCloud3D::GetStructuredHeight() const
{
return settings.getDefault("height",0);
}
void PointCloud3D::SetStructured(int w,int h)
{
settings.set("width",w);
settings.set("height",h);
points.resize(w*h);
}
Vector3 PointCloud3D::GetOrigin() const
{
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) return Vector3(0.0);
stringstream ss(viewpoint);
Vector3 o;
ss>>o;
return o;
}
void PointCloud3D::SetOrigin(const Vector3& origin)
{
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) {
stringstream ss;
ss<<origin<<" 1 0 0 0";
settings.set("viewpoint",ss.str());
return;
}
stringstream ss(viewpoint);
Vector3 o;
Vector4 q;
ss>>o>>q;
stringstream ss2;
ss2<<origin<<" "<<q;
settings.set("viewpoint",ss2.str());
}
RigidTransform PointCloud3D::GetViewpoint() const
{
RigidTransform T;
string viewpoint;
if(!settings.get("viewpoint",viewpoint)) {
T.setIdentity();
return T;
}
stringstream ss(viewpoint);
QuaternionRotation q;
ss>>T.t>>q;
q.getMatrix(T.R);
return T;
}
void PointCloud3D::SetViewpoint(const RigidTransform& T)
{
QuaternionRotation q;
q.setMatrix(T.R);
stringstream ss;
ss<<T.t<<" "<<q;
settings.set("viewpoint",ss.str());
}
void PointCloud3D::GetAABB(Vector3& bmin,Vector3& bmax) const
{
AABB3D bb;
bb.minimize();
for(size_t i=0;i<points.size();i++)
bb.expand(points[i]);
bmin = bb.bmin;
bmax = bb.bmax;
}
void PointCloud3D::Transform(const Matrix4& mat)
{
bool hasNormals = false;
//names of the normal properties in the PCD file
static const char* nxprop = "normal_x", *nyprop = "normal_y", *nzprop = "normal_z";
int nxind = -1, nyind = -1, nzind = -1;
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i] == nxprop) {
nxind = (int)i;
continue;
}
if(propertyNames[i] == nyprop) {
nyind = (int)i;
continue;
}
if(propertyNames[i] == nzprop) {
nzind = (int)i;
continue;
}
}
hasNormals = (nxind >= 0 && nyind >= 0 && nzind >= 0);
for(size_t i=0;i<points.size();i++) {
Vector3 temp=points[i];
mat.mulPoint(temp,points[i]);
//transform normals if this has them
if(hasNormals) {
Vector3 temp2;
temp.set(properties[i][nxind],properties[i][nyind],properties[i][nzind]);
mat.mulVector(temp,temp2);
temp2.get(properties[i][nxind],properties[i][nyind],properties[i][nzind]);
}
}
}
bool PointCloud3D::HasXYZAsProperties() const
{
if(points.empty()) return false;
int elemIndex[3] = {-1,-1,-1};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(elemIndex[0]<0 || elemIndex[1]<0 || elemIndex[2]<0)
return false;
return true;
}
void PointCloud3D::SetXYZAsProperties(bool isprop)
{
if(HasXYZAsProperties() == isprop) return;
int elemIndex[3] = {-1,-1,-1};
const char* elementNames[3] = {"x","y","z"};
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i]=="x") elemIndex[0] = (int)i;
if(propertyNames[i]=="y") elemIndex[1] = (int)i;
if(propertyNames[i]=="z") elemIndex[2] = (int)i;
}
if(isprop) { //add
int numprops = propertyNames.size();
for(int i=0;i<3;i++)
if(elemIndex[i] < 0) {
propertyNames.push_back(elementNames[i]);
elemIndex[i] = numprops;
numprops++;
}
if(properties.empty())
properties.resize(points.size());
for(size_t i=0;i<points.size();i++) {
Vector oldprops = properties[i];
properties[i].resize(numprops);
properties[i].copySubVector(0,oldprops);
properties[i][elemIndex[0]] = points[i].x;
properties[i][elemIndex[1]] = points[i].y;
properties[i][elemIndex[2]] = points[i].z;
}
}
else {
//remove from properties
if(elemIndex[2] >= 0) RemoveProperty("z");
if(elemIndex[1] >= 0) RemoveProperty("y");
if(elemIndex[0] >= 0) RemoveProperty("x");
}
}
bool PointCloud3D::HasNormals() const
{
return HasProperty("normal_x") && HasProperty("normal_y") && HasProperty("normal_z") ;
}
bool PointCloud3D::GetNormals(vector<Vector3>& normals) const
{
int nx=PropertyIndex("normal_x"),ny=PropertyIndex("normal_y"),nz=PropertyIndex("normal_z");
if(nx < 0 || ny < 0 || nz < 0) return false;
normals.resize(properties.size());
for(size_t i=0;i<properties.size();i++)
normals[i].set(properties[i][nx],properties[i][ny],properties[i][nz]);
return true;
}
void PointCloud3D::SetNormals(const vector<Vector3>& normals)
{
int nx=PropertyIndex("normal_x"),ny=PropertyIndex("normal_y"),nz=PropertyIndex("normal_z");
if(nx < 0) {
vector<Real> items(points.size());
SetProperty("normal_x",items);
}
if(ny < 0) {
vector<Real> items(points.size());
SetProperty("normal_y",items);
}
if(nz < 0) {
vector<Real> items(points.size());
SetProperty("normal_z",items);
}
for(size_t i=0;i<properties.size();i++)
normals[i].get(properties[i][nx],properties[i][ny],properties[i][nz]);
}
bool PointCloud3D::HasColor() const
{
return HasProperty("c") || HasProperty("rgba") || HasProperty("rgb") || HasProperty("opacity") || (HasProperty("r") && HasProperty("g") && HasProperty("b"));
}
bool PointCloud3D::HasOpacity() const
{
return HasProperty("c") || HasProperty("opacity");
}
bool PointCloud3D::HasRGB() const
{
return HasProperty("rgb") || HasProperty("rgba") || (HasProperty("r") && HasProperty("g") && HasProperty("b"));
}
bool PointCloud3D::HasRGBA() const
{
return HasProperty("rgba") || (HasProperty("r") && HasProperty("g") && HasProperty("b") && HasProperty("a"));
}
bool PointCloud3D::UnpackColorChannels(bool alpha)
{
if(HasProperty("rgb")) {
vector<Real> r,g,b,a;
GetColors(r,g,b,a);
SetProperty("r",r);
SetProperty("g",g);
SetProperty("b",b);
if(alpha)
SetProperty("a",a);
RemoveProperty("rgb");
return true;
}
else if(HasProperty("rgba")) {
vector<Real> r,g,b,a;
GetColors(r,g,b,a);
SetProperty("r",r);
SetProperty("g",g);
SetProperty("b",b);
SetProperty("a",a);
RemoveProperty("rgba");
return true;
}
return false;
}
bool PointCloud3D::PackColorChannels(const char* fmt)
{
vector<Real> r,g,b,a;
if(!GetProperty("r",r)) return false;
if(!GetProperty("g",g)) return false;
if(!GetProperty("b",b)) return false;
if(0==strcmp(fmt,"rgb")) {
SetColors(r,g,b,false);
RemoveProperty("r");
RemoveProperty("g");
RemoveProperty("b");
if(HasProperty("a")) RemoveProperty("a");
return true;
}
else if(0==strcmp(fmt,"rgba")) {
if(!GetProperty("a",a)) {
a.resize(points.size());
fill(a.begin(),a.end(),1.0);
}
SetColors(r,g,b,a,true);
RemoveProperty("r");
RemoveProperty("g");
RemoveProperty("b");
RemoveProperty("a");
return true;
}
return false;
}
bool PointCloud3D::GetColors(vector<Vector4>& out) const
{
Timer timer;
vector<Real> rgb;
if(GetProperty("rgb",rgb)) {
//convert real to hex to GLcolor
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
unsigned int col = (unsigned int)rgb[i];
Real r=((col&0xff0000)>>16) *one_over_255;
Real g=((col&0xff00)>>8) *one_over_255;
Real b=(col&0xff) *one_over_255;
out[i].set(r,g,b,1.0);
}
return true;
}
else if(GetProperty("rgba",rgb)) {
//convert real to hex to GLcolor
//following PCD, this is actuall A-RGB
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
unsigned int col = (unsigned int)rgb[i];
Real r = ((col&0xff0000)>>16) *one_over_255;
Real g = ((col&0xff00)>>8) *one_over_255;
Real b = (col&0xff) *one_over_255;
Real a = ((col&0xff000000)>>24) *one_over_255;
out[i].set(r,g,b,a);
}
return true;
}
else if(GetProperty("opacity",rgb)) {
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
out[i].set(1,1,1,rgb[i]);
return true;
}
else if(GetProperty("c",rgb)) {
out.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
out[i].set(1,1,1,rgb[i]*one_over_255);
return true;
}
return false;
}
bool PointCloud3D::GetColors(vector<Real>& r,vector<Real>& g,vector<Real>& b,vector<Real>& a) const
{
vector<Real> rgb;
if(GetProperty("rgb",rgb)) {
//convert real to hex to GLcolor
r.resize(rgb.size());
g.resize(rgb.size());
b.resize(rgb.size());
a.resize(rgb.size());
fill(a.begin(),a.end(),1.0);
for(size_t i=0;i<rgb.size();i++) {
int col = (int)rgb[i];
r[i]=((col&0xff0000)>>16) *one_over_255;
g[i]=((col&0xff00)>>8) *one_over_255;
b[i]=(col&0xff) *one_over_255;
}
return true;
}
else if(GetProperty("rgba",rgb)) {
//convert real to hex to GLcolor
//following PCD, this is actuall A-RGB
r.resize(rgb.size());
g.resize(rgb.size());
b.resize(rgb.size());
a.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++) {
int col = (int)rgb[i];
r[i] = ((col&0xff0000)>>16) * one_over_255;
g[i] = ((col&0xff00)>>8) * one_over_255;
b[i] = (col&0xff) * one_over_255;
a[i] = ((col&0xff000000)>>24) * one_over_255;
}
return true;
}
else if(GetProperty("opacity",rgb)) {
r.resize(rgb.size(),1.0);
g.resize(rgb.size(),1.0);
b.resize(rgb.size(),1.0);
a = rgb;
return true;
}
else if(GetProperty("c",rgb)) {
r.resize(rgb.size(),1.0);
g.resize(rgb.size(),1.0);
b.resize(rgb.size(),1.0);
a.resize(rgb.size());
for(size_t i=0;i<rgb.size();i++)
a[i] = rgb[i]*one_over_255;
return true;
}
return false;
}
void PointCloud3D::SetColors(const vector<Real>& r,const vector<Real>& g,const vector<Real>& b,bool includeAlpha)
{
if(!includeAlpha) {
vector<Real> a;
SetColors(r,g,b,a,includeAlpha);
}
else {
vector<Real> a(points.size(),1.0);
SetColors(r,g,b,a,includeAlpha);
}
}
void PointCloud3D::SetColors(const vector<Real>& r,const vector<Real>& g,const vector<Real>& b,const vector<Real>& a,bool includeAlpha)
{
if(!includeAlpha) {
//pack it
vector<Real> rgb(r.size());
for(size_t i=0;i<r.size();i++) {
int col = ((int(r[i]*255.0) & 0xff) << 16) |
((int(g[i]*255.0) & 0xff) << 8) |
(int(b[i]*255.0) & 0xff);
rgb[i] = Real(col);
}
SetProperty("rgb",rgb);
}
else {
//pack it
vector<Real> rgba(r.size());
for(size_t i=0;i<r.size();i++) {
int col = ((int(a[i]*255.0) & 0xff) << 24) |
((int(r[i]*255.0) & 0xff) << 16) |
((int(g[i]*255.0) & 0xff) << 8) |
(int(b[i]*255.0) & 0xff);
rgba[i] = Real(col);
}
SetProperty("rgba",rgba);
}
}
void PointCloud3D::SetColors(const vector<Vector4>& rgba,bool includeAlpha)
{
Assert(points.size()==rgba.size());
Real r,g,b,a;
if(!includeAlpha) {
//pack it
vector<Real> packed(rgba.size());
for(size_t i=0;i<rgba.size();i++) {
rgba[i].get(r,g,b,a);
int col = ((int(r*255.0) & 0xff) << 16) |
((int(g*255.0) & 0xff) << 8) |
(int(b*255.0) & 0xff);
packed[i] = Real(col);
}
SetProperty("rgb",packed);
}
else {
//pack it
vector<Real> packed(rgba.size());
for(size_t i=0;i<rgba.size();i++) {
rgba[i].get(r,g,b,a);
int col = ((int(a*255.0) & 0xff) << 24) |
((int(r*255.0) & 0xff) << 16) |
((int(g*255.0) & 0xff) << 8) |
(int(b*255.0) & 0xff);
packed[i] = Real(col);
}
SetProperty("rgba",packed);
}
}
void PointCloud3D::SetUV(const vector<Vector2>& uvs)
{
Assert(points.size()==uvs.size());
vector<Real> u(uvs.size()),v(uvs.size());
for(size_t i=0;i<uvs.size();i++) {
uvs[i].get(u[i],v[i]);
}
SetProperty("u",u);
SetProperty("v",v);
}
bool PointCloud3D::GetUV(vector<Vector2>& uvs) const
{
vector<Real> u,v;
if(GetProperty("u",u) && GetProperty("v",v)) {
//convert real to hex to GLcolor
uvs.resize(u.size());
for(size_t i=0;i<uvs.size();i++) {
uvs[i].set(u[i],v[i]);
}
return true;
}
return false;
}
int PointCloud3D::PropertyIndex(const string& name) const
{
for(size_t i=0;i<propertyNames.size();i++) {
if(propertyNames[i] == name) return (int)i;
}
return -1;
}
bool PointCloud3D::GetProperty(const string& name,vector<Real>& items) const
{
int i = PropertyIndex(name);
if(i < 0) return false;
items.resize(properties.size());
for(size_t k=0;k<properties.size();k++)
items[k] = properties[k][i];
return true;
}
void PointCloud3D::SetProperty(const string& name,const vector<Real>& items)
{
int i = PropertyIndex(name);
if(i >= 0) {
for(size_t k=0;k<properties.size();k++) {
properties[k][i] = items[k];
}
return;
}
else {
//add it
propertyNames.push_back(name);
for(size_t k=0;k<properties.size();k++) {
Vector oldval = properties[k];
properties[k].resize(propertyNames.size());
properties[k].copySubVector(0,oldval);
properties[k][propertyNames.size()-1] = items[k];
}
}
}
void PointCloud3D::RemoveProperty(const string& name)
{
int i = PropertyIndex(name);
if(i >= 0) {
for(size_t k=0;k<properties.size();k++) {
for(size_t j=i+1;j<propertyNames.size();j++)
properties[k][j-1] = properties[k][j];
properties[k].n--;
}
propertyNames.erase(propertyNames.begin()+i);
return;
}
else
LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud3D::RemoveProperty: warning, property "<<name.c_str());
}
void PointCloud3D::GetSubCloud(const Vector3& bmin,const Vector3& bmax,PointCloud3D& subcloud)
{
AABB3D bb(bmin,bmax);
subcloud.Clear();
subcloud.propertyNames = propertyNames;
subcloud.settings = settings;
for(size_t i=0;i<points.size();i++)
if(bb.contains(points[i])) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
void PointCloud3D::GetSubCloud(const string& property,Real value,PointCloud3D& subcloud)
{
GetSubCloud(property,value,value,subcloud);
}
void PointCloud3D::GetSubCloud(const string& property,Real minValue,Real maxValue,PointCloud3D& subcloud)
{
subcloud.Clear();
subcloud.propertyNames = propertyNames;
subcloud.settings = settings;
if(property == "x") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].x && points[i].x <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else if(property == "y") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].y && points[i].y <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else if(property == "z") {
for(size_t i=0;i<points.size();i++)
if(minValue <= points[i].z && points[i].z <= maxValue) {
subcloud.points.push_back(points[i]);
subcloud.properties.push_back(properties[i]);
}
}
else {
int i=PropertyIndex(property);
if(i < 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"PointCloud3D::GetSubCloud: warning, property "<<property.c_str());
return;
}
for(size_t k=0;k<properties.size();k++)
if(minValue <= properties[k][i] && properties[k][i] <= maxValue) {
subcloud.points.push_back(points[k]);
subcloud.properties.push_back(properties[k]);
}
}
}
|
/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/*! \file command.hpp
* \brief Declarations for Event, Command and HostQueue objects.
*
* \author Laurent Morichetti
* \date October 2008
*/
#ifndef COMMAND_HPP_
#define COMMAND_HPP_
#include "top.hpp"
#include "thread/monitor.hpp"
#include "thread/thread.hpp"
#include "platform/agent.hpp"
#include "platform/object.hpp"
#include "platform/context.hpp"
#include "platform/ndrange.hpp"
#include "platform/kernel.hpp"
#include "device/device.hpp"
#include "utils/concurrent.hpp"
#include "platform/memory.hpp"
#include "platform/perfctr.hpp"
#include "platform/threadtrace.hpp"
#include "platform/activity.hpp"
#include "platform/command_utils.hpp"
#include "CL/cl_ext.h"
#include <algorithm>
#include <atomic>
#include <functional>
#include <vector>
namespace amd {
/*! \addtogroup Runtime
* @{
*
* \addtogroup Commands Event, Commands and Command-Queue
* @{
*/
class Command;
class HostQueue;
/*! \brief Encapsulates the status of a command.
*
* \details An event object encapsulates the status of a Command
* it is associated with and can be used to synchronize operations
* in a Context.
*/
class Event : public RuntimeObject {
typedef void(CL_CALLBACK* CallBackFunction)(cl_event event, int32_t command_exec_status,
void* user_data);
struct CallBackEntry : public HeapObject {
struct CallBackEntry* next_; //!< the next entry in the callback list.
std::atomic<CallBackFunction> callback_; //!< callback function pointer.
void* data_; //!< user data passed to the callback function.
int32_t status_; //!< execution status triggering the callback.
CallBackEntry(int32_t status, CallBackFunction callback, void* data)
: callback_(callback), data_(data), status_(status) {}
};
public:
typedef std::vector<Event*> EventWaitList;
private:
Monitor lock_;
Monitor notify_lock_; //!< Lock used for notification with direct dispatch only
std::atomic<CallBackEntry*> callbacks_; //!< linked list of callback entries.
std::atomic<int32_t> status_; //!< current execution status.
std::atomic_flag notified_; //!< Command queue was notified
void* hw_event_; //!< HW event ID associated with SW event
Event* notify_event_; //!< Notify event, which should contain HW signal
const Device* device_; //!< Device, this event associated with
protected:
static const EventWaitList nullWaitList;
struct ProfilingInfo {
ProfilingInfo(bool enabled = false) : enabled_(enabled), waves_(0), marker_ts_(false) {
if (enabled) {
clear();
callback_ = nullptr;
}
}
uint64_t queued_;
uint64_t submitted_;
uint64_t start_;
uint64_t end_;
bool enabled_; //!< Profiling enabled for the wave limiter
uint32_t waves_; //!< The number of waves used in a dispatch
ProfilingCallback* callback_;
bool marker_ts_;
void clear() {
queued_ = 0ULL;
submitted_ = 0ULL;
start_ = 0ULL;
end_ = 0ULL;
}
void setCallback(ProfilingCallback* callback, uint32_t waves) {
if (callback == NULL) {
return;
}
enabled_ = true;
waves_ = waves;
clear();
callback_ = callback;
}
} profilingInfo_;
activity_prof::ActivityProf activity_; //!< Activity profiling
//! Construct a new event.
Event();
//! Construct a new event associated to the given command \a queue.
Event(HostQueue& queue);
//! Destroy the event.
virtual ~Event();
//! Release the resources associated with this event.
virtual void releaseResources() {}
//! Record the profiling info for the given change of \a status.
// If the given \a timeStamp is 0 and profiling is enabled,
// use the current host clock time instead.
uint64_t recordProfilingInfo(int32_t status, uint64_t timeStamp = 0);
//! Process the callbacks for the given \a status change.
void processCallbacks(int32_t status) const;
//! Enable profiling for this command
void EnableProfiling() {
profilingInfo_.enabled_ = true;
profilingInfo_.clear();
profilingInfo_.callback_ = nullptr;
}
public:
//! Return the context for this event.
virtual const Context& context() const = 0;
//! Return the command this event is associated with.
inline Command& command();
inline const Command& command() const;
//! Return the profiling info.
const ProfilingInfo& profilingInfo() const { return profilingInfo_; }
//! Return this command's execution status.
int32_t status() const { return status_.load(std::memory_order_relaxed); }
//! Insert the given \a callback into the callback stack.
bool setCallback(int32_t status, CallBackFunction callback, void* data);
/*! \brief Set the event status.
*
* \details If the status becomes CL_COMPLETE, notify all threads
* awaiting this command's completion. If the given \a timeStamp is 0
* and profiling is enabled, use the current host clock time instead.
*
* \see amd::Event::awaitCompletion
*/
bool setStatus(int32_t status, uint64_t timeStamp = 0);
//! Reset the status of the command for reuse
bool resetStatus(int32_t status);
//! Signal all threads waiting on this event.
void signal() {
ScopedLock lock(lock_);
lock_.notifyAll();
}
/*! \brief Suspend the current thread until the status of the Command
* associated with this event changes to CL_COMPLETE. Return true if the
* command successfully completed.
*/
virtual bool awaitCompletion();
/*! \brief Notifies current command queue about execution status
*/
bool notifyCmdQueue(bool cpu_wait = false);
//! RTTI internal implementation
virtual ObjectType objectType() const { return ObjectTypeEvent; }
//! Returns the callback for this event
const CallBackEntry* Callback() const { return callbacks_; }
// Saves HW event, associated with the current command
void SetHwEvent(void* hw_event) { hw_event_ = hw_event; }
//! Returns HW event, associated with the current command
void* HwEvent() const { return hw_event_; }
//! Returns notify even associated with the current command
Event* NotifyEvent() const { return notify_event_; }
};
/*! \brief An operation that is submitted to a command queue.
*
* %Command is the abstract base type of all OpenCL operations
* submitted to a HostQueue for execution. Classes derived from
* %Command must implement the submit() function.
*
*/
class Command : public Event {
private:
HostQueue* queue_; //!< The command queue this command is enqueue into
Command* next_; //!< Next GPU command in the queue list
Command* batch_head_ = nullptr; //!< The head of the batch commands
cl_command_type type_; //!< This command's OpenCL type.
void* data_;
const Event* waitingEvent_; //!< Waiting event associated with the marker
protected:
bool cpu_wait_ = false; //!< If true, then the command was issued for CPU/GPU sync
//! The Events that need to complete before this command is submitted.
EventWaitList eventWaitList_;
//! Force await completion of previous command
//! 0x1 - wait before enqueue, 0x2 - wait after, 0x3 - wait both.
uint32_t commandWaitBits_;
//! Construct a new command of the given OpenCL type.
Command(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList = nullWaitList,
uint32_t commandWaitBits = 0, const Event* waitingEvent = nullptr);
//! Construct a new command of the given OpenCL type.
Command(cl_command_type type)
: Event(),
queue_(nullptr),
next_(nullptr),
type_(type),
data_(nullptr),
waitingEvent_(nullptr),
eventWaitList_(nullWaitList),
commandWaitBits_(0) {}
virtual bool terminate() {
if (IS_HIP) {
releaseResources();
}
if (Agent::shouldPostEventEvents() && type() != 0) {
Agent::postEventFree(as_cl(static_cast<Event*>(this)));
}
return true;
}
public:
//! Return the queue this command is enqueued into.
HostQueue* queue() const { return queue_; }
//! Enqueue this command into the associated command queue.
void enqueue();
//! Return the event encapsulating this command's status.
const Event& event() const { return *this; }
Event& event() { return *this; }
//! Return the list of events this command needs to wait on before dispatch
const EventWaitList& eventWaitList() const { return eventWaitList_; }
//! Update with the list of events this command needs to wait on before dispatch
void updateEventWaitList(const EventWaitList& waitList) {
for (auto event : waitList) {
eventWaitList_.push_back(event);
}
}
//! Return this command's OpenCL type.
cl_command_type type() const { return type_; }
//! Return the opaque, device specific data for this command.
void* data() const { return data_; }
//! Set the opaque, device specific data for this command.
void setData(void* data) { data_ = data; }
/*! \brief The execution engine for this command.
*
* \details All derived class must implement this virtual function.
*
* \note This function will execute in the command queue thread.
*/
virtual void submit(device::VirtualDevice& device) = 0;
//! Release the resources associated with this event.
virtual void releaseResources();
//! Set the next GPU command
void setNext(Command* next) { next_ = next; }
//! Get the next GPU command
Command* getNext() const { return next_; }
//! Return the context for this event.
virtual const Context& context() const;
//! Get command wait bits
uint32_t getWaitBits() const { return commandWaitBits_; }
void OverrrideCommandType(cl_command_type type) { type_ = type; }
//! Updates the batch head, associated with this command(marker)
void SetBatchHead(Command* command) { batch_head_ = command; }
//! Returns the current batch head
Command* GetBatchHead() const { return batch_head_; }
const Event* waitingEvent() const { return waitingEvent_; }
//! Check if this command(should be a marker) requires CPU wait
bool CpuWaitRequested() const { return cpu_wait_; }
};
class UserEvent : public Command {
const Context& context_;
public:
UserEvent(Context& context) : Command(CL_COMMAND_USER), context_(context) {
setStatus(CL_SUBMITTED);
}
virtual void submit(device::VirtualDevice& device) { ShouldNotCallThis(); }
virtual const Context& context() const { return context_; }
};
class ClGlEvent : public Command {
private:
const Context& context_;
bool waitForFence();
public:
ClGlEvent(Context& context) : Command(CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR), context_(context) {
setStatus(CL_SUBMITTED);
}
virtual void submit(device::VirtualDevice& device) { ShouldNotCallThis(); }
bool awaitCompletion() { return waitForFence(); }
virtual const Context& context() const { return context_; }
};
inline Command& Event::command() { return *static_cast<Command*>(this); }
inline const Command& Event::command() const { return *static_cast<const Command*>(this); }
class Kernel;
class NDRangeContainer;
//! A memory command that holds a single memory object reference.
//
class OneMemoryArgCommand : public Command {
protected:
Memory* memory_;
public:
OneMemoryArgCommand(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList,
Memory& memory)
: Command(queue, type, eventWaitList, AMD_SERIALIZE_COPY), memory_(&memory) {
memory_->retain();
}
virtual void releaseResources() {
memory_->release();
DEBUG_ONLY(memory_ = NULL);
Command::releaseResources();
}
bool validateMemory();
bool validatePeerMemory();
};
//! A memory command that holds a single memory object reference.
//
class TwoMemoryArgsCommand : public Command {
protected:
Memory* memory1_;
Memory* memory2_;
public:
TwoMemoryArgsCommand(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList,
Memory& memory1, Memory& memory2)
: Command(queue, type, eventWaitList, AMD_SERIALIZE_COPY),
memory1_(&memory1),
memory2_(&memory2) {
memory1_->retain();
memory2_->retain();
}
virtual void releaseResources() {
memory1_->release();
memory2_->release();
DEBUG_ONLY(memory1_ = memory2_ = NULL);
Command::releaseResources();
}
bool validateMemory();
bool validatePeerMemory();
};
/*! \brief A generic read memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translation. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*
* @todo Find a cleaner way of merging the row and slice pitch concepts at this level.
*
*/
class ReadMemoryCommand : public OneMemoryArgCommand {
private:
Coord3D origin_; //!< Origin of the region to read.
Coord3D size_; //!< Size of the region to read.
void* hostPtr_; //!< The host pointer destination.
size_t rowPitch_; //!< Row pitch (for image operations)
size_t slicePitch_; //!< Slice pitch (for image operations)
BufferRect bufRect_; //!< Buffer rectangle information
BufferRect hostRect_; //!< Host memory rectangle information
public:
//! Construct a new ReadMemoryCommand
ReadMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, void* hostPtr,
size_t rowPitch = 0, size_t slicePitch = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(rowPitch),
slicePitch_(slicePitch) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
//! Construct a new ReadMemoryCommand
ReadMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, void* hostPtr,
const BufferRect& bufRect, const BufferRect& hostRect)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(0),
slicePitch_(0),
bufRect_(bufRect),
hostRect_(hostRect) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitReadMemory(*this); }
//! Return the memory object to read from.
Memory& source() const { return *memory_; }
//! Return the host memory to write to
void* destination() const { return hostPtr_; }
//! Return the origin of the region to read
const Coord3D& origin() const { return origin_; }
//! Return the size of the region to read
const Coord3D& size() const { return size_; }
//! Return the row pitch
size_t rowPitch() const { return rowPitch_; }
//! Return the slice pitch
size_t slicePitch() const { return slicePitch_; }
//! Return the buffer rectangle information
const BufferRect& bufRect() const { return bufRect_; }
//! Return the host rectangle information
const BufferRect& hostRect() const { return hostRect_; }
//! Return true if the entire memory object is read.
bool isEntireMemory() const;
};
/*! \brief A generic write memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class WriteMemoryCommand : public OneMemoryArgCommand {
private:
Coord3D origin_; //!< Origin of the region to write to.
Coord3D size_; //!< Size of the region to write to.
const void* hostPtr_; //!< The host pointer source.
size_t rowPitch_; //!< Row pitch (for image operations)
size_t slicePitch_; //!< Slice pitch (for image operations)
BufferRect bufRect_; //!< Buffer rectangle information
BufferRect hostRect_; //!< Host memory rectangle information
public:
WriteMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, const void* hostPtr,
size_t rowPitch = 0, size_t slicePitch = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(rowPitch),
slicePitch_(slicePitch) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
WriteMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, const void* hostPtr,
const BufferRect& bufRect, const BufferRect& hostRect)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(0),
slicePitch_(0),
bufRect_(bufRect),
hostRect_(hostRect) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitWriteMemory(*this); }
//! Return the host memory to read from
const void* source() const { return hostPtr_; }
//! Return the memory object to write to.
Memory& destination() const { return *memory_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return the row pitch
size_t rowPitch() const { return rowPitch_; }
//! Return the slice pitch
size_t slicePitch() const { return slicePitch_; }
//! Return the buffer rectangle information
const BufferRect& bufRect() const { return bufRect_; }
//! Return the host rectangle information
const BufferRect& hostRect() const { return hostRect_; }
//! Return true if the entire memory object is written.
bool isEntireMemory() const;
};
/*! \brief A generic fill memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class FillMemoryCommand : public OneMemoryArgCommand {
public:
static constexpr size_t MaxFillPatterSize = sizeof(double[16]);
private:
Coord3D origin_; //!< Origin of the region to write to.
Coord3D size_; //!< Size of the region to write to.
char pattern_[MaxFillPatterSize]; //!< The fill pattern
size_t patternSize_; //!< Pattern size
public:
FillMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, const void* pattern, size_t patternSize, Coord3D origin,
Coord3D size)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
patternSize_(patternSize) {
// Sanity checks
assert(pattern != NULL && "pattern cannot be null");
assert(size.c[0] > 0 && "invalid");
memcpy(pattern_, pattern, patternSize);
}
virtual void submit(device::VirtualDevice& device) { device.submitFillMemory(*this); }
//! Return the pattern memory to fill with
const void* pattern() const { return reinterpret_cast<const void*>(pattern_); }
//! Return the pattern size
const size_t patternSize() const { return patternSize_; }
//! Return the memory object to write to.
Memory& memory() const { return *memory_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return true if the entire memory object is written.
bool isEntireMemory() const;
};
/*! \brief A stream operation command.
*
* \details Used to perform a stream wait or strem write operations.
* Wait: All the commands issued after stream wait are not executed until the wait
* condition is true.
* Write: Writes a 32 or 64 bit vaue to the memeory using a GPU Blit.
*/
class StreamOperationCommand : public OneMemoryArgCommand {
private:
uint64_t value_; // !< Value to Wait on or to Write.
uint64_t mask_; // !< Mask to be applied on signal value for Wait operation.
unsigned int flags_; // !< Flags defining the Wait condition.
size_t offset_; // !< Offset into memory for Write
size_t sizeBytes_; // !< Size in bytes to Write.
// NOTE: mask_ is only used for wait operation and
// offset and sizeBytes are only used for write.
public:
StreamOperationCommand(HostQueue& queue, cl_command_type cmdType,
const EventWaitList& eventWaitList, Memory& memory, const uint64_t value,
const uint64_t mask, unsigned int flags, size_t offset, size_t sizeBytes)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
value_(value),
mask_(mask),
flags_(flags),
offset_(offset),
sizeBytes_(sizeBytes) {
// Sanity check
assert((cmdType == ROCCLR_COMMAND_STREAM_WRITE_VALUE ||
(cmdType == ROCCLR_COMMAND_STREAM_WAIT_VALUE &&
memory_->getMemFlags() & ROCCLR_MEM_HSA_SIGNAL_MEMORY)) &&
"Invalid Stream Operation");
}
virtual void submit(device::VirtualDevice& device) { device.submitStreamOperation(*this); }
//! Returns the value
const uint64_t value() const { return value_; }
//! Returns the wait mask
const uint64_t mask() const { return mask_; }
//! Return the wait flags
const unsigned int flags() const { return flags_; }
//! Return the memory object.
Memory& memory() const { return *memory_; }
//! Return the write offset.
const size_t offset() const { return offset_; }
//! Return the write size.
const size_t sizeBytes() const { return sizeBytes_; }
};
/*! \brief A generic copy memory command
*
* \details Used for both buffers and images. Backends are expected
* to handle any required translation. Buffers are treated
* as 1D structures so origin_[0] and size_[0] are
* equivalent to offset_ and count_ respectively.
*/
class CopyMemoryCommand : public TwoMemoryArgsCommand {
private:
Coord3D srcOrigin_; //!< Origin of the source region.
Coord3D dstOrigin_; //!< Origin of the destination region.
Coord3D size_; //!< Size of the region to copy.
BufferRect srcRect_; //!< Source buffer rectangle information
BufferRect dstRect_; //!< Destination buffer rectangle information
public:
CopyMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& srcMemory, Memory& dstMemory, Coord3D srcOrigin, Coord3D dstOrigin,
Coord3D size)
: TwoMemoryArgsCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory),
srcOrigin_(srcOrigin),
dstOrigin_(dstOrigin),
size_(size) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
CopyMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& srcMemory, Memory& dstMemory, Coord3D srcOrigin, Coord3D dstOrigin,
Coord3D size, const BufferRect& srcRect, const BufferRect& dstRect)
: TwoMemoryArgsCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory),
srcOrigin_(srcOrigin),
dstOrigin_(dstOrigin),
size_(size),
srcRect_(srcRect),
dstRect_(dstRect) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitCopyMemory(*this); }
//! Return the host memory to read from
Memory& source() const { return *memory1_; }
//! Return the memory object to write to.
Memory& destination() const { return *memory2_; }
//! Return the source origin
const Coord3D& srcOrigin() const { return srcOrigin_; }
//! Return the offset in bytes in the destination.
const Coord3D& dstOrigin() const { return dstOrigin_; }
//! Return the number of bytes to copy.
const Coord3D& size() const { return size_; }
//! Return the source buffer rectangle information
const BufferRect& srcRect() const { return srcRect_; }
//! Return the destination buffer rectangle information
const BufferRect& dstRect() const { return dstRect_; }
//! Return true if the both memories are is read/written in their entirety.
bool isEntireMemory() const;
};
/*! \brief A generic map memory command. Makes a memory object accessible to the host.
*
* @todo:dgladdin Need to think more about how the pitch parameters operate in
* the context of unified buffer/image commands.
*/
class MapMemoryCommand : public OneMemoryArgCommand {
private:
cl_map_flags mapFlags_; //!< Flags controlling the map.
bool blocking_; //!< True for blocking maps
Coord3D origin_; //!< Origin of the region to map.
Coord3D size_; //!< Size of the region to map.
const void* mapPtr_; //!< Host-space pointer that the object is currently mapped at
public:
//! Construct a new MapMemoryCommand
MapMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, cl_map_flags mapFlags, bool blocking, Coord3D origin,
Coord3D size, size_t* imgRowPitch = nullptr, size_t* imgSlicePitch = nullptr,
void* mapPtr = nullptr)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
mapFlags_(mapFlags),
blocking_(blocking),
origin_(origin),
size_(size),
mapPtr_(mapPtr) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitMapMemory(*this); }
//! Read the memory object
Memory& memory() const { return *memory_; }
//! Read the map control flags
cl_map_flags mapFlags() const { return mapFlags_; }
//! Read the origin
const Coord3D& origin() const { return origin_; }
//! Read the size
const Coord3D& size() const { return size_; }
//! Read the blocking flag
bool blocking() const { return blocking_; }
//! Returns true if the entire memory object is mapped
bool isEntireMemory() const;
//! Read the map pointer
const void* mapPtr() const { return mapPtr_; }
};
/*! \brief A generic unmap memory command.
*
* @todo:dgladdin Need to think more about how the pitch parameters operate in
* the context of unified buffer/image commands.
*/
class UnmapMemoryCommand : public OneMemoryArgCommand {
private:
//! Host-space pointer that the object is currently mapped at
void* mapPtr_;
public:
//! Construct a new MapMemoryCommand
UnmapMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, void* mapPtr)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory), mapPtr_(mapPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitUnmapMemory(*this); }
virtual void releaseResources();
//! Read the memory object
Memory& memory() const { return *memory_; }
//! Read the map pointer
void* mapPtr() const { return mapPtr_; }
};
/*! \brief Migrate memory objects command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations.
*/
class MigrateMemObjectsCommand : public Command {
private:
cl_mem_migration_flags migrationFlags_; //!< Migration flags
std::vector<amd::Memory*> memObjects_; //!< The list of memory objects
public:
//! Construct a new AcquireExtObjectsCommand
MigrateMemObjectsCommand(HostQueue& queue, cl_command_type type,
const EventWaitList& eventWaitList,
const std::vector<amd::Memory*>& memObjects,
cl_mem_migration_flags flags)
: Command(queue, type, eventWaitList), migrationFlags_(flags) {
for (const auto& it : memObjects) {
it->retain();
memObjects_.push_back(it);
}
}
virtual void submit(device::VirtualDevice& device) { device.submitMigrateMemObjects(*this); }
//! Release all resources associated with this command
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
//! Returns the migration flags
cl_mem_migration_flags migrationFlags() const { return migrationFlags_; }
//! Returns the number of memory objects in the command
uint32_t numMemObjects() const { return (uint32_t)memObjects_.size(); }
//! Returns a pointer to the memory objects
const std::vector<amd::Memory*>& memObjects() const { return memObjects_; }
bool validateMemory();
};
//! To execute a kernel on a specific device.
class NDRangeKernelCommand : public Command {
private:
Kernel& kernel_;
NDRangeContainer sizes_;
address parameters_; //!< Pointer to the kernel argumets
// The below fields are specific to the HIP functionality
uint32_t sharedMemBytes_; //!< Size of reserved shared memory
uint32_t extraParam_; //!< Extra flags for the kernel launch
uint32_t gridId_; //!< Grid ID in the multi GPU kernel launch
uint32_t numGrids_; //!< Total number of grids in multi GPU launch
uint64_t prevGridSum_; //!< A sum of previous grids to the current launch
uint64_t allGridSum_; //!< A sum of all grids in multi GPU launch
uint32_t firstDevice_; //!< Device index of the first device in the grid
public:
enum {
CooperativeGroups = 0x01,
CooperativeMultiDeviceGroups = 0x02,
AnyOrderLaunch = 0x04,
};
//! Construct an ExecuteKernel command
NDRangeKernelCommand(HostQueue& queue, const EventWaitList& eventWaitList, Kernel& kernel,
const NDRangeContainer& sizes, uint32_t sharedMemBytes = 0,
uint32_t extraParam = 0, uint32_t gridId = 0, uint32_t numGrids = 0,
uint64_t prevGridSum = 0, uint64_t allGridSum = 0,
uint32_t firstDevice = 0, bool forceProfiling = false);
virtual void submit(device::VirtualDevice& device) { device.submitKernel(*this); }
//! Release all resources associated with this command (
void releaseResources();
//! Return the kernel.
const Kernel& kernel() const { return kernel_; }
//! Return the parameters given to this kernel.
const_address parameters() const { return parameters_; }
//! Return the kernel NDRange.
const NDRangeContainer& sizes() const { return sizes_; }
//! updates kernel NDRange.
void setSizes(const size_t* globalWorkOffset, const size_t* globalWorkSize,
const size_t* localWorkSize) {
sizes_.update(3, globalWorkOffset, globalWorkSize, localWorkSize);
}
//! Return the shared memory size
uint32_t sharedMemBytes() const { return sharedMemBytes_; }
//! updates shared memory size
uint32_t setSharedMemBytes(uint32_t sharedMemBytes) { sharedMemBytes_ = sharedMemBytes; }
//! Return the cooperative groups mode
bool cooperativeGroups() const { return (extraParam_ & CooperativeGroups) ? true : false; }
//! Return the cooperative multi device groups mode
bool cooperativeMultiDeviceGroups() const {
return (extraParam_ & CooperativeMultiDeviceGroups) ? true : false;
}
//! Returns extra Param, set when using anyorder launch
bool getAnyOrderLaunchFlag() const { return (extraParam_ & AnyOrderLaunch) ? true : false; }
//! Return the current grid ID for multidevice launch
uint32_t gridId() const { return gridId_; }
//! Return the number of launched grids
uint32_t numGrids() const { return numGrids_; }
//! Return the total workload size for up to the current
uint64_t prevGridSum() const { return prevGridSum_; }
//! Return the total workload size for all GPUs
uint64_t allGridSum() const { return allGridSum_; }
//! Return the index of the first device in multi GPU launch
uint64_t firstDevice() const { return firstDevice_; }
//! Set the local work size.
void setLocalWorkSize(const NDRange& local) { sizes_.local() = local; }
int32_t captureAndValidate();
};
class NativeFnCommand : public Command {
private:
void(CL_CALLBACK* nativeFn_)(void*);
char* args_;
size_t argsSize_;
std::vector<Memory*> memObjects_;
std::vector<size_t> memOffsets_;
public:
NativeFnCommand(HostQueue& queue, const EventWaitList& eventWaitList,
void(CL_CALLBACK* nativeFn)(void*), const void* args, size_t argsSize,
size_t numMemObjs, const cl_mem* memObjs, const void** memLocs);
~NativeFnCommand() { delete[] args_; }
void releaseResources() {
std::for_each(memObjects_.begin(), memObjects_.end(), std::mem_fun(&Memory::release));
Command::releaseResources();
}
virtual void submit(device::VirtualDevice& device) { device.submitNativeFn(*this); }
int32_t invoke();
};
class ExternalSemaphoreCmd : public Command {
public:
enum ExternalSemaphoreCmdType { COMMAND_WAIT_EXTSEMAPHORE, COMMAND_SIGNAL_EXTSEMAPHORE };
private:
const void* sem_ptr_; //!< Pointer to external semaphore
int fence_; //!< semaphore value to be set
ExternalSemaphoreCmdType cmd_type_; //!< Signal or Wait semaphore command
public:
ExternalSemaphoreCmd(HostQueue& queue, const void* sem_ptr, int fence,
ExternalSemaphoreCmdType cmd_type)
: Command::Command(queue, CL_COMMAND_USER), sem_ptr_(sem_ptr), fence_(fence), cmd_type_(cmd_type) {}
virtual void submit(device::VirtualDevice& device) {
device.submitExternalSemaphoreCmd(*this);
}
const void* sem_ptr() const { return sem_ptr_; }
const int fence() { return fence_; }
const ExternalSemaphoreCmdType semaphoreCmd() { return cmd_type_; }
};
class Marker : public Command {
public:
//! Create a new Marker
Marker(HostQueue& queue, bool userVisible, const EventWaitList& eventWaitList = nullWaitList,
const Event* waitingEvent = nullptr, bool cpu_wait = false)
: Command(queue, userVisible ? CL_COMMAND_MARKER : 0, eventWaitList, 0, waitingEvent) { cpu_wait_ = cpu_wait; }
//! The actual command implementation.
virtual void submit(device::VirtualDevice& device) { device.submitMarker(*this); }
};
/*! \brief Maps CL objects created from external ones and syncs the contents (blocking).
*
*/
class ExtObjectsCommand : public Command {
private:
std::vector<amd::Memory*> memObjects_; //!< The list of Memory based classes
public:
//! Construct a new AcquireExtObjectsCommand
ExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList, uint32_t num_objects,
const std::vector<amd::Memory*>& memoryObjects, cl_command_type type)
: Command(queue, type, eventWaitList) {
for (const auto& it : memoryObjects) {
it->retain();
memObjects_.push_back(it);
}
}
//! Release all resources associated with this command
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
//! Get number of GL objects
uint32_t getNumObjects() { return (uint32_t)memObjects_.size(); }
//! Get pointer to GL object list
const std::vector<amd::Memory*>& getMemList() const { return memObjects_; }
bool validateMemory();
virtual bool processGLResource(device::Memory* mem) = 0;
};
class AcquireExtObjectsCommand : public ExtObjectsCommand {
public:
//! Construct a new AcquireExtObjectsCommand
AcquireExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
uint32_t num_objects, const std::vector<amd::Memory*>& memoryObjects,
cl_command_type type)
: ExtObjectsCommand(queue, eventWaitList, num_objects, memoryObjects, type) {}
virtual void submit(device::VirtualDevice& device) { device.submitAcquireExtObjects(*this); }
virtual bool processGLResource(device::Memory* mem);
};
class ReleaseExtObjectsCommand : public ExtObjectsCommand {
public:
//! Construct a new ReleaseExtObjectsCommand
ReleaseExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
uint32_t num_objects, const std::vector<amd::Memory*>& memoryObjects,
cl_command_type type)
: ExtObjectsCommand(queue, eventWaitList, num_objects, memoryObjects, type) {}
virtual void submit(device::VirtualDevice& device) { device.submitReleaseExtObjects(*this); }
virtual bool processGLResource(device::Memory* mem);
};
class PerfCounterCommand : public Command {
public:
typedef std::vector<PerfCounter*> PerfCounterList;
enum State {
Begin = 0, //!< Issue a begin command
End = 1 //!< Issue an end command
};
//! Construct a new PerfCounterCommand
PerfCounterCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const PerfCounterList& counterList, State state)
: Command(queue, 1, eventWaitList), counterList_(counterList), state_(state) {
for (uint i = 0; i < counterList_.size(); ++i) {
counterList_[i]->retain();
}
}
void releaseResources() {
for (uint i = 0; i < counterList_.size(); ++i) {
counterList_[i]->release();
}
Command::releaseResources();
}
//! Gets the number of PerfCounter objects
size_t getNumCounters() const { return counterList_.size(); }
//! Gets the list of all counters
const PerfCounterList& getCounters() const { return counterList_; }
//! Gets the performance counter state
State getState() const { return state_; }
//! Process the command on the device queue
virtual void submit(device::VirtualDevice& device) { device.submitPerfCounter(*this); }
private:
PerfCounterList counterList_; //!< The list of performance counters
State state_; //!< State of the issued command
};
/*! \brief Thread Trace memory objects command.
*
* \details Used for bindig memory objects to therad trace mechanism.
*/
class ThreadTraceMemObjectsCommand : public Command {
public:
//! Construct a new ThreadTraceMemObjectsCommand
ThreadTraceMemObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
size_t numMemoryObjects, const cl_mem* memoryObjects,
size_t sizeMemoryObject, ThreadTrace& threadTrace,
cl_command_type type)
: Command(queue, type, eventWaitList),
sizeMemObjects_(sizeMemoryObject),
threadTrace_(threadTrace) {
memObjects_.resize(numMemoryObjects);
for (size_t i = 0; i < numMemoryObjects; ++i) {
Memory* obj = as_amd(memoryObjects[i]);
obj->retain();
memObjects_[i] = obj;
}
threadTrace_.retain();
}
//! Release all resources associated with this command
void releaseResources() {
threadTrace_.release();
for (const auto& itr : memObjects_) {
itr->release();
}
Command::releaseResources();
}
//! Get number of CL memory objects
uint32_t getNumObjects() { return (uint32_t)memObjects_.size(); }
//! Get pointer to CL memory object list
const std::vector<amd::Memory*>& getMemList() const { return memObjects_; }
//! Submit command to bind memory object to the Thread Trace mechanism
virtual void submit(device::VirtualDevice& device) { device.submitThreadTraceMemObjects(*this); }
//! Return the thread trace object.
ThreadTrace& getThreadTrace() const { return threadTrace_; }
//! Get memory object size
const size_t getMemoryObjectSize() const { return sizeMemObjects_; }
//! Validate memory bound to the thread thrace
bool validateMemory();
private:
std::vector<amd::Memory*> memObjects_; //!< The list of memory objects,bound to the thread trace
size_t sizeMemObjects_; //!< The size of each memory object from memObjects_ list (all memory
//! objects have the smae size)
ThreadTrace& threadTrace_; //!< The Thread Trace object
};
/*! \brief Thread Trace command.
*
* \details Used for issue begin/end/pause/resume for therad trace object.
*/
class ThreadTraceCommand : public Command {
private:
void* threadTraceConfig_;
public:
enum State {
Begin = 0, //!< Issue a begin command
End = 1, //!< Issue an end command
Pause = 2, //!< Issue a pause command
Resume = 3 //!< Issue a resume command
};
//! Construct a new ThreadTraceCommand
ThreadTraceCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const void* threadTraceConfig, ThreadTrace& threadTrace, State state,
cl_command_type type)
: Command(queue, type, eventWaitList), threadTrace_(threadTrace), state_(state) {
const unsigned int size = *static_cast<const unsigned int*>(threadTraceConfig);
threadTraceConfig_ = static_cast<void*>(new char[size]);
if (threadTraceConfig_) {
memcpy(threadTraceConfig_, threadTraceConfig, size);
}
threadTrace_.retain();
}
//! Release all resources associated with this command
void releaseResources() {
threadTrace_.release();
Command::releaseResources();
}
//! Get the thread trace object
ThreadTrace& getThreadTrace() const { return threadTrace_; }
//! Get the thread trace command state
State getState() const { return state_; }
//! Process the command on the device queue
virtual void submit(device::VirtualDevice& device) { device.submitThreadTrace(*this); }
// Accessor methods
void* threadTraceConfig() const { return threadTraceConfig_; }
private:
ThreadTrace& threadTrace_; //!< The list of performance counters
State state_; //!< State of the issued command
};
class SignalCommand : public OneMemoryArgCommand {
private:
uint32_t markerValue_;
uint64_t markerOffset_;
public:
SignalCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, uint32_t value, uint64_t offset = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
markerValue_(value),
markerOffset_(offset) {}
virtual void submit(device::VirtualDevice& device) { device.submitSignal(*this); }
const uint32_t markerValue() { return markerValue_; }
Memory& memory() { return *memory_; }
const uint64_t markerOffset() { return markerOffset_; }
};
class MakeBuffersResidentCommand : public Command {
private:
std::vector<amd::Memory*> memObjects_;
cl_bus_address_amd* busAddresses_;
public:
MakeBuffersResidentCommand(HostQueue& queue, cl_command_type type,
const EventWaitList& eventWaitList,
const std::vector<amd::Memory*>& memObjects,
cl_bus_address_amd* busAddr)
: Command(queue, type, eventWaitList), busAddresses_(busAddr) {
for (const auto& it : memObjects) {
it->retain();
memObjects_.push_back(it);
}
}
virtual void submit(device::VirtualDevice& device) { device.submitMakeBuffersResident(*this); }
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
bool validateMemory();
const std::vector<amd::Memory*>& memObjects() const { return memObjects_; }
cl_bus_address_amd* busAddress() const { return busAddresses_; }
};
//! A deallocation command used to free SVM or system pointers.
class SvmFreeMemoryCommand : public Command {
public:
typedef void(CL_CALLBACK* freeCallBack)(cl_command_queue, uint32_t, void**, void*);
private:
std::vector<void*> svmPointers_; //!< List of pointers to deallocate
freeCallBack pfnFreeFunc_; //!< User-defined deallocation callback
void* userData_; //!< Data passed to user-defined callback
public:
SvmFreeMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, uint32_t numSvmPointers,
void** svmPointers, freeCallBack pfnFreeFunc, void* userData)
: Command(queue, CL_COMMAND_SVM_FREE, eventWaitList),
//! We copy svmPointers since it can be reused/deallocated after
// command creation
svmPointers_(svmPointers, svmPointers + numSvmPointers),
pfnFreeFunc_(pfnFreeFunc),
userData_(userData) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmFreeMemory(*this); }
std::vector<void*>& svmPointers() { return svmPointers_; }
freeCallBack pfnFreeFunc() const { return pfnFreeFunc_; }
void* userData() const { return userData_; }
};
//! A copy command where the origin and destination memory locations are SVM
// pointers.
class SvmCopyMemoryCommand : public Command {
private:
void* dst_; //!< Destination pointer
const void* src_; //!< Source pointer
size_t srcSize_; //!< Size (in bytes) of the source buffer
public:
SvmCopyMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, void* dst,
const void* src, size_t srcSize)
: Command(queue, CL_COMMAND_SVM_MEMCPY, eventWaitList),
dst_(dst),
src_(src),
srcSize_(srcSize) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmCopyMemory(*this); }
void* dst() const { return dst_; }
const void* src() const { return src_; }
size_t srcSize() const { return srcSize_; }
};
//! A fill command where the pattern and destination memory locations are SVM
// pointers.
class SvmFillMemoryCommand : public Command {
private:
void* dst_; //!< Destination pointer
char pattern_[FillMemoryCommand::MaxFillPatterSize]; //!< The fill pattern
size_t patternSize_; //!< Pattern size
size_t times_; //!< Number of times to fill the
// destination buffer with the source buffer
public:
SvmFillMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, void* dst,
const void* pattern, size_t patternSize, size_t size)
: Command(queue, CL_COMMAND_SVM_MEMFILL, eventWaitList),
dst_(dst),
patternSize_(patternSize),
times_(size / patternSize) {
assert(amd::isMultipleOf(size, patternSize));
//! We copy the pattern buffer since it can be reused/deallocated after
// command creation
memcpy(pattern_, pattern, patternSize);
}
virtual void submit(device::VirtualDevice& device) { device.submitSvmFillMemory(*this); }
void* dst() const { return dst_; }
const char* pattern() const { return pattern_; }
size_t patternSize() const { return patternSize_; }
size_t times() const { return times_; }
};
/*! \brief A map memory command where the pointer to be mapped is a SVM shared
* buffer
*/
class SvmMapMemoryCommand : public Command {
private:
Memory* svmMem_; //!< the pointer to the amd::Memory object corresponding the svm pointer mapped
Coord3D size_; //!< the map size
Coord3D origin_; //!< the origin of the mapped svm pointer shift from the beginning of svm space
//! allocated
cl_map_flags flags_; //!< map flags
void* svmPtr_;
public:
SvmMapMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, Memory* svmMem,
const size_t size, const size_t offset, cl_map_flags flags, void* svmPtr)
: Command(queue, CL_COMMAND_SVM_MAP, eventWaitList),
svmMem_(svmMem),
size_(size),
origin_(offset),
flags_(flags),
svmPtr_(svmPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmMapMemory(*this); }
Memory* getSvmMem() const { return svmMem_; }
Coord3D size() const { return size_; }
cl_map_flags mapFlags() const { return flags_; }
Coord3D origin() const { return origin_; }
void* svmPtr() const { return svmPtr_; }
bool isEntireMemory() const;
};
/*! \brief An unmap memory command where the unmapped pointer is a SVM shared
* buffer
*/
class SvmUnmapMemoryCommand : public Command {
private:
Memory* svmMem_; //!< the pointer to the amd::Memory object corresponding the svm pointer mapped
void* svmPtr_; //!< SVM pointer
public:
SvmUnmapMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, Memory* svmMem,
void* svmPtr)
: Command(queue, CL_COMMAND_SVM_UNMAP, eventWaitList), svmMem_(svmMem), svmPtr_(svmPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmUnmapMemory(*this); }
Memory* getSvmMem() const { return svmMem_; }
void* svmPtr() const { return svmPtr_; }
};
/*! \brief A generic transfer memory from/to file command.
*
* \details Currently supports buffers only. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class TransferBufferFileCommand : public OneMemoryArgCommand {
public:
static constexpr uint NumStagingBuffers = 2;
static constexpr size_t StagingBufferSize = 4 * Mi;
static constexpr uint StagingBufferMemType = CL_MEM_USE_PERSISTENT_MEM_AMD;
protected:
const Coord3D origin_; //!< Origin of the region to write to
const Coord3D size_; //!< Size of the region to write to
LiquidFlashFile* file_; //!< The file object for data read
size_t fileOffset_; //!< Offset in the file for data read
amd::Memory* staging_[NumStagingBuffers]; //!< Staging buffers for transfer
public:
TransferBufferFileCommand(cl_command_type type, HostQueue& queue,
const EventWaitList& eventWaitList, Memory& memory,
const Coord3D& origin, const Coord3D& size, LiquidFlashFile* file,
size_t fileOffset)
: OneMemoryArgCommand(queue, type, eventWaitList, memory),
origin_(origin),
size_(size),
file_(file),
fileOffset_(fileOffset) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
for (uint i = 0; i < NumStagingBuffers; ++i) {
staging_[i] = NULL;
}
}
virtual void releaseResources();
virtual void submit(device::VirtualDevice& device);
//! Return the memory object to write to
Memory& memory() const { return *memory_; }
//! Return the host memory to read from
LiquidFlashFile* file() const { return file_; }
//! Returns file offset
size_t fileOffset() const { return fileOffset_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return the staging buffer for transfer
Memory& staging(uint i) const { return *staging_[i]; }
bool validateMemory();
};
/*! \brief A P2P copy memory command
*
* \details Used for buffers only. Backends are expected
* to handle any required translation. Buffers are treated
* as 1D structures so origin_[0] and size_[0] are
* equivalent to offset_ and count_ respectively.
*/
class CopyMemoryP2PCommand : public CopyMemoryCommand {
public:
CopyMemoryP2PCommand(HostQueue& queue, cl_command_type cmdType,
const EventWaitList& eventWaitList, Memory& srcMemory, Memory& dstMemory,
Coord3D srcOrigin, Coord3D dstOrigin, Coord3D size)
: CopyMemoryCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory, srcOrigin, dstOrigin,
size) {}
virtual void submit(device::VirtualDevice& device) { device.submitCopyMemoryP2P(*this); }
bool validateMemory();
};
/*! \brief Prefetch command for SVM memory
*
* \details Prefetches SVM memory into the current device or CPU
*/
class SvmPrefetchAsyncCommand : public Command {
const void* dev_ptr_; //!< Device pointer to memory for prefetch
size_t count_; //!< the size for prefetch
bool cpu_access_; //!< Prefetch data into CPU location
public:
SvmPrefetchAsyncCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const void* dev_ptr, size_t count, bool cpu_access)
: Command(queue, 1, eventWaitList), dev_ptr_(dev_ptr), count_(count), cpu_access_(cpu_access) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmPrefetchAsync(*this); }
bool validateMemory();
const void* dev_ptr() const { return dev_ptr_; }
size_t count() const { return count_; }
size_t cpu_access() const { return cpu_access_; }
};
/*! @}
* @}
*/
} // namespace amd
#endif /*COMMAND_HPP_*/
SWDEV-240806 - Fix Windows build
Fixes error "All control paths should return a value".
Change-Id: I4718688b55b24862465e15ea0d64b32fa44b3299
/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/*! \file command.hpp
* \brief Declarations for Event, Command and HostQueue objects.
*
* \author Laurent Morichetti
* \date October 2008
*/
#ifndef COMMAND_HPP_
#define COMMAND_HPP_
#include "top.hpp"
#include "thread/monitor.hpp"
#include "thread/thread.hpp"
#include "platform/agent.hpp"
#include "platform/object.hpp"
#include "platform/context.hpp"
#include "platform/ndrange.hpp"
#include "platform/kernel.hpp"
#include "device/device.hpp"
#include "utils/concurrent.hpp"
#include "platform/memory.hpp"
#include "platform/perfctr.hpp"
#include "platform/threadtrace.hpp"
#include "platform/activity.hpp"
#include "platform/command_utils.hpp"
#include "CL/cl_ext.h"
#include <algorithm>
#include <atomic>
#include <functional>
#include <vector>
namespace amd {
/*! \addtogroup Runtime
* @{
*
* \addtogroup Commands Event, Commands and Command-Queue
* @{
*/
class Command;
class HostQueue;
/*! \brief Encapsulates the status of a command.
*
* \details An event object encapsulates the status of a Command
* it is associated with and can be used to synchronize operations
* in a Context.
*/
class Event : public RuntimeObject {
typedef void(CL_CALLBACK* CallBackFunction)(cl_event event, int32_t command_exec_status,
void* user_data);
struct CallBackEntry : public HeapObject {
struct CallBackEntry* next_; //!< the next entry in the callback list.
std::atomic<CallBackFunction> callback_; //!< callback function pointer.
void* data_; //!< user data passed to the callback function.
int32_t status_; //!< execution status triggering the callback.
CallBackEntry(int32_t status, CallBackFunction callback, void* data)
: callback_(callback), data_(data), status_(status) {}
};
public:
typedef std::vector<Event*> EventWaitList;
private:
Monitor lock_;
Monitor notify_lock_; //!< Lock used for notification with direct dispatch only
std::atomic<CallBackEntry*> callbacks_; //!< linked list of callback entries.
std::atomic<int32_t> status_; //!< current execution status.
std::atomic_flag notified_; //!< Command queue was notified
void* hw_event_; //!< HW event ID associated with SW event
Event* notify_event_; //!< Notify event, which should contain HW signal
const Device* device_; //!< Device, this event associated with
protected:
static const EventWaitList nullWaitList;
struct ProfilingInfo {
ProfilingInfo(bool enabled = false) : enabled_(enabled), waves_(0), marker_ts_(false) {
if (enabled) {
clear();
callback_ = nullptr;
}
}
uint64_t queued_;
uint64_t submitted_;
uint64_t start_;
uint64_t end_;
bool enabled_; //!< Profiling enabled for the wave limiter
uint32_t waves_; //!< The number of waves used in a dispatch
ProfilingCallback* callback_;
bool marker_ts_;
void clear() {
queued_ = 0ULL;
submitted_ = 0ULL;
start_ = 0ULL;
end_ = 0ULL;
}
void setCallback(ProfilingCallback* callback, uint32_t waves) {
if (callback == NULL) {
return;
}
enabled_ = true;
waves_ = waves;
clear();
callback_ = callback;
}
} profilingInfo_;
activity_prof::ActivityProf activity_; //!< Activity profiling
//! Construct a new event.
Event();
//! Construct a new event associated to the given command \a queue.
Event(HostQueue& queue);
//! Destroy the event.
virtual ~Event();
//! Release the resources associated with this event.
virtual void releaseResources() {}
//! Record the profiling info for the given change of \a status.
// If the given \a timeStamp is 0 and profiling is enabled,
// use the current host clock time instead.
uint64_t recordProfilingInfo(int32_t status, uint64_t timeStamp = 0);
//! Process the callbacks for the given \a status change.
void processCallbacks(int32_t status) const;
//! Enable profiling for this command
void EnableProfiling() {
profilingInfo_.enabled_ = true;
profilingInfo_.clear();
profilingInfo_.callback_ = nullptr;
}
public:
//! Return the context for this event.
virtual const Context& context() const = 0;
//! Return the command this event is associated with.
inline Command& command();
inline const Command& command() const;
//! Return the profiling info.
const ProfilingInfo& profilingInfo() const { return profilingInfo_; }
//! Return this command's execution status.
int32_t status() const { return status_.load(std::memory_order_relaxed); }
//! Insert the given \a callback into the callback stack.
bool setCallback(int32_t status, CallBackFunction callback, void* data);
/*! \brief Set the event status.
*
* \details If the status becomes CL_COMPLETE, notify all threads
* awaiting this command's completion. If the given \a timeStamp is 0
* and profiling is enabled, use the current host clock time instead.
*
* \see amd::Event::awaitCompletion
*/
bool setStatus(int32_t status, uint64_t timeStamp = 0);
//! Reset the status of the command for reuse
bool resetStatus(int32_t status);
//! Signal all threads waiting on this event.
void signal() {
ScopedLock lock(lock_);
lock_.notifyAll();
}
/*! \brief Suspend the current thread until the status of the Command
* associated with this event changes to CL_COMPLETE. Return true if the
* command successfully completed.
*/
virtual bool awaitCompletion();
/*! \brief Notifies current command queue about execution status
*/
bool notifyCmdQueue(bool cpu_wait = false);
//! RTTI internal implementation
virtual ObjectType objectType() const { return ObjectTypeEvent; }
//! Returns the callback for this event
const CallBackEntry* Callback() const { return callbacks_; }
// Saves HW event, associated with the current command
void SetHwEvent(void* hw_event) { hw_event_ = hw_event; }
//! Returns HW event, associated with the current command
void* HwEvent() const { return hw_event_; }
//! Returns notify even associated with the current command
Event* NotifyEvent() const { return notify_event_; }
};
/*! \brief An operation that is submitted to a command queue.
*
* %Command is the abstract base type of all OpenCL operations
* submitted to a HostQueue for execution. Classes derived from
* %Command must implement the submit() function.
*
*/
class Command : public Event {
private:
HostQueue* queue_; //!< The command queue this command is enqueue into
Command* next_; //!< Next GPU command in the queue list
Command* batch_head_ = nullptr; //!< The head of the batch commands
cl_command_type type_; //!< This command's OpenCL type.
void* data_;
const Event* waitingEvent_; //!< Waiting event associated with the marker
protected:
bool cpu_wait_ = false; //!< If true, then the command was issued for CPU/GPU sync
//! The Events that need to complete before this command is submitted.
EventWaitList eventWaitList_;
//! Force await completion of previous command
//! 0x1 - wait before enqueue, 0x2 - wait after, 0x3 - wait both.
uint32_t commandWaitBits_;
//! Construct a new command of the given OpenCL type.
Command(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList = nullWaitList,
uint32_t commandWaitBits = 0, const Event* waitingEvent = nullptr);
//! Construct a new command of the given OpenCL type.
Command(cl_command_type type)
: Event(),
queue_(nullptr),
next_(nullptr),
type_(type),
data_(nullptr),
waitingEvent_(nullptr),
eventWaitList_(nullWaitList),
commandWaitBits_(0) {}
virtual bool terminate() {
if (IS_HIP) {
releaseResources();
}
if (Agent::shouldPostEventEvents() && type() != 0) {
Agent::postEventFree(as_cl(static_cast<Event*>(this)));
}
return true;
}
public:
//! Return the queue this command is enqueued into.
HostQueue* queue() const { return queue_; }
//! Enqueue this command into the associated command queue.
void enqueue();
//! Return the event encapsulating this command's status.
const Event& event() const { return *this; }
Event& event() { return *this; }
//! Return the list of events this command needs to wait on before dispatch
const EventWaitList& eventWaitList() const { return eventWaitList_; }
//! Update with the list of events this command needs to wait on before dispatch
void updateEventWaitList(const EventWaitList& waitList) {
for (auto event : waitList) {
eventWaitList_.push_back(event);
}
}
//! Return this command's OpenCL type.
cl_command_type type() const { return type_; }
//! Return the opaque, device specific data for this command.
void* data() const { return data_; }
//! Set the opaque, device specific data for this command.
void setData(void* data) { data_ = data; }
/*! \brief The execution engine for this command.
*
* \details All derived class must implement this virtual function.
*
* \note This function will execute in the command queue thread.
*/
virtual void submit(device::VirtualDevice& device) = 0;
//! Release the resources associated with this event.
virtual void releaseResources();
//! Set the next GPU command
void setNext(Command* next) { next_ = next; }
//! Get the next GPU command
Command* getNext() const { return next_; }
//! Return the context for this event.
virtual const Context& context() const;
//! Get command wait bits
uint32_t getWaitBits() const { return commandWaitBits_; }
void OverrrideCommandType(cl_command_type type) { type_ = type; }
//! Updates the batch head, associated with this command(marker)
void SetBatchHead(Command* command) { batch_head_ = command; }
//! Returns the current batch head
Command* GetBatchHead() const { return batch_head_; }
const Event* waitingEvent() const { return waitingEvent_; }
//! Check if this command(should be a marker) requires CPU wait
bool CpuWaitRequested() const { return cpu_wait_; }
};
class UserEvent : public Command {
const Context& context_;
public:
UserEvent(Context& context) : Command(CL_COMMAND_USER), context_(context) {
setStatus(CL_SUBMITTED);
}
virtual void submit(device::VirtualDevice& device) { ShouldNotCallThis(); }
virtual const Context& context() const { return context_; }
};
class ClGlEvent : public Command {
private:
const Context& context_;
bool waitForFence();
public:
ClGlEvent(Context& context) : Command(CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR), context_(context) {
setStatus(CL_SUBMITTED);
}
virtual void submit(device::VirtualDevice& device) { ShouldNotCallThis(); }
bool awaitCompletion() { return waitForFence(); }
virtual const Context& context() const { return context_; }
};
inline Command& Event::command() { return *static_cast<Command*>(this); }
inline const Command& Event::command() const { return *static_cast<const Command*>(this); }
class Kernel;
class NDRangeContainer;
//! A memory command that holds a single memory object reference.
//
class OneMemoryArgCommand : public Command {
protected:
Memory* memory_;
public:
OneMemoryArgCommand(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList,
Memory& memory)
: Command(queue, type, eventWaitList, AMD_SERIALIZE_COPY), memory_(&memory) {
memory_->retain();
}
virtual void releaseResources() {
memory_->release();
DEBUG_ONLY(memory_ = NULL);
Command::releaseResources();
}
bool validateMemory();
bool validatePeerMemory();
};
//! A memory command that holds a single memory object reference.
//
class TwoMemoryArgsCommand : public Command {
protected:
Memory* memory1_;
Memory* memory2_;
public:
TwoMemoryArgsCommand(HostQueue& queue, cl_command_type type, const EventWaitList& eventWaitList,
Memory& memory1, Memory& memory2)
: Command(queue, type, eventWaitList, AMD_SERIALIZE_COPY),
memory1_(&memory1),
memory2_(&memory2) {
memory1_->retain();
memory2_->retain();
}
virtual void releaseResources() {
memory1_->release();
memory2_->release();
DEBUG_ONLY(memory1_ = memory2_ = NULL);
Command::releaseResources();
}
bool validateMemory();
bool validatePeerMemory();
};
/*! \brief A generic read memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translation. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*
* @todo Find a cleaner way of merging the row and slice pitch concepts at this level.
*
*/
class ReadMemoryCommand : public OneMemoryArgCommand {
private:
Coord3D origin_; //!< Origin of the region to read.
Coord3D size_; //!< Size of the region to read.
void* hostPtr_; //!< The host pointer destination.
size_t rowPitch_; //!< Row pitch (for image operations)
size_t slicePitch_; //!< Slice pitch (for image operations)
BufferRect bufRect_; //!< Buffer rectangle information
BufferRect hostRect_; //!< Host memory rectangle information
public:
//! Construct a new ReadMemoryCommand
ReadMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, void* hostPtr,
size_t rowPitch = 0, size_t slicePitch = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(rowPitch),
slicePitch_(slicePitch) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
//! Construct a new ReadMemoryCommand
ReadMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, void* hostPtr,
const BufferRect& bufRect, const BufferRect& hostRect)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(0),
slicePitch_(0),
bufRect_(bufRect),
hostRect_(hostRect) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitReadMemory(*this); }
//! Return the memory object to read from.
Memory& source() const { return *memory_; }
//! Return the host memory to write to
void* destination() const { return hostPtr_; }
//! Return the origin of the region to read
const Coord3D& origin() const { return origin_; }
//! Return the size of the region to read
const Coord3D& size() const { return size_; }
//! Return the row pitch
size_t rowPitch() const { return rowPitch_; }
//! Return the slice pitch
size_t slicePitch() const { return slicePitch_; }
//! Return the buffer rectangle information
const BufferRect& bufRect() const { return bufRect_; }
//! Return the host rectangle information
const BufferRect& hostRect() const { return hostRect_; }
//! Return true if the entire memory object is read.
bool isEntireMemory() const;
};
/*! \brief A generic write memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class WriteMemoryCommand : public OneMemoryArgCommand {
private:
Coord3D origin_; //!< Origin of the region to write to.
Coord3D size_; //!< Size of the region to write to.
const void* hostPtr_; //!< The host pointer source.
size_t rowPitch_; //!< Row pitch (for image operations)
size_t slicePitch_; //!< Slice pitch (for image operations)
BufferRect bufRect_; //!< Buffer rectangle information
BufferRect hostRect_; //!< Host memory rectangle information
public:
WriteMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, const void* hostPtr,
size_t rowPitch = 0, size_t slicePitch = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(rowPitch),
slicePitch_(slicePitch) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
WriteMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, Coord3D origin, Coord3D size, const void* hostPtr,
const BufferRect& bufRect, const BufferRect& hostRect)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
hostPtr_(hostPtr),
rowPitch_(0),
slicePitch_(0),
bufRect_(bufRect),
hostRect_(hostRect) {
// Sanity checks
assert(hostPtr != NULL && "hostPtr cannot be null");
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitWriteMemory(*this); }
//! Return the host memory to read from
const void* source() const { return hostPtr_; }
//! Return the memory object to write to.
Memory& destination() const { return *memory_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return the row pitch
size_t rowPitch() const { return rowPitch_; }
//! Return the slice pitch
size_t slicePitch() const { return slicePitch_; }
//! Return the buffer rectangle information
const BufferRect& bufRect() const { return bufRect_; }
//! Return the host rectangle information
const BufferRect& hostRect() const { return hostRect_; }
//! Return true if the entire memory object is written.
bool isEntireMemory() const;
};
/*! \brief A generic fill memory command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class FillMemoryCommand : public OneMemoryArgCommand {
public:
static constexpr size_t MaxFillPatterSize = sizeof(double[16]);
private:
Coord3D origin_; //!< Origin of the region to write to.
Coord3D size_; //!< Size of the region to write to.
char pattern_[MaxFillPatterSize]; //!< The fill pattern
size_t patternSize_; //!< Pattern size
public:
FillMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, const void* pattern, size_t patternSize, Coord3D origin,
Coord3D size)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
origin_(origin),
size_(size),
patternSize_(patternSize) {
// Sanity checks
assert(pattern != NULL && "pattern cannot be null");
assert(size.c[0] > 0 && "invalid");
memcpy(pattern_, pattern, patternSize);
}
virtual void submit(device::VirtualDevice& device) { device.submitFillMemory(*this); }
//! Return the pattern memory to fill with
const void* pattern() const { return reinterpret_cast<const void*>(pattern_); }
//! Return the pattern size
const size_t patternSize() const { return patternSize_; }
//! Return the memory object to write to.
Memory& memory() const { return *memory_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return true if the entire memory object is written.
bool isEntireMemory() const;
};
/*! \brief A stream operation command.
*
* \details Used to perform a stream wait or strem write operations.
* Wait: All the commands issued after stream wait are not executed until the wait
* condition is true.
* Write: Writes a 32 or 64 bit vaue to the memeory using a GPU Blit.
*/
class StreamOperationCommand : public OneMemoryArgCommand {
private:
uint64_t value_; // !< Value to Wait on or to Write.
uint64_t mask_; // !< Mask to be applied on signal value for Wait operation.
unsigned int flags_; // !< Flags defining the Wait condition.
size_t offset_; // !< Offset into memory for Write
size_t sizeBytes_; // !< Size in bytes to Write.
// NOTE: mask_ is only used for wait operation and
// offset and sizeBytes are only used for write.
public:
StreamOperationCommand(HostQueue& queue, cl_command_type cmdType,
const EventWaitList& eventWaitList, Memory& memory, const uint64_t value,
const uint64_t mask, unsigned int flags, size_t offset, size_t sizeBytes)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
value_(value),
mask_(mask),
flags_(flags),
offset_(offset),
sizeBytes_(sizeBytes) {
// Sanity check
assert((cmdType == ROCCLR_COMMAND_STREAM_WRITE_VALUE ||
(cmdType == ROCCLR_COMMAND_STREAM_WAIT_VALUE &&
memory_->getMemFlags() & ROCCLR_MEM_HSA_SIGNAL_MEMORY)) &&
"Invalid Stream Operation");
}
virtual void submit(device::VirtualDevice& device) { device.submitStreamOperation(*this); }
//! Returns the value
const uint64_t value() const { return value_; }
//! Returns the wait mask
const uint64_t mask() const { return mask_; }
//! Return the wait flags
const unsigned int flags() const { return flags_; }
//! Return the memory object.
Memory& memory() const { return *memory_; }
//! Return the write offset.
const size_t offset() const { return offset_; }
//! Return the write size.
const size_t sizeBytes() const { return sizeBytes_; }
};
/*! \brief A generic copy memory command
*
* \details Used for both buffers and images. Backends are expected
* to handle any required translation. Buffers are treated
* as 1D structures so origin_[0] and size_[0] are
* equivalent to offset_ and count_ respectively.
*/
class CopyMemoryCommand : public TwoMemoryArgsCommand {
private:
Coord3D srcOrigin_; //!< Origin of the source region.
Coord3D dstOrigin_; //!< Origin of the destination region.
Coord3D size_; //!< Size of the region to copy.
BufferRect srcRect_; //!< Source buffer rectangle information
BufferRect dstRect_; //!< Destination buffer rectangle information
public:
CopyMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& srcMemory, Memory& dstMemory, Coord3D srcOrigin, Coord3D dstOrigin,
Coord3D size)
: TwoMemoryArgsCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory),
srcOrigin_(srcOrigin),
dstOrigin_(dstOrigin),
size_(size) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
CopyMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& srcMemory, Memory& dstMemory, Coord3D srcOrigin, Coord3D dstOrigin,
Coord3D size, const BufferRect& srcRect, const BufferRect& dstRect)
: TwoMemoryArgsCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory),
srcOrigin_(srcOrigin),
dstOrigin_(dstOrigin),
size_(size),
srcRect_(srcRect),
dstRect_(dstRect) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitCopyMemory(*this); }
//! Return the host memory to read from
Memory& source() const { return *memory1_; }
//! Return the memory object to write to.
Memory& destination() const { return *memory2_; }
//! Return the source origin
const Coord3D& srcOrigin() const { return srcOrigin_; }
//! Return the offset in bytes in the destination.
const Coord3D& dstOrigin() const { return dstOrigin_; }
//! Return the number of bytes to copy.
const Coord3D& size() const { return size_; }
//! Return the source buffer rectangle information
const BufferRect& srcRect() const { return srcRect_; }
//! Return the destination buffer rectangle information
const BufferRect& dstRect() const { return dstRect_; }
//! Return true if the both memories are is read/written in their entirety.
bool isEntireMemory() const;
};
/*! \brief A generic map memory command. Makes a memory object accessible to the host.
*
* @todo:dgladdin Need to think more about how the pitch parameters operate in
* the context of unified buffer/image commands.
*/
class MapMemoryCommand : public OneMemoryArgCommand {
private:
cl_map_flags mapFlags_; //!< Flags controlling the map.
bool blocking_; //!< True for blocking maps
Coord3D origin_; //!< Origin of the region to map.
Coord3D size_; //!< Size of the region to map.
const void* mapPtr_; //!< Host-space pointer that the object is currently mapped at
public:
//! Construct a new MapMemoryCommand
MapMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, cl_map_flags mapFlags, bool blocking, Coord3D origin,
Coord3D size, size_t* imgRowPitch = nullptr, size_t* imgSlicePitch = nullptr,
void* mapPtr = nullptr)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
mapFlags_(mapFlags),
blocking_(blocking),
origin_(origin),
size_(size),
mapPtr_(mapPtr) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
}
virtual void submit(device::VirtualDevice& device) { device.submitMapMemory(*this); }
//! Read the memory object
Memory& memory() const { return *memory_; }
//! Read the map control flags
cl_map_flags mapFlags() const { return mapFlags_; }
//! Read the origin
const Coord3D& origin() const { return origin_; }
//! Read the size
const Coord3D& size() const { return size_; }
//! Read the blocking flag
bool blocking() const { return blocking_; }
//! Returns true if the entire memory object is mapped
bool isEntireMemory() const;
//! Read the map pointer
const void* mapPtr() const { return mapPtr_; }
};
/*! \brief A generic unmap memory command.
*
* @todo:dgladdin Need to think more about how the pitch parameters operate in
* the context of unified buffer/image commands.
*/
class UnmapMemoryCommand : public OneMemoryArgCommand {
private:
//! Host-space pointer that the object is currently mapped at
void* mapPtr_;
public:
//! Construct a new MapMemoryCommand
UnmapMemoryCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, void* mapPtr)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory), mapPtr_(mapPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitUnmapMemory(*this); }
virtual void releaseResources();
//! Read the memory object
Memory& memory() const { return *memory_; }
//! Read the map pointer
void* mapPtr() const { return mapPtr_; }
};
/*! \brief Migrate memory objects command.
*
* \details Used for operations on both buffers and images. Backends
* are expected to handle any required translations.
*/
class MigrateMemObjectsCommand : public Command {
private:
cl_mem_migration_flags migrationFlags_; //!< Migration flags
std::vector<amd::Memory*> memObjects_; //!< The list of memory objects
public:
//! Construct a new AcquireExtObjectsCommand
MigrateMemObjectsCommand(HostQueue& queue, cl_command_type type,
const EventWaitList& eventWaitList,
const std::vector<amd::Memory*>& memObjects,
cl_mem_migration_flags flags)
: Command(queue, type, eventWaitList), migrationFlags_(flags) {
for (const auto& it : memObjects) {
it->retain();
memObjects_.push_back(it);
}
}
virtual void submit(device::VirtualDevice& device) { device.submitMigrateMemObjects(*this); }
//! Release all resources associated with this command
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
//! Returns the migration flags
cl_mem_migration_flags migrationFlags() const { return migrationFlags_; }
//! Returns the number of memory objects in the command
uint32_t numMemObjects() const { return (uint32_t)memObjects_.size(); }
//! Returns a pointer to the memory objects
const std::vector<amd::Memory*>& memObjects() const { return memObjects_; }
bool validateMemory();
};
//! To execute a kernel on a specific device.
class NDRangeKernelCommand : public Command {
private:
Kernel& kernel_;
NDRangeContainer sizes_;
address parameters_; //!< Pointer to the kernel argumets
// The below fields are specific to the HIP functionality
uint32_t sharedMemBytes_; //!< Size of reserved shared memory
uint32_t extraParam_; //!< Extra flags for the kernel launch
uint32_t gridId_; //!< Grid ID in the multi GPU kernel launch
uint32_t numGrids_; //!< Total number of grids in multi GPU launch
uint64_t prevGridSum_; //!< A sum of previous grids to the current launch
uint64_t allGridSum_; //!< A sum of all grids in multi GPU launch
uint32_t firstDevice_; //!< Device index of the first device in the grid
public:
enum {
CooperativeGroups = 0x01,
CooperativeMultiDeviceGroups = 0x02,
AnyOrderLaunch = 0x04,
};
//! Construct an ExecuteKernel command
NDRangeKernelCommand(HostQueue& queue, const EventWaitList& eventWaitList, Kernel& kernel,
const NDRangeContainer& sizes, uint32_t sharedMemBytes = 0,
uint32_t extraParam = 0, uint32_t gridId = 0, uint32_t numGrids = 0,
uint64_t prevGridSum = 0, uint64_t allGridSum = 0,
uint32_t firstDevice = 0, bool forceProfiling = false);
virtual void submit(device::VirtualDevice& device) { device.submitKernel(*this); }
//! Release all resources associated with this command (
void releaseResources();
//! Return the kernel.
const Kernel& kernel() const { return kernel_; }
//! Return the parameters given to this kernel.
const_address parameters() const { return parameters_; }
//! Return the kernel NDRange.
const NDRangeContainer& sizes() const { return sizes_; }
//! updates kernel NDRange.
void setSizes(const size_t* globalWorkOffset, const size_t* globalWorkSize,
const size_t* localWorkSize) {
sizes_.update(3, globalWorkOffset, globalWorkSize, localWorkSize);
}
//! Return the shared memory size
uint32_t sharedMemBytes() const { return sharedMemBytes_; }
//! updates shared memory size
void setSharedMemBytes(uint32_t sharedMemBytes) { sharedMemBytes_ = sharedMemBytes; }
//! Return the cooperative groups mode
bool cooperativeGroups() const { return (extraParam_ & CooperativeGroups) ? true : false; }
//! Return the cooperative multi device groups mode
bool cooperativeMultiDeviceGroups() const {
return (extraParam_ & CooperativeMultiDeviceGroups) ? true : false;
}
//! Returns extra Param, set when using anyorder launch
bool getAnyOrderLaunchFlag() const { return (extraParam_ & AnyOrderLaunch) ? true : false; }
//! Return the current grid ID for multidevice launch
uint32_t gridId() const { return gridId_; }
//! Return the number of launched grids
uint32_t numGrids() const { return numGrids_; }
//! Return the total workload size for up to the current
uint64_t prevGridSum() const { return prevGridSum_; }
//! Return the total workload size for all GPUs
uint64_t allGridSum() const { return allGridSum_; }
//! Return the index of the first device in multi GPU launch
uint64_t firstDevice() const { return firstDevice_; }
//! Set the local work size.
void setLocalWorkSize(const NDRange& local) { sizes_.local() = local; }
int32_t captureAndValidate();
};
class NativeFnCommand : public Command {
private:
void(CL_CALLBACK* nativeFn_)(void*);
char* args_;
size_t argsSize_;
std::vector<Memory*> memObjects_;
std::vector<size_t> memOffsets_;
public:
NativeFnCommand(HostQueue& queue, const EventWaitList& eventWaitList,
void(CL_CALLBACK* nativeFn)(void*), const void* args, size_t argsSize,
size_t numMemObjs, const cl_mem* memObjs, const void** memLocs);
~NativeFnCommand() { delete[] args_; }
void releaseResources() {
std::for_each(memObjects_.begin(), memObjects_.end(), std::mem_fun(&Memory::release));
Command::releaseResources();
}
virtual void submit(device::VirtualDevice& device) { device.submitNativeFn(*this); }
int32_t invoke();
};
class ExternalSemaphoreCmd : public Command {
public:
enum ExternalSemaphoreCmdType { COMMAND_WAIT_EXTSEMAPHORE, COMMAND_SIGNAL_EXTSEMAPHORE };
private:
const void* sem_ptr_; //!< Pointer to external semaphore
int fence_; //!< semaphore value to be set
ExternalSemaphoreCmdType cmd_type_; //!< Signal or Wait semaphore command
public:
ExternalSemaphoreCmd(HostQueue& queue, const void* sem_ptr, int fence,
ExternalSemaphoreCmdType cmd_type)
: Command::Command(queue, CL_COMMAND_USER), sem_ptr_(sem_ptr), fence_(fence), cmd_type_(cmd_type) {}
virtual void submit(device::VirtualDevice& device) {
device.submitExternalSemaphoreCmd(*this);
}
const void* sem_ptr() const { return sem_ptr_; }
const int fence() { return fence_; }
const ExternalSemaphoreCmdType semaphoreCmd() { return cmd_type_; }
};
class Marker : public Command {
public:
//! Create a new Marker
Marker(HostQueue& queue, bool userVisible, const EventWaitList& eventWaitList = nullWaitList,
const Event* waitingEvent = nullptr, bool cpu_wait = false)
: Command(queue, userVisible ? CL_COMMAND_MARKER : 0, eventWaitList, 0, waitingEvent) { cpu_wait_ = cpu_wait; }
//! The actual command implementation.
virtual void submit(device::VirtualDevice& device) { device.submitMarker(*this); }
};
/*! \brief Maps CL objects created from external ones and syncs the contents (blocking).
*
*/
class ExtObjectsCommand : public Command {
private:
std::vector<amd::Memory*> memObjects_; //!< The list of Memory based classes
public:
//! Construct a new AcquireExtObjectsCommand
ExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList, uint32_t num_objects,
const std::vector<amd::Memory*>& memoryObjects, cl_command_type type)
: Command(queue, type, eventWaitList) {
for (const auto& it : memoryObjects) {
it->retain();
memObjects_.push_back(it);
}
}
//! Release all resources associated with this command
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
//! Get number of GL objects
uint32_t getNumObjects() { return (uint32_t)memObjects_.size(); }
//! Get pointer to GL object list
const std::vector<amd::Memory*>& getMemList() const { return memObjects_; }
bool validateMemory();
virtual bool processGLResource(device::Memory* mem) = 0;
};
class AcquireExtObjectsCommand : public ExtObjectsCommand {
public:
//! Construct a new AcquireExtObjectsCommand
AcquireExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
uint32_t num_objects, const std::vector<amd::Memory*>& memoryObjects,
cl_command_type type)
: ExtObjectsCommand(queue, eventWaitList, num_objects, memoryObjects, type) {}
virtual void submit(device::VirtualDevice& device) { device.submitAcquireExtObjects(*this); }
virtual bool processGLResource(device::Memory* mem);
};
class ReleaseExtObjectsCommand : public ExtObjectsCommand {
public:
//! Construct a new ReleaseExtObjectsCommand
ReleaseExtObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
uint32_t num_objects, const std::vector<amd::Memory*>& memoryObjects,
cl_command_type type)
: ExtObjectsCommand(queue, eventWaitList, num_objects, memoryObjects, type) {}
virtual void submit(device::VirtualDevice& device) { device.submitReleaseExtObjects(*this); }
virtual bool processGLResource(device::Memory* mem);
};
class PerfCounterCommand : public Command {
public:
typedef std::vector<PerfCounter*> PerfCounterList;
enum State {
Begin = 0, //!< Issue a begin command
End = 1 //!< Issue an end command
};
//! Construct a new PerfCounterCommand
PerfCounterCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const PerfCounterList& counterList, State state)
: Command(queue, 1, eventWaitList), counterList_(counterList), state_(state) {
for (uint i = 0; i < counterList_.size(); ++i) {
counterList_[i]->retain();
}
}
void releaseResources() {
for (uint i = 0; i < counterList_.size(); ++i) {
counterList_[i]->release();
}
Command::releaseResources();
}
//! Gets the number of PerfCounter objects
size_t getNumCounters() const { return counterList_.size(); }
//! Gets the list of all counters
const PerfCounterList& getCounters() const { return counterList_; }
//! Gets the performance counter state
State getState() const { return state_; }
//! Process the command on the device queue
virtual void submit(device::VirtualDevice& device) { device.submitPerfCounter(*this); }
private:
PerfCounterList counterList_; //!< The list of performance counters
State state_; //!< State of the issued command
};
/*! \brief Thread Trace memory objects command.
*
* \details Used for bindig memory objects to therad trace mechanism.
*/
class ThreadTraceMemObjectsCommand : public Command {
public:
//! Construct a new ThreadTraceMemObjectsCommand
ThreadTraceMemObjectsCommand(HostQueue& queue, const EventWaitList& eventWaitList,
size_t numMemoryObjects, const cl_mem* memoryObjects,
size_t sizeMemoryObject, ThreadTrace& threadTrace,
cl_command_type type)
: Command(queue, type, eventWaitList),
sizeMemObjects_(sizeMemoryObject),
threadTrace_(threadTrace) {
memObjects_.resize(numMemoryObjects);
for (size_t i = 0; i < numMemoryObjects; ++i) {
Memory* obj = as_amd(memoryObjects[i]);
obj->retain();
memObjects_[i] = obj;
}
threadTrace_.retain();
}
//! Release all resources associated with this command
void releaseResources() {
threadTrace_.release();
for (const auto& itr : memObjects_) {
itr->release();
}
Command::releaseResources();
}
//! Get number of CL memory objects
uint32_t getNumObjects() { return (uint32_t)memObjects_.size(); }
//! Get pointer to CL memory object list
const std::vector<amd::Memory*>& getMemList() const { return memObjects_; }
//! Submit command to bind memory object to the Thread Trace mechanism
virtual void submit(device::VirtualDevice& device) { device.submitThreadTraceMemObjects(*this); }
//! Return the thread trace object.
ThreadTrace& getThreadTrace() const { return threadTrace_; }
//! Get memory object size
const size_t getMemoryObjectSize() const { return sizeMemObjects_; }
//! Validate memory bound to the thread thrace
bool validateMemory();
private:
std::vector<amd::Memory*> memObjects_; //!< The list of memory objects,bound to the thread trace
size_t sizeMemObjects_; //!< The size of each memory object from memObjects_ list (all memory
//! objects have the smae size)
ThreadTrace& threadTrace_; //!< The Thread Trace object
};
/*! \brief Thread Trace command.
*
* \details Used for issue begin/end/pause/resume for therad trace object.
*/
class ThreadTraceCommand : public Command {
private:
void* threadTraceConfig_;
public:
enum State {
Begin = 0, //!< Issue a begin command
End = 1, //!< Issue an end command
Pause = 2, //!< Issue a pause command
Resume = 3 //!< Issue a resume command
};
//! Construct a new ThreadTraceCommand
ThreadTraceCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const void* threadTraceConfig, ThreadTrace& threadTrace, State state,
cl_command_type type)
: Command(queue, type, eventWaitList), threadTrace_(threadTrace), state_(state) {
const unsigned int size = *static_cast<const unsigned int*>(threadTraceConfig);
threadTraceConfig_ = static_cast<void*>(new char[size]);
if (threadTraceConfig_) {
memcpy(threadTraceConfig_, threadTraceConfig, size);
}
threadTrace_.retain();
}
//! Release all resources associated with this command
void releaseResources() {
threadTrace_.release();
Command::releaseResources();
}
//! Get the thread trace object
ThreadTrace& getThreadTrace() const { return threadTrace_; }
//! Get the thread trace command state
State getState() const { return state_; }
//! Process the command on the device queue
virtual void submit(device::VirtualDevice& device) { device.submitThreadTrace(*this); }
// Accessor methods
void* threadTraceConfig() const { return threadTraceConfig_; }
private:
ThreadTrace& threadTrace_; //!< The list of performance counters
State state_; //!< State of the issued command
};
class SignalCommand : public OneMemoryArgCommand {
private:
uint32_t markerValue_;
uint64_t markerOffset_;
public:
SignalCommand(HostQueue& queue, cl_command_type cmdType, const EventWaitList& eventWaitList,
Memory& memory, uint32_t value, uint64_t offset = 0)
: OneMemoryArgCommand(queue, cmdType, eventWaitList, memory),
markerValue_(value),
markerOffset_(offset) {}
virtual void submit(device::VirtualDevice& device) { device.submitSignal(*this); }
const uint32_t markerValue() { return markerValue_; }
Memory& memory() { return *memory_; }
const uint64_t markerOffset() { return markerOffset_; }
};
class MakeBuffersResidentCommand : public Command {
private:
std::vector<amd::Memory*> memObjects_;
cl_bus_address_amd* busAddresses_;
public:
MakeBuffersResidentCommand(HostQueue& queue, cl_command_type type,
const EventWaitList& eventWaitList,
const std::vector<amd::Memory*>& memObjects,
cl_bus_address_amd* busAddr)
: Command(queue, type, eventWaitList), busAddresses_(busAddr) {
for (const auto& it : memObjects) {
it->retain();
memObjects_.push_back(it);
}
}
virtual void submit(device::VirtualDevice& device) { device.submitMakeBuffersResident(*this); }
void releaseResources() {
for (const auto& it : memObjects_) {
it->release();
}
Command::releaseResources();
}
bool validateMemory();
const std::vector<amd::Memory*>& memObjects() const { return memObjects_; }
cl_bus_address_amd* busAddress() const { return busAddresses_; }
};
//! A deallocation command used to free SVM or system pointers.
class SvmFreeMemoryCommand : public Command {
public:
typedef void(CL_CALLBACK* freeCallBack)(cl_command_queue, uint32_t, void**, void*);
private:
std::vector<void*> svmPointers_; //!< List of pointers to deallocate
freeCallBack pfnFreeFunc_; //!< User-defined deallocation callback
void* userData_; //!< Data passed to user-defined callback
public:
SvmFreeMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, uint32_t numSvmPointers,
void** svmPointers, freeCallBack pfnFreeFunc, void* userData)
: Command(queue, CL_COMMAND_SVM_FREE, eventWaitList),
//! We copy svmPointers since it can be reused/deallocated after
// command creation
svmPointers_(svmPointers, svmPointers + numSvmPointers),
pfnFreeFunc_(pfnFreeFunc),
userData_(userData) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmFreeMemory(*this); }
std::vector<void*>& svmPointers() { return svmPointers_; }
freeCallBack pfnFreeFunc() const { return pfnFreeFunc_; }
void* userData() const { return userData_; }
};
//! A copy command where the origin and destination memory locations are SVM
// pointers.
class SvmCopyMemoryCommand : public Command {
private:
void* dst_; //!< Destination pointer
const void* src_; //!< Source pointer
size_t srcSize_; //!< Size (in bytes) of the source buffer
public:
SvmCopyMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, void* dst,
const void* src, size_t srcSize)
: Command(queue, CL_COMMAND_SVM_MEMCPY, eventWaitList),
dst_(dst),
src_(src),
srcSize_(srcSize) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmCopyMemory(*this); }
void* dst() const { return dst_; }
const void* src() const { return src_; }
size_t srcSize() const { return srcSize_; }
};
//! A fill command where the pattern and destination memory locations are SVM
// pointers.
class SvmFillMemoryCommand : public Command {
private:
void* dst_; //!< Destination pointer
char pattern_[FillMemoryCommand::MaxFillPatterSize]; //!< The fill pattern
size_t patternSize_; //!< Pattern size
size_t times_; //!< Number of times to fill the
// destination buffer with the source buffer
public:
SvmFillMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, void* dst,
const void* pattern, size_t patternSize, size_t size)
: Command(queue, CL_COMMAND_SVM_MEMFILL, eventWaitList),
dst_(dst),
patternSize_(patternSize),
times_(size / patternSize) {
assert(amd::isMultipleOf(size, patternSize));
//! We copy the pattern buffer since it can be reused/deallocated after
// command creation
memcpy(pattern_, pattern, patternSize);
}
virtual void submit(device::VirtualDevice& device) { device.submitSvmFillMemory(*this); }
void* dst() const { return dst_; }
const char* pattern() const { return pattern_; }
size_t patternSize() const { return patternSize_; }
size_t times() const { return times_; }
};
/*! \brief A map memory command where the pointer to be mapped is a SVM shared
* buffer
*/
class SvmMapMemoryCommand : public Command {
private:
Memory* svmMem_; //!< the pointer to the amd::Memory object corresponding the svm pointer mapped
Coord3D size_; //!< the map size
Coord3D origin_; //!< the origin of the mapped svm pointer shift from the beginning of svm space
//! allocated
cl_map_flags flags_; //!< map flags
void* svmPtr_;
public:
SvmMapMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, Memory* svmMem,
const size_t size, const size_t offset, cl_map_flags flags, void* svmPtr)
: Command(queue, CL_COMMAND_SVM_MAP, eventWaitList),
svmMem_(svmMem),
size_(size),
origin_(offset),
flags_(flags),
svmPtr_(svmPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmMapMemory(*this); }
Memory* getSvmMem() const { return svmMem_; }
Coord3D size() const { return size_; }
cl_map_flags mapFlags() const { return flags_; }
Coord3D origin() const { return origin_; }
void* svmPtr() const { return svmPtr_; }
bool isEntireMemory() const;
};
/*! \brief An unmap memory command where the unmapped pointer is a SVM shared
* buffer
*/
class SvmUnmapMemoryCommand : public Command {
private:
Memory* svmMem_; //!< the pointer to the amd::Memory object corresponding the svm pointer mapped
void* svmPtr_; //!< SVM pointer
public:
SvmUnmapMemoryCommand(HostQueue& queue, const EventWaitList& eventWaitList, Memory* svmMem,
void* svmPtr)
: Command(queue, CL_COMMAND_SVM_UNMAP, eventWaitList), svmMem_(svmMem), svmPtr_(svmPtr) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmUnmapMemory(*this); }
Memory* getSvmMem() const { return svmMem_; }
void* svmPtr() const { return svmPtr_; }
};
/*! \brief A generic transfer memory from/to file command.
*
* \details Currently supports buffers only. Buffers
* are treated as 1D structures so origin_[0] and size_[0]
* are equivalent to offset_ and count_ respectively.
*/
class TransferBufferFileCommand : public OneMemoryArgCommand {
public:
static constexpr uint NumStagingBuffers = 2;
static constexpr size_t StagingBufferSize = 4 * Mi;
static constexpr uint StagingBufferMemType = CL_MEM_USE_PERSISTENT_MEM_AMD;
protected:
const Coord3D origin_; //!< Origin of the region to write to
const Coord3D size_; //!< Size of the region to write to
LiquidFlashFile* file_; //!< The file object for data read
size_t fileOffset_; //!< Offset in the file for data read
amd::Memory* staging_[NumStagingBuffers]; //!< Staging buffers for transfer
public:
TransferBufferFileCommand(cl_command_type type, HostQueue& queue,
const EventWaitList& eventWaitList, Memory& memory,
const Coord3D& origin, const Coord3D& size, LiquidFlashFile* file,
size_t fileOffset)
: OneMemoryArgCommand(queue, type, eventWaitList, memory),
origin_(origin),
size_(size),
file_(file),
fileOffset_(fileOffset) {
// Sanity checks
assert(size.c[0] > 0 && "invalid");
for (uint i = 0; i < NumStagingBuffers; ++i) {
staging_[i] = NULL;
}
}
virtual void releaseResources();
virtual void submit(device::VirtualDevice& device);
//! Return the memory object to write to
Memory& memory() const { return *memory_; }
//! Return the host memory to read from
LiquidFlashFile* file() const { return file_; }
//! Returns file offset
size_t fileOffset() const { return fileOffset_; }
//! Return the region origin
const Coord3D& origin() const { return origin_; }
//! Return the region size
const Coord3D& size() const { return size_; }
//! Return the staging buffer for transfer
Memory& staging(uint i) const { return *staging_[i]; }
bool validateMemory();
};
/*! \brief A P2P copy memory command
*
* \details Used for buffers only. Backends are expected
* to handle any required translation. Buffers are treated
* as 1D structures so origin_[0] and size_[0] are
* equivalent to offset_ and count_ respectively.
*/
class CopyMemoryP2PCommand : public CopyMemoryCommand {
public:
CopyMemoryP2PCommand(HostQueue& queue, cl_command_type cmdType,
const EventWaitList& eventWaitList, Memory& srcMemory, Memory& dstMemory,
Coord3D srcOrigin, Coord3D dstOrigin, Coord3D size)
: CopyMemoryCommand(queue, cmdType, eventWaitList, srcMemory, dstMemory, srcOrigin, dstOrigin,
size) {}
virtual void submit(device::VirtualDevice& device) { device.submitCopyMemoryP2P(*this); }
bool validateMemory();
};
/*! \brief Prefetch command for SVM memory
*
* \details Prefetches SVM memory into the current device or CPU
*/
class SvmPrefetchAsyncCommand : public Command {
const void* dev_ptr_; //!< Device pointer to memory for prefetch
size_t count_; //!< the size for prefetch
bool cpu_access_; //!< Prefetch data into CPU location
public:
SvmPrefetchAsyncCommand(HostQueue& queue, const EventWaitList& eventWaitList,
const void* dev_ptr, size_t count, bool cpu_access)
: Command(queue, 1, eventWaitList), dev_ptr_(dev_ptr), count_(count), cpu_access_(cpu_access) {}
virtual void submit(device::VirtualDevice& device) { device.submitSvmPrefetchAsync(*this); }
bool validateMemory();
const void* dev_ptr() const { return dev_ptr_; }
size_t count() const { return count_; }
size_t cpu_access() const { return cpu_access_; }
};
/*! @}
* @}
*/
} // namespace amd
#endif /*COMMAND_HPP_*/
|
#include <sys/time.h>
#include <string>
#include <ctype.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <vector>
#include "../txn.h"
#include "../macros.h"
#include "../scopedperf.hh"
#include "../spinlock.h"
#include "bench.h"
#include "tpce.h"
using namespace std;
using namespace util;
using namespace TPCE;
// TPC-E workload mix
int64_t lastTradeId;
int64_t last_list = 0;
int64_t min_ca_id = numeric_limits<int64_t>::max();
int64_t max_ca_id = 0;
static double g_txn_workload_mix[] = {4.9,13,1,18,14,8,10.1,10,19,2,0};
int64_t long_query_scan_range=20;
// Egen
int egen_init(int argc, char* argv[]);
void egen_release();
CCETxnInputGenerator* transactions_input_init(int customers, int sf, int wdays);
CDM* data_maintenance_init(int customers, int sf, int wdays);
CMEE* market_init(INT32 TradingTimeSoFar, CMEESUTInterface *pSUT, UINT32 UniqueId);
extern CGenerateAndLoad* pGenerateAndLoad;
CCETxnInputGenerator* m_TxnInputGenerator;
CDM* m_CDM;
//CMEESUT* meesut;
vector<CMEE*> mees;
vector<MFBuffer*> MarketFeedInputBuffers;
vector<TRBuffer*> TradeResultInputBuffers;
//Buffers
const int loadUnit = 1000;
AccountPermissionBuffer accountPermissionBuffer (3015);
CustomerBuffer customerBuffer (1005);
CustomerAccountBuffer customerAccountBuffer (1005);
CustomerTaxrateBuffer customerTaxrateBuffer (2010);
HoldingBuffer holdingBuffer(10000);
HoldingHistoryBuffer holdingHistoryBuffer(2*loadUnit);
HoldingSummaryBuffer holdingSummaryBuffer(6000);
WatchItemBuffer watchItemBuffer (iMaxItemsInWL*1020+5000);
WatchListBuffer watchListBuffer (1020);
BrokerBuffer brokerBuffer(100);
CashTransactionBuffer cashTransactionBuffer(loadUnit);
ChargeBuffer chargeBuffer(20);
CommissionRateBuffer commissionRateBuffer (245);
SettlementBuffer settlementBuffer(loadUnit);
TradeBuffer tradeBuffer(loadUnit);
TradeHistoryBuffer tradeHistoryBuffer(3*loadUnit);
TradeTypeBuffer tradeTypeBuffer (10);
CompanyBuffer companyBuffer (1000);
CompanyCompetitorBuffer companyCompetitorBuffer(3000);
DailyMarketBuffer dailyMarketBuffer(3000);
ExchangeBuffer exchangeBuffer(9);
FinancialBuffer financialBuffer (1500);
IndustryBuffer industryBuffer(107);
LastTradeBuffer lastTradeBuffer (1005);
NewsItemBuffer newsItemBuffer(200);
NewsXRefBuffer newsXRefBuffer(200);//big
SectorBuffer sectorBuffer(17);
SecurityBuffer securityBuffer(1005);
AddressBuffer addressBuffer(1005);
StatusTypeBuffer statusTypeBuffer (10);
TaxrateBuffer taxrateBuffer (325);
ZipCodeBuffer zipCodeBuffer (14850);
// Utils
class table_scanner: public abstract_ordered_index::scan_callback {
public:
table_scanner( str_arena* arena) : _arena(arena) {}
virtual bool invoke( const char *keyp, size_t keylen, const varstr &value)
{
varstr * const k = _arena->next(keylen);
INVARIANT(k);
k->copy_from(keyp, keylen);
output.emplace_back(k, &value);
return true;
}
std::vector<std::pair<varstr *, const varstr *>> output;
str_arena* _arena;
};
int64_t GetLastListID()
{
//TODO. decentralize, thread ID + local counter and TLS
auto ret = __sync_add_and_fetch(&last_list,1);
ALWAYS_ASSERT( ret );
return ret;
}
int64_t GetLastTradeID()
{
//TODO. decentralize, thread ID + local counter and TLS
auto ret = __sync_add_and_fetch(&lastTradeId,1);
ALWAYS_ASSERT( ret );
return ret;
}
static inline ALWAYS_INLINE size_t NumPartitions()
{
return (size_t) scale_factor;
}
void setRNGSeeds(CCETxnInputGenerator* gen, unsigned int UniqueId )
{
CDateTime Now;
INT32 BaseYear;
INT32 Tmp1, Tmp2;
Now.GetYMD( &BaseYear, &Tmp1, &Tmp2 );
// Set the base year to be the most recent year that was a multiple of 5.
BaseYear -= ( BaseYear % 5 );
CDateTime Base( BaseYear, 1, 1 ); // January 1st in the BaseYear
// Initialize the seed with the current time of day measured in 1/10's of a second.
// This will use up to 20 bits.
RNGSEED Seed;
Seed = Now.MSec() / 100;
// Now add in the number of days since the base time.
// The number of days in the 5 year period requires 11 bits.
// So shift up by that much to make room in the "lower" bits.
Seed <<= 11;
Seed += (RNGSEED)((INT64)Now.DayNo() - (INT64)Base.DayNo());
// So far, we've used up 31 bits.
// Save the "last" bit of the "upper" 32 for the RNG id.
// In addition, make room for the caller's 32-bit unique id.
// So shift a total of 33 bits.
Seed <<= 33;
// Now the "upper" 32-bits have been set with a value for RNG 0.
// Add in the sponsor's unique id for the "lower" 32-bits.
// Seed += UniqueId;
Seed += UniqueId;
// Set the TxnMixGenerator RNG to the unique seed.
gen->SetRNGSeed( Seed );
// m_DriverCESettings.cur.TxnMixRNGSeed = Seed;
// Set the RNG Id to 1 for the TxnInputGenerator.
Seed |= UINT64_CONST(0x0000000100000000);
gen->SetRNGSeed( Seed );
// m_DriverCESettings.cur.TxnInputRNGSeed = Seed;
}
unsigned int AutoRand()
{
struct timeval tv;
struct tm ltr;
gettimeofday(&tv, NULL);
struct tm* lt = localtime_r(&tv.tv_sec, <r);
return (((lt->tm_hour * MinutesPerHour + lt->tm_min) * SecondsPerMinute +
lt->tm_sec) * MsPerSecond + tv.tv_usec / 1000);
}
struct _dummy {}; // exists so we can inherit from it, so we can use a macro in
// an init list...
class tpce_worker_mixin : private _dummy {
#define DEFN_TBL_INIT_X(name) \
, tbl_ ## name ## _vec(partitions.at(#name))
public:
tpce_worker_mixin(const map<string, vector<abstract_ordered_index *>> &partitions) :
_dummy() // so hacky...
TPCE_TABLE_LIST(DEFN_TBL_INIT_X)
{
}
#undef DEFN_TBL_INIT_X
protected:
#define DEFN_TBL_ACCESSOR_X(name) \
private: \
vector<abstract_ordered_index *> tbl_ ## name ## _vec; \
protected: \
inline ALWAYS_INLINE abstract_ordered_index * \
tbl_ ## name (unsigned int pid) \
{ \
return tbl_ ## name ## _vec[pid - 1]; \
}
TPCE_TABLE_LIST(DEFN_TBL_ACCESSOR_X)
#undef DEFN_TBL_ACCESSOR_X
// only TPCE loaders need to call this- workers are automatically
// pinned by their worker id (which corresponds to partition id
// in TPCE)
//
// pins the *calling* thread
static void
PinToPartition(unsigned int pid)
{
}
public:
static inline uint32_t
GetCurrentTimeMillis()
{
//struct timeval tv;
//ALWAYS_ASSERT(gettimeofday(&tv, 0) == 0);
//return tv.tv_sec * 1000;
// XXX(stephentu): implement a scalable GetCurrentTimeMillis()
// for now, we just give each core an increasing number
static __thread uint32_t tl_hack = 0;
return tl_hack++;
}
// utils for generating random #s and strings
static inline ALWAYS_INLINE int
CheckBetweenInclusive(int v, int lower, int upper)
{
INVARIANT(v >= lower);
INVARIANT(v <= upper);
return v;
}
static inline ALWAYS_INLINE int
RandomNumber(fast_random &r, int min, int max)
{
return CheckBetweenInclusive((int) (r.next_uniform() * (max - min + 1) + min), min, max);
}
static inline ALWAYS_INLINE int
NonUniformRandom(fast_random &r, int A, int C, int min, int max)
{
return (((RandomNumber(r, 0, A) | RandomNumber(r, min, max)) + C) % (max - min + 1)) + min;
}
// following oltpbench, we really generate strings of len - 1...
static inline string
RandomStr(fast_random &r, uint len)
{
// this is a property of the oltpbench implementation...
if (!len)
return "";
uint i = 0;
string buf(len - 1, 0);
while (i < (len - 1)) {
const char c = (char) r.next_char();
// XXX(stephentu): oltpbench uses java's Character.isLetter(), which
// is a less restrictive filter than isalnum()
if (!isalnum(c))
continue;
buf[i++] = c;
}
return buf;
}
// RandomNStr() actually produces a string of length len
static inline string
RandomNStr(fast_random &r, uint len)
{
const char base = '0';
string buf(len, 0);
for (uint i = 0; i < len; i++)
buf[i] = (char)(base + (r.next() % 10));
return buf;
}
};
// TPCE workers implement TxnHarness interfaces
class tpce_worker :
public bench_worker,
public tpce_worker_mixin,
public CBrokerVolumeDBInterface,
public CCustomerPositionDBInterface,
public CMarketFeedDBInterface,
public CMarketWatchDBInterface,
public CSecurityDetailDBInterface,
public CTradeLookupDBInterface,
public CTradeOrderDBInterface,
public CTradeResultDBInterface,
public CTradeStatusDBInterface,
public CTradeUpdateDBInterface,
public CDataMaintenanceDBInterface,
public CTradeCleanupDBInterface,
public CSendToMarketInterface
{
public:
// resp for [partition_id_start, partition_id_end)
tpce_worker(unsigned int worker_id,
unsigned long seed, abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
spin_barrier *barrier_a, spin_barrier *barrier_b,
uint partition_id_start, uint partition_id_end)
: bench_worker(worker_id, true, seed, db,
open_tables, barrier_a, barrier_b),
tpce_worker_mixin(partitions),
partition_id_start(partition_id_start),
partition_id_end(partition_id_end)
{
INVARIANT(partition_id_start >= 1);
INVARIANT(partition_id_start <= NumPartitions());
INVARIANT(partition_id_end > partition_id_start);
INVARIANT(partition_id_end <= (NumPartitions() + 1));
if (verbose) {
cerr << "tpce: worker id " << worker_id
<< " => partitions [" << partition_id_start
<< ", " << partition_id_end << ")"
<< endl;
}
const unsigned base = coreid::num_cpus_online();
mee = mees[worker_id - base ];
MarketFeedInputBuffer = MarketFeedInputBuffers[worker_id - base ];
TradeResultInputBuffer = TradeResultInputBuffers[worker_id - base ];
ALWAYS_ASSERT( TradeResultInputBuffer and MarketFeedInputBuffer and mee );
}
// Market Interface
bool SendToMarket(TTradeRequest &trade_mes)
{
mee->SubmitTradeRequest(&trade_mes);
return true;
}
// BrokerVolume transaction
static bench_worker::txn_result BrokerVolume(bench_worker *w)
{
ANON_REGION("BrokerVolume:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->broker_volume();
}
bench_worker::txn_result broker_volume()
{
scoped_str_arena s_arena(arena);
TBrokerVolumeTxnInput input;
TBrokerVolumeTxnOutput output;
m_TxnInputGenerator->GenerateBrokerVolumeInput(input);
CBrokerVolume* harness= new CBrokerVolume(this);
auto ret = harness->DoTxn( (PBrokerVolumeTxnInput)&input, (PBrokerVolumeTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoBrokerVolumeFrame1(const TBrokerVolumeFrame1Input *pIn, TBrokerVolumeFrame1Output *pOut);
// CustomerPosition transaction
static bench_worker::txn_result CustomerPosition(bench_worker *w)
{
ANON_REGION("CustomerPosition:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->customer_position();
}
bench_worker::txn_result customer_position()
{
scoped_str_arena s_arena(arena);
TCustomerPositionTxnInput input;
TCustomerPositionTxnOutput output;
m_TxnInputGenerator->GenerateCustomerPositionInput(input);
CCustomerPosition* harness= new CCustomerPosition(this);
auto ret = harness->DoTxn( (PCustomerPositionTxnInput)&input, (PCustomerPositionTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoCustomerPositionFrame1(const TCustomerPositionFrame1Input *pIn, TCustomerPositionFrame1Output *pOut);
bench_worker::txn_result DoCustomerPositionFrame2(const TCustomerPositionFrame2Input *pIn, TCustomerPositionFrame2Output *pOut);
bench_worker::txn_result DoCustomerPositionFrame3(void );
// MarketFeed transaction
static bench_worker::txn_result MarketFeed(bench_worker *w)
{
ANON_REGION("MarketFeed:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->market_feed();
}
bench_worker::txn_result market_feed()
{
scoped_str_arena s_arena(arena);
TMarketFeedTxnInput* input= MarketFeedInputBuffer->get();
if( not input )
{
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0); // XXX. do we have to do this? MFQueue is empty, meaning no Trade-order submitted yet
}
TMarketFeedTxnOutput output;
CMarketFeed* harness= new CMarketFeed(this, this);
auto ret = harness->DoTxn( (PMarketFeedTxnInput)input, (PMarketFeedTxnOutput)&output);
delete input;
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoMarketFeedFrame1(const TMarketFeedFrame1Input *pIn, TMarketFeedFrame1Output *pOut, CSendToMarketInterface *pSendToMarket);
// MarketWatch
static bench_worker::txn_result MarketWatch(bench_worker *w)
{
ANON_REGION("MarketWatch:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->market_watch();
}
bench_worker::txn_result market_watch()
{
scoped_str_arena s_arena(arena);
TMarketWatchTxnInput input;
TMarketWatchTxnOutput output;
m_TxnInputGenerator->GenerateMarketWatchInput(input);
CMarketWatch* harness= new CMarketWatch(this);
auto ret = harness->DoTxn( (PMarketWatchTxnInput)&input, (PMarketWatchTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoMarketWatchFrame1 (const TMarketWatchFrame1Input *pIn, TMarketWatchFrame1Output *pOut);
// SecurityDetail
static bench_worker::txn_result SecurityDetail(bench_worker *w)
{
ANON_REGION("SecurityDetail:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->security_detail();
}
bench_worker::txn_result security_detail()
{
scoped_str_arena s_arena(arena);
TSecurityDetailTxnInput input;
TSecurityDetailTxnOutput output;
m_TxnInputGenerator->GenerateSecurityDetailInput(input);
CSecurityDetail* harness= new CSecurityDetail(this);
auto ret = harness->DoTxn( (PSecurityDetailTxnInput)&input, (PSecurityDetailTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoSecurityDetailFrame1(const TSecurityDetailFrame1Input *pIn, TSecurityDetailFrame1Output *pOut);
// TradeLookup
static bench_worker::txn_result TradeLookup(bench_worker *w)
{
ANON_REGION("TradeLookup:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_lookup();
}
bench_worker::txn_result trade_lookup()
{
scoped_str_arena s_arena(arena);
TTradeLookupTxnInput input;
TTradeLookupTxnOutput output;
m_TxnInputGenerator->GenerateTradeLookupInput(input);
CTradeLookup* harness= new CTradeLookup(this);
auto ret = harness->DoTxn( (PTradeLookupTxnInput)&input, (PTradeLookupTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeLookupFrame1(const TTradeLookupFrame1Input *pIn, TTradeLookupFrame1Output *pOut);
bench_worker::txn_result DoTradeLookupFrame2(const TTradeLookupFrame2Input *pIn, TTradeLookupFrame2Output *pOut);
bench_worker::txn_result DoTradeLookupFrame3(const TTradeLookupFrame3Input *pIn, TTradeLookupFrame3Output *pOut);
bench_worker::txn_result DoTradeLookupFrame4(const TTradeLookupFrame4Input *pIn, TTradeLookupFrame4Output *pOut);
// TradeOrder
static bench_worker::txn_result TradeOrder(bench_worker *w)
{
ANON_REGION("TradeOrder:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_order();
}
bench_worker::txn_result trade_order()
{
scoped_str_arena s_arena(arena);
TTradeOrderTxnInput input;
TTradeOrderTxnOutput output;
bool bExecutorIsAccountOwner;
int32_t iTradeType;
m_TxnInputGenerator->GenerateTradeOrderInput(input, iTradeType, bExecutorIsAccountOwner);
CTradeOrder* harness= new CTradeOrder(this, this);
auto ret = harness->DoTxn( (PTradeOrderTxnInput)&input, (PTradeOrderTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeOrderFrame1(const TTradeOrderFrame1Input *pIn, TTradeOrderFrame1Output *pOut);
bench_worker::txn_result DoTradeOrderFrame2(const TTradeOrderFrame2Input *pIn, TTradeOrderFrame2Output *pOut);
bench_worker::txn_result DoTradeOrderFrame3(const TTradeOrderFrame3Input *pIn, TTradeOrderFrame3Output *pOut);
bench_worker::txn_result DoTradeOrderFrame4(const TTradeOrderFrame4Input *pIn, TTradeOrderFrame4Output *pOut);
bench_worker::txn_result DoTradeOrderFrame5(void );
bench_worker::txn_result DoTradeOrderFrame6(void );
// TradeResult
static bench_worker::txn_result TradeResult(bench_worker *w)
{
ANON_REGION("TradeResult:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_result();
}
bench_worker::txn_result trade_result()
{
scoped_str_arena s_arena(arena);
TTradeResultTxnInput* input = TradeResultInputBuffer->get();
if( not input )
{
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0); // XXX. do we have to do this? TRQueue is empty, meaning no Trade-order submitted yet
}
TTradeResultTxnOutput output;
CTradeResult* harness= new CTradeResult(this);
auto ret = harness->DoTxn( (PTradeResultTxnInput)input, (PTradeResultTxnOutput)&output);
delete input;
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeResultFrame1(const TTradeResultFrame1Input *pIn, TTradeResultFrame1Output *pOut);
bench_worker::txn_result DoTradeResultFrame2(const TTradeResultFrame2Input *pIn, TTradeResultFrame2Output *pOut);
bench_worker::txn_result DoTradeResultFrame3(const TTradeResultFrame3Input *pIn, TTradeResultFrame3Output *pOut);
bench_worker::txn_result DoTradeResultFrame4(const TTradeResultFrame4Input *pIn, TTradeResultFrame4Output *pOut);
bench_worker::txn_result DoTradeResultFrame5(const TTradeResultFrame5Input *pIn );
bench_worker::txn_result DoTradeResultFrame6(const TTradeResultFrame6Input *pIn, TTradeResultFrame6Output *pOut);
// TradeStatus
static bench_worker::txn_result TradeStatus(bench_worker *w)
{
ANON_REGION("TradeStatus:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_status();
}
bench_worker::txn_result trade_status()
{
scoped_str_arena s_arena(arena);
TTradeStatusTxnInput input;
TTradeStatusTxnOutput output;
m_TxnInputGenerator->GenerateTradeStatusInput(input);
CTradeStatus* harness= new CTradeStatus(this);
auto ret = harness->DoTxn( (PTradeStatusTxnInput)&input, (PTradeStatusTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeStatusFrame1(const TTradeStatusFrame1Input *pIn, TTradeStatusFrame1Output *pOut);
// TradeUpdate
static bench_worker::txn_result TradeUpdate(bench_worker *w)
{
ANON_REGION("TradeUpdate:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_update();
}
bench_worker::txn_result trade_update()
{
scoped_str_arena s_arena(arena);
TTradeUpdateTxnInput input;
TTradeUpdateTxnOutput output;
m_TxnInputGenerator->GenerateTradeUpdateInput(input);
CTradeUpdate* harness= new CTradeUpdate(this);
auto ret = harness->DoTxn( (PTradeUpdateTxnInput)&input, (PTradeUpdateTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeUpdateFrame1(const TTradeUpdateFrame1Input *pIn, TTradeUpdateFrame1Output *pOut);
bench_worker::txn_result DoTradeUpdateFrame2(const TTradeUpdateFrame2Input *pIn, TTradeUpdateFrame2Output *pOut);
bench_worker::txn_result DoTradeUpdateFrame3(const TTradeUpdateFrame3Input *pIn, TTradeUpdateFrame3Output *pOut);
// Long query
static bench_worker::txn_result LongQuery(bench_worker *w)
{
ANON_REGION("LongQuery:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->long_query();
}
bench_worker::txn_result long_query()
{
scoped_str_arena s_arena(arena);
return DoLongQueryFrame1();
}
bench_worker::txn_result DoLongQueryFrame1();
// DataMaintenance
static bench_worker::txn_result DataMaintenance(bench_worker *w)
{
ANON_REGION("DataMaintenance:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->data_maintenance();
}
bench_worker::txn_result data_maintenance()
{
scoped_str_arena s_arena(arena);
TDataMaintenanceTxnInput* input = m_CDM->createDMInput();
TDataMaintenanceTxnOutput output;
CDataMaintenance* harness= new CDataMaintenance(this);
// return harness->DoTxn( (PDataMaintenanceTxnInput)&input, (PDataMaintenanceTxnOutput)&output);
}
bench_worker::txn_result DoDataMaintenanceFrame1(const TDataMaintenanceFrame1Input *pIn);
// TradeCleanup
static bench_worker::txn_result TradeCleanup(bench_worker *w)
{
ANON_REGION("TradeCleanup:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_cleanup();
}
bench_worker::txn_result trade_cleanup()
{
scoped_str_arena s_arena(arena);
TTradeCleanupTxnInput* input = m_CDM->createTCInput();
TTradeCleanupTxnOutput output;
CTradeCleanup* harness= new CTradeCleanup(this);
// return harness->DoTxn( (PTradeCleanupTxnInput)&input, (PTradeCleanupTxnOutput)&output);
}
bench_worker::txn_result DoTradeCleanupFrame1(const TTradeCleanupFrame1Input *pIn);
virtual workload_desc_vec
get_workload() const
{
workload_desc_vec w;
double m = 0;
for (size_t i = 0; i < ARRAY_NELEMS(g_txn_workload_mix); i++)
m += g_txn_workload_mix[i];
ALWAYS_ASSERT(m == 100);
if (g_txn_workload_mix[0])
w.push_back(workload_desc("BrokerVolume", double(g_txn_workload_mix[0])/100.0, BrokerVolume));
if (g_txn_workload_mix[1])
w.push_back(workload_desc("CustomerPosition", double(g_txn_workload_mix[1])/100.0, CustomerPosition));
if (g_txn_workload_mix[2])
w.push_back(workload_desc("MarketFeed", double(g_txn_workload_mix[2])/100.0, MarketFeed));
if (g_txn_workload_mix[3])
w.push_back(workload_desc("MarketWatch", double(g_txn_workload_mix[3])/100.0, MarketWatch));
if (g_txn_workload_mix[4])
w.push_back(workload_desc("SecurityDetail", double(g_txn_workload_mix[4])/100.0, SecurityDetail));
if (g_txn_workload_mix[5])
w.push_back(workload_desc("TradeLookup", double(g_txn_workload_mix[5])/100.0, TradeLookup));
if (g_txn_workload_mix[6])
w.push_back(workload_desc("TradeOrder", double(g_txn_workload_mix[6])/100.0, TradeOrder));
if (g_txn_workload_mix[7])
w.push_back(workload_desc("TradeResult", double(g_txn_workload_mix[7])/100.0, TradeResult));
if (g_txn_workload_mix[8])
w.push_back(workload_desc("TradeStatus", double(g_txn_workload_mix[8])/100.0, TradeStatus));
if (g_txn_workload_mix[9])
w.push_back(workload_desc("TradeUpdate", double(g_txn_workload_mix[9])/100.0, TradeUpdate));
if (g_txn_workload_mix[10])
w.push_back(workload_desc("LongQuery", double(g_txn_workload_mix[10])/100.0, LongQuery));
// if (g_txn_workload_mix[10])
// w.push_back(workload_desc("DataMaintenance", double(g_txn_workload_mix[10])/100.0, DataMaintenance));
// if (g_txn_workload_mix[11])
// w.push_back(workload_desc("TradeCleanup", double(g_txn_workload_mix[11])/100.0, TradeCleanup));
return w;
}
protected:
virtual void
on_run_setup() OVERRIDE
{
if (!pin_cpus)
return;
const size_t a = worker_id % coreid::num_cpus_online();
const size_t b = a % nthreads;
RCU::pin_current_thread(b);
}
inline ALWAYS_INLINE varstr &
str(uint64_t size)
{
return *arena.next(size);
}
private:
void* txn;
const uint partition_id_start;
const uint partition_id_end;
// some scratch buffer space
varstr obj_key0;
varstr obj_key1;
varstr obj_v;
CMEE* mee; // thread-local MEE
MFBuffer* MarketFeedInputBuffer;
TRBuffer* TradeResultInputBuffer;
};
bench_worker::txn_result tpce_worker::DoBrokerVolumeFrame1(const TBrokerVolumeFrame1Input *pIn, TBrokerVolumeFrame1Output *pOut)
{
/* SQL
start transaction
// Should return 0 to 40 rows
select
broker_name[] = B_NAME,
volume[] = sum(TR_QTY * TR_BID_PRICE)
from
TRADE_REQUEST,
SECTOR,
INDUSTRY
COMPANY,
BROKER,
SECURITY
where
TR_B_ID = B_ID and
TR_S_SYMB = S_SYMB and
S_CO_ID = CO_ID and
CO_IN_ID = IN_ID and
SC_ID = IN_SC_ID and
B_NAME in (broker_list) and
SC_NAME = sector_name
group by
B_NAME
order by
2 DESC
// row_count will frequently be zero near the start of a Test Run when
// TRADE_REQUEST table is mostly empty.
list_len = row_count
commit transaction
*/
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
std::vector<std::pair<varstr *, const varstr *>> brokers;
for( auto i = 0; i < max_broker_list_len and pIn->broker_list[i] ; i++ )
{
const b_name_index::key k_b_0( string(pIn->broker_list[i]), MIN_VAL(k_b_0.b_id) );
const b_name_index::key k_b_1( string(pIn->broker_list[i]), MAX_VAL(k_b_1.b_id) );
table_scanner b_scanner(&arena);
try_catch(tbl_b_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_b_0)), k_b_0), &Encode(obj_key1=str(sizeof(k_b_1)), k_b_1), b_scanner, &arena));
if( not b_scanner.output.size())
continue;
for( auto &r_b : b_scanner.output )
brokers.push_back( r_b );
}
// NLJ
pOut->list_len = 0;
const sector::key k_sc_0( pIn->sector_name, string(cSC_ID_len, (char)0 ));
const sector::key k_sc_1( pIn->sector_name, string(cSC_ID_len, (char)255));
table_scanner sc_scanner(&arena);
try_catch(tbl_sector(1)->scan(txn, Encode(obj_key0=str(sizeof(k_sc_0)), k_sc_0), &Encode(obj_key1=str(sizeof(k_sc_1)), k_sc_1), sc_scanner, &arena));
ALWAYS_ASSERT(sc_scanner.output.size() == 1);
for( auto &r_sc: sc_scanner.output )
{
sector::key k_sc_temp;
const sector::key* k_sc = Decode(*r_sc.first, k_sc_temp );
// in_sc_id_index scan
const in_sc_id_index::key k_in_0( k_sc->sc_id, string(cIN_ID_len, (char)0) );
const in_sc_id_index::key k_in_1( k_sc->sc_id, string(cIN_ID_len, (char)255) );
table_scanner in_scanner(&arena);
try_catch(tbl_in_sc_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), in_scanner, &arena));
ALWAYS_ASSERT(in_scanner.output.size());
for( auto &r_in: in_scanner.output)
{
in_sc_id_index::key k_in_temp;
const in_sc_id_index::key* k_in = Decode(*r_in.first, k_in_temp );
// co_in_id_index scan
const co_in_id_index::key k_in_0( k_in->in_id, MIN_VAL(k_in_0.co_id) );
const co_in_id_index::key k_in_1( k_in->in_id, MAX_VAL(k_in_1.co_id) );
table_scanner co_scanner(&arena);
try_catch(tbl_co_in_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), co_scanner, &arena));
ALWAYS_ASSERT(co_scanner.output.size());
for( auto &r_co : co_scanner.output )
{
co_in_id_index::key k_co_temp;
const co_in_id_index::key* k_co = Decode(*r_co.first, k_co_temp );
// security_index scan
const security_index::key k_s_0( k_co->co_id, string(cS_ISSUE_len, (char)0) , string(cSYMBOL_len, (char)0) );
const security_index::key k_s_1( k_co->co_id, string(cS_ISSUE_len, (char)255), string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT(s_scanner.output.size());
for( auto &r_s : s_scanner.output )
{
security_index::key k_s_temp;
const security_index::key* k_s = Decode( *r_s.first, k_s_temp );
for( auto &r_b_idx : brokers )
{
if( pOut->list_len >= max_broker_list_len )
break;
b_name_index::key k_b_idx_temp;
const b_name_index::key* k_b_idx = Decode( *r_b_idx.first, k_b_idx_temp );
const trade_request::key k_tr_0( k_s->s_symb, k_b_idx->b_id, MIN_VAL(k_tr_0.tr_t_id) );
const trade_request::key k_tr_1( k_s->s_symb, k_b_idx->b_id, MAX_VAL(k_tr_1.tr_t_id) );
table_scanner tr_scanner(&arena);
try_catch(tbl_trade_request(1)->scan(txn, Encode(obj_key0=str(sizeof(k_tr_0)), k_tr_0), &Encode(obj_key1=str(sizeof(k_tr_1)), k_tr_1), tr_scanner, &arena));
// ALWAYS_ASSERT( tr_scanner.output.size() ); // XXX. If there's no previous trade, this can happen
for( auto &r_tr : tr_scanner.output )
{
trade_request::value v_tr_temp;
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
pOut->volume[pOut->list_len] += v_tr->tr_bid_price * v_tr->tr_qty;
}
memcpy(pOut->broker_name[pOut->list_len], k_b_idx->b_name.data(), k_b_idx->b_name.size());
// pOut->volume[pOut->list_len] = v_tr->tr_bid_price * v_tr->tr_qty;
pOut->list_len++;
}
}
}
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame1(const TCustomerPositionFrame1Input *pIn, TCustomerPositionFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
// Get c_id;
const c_tax_id_index::key k_c_0( pIn->tax_id, MIN_VAL(k_c_0.c_id) );
const c_tax_id_index::key k_c_1( pIn->tax_id, MAX_VAL(k_c_1.c_id) );
table_scanner c_scanner(&arena);
if(pIn->cust_id)
pOut->cust_id = pIn->cust_id;
else
{
try_catch(tbl_c_tax_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_c_0)), k_c_0), &Encode(obj_key1=str(sizeof(k_c_1)), k_c_1), c_scanner, &arena));
// XXX. input generator's tax_id doesn't exist. ???
if( not c_scanner.output.size())
{
// return;
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
c_tax_id_index::key k_c_temp;
const c_tax_id_index::key* k_c = Decode( *(c_scanner.output.front().first), k_c_temp );
pOut->cust_id = k_c->c_id;
}
ALWAYS_ASSERT( pOut->cust_id );
// probe Customers
const customers::key k_c(pOut->cust_id);
customers::value v_c_temp;
try_verify_strict(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
memcpy(pOut->c_st_id, v_c->c_st_id.data(), v_c->c_st_id.size() );
memcpy(pOut->c_l_name, v_c->c_l_name.data(), v_c->c_l_name.size());
memcpy(pOut->c_f_name, v_c->c_f_name.data(), v_c->c_f_name.size());
memcpy(pOut->c_m_name, v_c->c_m_name.data(), v_c->c_m_name.size());
pOut->c_gndr[0] = v_c->c_gndr; pOut->c_gndr[1] = 0;
pOut->c_tier = v_c->c_tier;
CDateTime(v_c->c_dob).GetTimeStamp(&pOut->c_dob );
pOut->c_ad_id = v_c->c_ad_id;
memcpy(pOut->c_ctry_1, v_c->c_ctry_1.data(), v_c->c_ctry_1.size());
memcpy(pOut->c_area_1, v_c->c_area_1.data(), v_c->c_area_1.size());
memcpy(pOut->c_local_1, v_c->c_local_1.data(), v_c->c_local_1.size());
memcpy(pOut->c_ext_1, v_c->c_ext_1.data(), v_c->c_ext_1.size());
memcpy(pOut->c_ctry_2, v_c->c_ctry_2.data(), v_c->c_ctry_2.size());
memcpy(pOut->c_area_2, v_c->c_area_2.data(), v_c->c_area_2.size());
memcpy(pOut->c_local_2, v_c->c_local_2.data(), v_c->c_local_2.size());
memcpy(pOut->c_ext_2, v_c->c_ext_2.data(), v_c->c_ext_2.size());
memcpy(pOut->c_ctry_3, v_c->c_ctry_3.data(), v_c->c_ctry_3.size());
memcpy(pOut->c_area_3, v_c->c_area_3.data(), v_c->c_area_3.size());
memcpy(pOut->c_local_3, v_c->c_local_3.data(), v_c->c_local_3.size());
memcpy(pOut->c_ext_3, v_c->c_ext_3.data(), v_c->c_ext_3.size());
memcpy(pOut->c_email_1, v_c->c_email_1.data(), v_c->c_email_1.size());
memcpy(pOut->c_email_2, v_c->c_email_2.data(), v_c->c_email_2.size());
// CustomerAccount scan
const ca_id_index::key k_ca_0( pOut->cust_id, MIN_VAL(k_ca_0.ca_id) );
const ca_id_index::key k_ca_1( pOut->cust_id, MAX_VAL(k_ca_1.ca_id) );
table_scanner ca_scanner(&arena);
try_catch(tbl_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_ca_0)), k_ca_0), &Encode(obj_key1=str(sizeof(k_ca_1)), k_ca_1), ca_scanner, &arena));
ALWAYS_ASSERT( ca_scanner.output.size() );
for( auto& r_ca : ca_scanner.output )
{
ca_id_index::key k_ca_temp;
ca_id_index::value v_ca_temp;
const ca_id_index::key* k_ca = Decode( *r_ca.first, k_ca_temp );
const ca_id_index::value* v_ca = Decode(*r_ca.second, v_ca_temp );
// HoldingSummary scan
const holding_summary::key k_hs_0( k_ca->ca_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( k_ca->ca_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
//ALWAYS_ASSERT( hs_scanner.output.size() ); // left-outer join. S table could be empty.
auto asset = 0;
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode(*r_hs.second, v_hs_temp );
// LastTrade probe & equi-join
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
asset += v_hs->hs_qty * v_lt->lt_price;
}
// TODO. sorting
// Since we are doing left outer join, non-join rows just emit 0 asset here.
pOut->acct_id[pOut->acct_len] = k_ca->ca_id;
pOut->cash_bal[pOut->acct_len] = v_ca->ca_bal;
pOut->asset_total[pOut->acct_len] = asset;
pOut->acct_len++;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame2(const TCustomerPositionFrame2Input *pIn, TCustomerPositionFrame2Output *pOut)
{
// XXX. If, CP frame 1 doesn't give output, then, we don't have valid input at here. so just return
if( not pIn->acct_id )
{
// try_catch(db->commit_txn(txn));
// return txn_result(true, 0);
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
// Trade scan and collect 10 TID
const t_ca_id_index::key k_t_0( pIn->acct_id, MIN_VAL(k_t_0.t_dts), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_0.t_dts), MAX_VAL(k_t_0.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
std::vector<std::pair<varstr *, const varstr *>> tids;
for( auto &r_t : t_scanner.output )
{
tids.push_back( r_t );
if( tids.size() >= 10 )
break;
}
reverse(tids.begin(), tids.end());
for( auto &r_t : tids )
{
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode(*r_t.second, v_t_temp );
// Join
const trade_history::key k_th_0( k_t->t_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( k_t->t_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
status_type::key k_st(k_th->th_st_id);
status_type::value v_st_temp;
try_verify_relax(tbl_status_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_st)), k_st), obj_v=str(sizeof(v_st_temp))));
const status_type::value *v_st = Decode(obj_v,v_st_temp);
// TODO. order by and grab 30 rows
pOut->trade_id[pOut->hist_len] = k_t->t_id;
pOut->qty[pOut->hist_len] = v_t->t_qty;
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->hist_dts[pOut->hist_len] );
memcpy(pOut->symbol[pOut->hist_len], v_t->t_s_symb.data(), v_t->t_s_symb.size());
memcpy(pOut->trade_status[pOut->hist_len], v_st->st_name.data(), v_st->st_name.size());
pOut->hist_len++;
if( pOut->hist_len >= max_hist_len )
goto commit;
}
}
commit:
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame3(void)
{
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoMarketFeedFrame1(const TMarketFeedFrame1Input *pIn, TMarketFeedFrame1Output *pOut, CSendToMarketInterface *pSendToMarket)
{
auto now_dts = CDateTime().GetDate();
vector<TTradeRequest> TradeRequestBuffer;
double req_price_quote = 0;
uint64_t req_trade_id = 0;
int32_t req_trade_qty = 0;
inline_str_fixed<cTT_ID_len> req_trade_type;
TStatusAndTradeType type = pIn->StatusAndTradeType;
for( int i = 0; i < max_feed_len; i++ )
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
TTickerEntry ticker = pIn->Entries[i];
last_trade::key k_lt(ticker.symbol);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
last_trade::value v_lt_new(*v_lt);
v_lt_new.lt_dts = now_dts;
v_lt_new.lt_price = v_lt->lt_price + ticker.price_quote;
v_lt_new.lt_vol = ticker.price_quote;
try_catch(tbl_last_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), Encode(obj_v=str(sizeof(v_lt_new)), v_lt_new)));
pOut->num_updated++;
const trade_request::key k_tr_0( string(ticker.symbol), MIN_VAL(k_tr_0.tr_b_id), MIN_VAL(k_tr_0.tr_t_id) );
const trade_request::key k_tr_1( string(ticker.symbol), MAX_VAL(k_tr_1.tr_b_id), MAX_VAL(k_tr_1.tr_t_id) );
table_scanner tr_scanner(&arena);
try_catch(tbl_trade_request(1)->scan(txn, Encode(obj_key0=str(sizeof(k_tr_0)), k_tr_0), &Encode(obj_key1=str(sizeof(k_tr_1)), k_tr_1), tr_scanner, &arena));
// ALWAYS_ASSERT( tr_scanner.output.size() ); // XXX. If there's no previous trade, this can happen. Higher initial trading days would enlarge this scan set
std::vector<std::pair<varstr *, const varstr *>> request_list_cursor;
for( auto &r_tr : tr_scanner.output )
{
trade_request::value v_tr_temp;
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
if( (v_tr->tr_tt_id == string(type.type_stop_loss) and v_tr->tr_bid_price >= ticker.price_quote) or
(v_tr->tr_tt_id == string(type.type_limit_sell) and v_tr->tr_bid_price <= ticker.price_quote) or
(v_tr->tr_tt_id == string(type.type_limit_buy) and v_tr->tr_bid_price >= ticker.price_quote) )
{
request_list_cursor.push_back( r_tr );
}
}
for( auto &r_tr : request_list_cursor )
{
trade_request::key k_tr_temp;
trade_request::value v_tr_temp;
const trade_request::key* k_tr = Decode( *r_tr.first, k_tr_temp );
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
req_trade_id = k_tr->tr_t_id;
req_price_quote = v_tr->tr_bid_price;
req_trade_type = v_tr->tr_tt_id;
req_trade_qty = v_tr->tr_qty;
const trade::key k_t(req_trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_dts = now_dts;
v_t_new.t_st_id = string(type.status_submitted);
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
// DTS field is updated. cascading update( actually insert after remove, because dts is included in PK )
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t->t_ca_id;
k_t_idx1.t_dts = v_t->t_dts;
k_t_idx1.t_id = k_t.t_id;
try_verify_relax(tbl_t_ca_id_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1)));
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t->t_s_symb;
k_t_idx2.t_dts = v_t->t_dts;
k_t_idx2.t_id = k_t.t_id;
try_verify_relax(tbl_t_s_symb_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2)));
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
trade_request::key k_tr_new(*k_tr);
try_verify_relax(tbl_trade_request(1)->remove(txn, Encode(obj_key0=str(sizeof(k_tr_new)), k_tr_new)));
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = req_trade_id;
k_th.th_dts = now_dts;
k_th.th_st_id = string(type.status_submitted);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
TTradeRequest request;
memset( &request, 0, sizeof(request));
memcpy(request.symbol, ticker.symbol, cSYMBOL_len+1);
request.trade_id = req_trade_id;
request.price_quote = req_price_quote;
request.trade_qty = req_trade_qty;
memcpy(request.trade_type_id, req_trade_type.data(), req_trade_type.size());
TradeRequestBuffer.emplace_back( request );
}
try_catch(db->commit_txn(txn));
pOut->send_len += request_list_cursor.size();
for( size_t i = 0; i < request_list_cursor.size(); i++ )
{
SendToMarketFromFrame(TradeRequestBuffer[i]);
}
TradeRequestBuffer.clear();
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoMarketWatchFrame1 (const TMarketWatchFrame1Input *pIn, TMarketWatchFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
std::vector<inline_str_fixed<cSYMBOL_len>> stock_list_cursor;
if( pIn->c_id )
{
const watch_list::key k_wl_0( pIn->c_id, MIN_VAL(k_wl_0.wl_id) );
const watch_list::key k_wl_1( pIn->c_id, MAX_VAL(k_wl_1.wl_id) );
table_scanner wl_scanner(&arena);
try_catch(tbl_watch_list(1)->scan(txn, Encode(obj_key0=str(sizeof(k_wl_0)), k_wl_0), &Encode(obj_key1=str(sizeof(k_wl_1)), k_wl_1), wl_scanner, &arena));
ALWAYS_ASSERT( wl_scanner.output.size() );
for( auto &r_wl: wl_scanner.output )
{
watch_list::key k_wl_temp;
const watch_list::key* k_wl = Decode( *r_wl.first, k_wl_temp );
const watch_item::key k_wi_0( k_wl->wl_id, string(cSYMBOL_len, (char)0 ) );
const watch_item::key k_wi_1( k_wl->wl_id, string(cSYMBOL_len, (char)255) );
table_scanner wi_scanner(&arena);
try_catch(tbl_watch_item(1)->scan(txn, Encode(obj_key0=str(sizeof(k_wi_0)), k_wi_0), &Encode(obj_key1=str(sizeof(k_wi_1)), k_wi_1), wi_scanner, &arena));
ALWAYS_ASSERT( wi_scanner.output.size() );
for( auto &r_wi : wi_scanner.output )
{
watch_item::key k_wi_temp;
const watch_item::key* k_wi = Decode( *r_wi.first, k_wi_temp );
stock_list_cursor.push_back( k_wi->wi_s_symb );
}
}
}
else if ( pIn->industry_name[0] )
{
const in_name_index::key k_in_0( string(pIn->industry_name), string(cIN_ID_len, (char)0 ) );
const in_name_index::key k_in_1( string(pIn->industry_name), string(cIN_ID_len, (char)255) );
table_scanner in_scanner(&arena);
try_catch(tbl_in_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), in_scanner, &arena));
ALWAYS_ASSERT( in_scanner.output.size() );
const company::key k_co_0( pIn->starting_co_id );
const company::key k_co_1( pIn->ending_co_id );
table_scanner co_scanner(&arena);
try_catch(tbl_company(1)->scan(txn, Encode(obj_key0=str(sizeof(k_co_0)), k_co_0), &Encode(obj_key1=str(sizeof(k_co_1)), k_co_1), co_scanner, &arena));
ALWAYS_ASSERT( co_scanner.output.size() );
const security::key k_s_0( string(cSYMBOL_len, (char)0 ));
const security::key k_s_1( string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT( s_scanner.output.size() );
for( auto &r_in : in_scanner.output )
{
in_name_index::key k_in_temp;
const in_name_index::key* k_in = Decode( *r_in.first, k_in_temp );
for( auto &r_co: co_scanner.output )
{
company::key k_co_temp;
company::value v_co_temp;
const company::key* k_co = Decode( *r_co.first, k_co_temp );
const company::value* v_co = Decode( *r_co.second, v_co_temp );
if( v_co->co_in_id != k_in->in_id )
continue;
for( auto &r_s : s_scanner.output )
{
security::key k_s_temp;
security::value v_s_temp;
const security::key* k_s = Decode( *r_s.first, k_s_temp );
const security::value* v_s = Decode( *r_s.second, v_s_temp );
if( v_s->s_co_id == k_co->co_id )
{
stock_list_cursor.push_back( k_s->s_symb );
}
}
}
}
}
else if( pIn->acct_id )
{
const holding_summary::key k_hs_0( pIn->acct_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( pIn->acct_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
// ALWAYS_ASSERT( hs_scanner.output.size() );
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
stock_list_cursor.push_back( k_hs->hs_s_symb );
}
}
else
ALWAYS_ASSERT(false);
double old_mkt_cap = 0;
double new_mkt_cap = 0;
for( auto &s : stock_list_cursor )
{
const last_trade::key k_lt(s);
last_trade::value v_lt_temp;
try_catch(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
const security::key k_s(s);
security::value v_s_temp;
try_catch(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
const daily_market::key k_dm(s, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_day).GetDate() );
daily_market::value v_dm_temp;
try_catch(tbl_daily_market(1)->get(txn, Encode(obj_key0=str(sizeof(k_dm)), k_dm), obj_v=str(sizeof(v_dm_temp))));
const daily_market::value *v_dm = Decode(obj_v,v_dm_temp);
auto s_num_out = v_s->s_num_out;
auto old_price = v_dm->dm_close;
auto new_price = v_lt->lt_price;
old_mkt_cap += s_num_out * old_price;
new_mkt_cap += s_num_out * new_price;
}
if( old_mkt_cap != 0 )
pOut->pct_change = 100 * (new_mkt_cap / old_mkt_cap - 1);
else
pOut->pct_change = 0;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoSecurityDetailFrame1(const TSecurityDetailFrame1Input *pIn, TSecurityDetailFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
int64_t co_id;
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
co_id = v_s->s_co_id;
const company::key k_co(co_id);
company::value v_co_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co)), k_co), obj_v=str(sizeof(v_co_temp))));
const company::value *v_co = Decode(obj_v,v_co_temp);
const address::key k_ca(v_co->co_ad_id);
address::value v_ca_temp;
try_verify_relax(tbl_address(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const address::value *v_ca = Decode(obj_v,v_ca_temp);
const zip_code::key k_zca(v_ca->ad_zc_code);
zip_code::value v_zca_temp;
try_verify_relax(tbl_zip_code(1)->get(txn, Encode(obj_key0=str(sizeof(k_zca)), k_zca), obj_v=str(sizeof(v_zca_temp))));
const zip_code::value *v_zca = Decode(obj_v,v_zca_temp);
const exchange::key k_ex(v_s->s_ex_id);
exchange::value v_ex_temp;
try_verify_relax(tbl_exchange(1)->get(txn, Encode(obj_key0=str(sizeof(k_ex)), k_ex), obj_v=str(sizeof(v_ex_temp))));
const exchange::value *v_ex = Decode(obj_v,v_ex_temp);
const address::key k_ea(v_ex->ex_ad_id);
address::value v_ea_temp;
try_verify_relax(tbl_address(1)->get(txn, Encode(obj_key0=str(sizeof(k_ea)), k_ea), obj_v=str(sizeof(v_ea_temp))));
const address::value *v_ea = Decode(obj_v,v_ea_temp);
const zip_code::key k_zea(v_ea->ad_zc_code);
zip_code::value v_zea_temp;
try_verify_relax(tbl_zip_code(1)->get(txn, Encode(obj_key0=str(sizeof(k_zea)), k_zea), obj_v=str(sizeof(v_zea_temp))));
const zip_code::value *v_zea = Decode(obj_v,v_zea_temp);
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size());
pOut->num_out = v_s->s_num_out;
CDateTime(v_s->s_start_date).GetTimeStamp(&pOut->start_date );
CDateTime(v_s->s_exch_date).GetTimeStamp(&pOut->ex_date);
pOut->pe_ratio = v_s->s_pe;
pOut->s52_wk_high = v_s->s_52wk_high;
CDateTime(v_s->s_52wk_high_date).GetTimeStamp(&pOut->s52_wk_high_date );
pOut->s52_wk_low = v_s->s_52wk_low;
CDateTime(v_s->s_52wk_low_date).GetTimeStamp(&pOut->s52_wk_low_date );
pOut->divid = v_s->s_dividend;
pOut->yield = v_s->s_yield;
memcpy(pOut->co_name, v_co->co_name.data(), v_co->co_name.size());
memcpy(pOut->sp_rate, v_co->co_sp_rate.data(), v_co->co_sp_rate.size());
memcpy(pOut->ceo_name, v_co->co_ceo.data(), v_co->co_ceo.size());
memcpy(pOut->co_desc, v_co->co_desc.data(), v_co->co_desc.size());
CDateTime(v_co->co_open_date).GetTimeStamp(&pOut->open_date );
memcpy(pOut->co_st_id, v_co->co_st_id.data(), v_co->co_st_id.size());
memcpy(pOut->co_ad_line1, v_ca->ad_line1.data(), v_ca->ad_line1.size());
memcpy(pOut->co_ad_line2, v_ca->ad_line2.data(), v_ca->ad_line2.size());
memcpy(pOut->co_ad_zip, v_ca->ad_zc_code.data(), v_ca->ad_zc_code.size());
memcpy(pOut->co_ad_cty, v_ca->ad_ctry.data(), v_ca->ad_ctry.size());
memcpy(pOut->ex_ad_line1, v_ea->ad_line1.data(), v_ea->ad_line1.size());
memcpy(pOut->ex_ad_line2, v_ea->ad_line2.data(), v_ea->ad_line2.size());
memcpy(pOut->ex_ad_zip, v_ea->ad_zc_code.data(), v_ea->ad_zc_code.size());
memcpy(pOut->ex_ad_cty, v_ea->ad_ctry.data(), v_ea->ad_ctry.size());
pOut->ex_open = v_ex->ex_open;
pOut->ex_close = v_ex->ex_close;
pOut->ex_num_symb = v_ex->ex_num_symb;
memcpy(pOut->ex_name, v_ex->ex_name.data(), v_ex->ex_name.size());
memcpy(pOut->ex_desc, v_ex->ex_desc.data(), v_ex->ex_desc.size());
memcpy(pOut->co_ad_town, v_zca->zc_town.data(), v_zca->zc_town.size());
memcpy(pOut->co_ad_div, v_zca->zc_div.data(), v_zca->zc_div.size());
memcpy(pOut->ex_ad_town, v_zea->zc_town.data(), v_zea->zc_town.size());
memcpy(pOut->ex_ad_div, v_zea->zc_div.data(), v_zea->zc_div.size());
const company_competitor::key k_cp_0( co_id, MIN_VAL(k_cp_0.cp_comp_co_id), string(cIN_ID_len, (char)0 ));
const company_competitor::key k_cp_1( co_id, MAX_VAL(k_cp_1.cp_comp_co_id), string(cIN_ID_len, (char)255));
table_scanner cp_scanner(&arena);
try_catch(tbl_company_competitor(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cp_0)), k_cp_0), &Encode(obj_key1=str(sizeof(k_cp_1)), k_cp_1), cp_scanner, &arena));
ALWAYS_ASSERT( cp_scanner.output.size() );
for(auto i = 0; i < max_comp_len; i++ )
{
auto &r_cp = cp_scanner.output[i];
company_competitor::key k_cp_temp;
const company_competitor::key* k_cp = Decode( *r_cp.first, k_cp_temp );
const company::key k_co3(k_cp->cp_comp_co_id);
company::value v_co3_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co3)), k_co3), obj_v=str(sizeof(v_co3_temp))));
const company::value *v_co3 = Decode(obj_v,v_co3_temp);
const industry::key k_in(k_cp->cp_in_id);
industry::value v_in_temp;
try_verify_relax(tbl_industry(1)->get(txn, Encode(obj_key0=str(sizeof(k_in)), k_in), obj_v=str(sizeof(v_in_temp))));
const industry::value *v_in = Decode(obj_v,v_in_temp);
memcpy( pOut->cp_co_name[i], v_co3->co_name.data(), v_co3->co_name.size() );
memcpy( pOut->cp_in_name[i], v_in->in_name.data(), v_in->in_name.size() );
}
const financial::key k_fi_0( co_id, MIN_VAL(k_fi_0.fi_year), MIN_VAL(k_fi_0.fi_qtr) );
const financial::key k_fi_1( co_id, MAX_VAL(k_fi_1.fi_year), MAX_VAL(k_fi_1.fi_qtr) );
table_scanner fi_scanner(&arena);
try_catch(tbl_financial(1)->scan(txn, Encode(obj_key0=str(sizeof(k_fi_0)), k_fi_0), &Encode(obj_key1=str(sizeof(k_fi_1)), k_fi_1), fi_scanner, &arena));
ALWAYS_ASSERT( fi_scanner.output.size() );
for( uint64_t i = 0; i < max_fin_len; i++ )
{
auto &r_fi = fi_scanner.output[i];
financial::key k_fi_temp;
financial::value v_fi_temp;
const financial::key* k_fi = Decode( *r_fi.first, k_fi_temp );
const financial::value* v_fi = Decode( *r_fi.second, v_fi_temp );
// TODO. order by
pOut->fin[i].year = k_fi->fi_year;
pOut->fin[i].qtr = k_fi->fi_qtr;
CDateTime(v_fi->fi_qtr_start_date).GetTimeStamp(&pOut->fin[i].start_date );
pOut->fin[i].rev = v_fi->fi_revenue;
pOut->fin[i].net_earn = v_fi->fi_net_earn;
pOut->fin[i].basic_eps = v_fi->fi_basic_eps;
pOut->fin[i].dilut_eps = v_fi->fi_dilut_eps;
pOut->fin[i].margin = v_fi->fi_margin;
pOut->fin[i].invent = v_fi->fi_inventory;
pOut->fin[i].assets = v_fi->fi_assets;
pOut->fin[i].liab = v_fi->fi_liability;
pOut->fin[i].out_basic = v_fi->fi_out_basic;
pOut->fin[i].out_dilut = v_fi->fi_out_dilut;
}
pOut->fin_len = max_fin_len;
const daily_market::key k_dm_0(string(pIn->symbol),CDateTime((TIMESTAMP_STRUCT*)&pIn->start_day).GetDate() );
const daily_market::key k_dm_1(string(pIn->symbol),MAX_VAL(k_dm_1.dm_date));
table_scanner dm_scanner(&arena);
try_catch(tbl_daily_market(1)->scan(txn, Encode(obj_key0=str(sizeof(k_dm_0)), k_dm_0), &Encode(obj_key1=str(sizeof(k_dm_1)), k_dm_1), dm_scanner, &arena));
ALWAYS_ASSERT( dm_scanner.output.size() );
for(size_t i=0; i < (size_t)pIn->max_rows_to_return and i< dm_scanner.output.size(); i++ )
{
auto &r_dm = dm_scanner.output[i];
daily_market::key k_dm_temp;
daily_market::value v_dm_temp;
const daily_market::key* k_dm = Decode( *r_dm.first, k_dm_temp );
const daily_market::value* v_dm = Decode( *r_dm.second, v_dm_temp );
CDateTime(k_dm->dm_date).GetTimeStamp(&pOut->day[i].date );
pOut->day[i].close = v_dm->dm_close;
pOut->day[i].high = v_dm->dm_high;
pOut->day[i].low = v_dm->dm_low;
pOut->day[i].vol = v_dm->dm_vol;
}
// TODO. order by
pOut->day_len = ((size_t)pIn->max_rows_to_return > dm_scanner.output.size()) ? pIn->max_rows_to_return : dm_scanner.output.size();
const last_trade::key k_lt(string(pIn->symbol));
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
pOut->last_price = v_lt->lt_price;
pOut->last_open = v_lt->lt_open_price;
pOut->last_vol = v_lt->lt_vol;
const news_xref::key k_nx_0( co_id , MIN_VAL(k_nx_0.nx_ni_id) );
const news_xref::key k_nx_1( co_id , MAX_VAL(k_nx_0.nx_ni_id) );
table_scanner nx_scanner(&arena);
try_catch(tbl_news_xref(1)->scan(txn, Encode(obj_key0=str(sizeof(k_nx_0)), k_nx_0), &Encode(obj_key1=str(sizeof(k_nx_1)), k_nx_1), nx_scanner, &arena));
ALWAYS_ASSERT( nx_scanner.output.size() );
for(int i = 0; i < max_news_len; i++ )
{
auto &r_nx = nx_scanner.output[i];
news_xref::key k_nx_temp;
const news_xref::key* k_nx = Decode( *r_nx.first, k_nx_temp );
const news_item::key k_ni(k_nx->nx_ni_id);
news_item::value v_ni_temp;
try_verify_relax(tbl_news_item(1)->get(txn, Encode(obj_key0=str(sizeof(k_ni)), k_ni), obj_v=str(sizeof(v_ni_temp))));
const news_item::value *v_ni = Decode(obj_v,v_ni_temp);
if( pIn->access_lob_flag )
{
memcpy(pOut->news[i].item, v_ni->ni_item.data(), v_ni->ni_item.size());
CDateTime(v_ni->ni_dts).GetTimeStamp(&pOut->news[i].dts );
memcpy(pOut->news[i].src , v_ni->ni_source.data(), v_ni->ni_source.size());
memcpy(pOut->news[i].auth , v_ni->ni_author.data(), v_ni->ni_author.size());
pOut->news[i].headline[0] = 0;
pOut->news[i].summary[0] = 0;
}
else
{
pOut->news[i].item[0] = 0;
CDateTime(v_ni->ni_dts).GetTimeStamp(&pOut->news[i].dts );
memcpy(pOut->news[i].src , v_ni->ni_source.data(), v_ni->ni_source.size());
memcpy(pOut->news[i].auth , v_ni->ni_author.data(), v_ni->ni_author.size());
memcpy(pOut->news[i].headline , v_ni->ni_headline.data(), v_ni->ni_headline.size());
memcpy(pOut->news[i].summary , v_ni->ni_summary.data(), v_ni->ni_summary.size());
}
}
pOut->news_len = ( max_news_len > nx_scanner.output.size() ) ? max_news_len : nx_scanner.output.size();
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame1(const TTradeLookupFrame1Input *pIn, TTradeLookupFrame1Output *pOut)
{
int i;
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
pOut->num_found = 0;
for( i = 0; i < pIn->max_trades; i++ )
{
const trade::key k_t(pIn->trade_id[i]);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->trade_info[i].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[i].is_cash= v_t->t_is_cash;
pOut->trade_info[i].is_market= v_tt->tt_is_mrkt;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
pOut->num_found++;
const settlement::key k_se(pIn->trade_id[i]);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pIn->trade_id[i]);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
// Scan
const trade_history::key k_th_0( pIn->trade_id[i], string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pIn->trade_id[i], string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame2(const TTradeLookupFrame2Input *pIn, TTradeLookupFrame2Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
auto num_found = 0;
for( auto &r_t : t_scanner.output )
{
if( num_found >= pIn->max_trades )
break;
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[num_found].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[num_found].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[num_found].is_cash = v_t->t_is_cash;
pOut->trade_info[num_found].trade_id= k_t->t_id;
pOut->trade_info[num_found].trade_price= v_t->t_trade_price;
num_found++;
}
pOut->num_found = num_found;
for( auto i = 0; i < num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame3(const TTradeLookupFrame3Input *pIn, TTradeLookupFrame3Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_s_symb_index::key k_t_0( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_s_symb_index::key k_t_1( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_s_symb_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
auto num_found = 0;
for( auto &r_t : t_scanner.output )
{
if( num_found >= pIn->max_trades )
break;
t_s_symb_index::key k_t_temp;
t_s_symb_index::value v_t_temp;
const t_s_symb_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_s_symb_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[num_found].acct_id = v_t->t_ca_id;
memcpy(pOut->trade_info[num_found].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[num_found].is_cash = v_t->t_is_cash;
pOut->trade_info[num_found].price= v_t->t_trade_price;
pOut->trade_info[num_found].quantity = v_t->t_qty;
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_info[num_found].trade_dts );
pOut->trade_info[num_found].trade_id = k_t->t_id;
memcpy(pOut->trade_info[num_found].trade_type, v_t->t_tt_id.data(), v_t->t_tt_id.size() );
num_found++;
}
pOut->num_found = num_found;
for( int i = 0; i < num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
// TODO. order by
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame4(const TTradeLookupFrame4Input *pIn, TTradeLookupFrame4Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_1.t_dts), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
if( not t_scanner.output.size() ) // XXX. can happen? or something is wrong?
{
pOut->num_trades_found = 0;
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
for( auto &r_t : t_scanner.output )
{
t_ca_id_index::key k_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
pOut->trade_id = k_t->t_id;
break;
}
pOut->num_trades_found = 1;
// XXX. holding_history PK isn't unique. combine T_ID and row ID.
const holding_history::key k_hh_0(pOut->trade_id, MIN_VAL(k_hh_0.hh_h_t_id));
const holding_history::key k_hh_1(pOut->trade_id, MAX_VAL(k_hh_1.hh_h_t_id));
table_scanner hh_scanner(&arena);
try_catch(tbl_holding_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hh_0)), k_hh_0), &Encode(obj_key1=str(sizeof(k_hh_1)), k_hh_1), hh_scanner, &arena));
ALWAYS_ASSERT( hh_scanner.output.size() ); // possible case. no holding for the customer
auto hh_cursor = 0;
for( auto& r_hh : hh_scanner.output )
{
holding_history::key k_hh_temp;
holding_history::value v_hh_temp;
const holding_history::key* k_hh = Decode( *r_hh.first, k_hh_temp );
const holding_history::value* v_hh = Decode( *r_hh.second, v_hh_temp );
pOut->trade_info[hh_cursor].holding_history_id = k_hh->hh_h_t_id;
pOut->trade_info[hh_cursor].holding_history_trade_id = k_hh->hh_t_id;
pOut->trade_info[hh_cursor].quantity_after = v_hh->hh_after_qty;
pOut->trade_info[hh_cursor].quantity_before = v_hh->hh_before_qty;
hh_cursor++;
if( hh_cursor >= TradeLookupFrame4MaxRows )
break;
}
pOut->num_found = hh_cursor;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame1(const TTradeOrderFrame1Input *pIn, TTradeOrderFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
memcpy( pOut->acct_name, v_ca->ca_name.data(), v_ca->ca_name.size() );
pOut->broker_id = v_ca->ca_b_id;
pOut->cust_id = v_ca->ca_c_id;
pOut->tax_status = v_ca->ca_tax_st;
pOut->num_found = 1;
const customers::key k_c(pOut->cust_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
memcpy( pOut->cust_f_name, v_c->c_f_name.data(), v_c->c_f_name.size() );
memcpy( pOut->cust_l_name, v_c->c_l_name.data(), v_c->c_l_name.size() );
pOut->cust_tier = v_c->c_tier;
memcpy(pOut->tax_id, v_c->c_tax_id.data(), v_c->c_tax_id.size() );
const broker::key k_b(pOut->broker_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
memcpy( pOut->broker_name, v_b->b_name.data(), v_b->b_name.size() );
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame2(const TTradeOrderFrame2Input *pIn, TTradeOrderFrame2Output *pOut)
{
const account_permission::key k_ap(pIn->acct_id, string(pIn->exec_tax_id) );
account_permission::value v_ap_temp;
rc_t ret;
try_catch( ret = tbl_account_permission(1)->get(txn, Encode(obj_key0=str(sizeof(k_ap)), k_ap), obj_v=str(sizeof(v_ap_temp))));
if( ret._val == RC_TRUE )
{
const account_permission::value *v_ap = Decode(obj_v,v_ap_temp);
if( v_ap->ap_f_name == string(pIn->exec_f_name) and v_ap->ap_l_name == string(pIn->exec_l_name) )
{
memcpy(pOut->ap_acl, v_ap->ap_acl.data(), v_ap->ap_acl.size() );
return bench_worker::txn_result(true, 0);
}
}
pOut->ap_acl[0] = '\0';
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame3(const TTradeOrderFrame3Input *pIn, TTradeOrderFrame3Output *pOut)
{
int64_t co_id = 0;
char exch_id[cEX_ID_len + 1]; // XXX. without "+1", gdb can be killed!
memset(exch_id, 0, cEX_ID_len + 1);
if( not pIn->symbol[0] )
{
const co_name_index::key k_co_0( string(pIn->co_name), MIN_VAL(k_co_0.co_id) );
const co_name_index::key k_co_1( string(pIn->co_name), MAX_VAL(k_co_1.co_id) );
table_scanner co_scanner(&arena);
try_catch(tbl_co_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_co_0)), k_co_0), &Encode(obj_key1=str(sizeof(k_co_1)), k_co_1), co_scanner, &arena));
ALWAYS_ASSERT( co_scanner.output.size() );
co_name_index::key k_co_temp;
const co_name_index::key* k_co = Decode( *co_scanner.output.front().first, k_co_temp );
co_id = k_co->co_id;
ALWAYS_ASSERT(co_id);
const security_index::key k_s_0( co_id, pIn->issue, string(cSYMBOL_len, (char)0) );
const security_index::key k_s_1( co_id, pIn->issue, string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT(s_scanner.output.size());
for( auto &r_s : s_scanner.output )
{
security_index::key k_s_temp;
security_index::value v_s_temp;
const security_index::key* k_s = Decode( *r_s.first, k_s_temp );
const security_index::value* v_s = Decode( *r_s.second, v_s_temp );
memcpy(exch_id, v_s->s_ex_id.data(), v_s->s_ex_id.size() );
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
memcpy(pOut->symbol, k_s->s_symb.data(), k_s->s_symb.size() );
break;
}
}
else
{
memcpy(pOut->symbol, pIn->symbol, cSYMBOL_len);
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
co_id = v_s->s_co_id;
memcpy(exch_id, v_s->s_ex_id.data(), v_s->s_ex_id.size() );
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
const company::key k_co(co_id);
company::value v_co_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co)), k_co), obj_v=str(sizeof(v_co_temp))));
const company::value *v_co = Decode(obj_v,v_co_temp);
memcpy(pOut->co_name, v_co->co_name.data(), v_co->co_name.size() );
}
const last_trade::key k_lt(string(pOut->symbol));
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
pOut->market_price = v_lt->lt_price;
const trade_type::key k_tt(pIn->trade_type_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->type_is_market = v_tt->tt_is_mrkt;
pOut->type_is_sell = v_tt->tt_is_sell;
if( pOut->type_is_market )
{
pOut->requested_price = pOut->market_price;
}
else
pOut->requested_price = pIn->requested_price;
auto hold_qty = 0;
auto hold_price = 0.0;
auto hs_qty = 0;
auto buy_value = 0.0;
auto sell_value = 0.0;
auto needed_qty = pIn->trade_qty;
const holding_summary::key k_hs(pIn->acct_id, string(pOut->symbol));
holding_summary::value v_hs_temp;
rc_t ret;
try_catch(ret = tbl_holding_summary(1)->get(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), obj_v=str(sizeof(v_hs_temp))));
if( ret._val == RC_TRUE )
{
const holding_summary::value *v_hs = Decode(obj_v,v_hs_temp);
hs_qty = v_hs->hs_qty;
}
if( pOut->type_is_sell )
{
if( hs_qty > 0 )
{
vector<pair<int32_t, double>> hold_list;
const holding::key k_h_0( pIn->acct_id, string(pOut->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pOut->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // this set could be empty
for( auto &r_h : h_scanner.output )
{
holding::value v_h_temp;
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_list.push_back( make_pair(v_h->h_qty, v_h->h_price) );
}
if( pIn->is_lifo )
{
reverse(hold_list.begin(), hold_list.end());
}
for( auto& hold_list_cursor : hold_list )
{
if( not needed_qty )
break;
hold_qty = hold_list_cursor.first;
hold_price = hold_list_cursor.second;
if( hold_qty > needed_qty )
{
buy_value += needed_qty * hold_price;
sell_value += needed_qty * pOut->requested_price;
needed_qty = 0;
}
else
{
buy_value += hold_qty * hold_price;
sell_value += hold_qty * pOut->requested_price;
needed_qty -= hold_qty;
}
}
}
}
else
{
if( hs_qty < 0 )
{
vector<pair<int32_t, double>> hold_list;
const holding::key k_h_0( pIn->acct_id, string(pOut->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pOut->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // this set could be empty
for( auto &r_h : h_scanner.output )
{
holding::value v_h_temp;
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_list.push_back( make_pair(v_h->h_qty, v_h->h_price) );
}
if( pIn->is_lifo )
{
reverse(hold_list.begin(), hold_list.end());
}
for( auto& hold_list_cursor : hold_list )
{
if( not needed_qty )
break;
hold_qty = hold_list_cursor.first;
hold_price = hold_list_cursor.second;
if( hold_qty + needed_qty < 0 )
{
sell_value += needed_qty * hold_price;
buy_value += needed_qty * pOut->requested_price;
needed_qty = 0;
}
else
{
hold_qty -= hold_qty;
sell_value += hold_qty * hold_price;
buy_value += hold_qty * pOut->requested_price;
needed_qty -= hold_qty;
}
}
}
}
pOut->tax_amount = 0.0;
if( sell_value > buy_value and (pIn->tax_status == 1 or pIn->tax_status == 2 ))
{
const customer_taxrate::key k_cx_0( pIn->cust_id, string(cTX_ID_len, (char)0 ));
const customer_taxrate::key k_cx_1( pIn->cust_id, string(cTX_ID_len, (char)255));
table_scanner cx_scanner(&arena);
try_catch(tbl_customer_taxrate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cx_0)), k_cx_0), &Encode(obj_key1=str(sizeof(k_cx_1)), k_cx_1), cx_scanner, &arena));
ALWAYS_ASSERT( cx_scanner.output.size() );
auto tax_rates = 0.0;
for( auto &r_cx : cx_scanner.output )
{
customer_taxrate::key k_cx_temp;
const customer_taxrate::key* k_cx = Decode( *r_cx.first, k_cx_temp );
const tax_rate::key k_tx(k_cx->cx_tx_id);
tax_rate::value v_tx_temp;
try_verify_relax(tbl_tax_rate(1)->get(txn, Encode(obj_key0=str(sizeof(k_tx)), k_tx), obj_v=str(sizeof(v_tx_temp))));
const tax_rate::value *v_tx = Decode(obj_v,v_tx_temp);
tax_rates += v_tx->tx_rate;
}
pOut->tax_amount = (sell_value - buy_value) * tax_rates;
}
const commission_rate::key k_cr_0( pIn->cust_tier, string(pIn->trade_type_id), string(exch_id), 0 );
const commission_rate::key k_cr_1( pIn->cust_tier, string(pIn->trade_type_id), string(exch_id), pIn->trade_qty );
table_scanner cr_scanner(&arena);
try_catch(tbl_commission_rate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cr_0)), k_cr_0), &Encode(obj_key1=str(sizeof(k_cr_1)), k_cr_1), cr_scanner, &arena));
ALWAYS_ASSERT(cr_scanner.output.size());
for( auto &r_cr : cr_scanner.output )
{
commission_rate::value v_cr_temp;
const commission_rate::value* v_cr = Decode( *r_cr.second, v_cr_temp );
if( v_cr->cr_to_qty < pIn->trade_qty )
continue;
pOut->comm_rate = v_cr->cr_rate;
break;
}
const charge::key k_ch(pIn->trade_type_id, pIn->cust_tier );
charge::value v_ch_temp;
try_verify_relax(tbl_charge(1)->get(txn, Encode(obj_key0=str(sizeof(k_ch)), k_ch), obj_v=str(sizeof(v_ch_temp))));
const charge::value *v_ch = Decode(obj_v,v_ch_temp);
pOut->charge_amount = v_ch->ch_chrg;
double acct_bal = 0.0;
double hold_assets = 0.0;
pOut->acct_assets = 0.0;
if( pIn->type_is_margin )
{
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
acct_bal = v_ca->ca_bal;
const holding_summary::key k_hs_0( pIn->acct_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( pIn->acct_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
// ALWAYS_ASSERT( hs_scanner.output.size() ); // XXX. allowed?
for( auto &r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode( *r_hs.second, v_hs_temp );
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
hold_assets += v_hs->hs_qty * v_lt->lt_price;
}
if( not hold_assets )
pOut->acct_assets = acct_bal;
else
pOut->acct_assets = hold_assets + acct_bal;
}
if( pOut->type_is_market )
memcpy(pOut->status_id, pIn->st_submitted_id, cST_ID_len );
else
memcpy(pOut->status_id, pIn->st_pending_id, cST_ID_len );
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame4(const TTradeOrderFrame4Input *pIn, TTradeOrderFrame4Output *pOut)
{
auto now_dts = CDateTime().GetDate();
pOut->trade_id = GetLastTradeID();
trade::key k_t;
trade::value v_t;
k_t.t_id = pOut->trade_id;
v_t.t_dts = now_dts;
v_t.t_st_id = string(pIn->status_id);
v_t.t_tt_id = string(pIn->trade_type_id);
v_t.t_is_cash = pIn->is_cash;
v_t.t_s_symb = string(pIn->symbol);
v_t.t_qty = pIn->trade_qty;
v_t.t_bid_price = pIn->requested_price;
v_t.t_ca_id = pIn->acct_id;
v_t.t_exec_name = string(pIn->exec_name);
v_t.t_trade_price = 0;
v_t.t_chrg = pIn->charge_amount;
v_t.t_comm = pIn->comm_amount;
v_t.t_tax = 0;
v_t.t_lifo = pIn->is_lifo;
try_catch(tbl_trade(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t)), v_t)));
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t.t_ca_id;
k_t_idx1.t_dts = v_t.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t.t_st_id ;
v_t_idx1.t_tt_id = v_t.t_tt_id ;
v_t_idx1.t_is_cash = v_t.t_is_cash ;
v_t_idx1.t_s_symb = v_t.t_s_symb ;
v_t_idx1.t_qty = v_t.t_qty ;
v_t_idx1.t_bid_price = v_t.t_bid_price ;
v_t_idx1.t_exec_name = v_t.t_exec_name ;
v_t_idx1.t_trade_price = v_t.t_trade_price ;
v_t_idx1.t_chrg = v_t.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t.t_s_symb ;
k_t_idx2.t_dts = v_t.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t.t_ca_id;
v_t_idx2.t_st_id = v_t.t_st_id ;
v_t_idx2.t_tt_id = v_t.t_tt_id ;
v_t_idx2.t_is_cash = v_t.t_is_cash ;
v_t_idx2.t_qty = v_t.t_qty ;
v_t_idx2.t_exec_name = v_t.t_exec_name ;
v_t_idx2.t_trade_price = v_t.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
if( not pIn->type_is_market )
{
trade_request::key k_tr;
trade_request::value v_tr;
k_tr.tr_s_symb = string(pIn->symbol);
k_tr.tr_b_id = pIn->broker_id;
k_tr.tr_t_id = pOut->trade_id;
v_tr.tr_tt_id = string(pIn->trade_type_id);
v_tr.tr_qty = pIn->trade_qty;
v_tr.tr_bid_price = pIn->requested_price;
try_catch(tbl_trade_request(1)->insert(txn, Encode(obj_key0=str(sizeof(k_tr)), k_tr), Encode(obj_v=str(sizeof(v_tr)), v_tr)));
}
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = pOut->trade_id;
k_th.th_dts = now_dts;
k_th.th_st_id = string(pIn->status_id);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame5(void)
{
db->abort_txn(txn);
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame6(void)
{
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame1(const TTradeResultFrame1Input *pIn, TTradeResultFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
pOut->acct_id = v_t->t_ca_id;
memcpy(pOut->type_id, v_t->t_tt_id.data(), v_t->t_tt_id.size());
memcpy(pOut->symbol, v_t->t_s_symb.data(), v_t->t_s_symb.size());
pOut->trade_qty = v_t->t_qty;
pOut->charge = v_t->t_chrg;
pOut->is_lifo = v_t->t_lifo;
pOut->trade_is_cash = v_t->t_is_cash;
pOut->num_found = 1;
const trade_type::key k_tt(pOut->type_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
memcpy(pOut->type_name, v_tt->tt_name.data(), v_tt->tt_name.size());
pOut->type_is_sell = v_tt->tt_is_sell;
pOut->type_is_market = v_tt->tt_is_mrkt;
pOut->hs_qty = 0;
const holding_summary::key k_hs(pOut->acct_id, string(pOut->symbol));
holding_summary::value v_hs_temp;
rc_t ret;
try_catch( ret = tbl_holding_summary(1)->get(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), obj_v=str(sizeof(v_hs_temp))));
if(ret._val == RC_TRUE )
{
const holding_summary::value *v_hs = Decode(obj_v,v_hs_temp);
pOut->hs_qty = v_hs->hs_qty;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame2(const TTradeResultFrame2Input *pIn, TTradeResultFrame2Output *pOut)
{
auto buy_value = 0.0;
auto sell_value = 0.0;
auto needed_qty = pIn->trade_qty;
uint64_t trade_dts = CDateTime().GetDate();
auto hold_id=0;
auto hold_price=0;
auto hold_qty=0;
CDateTime(trade_dts).GetTimeStamp(&pOut->trade_dts );
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
pOut->broker_id = v_ca->ca_b_id;
pOut->cust_id = v_ca->ca_c_id;
pOut->tax_status = v_ca->ca_tax_st;
if( pIn->type_is_sell )
{
if( pIn->hs_qty == 0 )
{
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = -1 * pIn->trade_qty;
try_catch(tbl_holding_summary(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
else
{
if( pIn->hs_qty != pIn->trade_qty )
{
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->hs_qty - pIn->trade_qty;
try_catch(tbl_holding_summary(1)->put(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
}
if( pIn->hs_qty > 0 )
{
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // guessing this could be empty set
if( pIn->is_lifo )
{
reverse(h_scanner.output.begin(), h_scanner.output.end());
}
for( auto& r_h : h_scanner.output )
{
if( needed_qty == 0 )
break;
holding::key k_h_temp;
holding::value v_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_id = k_h->h_t_id;
hold_qty = v_h->h_qty;
hold_price = v_h->h_price;
if( hold_qty > needed_qty )
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = hold_qty - needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// update with current holding cursor. use the same key
holding::key k_h_new(*k_h);
holding::value v_h_new(*v_h);
v_h_new.h_qty = hold_qty - needed_qty;
try_catch(tbl_holding(1)->put(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new), Encode(obj_v=str(sizeof(v_h_new)), v_h_new)));
buy_value += needed_qty * hold_price;
sell_value += needed_qty * pIn->trade_price;
needed_qty = 0;
}
else
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = 0;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
buy_value += hold_qty * hold_price;
sell_value += hold_qty * pIn->trade_price;
needed_qty -= hold_qty;
}
}
}
if( needed_qty > 0)
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = pIn->trade_id;
v_hh.hh_before_qty = 0;
v_hh.hh_after_qty = -1 * needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h;
holding::value v_h;
k_h.h_ca_id = pIn->acct_id;
k_h.h_s_symb = string(pIn->symbol);
k_h.h_dts = trade_dts;
k_h.h_t_id = pIn->trade_id;
v_h.h_price = pIn->trade_price;
v_h.h_qty = -1 * needed_qty;
try_catch(tbl_holding(1)->insert(txn, Encode(obj_key0=str(sizeof(k_h)), k_h), Encode(obj_v=str(sizeof(v_h)), v_h)));
}
else
{
if( pIn->hs_qty == pIn->trade_qty )
{
holding_summary::key k_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
try_catch(tbl_holding_summary(1)->remove(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs)));
// Cascade delete for FK integrity
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
for( auto& r_h : h_scanner.output )
{
holding::key k_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
}
}
}
}
else // BUY
{
if( pIn->hs_qty == 0 )
{
// HS insert
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->trade_qty;
try_catch(tbl_holding_summary(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
else if ( -1*pIn->hs_qty != pIn->trade_qty )
{
// HS update
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->trade_qty + pIn->hs_qty;
try_catch(tbl_holding_summary(1)->put(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
if( pIn->hs_qty < 0 )
{
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // XXX. guessing could be empty
if( pIn->is_lifo )
{
reverse(h_scanner.output.begin(), h_scanner.output.end());
}
// hold list cursor
for( auto& r_h : h_scanner.output )
{
if( needed_qty == 0 )
break;
holding::key k_h_temp;
holding::value v_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_id = k_h->h_t_id;
hold_qty = v_h->h_qty;
hold_price = v_h->h_price;
if( hold_qty + needed_qty < 0 )
{
// HH insert
// H update
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = hold_qty + needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// update with current holding cursor. use the same key
holding::key k_h_new(*k_h);
holding::value v_h_new(*v_h);
v_h_new.h_qty = hold_qty + needed_qty;
try_catch(tbl_holding(1)->put(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new), Encode(obj_v=str(sizeof(v_h_new)), v_h_new)));
sell_value += needed_qty * hold_price;
buy_value += needed_qty * pIn->trade_price;
needed_qty = 0;
}
else
{
// HH insert
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = 0;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// H delete
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
hold_qty *= -1;
sell_value += hold_qty * hold_price;
buy_value += hold_qty * pIn->trade_price;
needed_qty -= hold_qty;
}
}
}
if( needed_qty > 0 )
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = pIn->trade_id;
v_hh.hh_before_qty = 0;
v_hh.hh_after_qty = needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h;
holding::value v_h;
k_h.h_ca_id = pIn->acct_id;
k_h.h_s_symb = string(pIn->symbol);
k_h.h_dts = trade_dts;
k_h.h_t_id = pIn->trade_id;
v_h.h_price = pIn->trade_price;
v_h.h_qty = needed_qty;
try_catch(tbl_holding(1)->insert(txn, Encode(obj_key0=str(sizeof(k_h)), k_h), Encode(obj_v=str(sizeof(v_h)), v_h)));
}
else if ( -1*pIn->hs_qty == pIn->trade_qty )
{
holding_summary::key k_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
try_catch(tbl_holding_summary(1)->remove(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs)));
// Cascade delete for FK integrity
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
for( auto& r_h : h_scanner.output )
{
holding::key k_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
}
}
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame3(const TTradeResultFrame3Input *pIn, TTradeResultFrame3Output *pOut)
{
const customer_taxrate::key k_cx_0( pIn->cust_id, string(cTX_ID_len, (char)0 ) );
const customer_taxrate::key k_cx_1( pIn->cust_id, string(cTX_ID_len, (char)255) );
table_scanner cx_scanner(&arena);
try_catch(tbl_customer_taxrate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cx_0)), k_cx_0), &Encode(obj_key1=str(sizeof(k_cx_1)), k_cx_1), cx_scanner, &arena));
ALWAYS_ASSERT( cx_scanner.output.size() );
double tax_rates = 0.0;
for( auto &r_cx : cx_scanner.output )
{
customer_taxrate::key k_cx_temp;
customer_taxrate::value v_cx_temp;
const customer_taxrate::key* k_cx = Decode( *r_cx.first, k_cx_temp );
const tax_rate::key k_tx(k_cx->cx_tx_id);
tax_rate::value v_tx_temp;
try_verify_relax(tbl_tax_rate(1)->get(txn, Encode(obj_key0=str(sizeof(k_tx)), k_tx), obj_v=str(sizeof(v_tx_temp))));
const tax_rate::value *v_tx = Decode(obj_v,v_tx_temp);
tax_rates += v_tx->tx_rate;
}
pOut->tax_amount = (pIn->sell_value - pIn->buy_value) * tax_rates;
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_tax = pOut->tax_amount; // secondary indices don't have t_tax field. no need for cascading update
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame4(const TTradeResultFrame4Input *pIn, TTradeResultFrame4Output *pOut)
{
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
const customers::key k_c(pIn->cust_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
const commission_rate::key k_cr_0( v_c->c_tier, string(pIn->type_id), v_s->s_ex_id, 0);
const commission_rate::key k_cr_1( v_c->c_tier, string(pIn->type_id), v_s->s_ex_id, pIn->trade_qty );
table_scanner cr_scanner(&arena);
try_catch(tbl_commission_rate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cr_0)), k_cr_0), &Encode(obj_key1=str(sizeof(k_cr_1)), k_cr_1), cr_scanner, &arena));
ALWAYS_ASSERT(cr_scanner.output.size());
for( auto &r_cr : cr_scanner.output )
{
commission_rate::value v_cr_temp;
const commission_rate::value* v_cr = Decode( *r_cr.second, v_cr_temp );
if( v_cr->cr_to_qty < pIn->trade_qty )
continue;
pOut->comm_rate = v_cr->cr_rate;
break;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame5(const TTradeResultFrame5Input *pIn )
{
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_comm = pIn->comm_amount;
v_t_new.t_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
v_t_new.t_st_id = string(pIn->st_completed_id);
v_t_new.t_trade_price = pIn->trade_price;
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
// DTS field is updated. cascading update( actually insert after remove, because dts is included in PK )
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t->t_ca_id;
k_t_idx1.t_dts = v_t->t_dts;
k_t_idx1.t_id = k_t.t_id;
try_verify_relax(tbl_t_ca_id_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1)));
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t->t_s_symb;
k_t_idx2.t_dts = v_t->t_dts;
k_t_idx2.t_id = k_t.t_id;
try_verify_relax(tbl_t_s_symb_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2)));
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = pIn->trade_id;
k_th.th_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
k_th.th_st_id = string(pIn->st_completed_id);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
const broker::key k_b(pIn->broker_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
broker::value v_b_new(*v_b);
v_b_new.b_comm_total += pIn->comm_amount;
v_b_new.b_num_trades += 1;
try_catch(tbl_broker(1)->put(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), Encode(obj_v=str(sizeof(v_b_new)), v_b_new)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame6(const TTradeResultFrame6Input *pIn, TTradeResultFrame6Output *pOut)
{
string cash_type;
if( pIn->trade_is_cash )
cash_type = "Cash Account";
else
cash_type = "Margin";
settlement::key k_se;
settlement::value v_se;
k_se.se_t_id = pIn->trade_id;
v_se.se_cash_type = cash_type;
v_se.se_cash_due_date = CDateTime((TIMESTAMP_STRUCT*)&pIn->due_date).GetDate();
v_se.se_amt = pIn->se_amount;
try_catch(tbl_settlement(1)->insert(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), Encode(obj_v=str(sizeof(v_se)), v_se)));
if( pIn->trade_is_cash )
{
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
customer_account::value v_ca_new(*v_ca);
v_ca_new.ca_bal += pIn->se_amount;
try_catch(tbl_customer_account(1)->put(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), Encode(obj_v=str(sizeof(v_ca_new)), v_ca_new)));
ca_id_index::key k_idx_ca;
ca_id_index::value v_idx_ca;
k_idx_ca.ca_id = k_ca.ca_id;
k_idx_ca.ca_c_id = v_ca_new.ca_c_id;
v_idx_ca.ca_bal = v_ca_new.ca_bal;
try_catch(tbl_ca_id_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_idx_ca)), k_idx_ca), Encode(obj_v=str(sizeof(v_idx_ca)), v_idx_ca)));
cash_transaction::key k_ct;
cash_transaction::value v_ct;
k_ct.ct_t_id = pIn->trade_id;
v_ct.ct_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
v_ct.ct_amt = pIn->se_amount;
v_ct.ct_name = string(pIn->type_name) + " " + to_string(pIn->trade_qty) + " shares of " + string(pIn->s_name);
try_catch(tbl_cash_transaction(1)->insert(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), Encode(obj_v=str(sizeof(v_ct)), v_ct)));
}
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
pOut->acct_bal = v_ca->ca_bal;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeStatusFrame1(const TTradeStatusFrame1Input *pIn, TTradeStatusFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, MIN_VAL(k_t_0.t_dts), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_1.t_dts), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
int t_cursor = 0;
for( auto &r_t : t_scanner.output )
{
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
const status_type::key k_st(v_t->t_st_id);
status_type::value v_st_temp;
try_verify_relax(tbl_status_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_st)), k_st), obj_v=str(sizeof(v_st_temp))));
const status_type::value *v_st = Decode(obj_v,v_st_temp);
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
const security::key k_s(v_t->t_s_symb);
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
const exchange::key k_ex(v_s->s_ex_id);
exchange::value v_ex_temp;
try_verify_relax(tbl_exchange(1)->get(txn, Encode(obj_key0=str(sizeof(k_ex)), k_ex), obj_v=str(sizeof(v_ex_temp))));
const exchange::value *v_ex = Decode(obj_v,v_ex_temp);
pOut->trade_id[t_cursor] = k_t->t_id;
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_dts[t_cursor] );
memcpy(pOut->status_name[t_cursor], v_st->st_name.data(), v_st->st_name.size() );
memcpy(pOut->type_name[t_cursor], v_tt->tt_name.data(), v_tt->tt_name.size());
memcpy(pOut->symbol[t_cursor], v_t->t_s_symb.data(), v_t->t_s_symb.size() );
pOut->trade_qty[t_cursor] = v_t->t_qty;
memcpy(pOut->exec_name[t_cursor], v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->charge[t_cursor] = v_t->t_chrg;
memcpy(pOut->s_name[t_cursor], v_s->s_name.data(), v_s->s_name.size());
memcpy(pOut->ex_name[t_cursor], v_ex->ex_name.data(), v_ex->ex_name.size() );
t_cursor++;
if( t_cursor >= max_trade_status_len )
break;
}
pOut->num_found = t_cursor;
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
const customers::key k_c(v_ca->ca_c_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
const broker::key k_b(v_ca->ca_b_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
memcpy(pOut->cust_f_name, v_c->c_f_name.data(), v_c->c_f_name.size() );
memcpy(pOut->cust_l_name, v_c->c_l_name.data(), v_c->c_l_name.size() );
memcpy(pOut->broker_name, v_b->b_name.data(), v_b->b_name.size() );
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame1(const TTradeUpdateFrame1Input *pIn, TTradeUpdateFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
for( auto i = 0; i < pIn->max_trades; i++ )
{
const trade::key k_t(pIn->trade_id[i]);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
pOut->num_found++;
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->trade_info[i].bid_price = v_t->t_bid_price;
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].is_market = v_tt->tt_is_mrkt;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
if( pOut->num_updated < pIn->max_updates )
{
string temp_exec_name = v_t->t_exec_name.str();
size_t index = temp_exec_name.find(" X ");
if(index != string::npos){
temp_exec_name.replace(index, 3, " ");
} else {
index = temp_exec_name.find(" ");
temp_exec_name.replace(index, 3, " X ");
}
trade::value v_t_new(*v_t);
v_t_new.t_exec_name = temp_exec_name;
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
pOut->num_updated++;
memcpy(pOut->trade_info[i].exec_name, temp_exec_name.data(), temp_exec_name.size());
}
else
{
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
}
const settlement::key k_se(pIn->trade_id[i]);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date);
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size());
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pIn->trade_id[i]);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
const trade_history::key k_th_0( pIn->trade_id[i], string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pIn->trade_id[i], string(cST_ID_len, (char)255) , MIN_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame2(const TTradeUpdateFrame2Input *pIn, TTradeUpdateFrame2Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_0.t_id));
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
for( size_t i = 0; i < (size_t)pIn->max_trades and i < t_scanner.output.size(); i++ )
{
auto &r_t = t_scanner.output[i];
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[i].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].trade_id= k_t->t_id;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
pOut->num_found = i;
}
pOut->num_updated = 0;
for( int i = 0; i < pOut->num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
if( pOut->num_updated < pIn->max_updates )
{
settlement::value v_se_new(*v_se);
if( pOut->trade_info[i].is_cash ){
if( v_se_new.se_cash_type == "Cash Account")
v_se_new.se_cash_type = "Cash";
else
v_se_new.se_cash_type = "Cash Account";
}
else{
if( v_se_new.se_cash_type == "Margin Account")
v_se_new.se_cash_type = "Margin";
else
v_se_new.se_cash_type = "Margin Account";
}
try_catch(tbl_settlement(1)->put(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), Encode(obj_v=str(sizeof(v_se_new)), v_se_new)));
pOut->num_updated++;
}
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date);
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size());
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame3(const TTradeUpdateFrame3Input *pIn, TTradeUpdateFrame3Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_s_symb_index::key k_t_0( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_s_symb_index::key k_t_1( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_0.t_id));
table_scanner t_scanner(&arena);
try_catch(tbl_t_s_symb_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() ); // XXX. short innitial trading day can make this case happening?
for( size_t i = 0; i < (size_t)pIn->max_trades and i < t_scanner.output.size() ; i++ )
{
auto &r_t = t_scanner.output[i];
t_s_symb_index::key k_t_temp;
t_s_symb_index::value v_t_temp;
const t_s_symb_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_s_symb_index::value* v_t = Decode( *r_t.second, v_t_temp );
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
const security::key k_s(k_t->t_s_symb);
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
/*
acct_id[] = T_CA_ID,
exec_name[] = T_EXEC_NAME,
is_cash[] = T_IS_CASH,
price[] = T_TRADE_PRICE,
quantity[] = T_QTY,
s_name[] = S_NAME,
trade_dts[] = T_DTS,
trade_list[] = T_ID,
trade_type[] = T_TT_ID,
type_name[] = TT_NAME
*/
pOut->trade_info[i].acct_id = v_t->t_ca_id;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].price = v_t->t_trade_price;
pOut->trade_info[i].quantity = v_t->t_qty;
memcpy(pOut->trade_info[i].s_name, v_s->s_name.data(), v_s->s_name.size());
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_info[i].trade_dts);
pOut->trade_info[i].trade_id = k_t->t_id;
memcpy(pOut->trade_info[i].trade_type, v_t->t_tt_id.data(), v_t->t_tt_id.size());
memcpy(pOut->trade_info[i].type_name, v_tt->tt_name.data(), v_tt->tt_name.size());
pOut->num_found = i;
}
pOut->num_updated = 0;
for( int i = 0; i < pOut->num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
if( pOut->num_updated < pIn->max_updates )
{
string temp_ct_name = v_ct->ct_name.str();
size_t index = temp_ct_name.find(" shares of ");
if(index != string::npos){
stringstream ss;
ss << pOut->trade_info[i].type_name << " " << pOut->trade_info[i].quantity
<< " Shares of " << pOut->trade_info[i].s_name;
temp_ct_name = ss.str();
} else {
stringstream ss;
ss << pOut->trade_info[i].type_name << " " << pOut->trade_info[i].quantity
<< " shares of " << pOut->trade_info[i].s_name;
temp_ct_name = ss.str();
}
cash_transaction::value v_ct_new(*v_ct);
v_ct_new.ct_name = temp_ct_name;
try_catch(tbl_cash_transaction(1)->put(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), Encode(obj_v=str(sizeof(v_ct_new)), v_ct_new)));
pOut->num_updated++;
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct_new.ct_name.data(), v_ct_new.ct_name.size());
}
else
{
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoLongQueryFrame1()
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
auto total_range = max_ca_id - min_ca_id;
auto scan_range_size = (max_ca_id - min_ca_id) / 100 * long_query_scan_range;
auto start_pos = min_ca_id + RandomNumber( r, 0, total_range - scan_range_size );
auto end_pos = start_pos + scan_range_size;
const customer_account::key k_ca_0( start_pos);
const customer_account::key k_ca_1( end_pos );
table_scanner ca_scanner(&arena);
try_catch(tbl_customer_account(1)->scan(txn, Encode(obj_key0=str(sizeof(k_ca_0)), k_ca_0), &Encode(obj_key1=str(sizeof(k_ca_1)), k_ca_1), ca_scanner, &arena));
ALWAYS_ASSERT( ca_scanner.output.size() );
auto asset = 0;
for( auto& r_ca : ca_scanner.output )
{
customer_account::key k_ca_temp;
const customer_account::key* k_ca = Decode( *r_ca.first, k_ca_temp );
const holding_summary::key k_hs_0( k_ca->ca_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( k_ca->ca_id, string(cSYMBOL_len, (char)255) );
static __thread table_scanner hs_scanner(&arena);
hs_scanner.output.clear();
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode(*r_hs.second, v_hs_temp );
// LastTrade probe & equi-join
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_catch(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
asset += v_hs->hs_qty * v_lt->lt_price;
}
}
assets_history::key k_ah;
assets_history::value v_ah;
k_ah.ah_id = GetLastListID();
v_ah.start_ca_id = start_pos;
v_ah.end_ca_id = start_pos;
v_ah.total_assets = asset;
try_catch(tbl_assets_history(1)->insert(txn, Encode(str(sizeof(k_ah)), k_ah), Encode(str(sizeof(v_ah)), v_ah)));
// nothing to do actually. just bothering writers.
try_catch(db->commit_txn(txn));
inc_ntxn_query_commits();
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoDataMaintenanceFrame1(const TDataMaintenanceFrame1Input *pIn){}
bench_worker::txn_result tpce_worker::DoTradeCleanupFrame1(const TTradeCleanupFrame1Input *pIn){}
class tpce_charge_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_charge_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCharge();
bool isLast = pGenerateAndLoad->isLastCharge();
while(!isLast) {
PCHARGE_ROW record = pGenerateAndLoad->getChargeRow();
chargeBuffer.append(record);
isLast= pGenerateAndLoad->isLastCharge();
}
chargeBuffer.setMoreToRead(false);
int rows=chargeBuffer.getSize();
for(int i=0; i<rows; i++){
PCHARGE_ROW record = chargeBuffer.get(i);
charge::key k;
charge::value v;
k.ch_tt_id = string( record->CH_TT_ID );
k.ch_c_tier = record->CH_C_TIER;
v.ch_chrg = record->CH_CHRG;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_charge(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
// TODO. sanity check
// Partitioning by customer?
}
pGenerateAndLoad->ReleaseCharge();
chargeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_commission_rate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_commission_rate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCommissionRate();
bool isLast = pGenerateAndLoad->isLastCommissionRate();
while(!isLast) {
PCOMMISSION_RATE_ROW record = pGenerateAndLoad->getCommissionRateRow();
commissionRateBuffer.append(record);
isLast= pGenerateAndLoad->isLastCommissionRate();
}
commissionRateBuffer.setMoreToRead(false);
int rows=commissionRateBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMMISSION_RATE_ROW record = commissionRateBuffer.get(i);
commission_rate::key k;
commission_rate::value v;
k.cr_c_tier = record->CR_C_TIER;
k.cr_tt_id = string(record->CR_TT_ID);
k.cr_ex_id = string(record->CR_EX_ID);
k.cr_from_qty = record->CR_FROM_QTY;
v.cr_to_qty = record->CR_TO_QTY;
v.cr_rate = record->CR_RATE;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_commission_rate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseCommissionRate();
commissionRateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_exchange_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_exchange_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions)
{}
protected:
virtual void
load()
{
pGenerateAndLoad->InitExchange();
bool isLast = pGenerateAndLoad->isLastExchange();
while(!isLast) {
PEXCHANGE_ROW record = pGenerateAndLoad->getExchangeRow();
exchangeBuffer.append(record);
isLast= pGenerateAndLoad->isLastExchange();
}
exchangeBuffer.setMoreToRead(false);
int rows=exchangeBuffer.getSize();
for(int i=0; i<rows; i++){
PEXCHANGE_ROW record = exchangeBuffer.get(i);
exchange::key k;
exchange::value v;
k.ex_id = string(record->EX_ID);
v.ex_name = string(record->EX_NAME);
v.ex_num_symb = record->EX_NUM_SYMB;
v.ex_open= record->EX_OPEN;
v.ex_close= record->EX_CLOSE;
v.ex_desc = string(record->EX_DESC);
v.ex_ad_id= record->EX_AD_ID;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_exchange(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseExchange();
exchangeBuffer.release();
}
};
class tpce_industry_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_industry_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitIndustry();
bool isLast = pGenerateAndLoad->isLastIndustry();
while(!isLast) {
PINDUSTRY_ROW record = pGenerateAndLoad->getIndustryRow();
industryBuffer.append(record);
isLast= pGenerateAndLoad->isLastIndustry();
}
industryBuffer.setMoreToRead(false);
int rows=industryBuffer.getSize();
for(int i=0; i<rows; i++){
PINDUSTRY_ROW record = industryBuffer.get(i);
industry::key k_in;
industry::value v_in;
in_name_index::key k_in_idx1;
in_name_index::value v_in_idx1;
in_sc_id_index::key k_in_idx2;
in_sc_id_index::value v_in_idx2;
k_in.in_id = string(record->IN_ID);
v_in.in_name = string(record->IN_NAME);
v_in.in_sc_id = string(record->IN_SC_ID);
k_in_idx1.in_name = string(record->IN_NAME);
k_in_idx1.in_id = string(record->IN_ID);
k_in_idx2.in_sc_id = string(record->IN_SC_ID);
k_in_idx2.in_id = string(record->IN_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_industry(1)->insert(txn, Encode(str(sizeof(k_in)), k_in), Encode(str(sizeof(v_in)), v_in)));
try_verify_strict(tbl_in_name_index(1)->insert(txn, Encode(str(sizeof(k_in_idx1)), k_in_idx1), Encode(str(sizeof(v_in_idx1)), v_in_idx1)));
try_verify_strict(tbl_in_sc_id_index(1)->insert(txn, Encode(str(sizeof(k_in_idx2)), k_in_idx2), Encode(str(sizeof(v_in_idx2)), v_in_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseIndustry();
industryBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_sector_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_sector_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitSector();
bool isLast = pGenerateAndLoad->isLastSector();
while(!isLast) {
PSECTOR_ROW record = pGenerateAndLoad->getSectorRow();
sectorBuffer.append(record);
isLast= pGenerateAndLoad->isLastSector();
}
sectorBuffer.setMoreToRead(false);
int rows=sectorBuffer.getSize();
for(int i=0; i<rows; i++){
PSECTOR_ROW record = sectorBuffer.get(i);
sector::key k;
sector::value v;
k.sc_name= string(record->SC_NAME);
k.sc_id= string(record->SC_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_sector(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseSector();
sectorBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_status_type_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_status_type_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitStatusType();
bool isLast = pGenerateAndLoad->isLastStatusType();
while(!isLast) {
PSTATUS_TYPE_ROW record = pGenerateAndLoad->getStatusTypeRow();
statusTypeBuffer.append(record);
isLast= pGenerateAndLoad->isLastStatusType();
}
statusTypeBuffer.setMoreToRead(false);
int rows=statusTypeBuffer.getSize();
for(int i=0; i<rows; i++){
PSTATUS_TYPE_ROW record = statusTypeBuffer.get(i);
status_type::key k;
status_type::value v;
k.st_id = string(record->ST_ID);
v.st_name = string(record->ST_NAME );
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_status_type(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseStatusType();
statusTypeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_tax_rate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_tax_rate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitTaxrate();
bool hasNext;
do{
hasNext= pGenerateAndLoad->hasNextTaxrate();
PTAXRATE_ROW record = pGenerateAndLoad->getTaxrateRow();
taxrateBuffer.append(record);
} while(hasNext);
taxrateBuffer.setMoreToRead(false);
int rows=taxrateBuffer.getSize();
for(int i=0; i<rows; i++){
PTAXRATE_ROW record = taxrateBuffer.get(i);
tax_rate::key k;
tax_rate::value v;
k.tx_id = string(record->TX_ID);
v.tx_name = string(record->TX_NAME );
v.tx_rate = record->TX_RATE;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_tax_rate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseTaxrate();
taxrateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_trade_type_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_trade_type_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitTradeType();
bool isLast = pGenerateAndLoad->isLastTradeType();
while(!isLast) {
PTRADE_TYPE_ROW record = pGenerateAndLoad->getTradeTypeRow();
tradeTypeBuffer.append(record);
isLast= pGenerateAndLoad->isLastTradeType();
}
tradeTypeBuffer.setMoreToRead(false);
int rows=tradeTypeBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_TYPE_ROW record = tradeTypeBuffer.get(i);
trade_type::key k;
trade_type::value v;
k.tt_id = string(record->TT_ID);
v.tt_name = string(record->TT_NAME );
v.tt_is_sell = record->TT_IS_SELL;
v.tt_is_mrkt = record->TT_IS_MRKT;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade_type(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseTradeType();
tradeTypeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_zip_code_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_zip_code_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitZipCode();
bool hasNext = pGenerateAndLoad->hasNextZipCode();
while(hasNext) {
PZIP_CODE_ROW record = pGenerateAndLoad->getZipCodeRow();
zipCodeBuffer.append(record);
hasNext= pGenerateAndLoad->hasNextZipCode();
}
zipCodeBuffer.setMoreToRead(false);
int rows=zipCodeBuffer.getSize();
for(int i=0; i<rows; i++){
PZIP_CODE_ROW record = zipCodeBuffer.get(i);
zip_code::key k;
zip_code::value v;
k.zc_code = string(record->ZC_CODE);
v.zc_town = string(record->ZC_TOWN);
v.zc_div = string(record->ZC_DIV);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_zip_code(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseZipCode();
zipCodeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_address_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_address_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitAddress();
while(addressBuffer.hasMoreToRead()){
addressBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextAddress();
PADDRESS_ROW record = pGenerateAndLoad->getAddressRow();
addressBuffer.append(record);
} while((hasNext && addressBuffer.hasSpace()));
addressBuffer.setMoreToRead(hasNext);
int rows=addressBuffer.getSize();
for(int i=0; i<rows; i++){
PADDRESS_ROW record = addressBuffer.get(i);
address::key k;
address::value v;
k.ad_id = record->AD_ID;
v.ad_line1 = string(record->AD_LINE1);
v.ad_line2 = string(record->AD_LINE2);
v.ad_zc_code = string(record->AD_ZC_CODE );
v.ad_ctry = string(record->AD_CTRY );
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_address(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseAddress();
addressBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_customer_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_customer_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomer();
while(customerBuffer.hasMoreToRead()){
customerBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCustomer();
PCUSTOMER_ROW record = pGenerateAndLoad->getCustomerRow();
customerBuffer.append(record);
} while((hasNext && customerBuffer.hasSpace()));
customerBuffer.setMoreToRead(hasNext);
int rows=customerBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_ROW record = customerBuffer.get(i);
customers::key k;
customers::value v;
k.c_id = record->C_ID;
v.c_tax_id = string(record->C_TAX_ID);
v.c_st_id = string(record->C_ST_ID);
v.c_l_name = string(record->C_L_NAME);
v.c_f_name = string(record->C_F_NAME);
v.c_m_name = string(record->C_M_NAME);
v.c_gndr = record->C_GNDR;
v.c_tier = record->C_TIER;
v.c_dob = record->C_DOB.GetDate();
v.c_ad_id = record->C_AD_ID;
v.c_ctry_1 = string(record->C_CTRY_1);
v.c_area_1 = string(record->C_AREA_1);
v.c_local_1 = string(record->C_LOCAL_1);
v.c_ext_1 = string(record->C_EXT_1);
v.c_ctry_2 = string(record->C_CTRY_2);
v.c_area_2 = string(record->C_AREA_2);
v.c_local_2 = string(record->C_LOCAL_2);
v.c_ext_2 = string(record->C_EXT_2);
v.c_ctry_3 = string(record->C_CTRY_3);
v.c_area_3 = string(record->C_AREA_3);
v.c_local_3 = string(record->C_LOCAL_3);
v.c_ext_3 = string(record->C_EXT_3);
v.c_email_1 = string(record->C_EMAIL_1);
v.c_email_2 = string(record->C_EMAIL_2);
c_tax_id_index::key k_idx_tax_id;
c_tax_id_index::value v_idx_tax_id;
k_idx_tax_id.c_id = record->C_ID;
k_idx_tax_id.c_tax_id = string(record->C_TAX_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customers(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_c_tax_id_index(1)->insert(txn, Encode(str(sizeof(k_idx_tax_id)), k_idx_tax_id), Encode(str(sizeof(v_idx_tax_id)), v_idx_tax_id)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomer();
customerBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_ca_and_ap_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_ca_and_ap_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomerAccountAndAccountPermission();
while(customerAccountBuffer.hasMoreToRead()){
customerAccountBuffer.reset();
accountPermissionBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCustomerAccount();
PCUSTOMER_ACCOUNT_ROW record = pGenerateAndLoad->getCustomerAccountRow();
customerAccountBuffer.append(record);
int perms = pGenerateAndLoad->PermissionsPerCustomer();
for(int i=0; i<perms; i++) {
PACCOUNT_PERMISSION_ROW row =
pGenerateAndLoad->getAccountPermissionRow(i);
accountPermissionBuffer.append(row);
}
} while((hasNext && customerAccountBuffer.hasSpace()));
customerAccountBuffer.setMoreToRead(hasNext);
int rows=customerAccountBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_ACCOUNT_ROW record = customerAccountBuffer.get(i);
customer_account::key k;
customer_account::value v;
ca_id_index::key k_idx1;
ca_id_index::value v_idx1;
k.ca_id = record->CA_ID;
if( likely( record->CA_ID > max_ca_id ) )
max_ca_id = record->CA_ID;
if( unlikely( record->CA_ID < min_ca_id ) )
min_ca_id = record->CA_ID;
v.ca_b_id = record->CA_B_ID;
v.ca_c_id = record->CA_C_ID;
v.ca_name = string(record->CA_NAME);
v.ca_tax_st = record->CA_TAX_ST;
v.ca_bal = record->CA_BAL;
k_idx1.ca_id = record->CA_ID;
k_idx1.ca_c_id = record->CA_C_ID;
v_idx1.ca_bal = record->CA_BAL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customer_account(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_ca_id_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=customerAccountBuffer.getSize();
for(int i=0; i<rows; i++){
PACCOUNT_PERMISSION_ROW record = accountPermissionBuffer.get(i);
account_permission::key k;
account_permission::value v;
k.ap_ca_id = record->AP_CA_ID;
k.ap_tax_id = string(record->AP_TAX_ID);
v.ap_acl = string(record->AP_ACL);
v.ap_l_name = string(record->AP_L_NAME);
v.ap_f_name = string(record->AP_F_NAME);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_account_permission(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomerAccountAndAccountPermission();
customerAccountBuffer.release();
accountPermissionBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_customer_taxrate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_customer_taxrate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomerTaxrate();
while(customerTaxrateBuffer.hasMoreToRead()){
customerTaxrateBuffer.reset();
bool hasNext;
int taxrates=pGenerateAndLoad->getTaxratesCount();
do {
hasNext= pGenerateAndLoad->hasNextCustomerTaxrate();
for(int i=0; i<taxrates; i++) {
PCUSTOMER_TAXRATE_ROW record = pGenerateAndLoad->getCustomerTaxrateRow(i);
customerTaxrateBuffer.append(record);
}
} while((hasNext && customerTaxrateBuffer.hasSpace()));
customerTaxrateBuffer.setMoreToRead(hasNext);
int rows=customerTaxrateBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_TAXRATE_ROW record = customerTaxrateBuffer.get(i);
customer_taxrate::key k;
customer_taxrate::value v;
k.cx_c_id = record->CX_C_ID;
k.cx_tx_id = string(record->CX_TX_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customer_taxrate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomerTaxrate();
customerTaxrateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_wl_and_wi_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_wl_and_wi_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitWatchListAndWatchItem();
while(watchListBuffer.hasMoreToRead()){
watchItemBuffer.reset();
watchListBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextWatchList();
PWATCH_LIST_ROW record = pGenerateAndLoad->getWatchListRow();
watchListBuffer.append(record);
int items = pGenerateAndLoad->ItemsPerWatchList();
for(int i=0; i<items; i++) {
PWATCH_ITEM_ROW row = pGenerateAndLoad->getWatchItemRow(i);
watchItemBuffer.append(row);
}
} while(hasNext && watchListBuffer.hasSpace());
watchListBuffer.setMoreToRead(hasNext);
int rows=watchListBuffer.getSize();
for(int i=0; i<rows; i++){
PWATCH_LIST_ROW record = watchListBuffer.get(i);
watch_list::key k;
watch_list::value v;
k.wl_c_id = record->WL_C_ID;
k.wl_id = record->WL_ID;
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_watch_list(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=watchItemBuffer.getSize();
for(int i=0; i<rows; i++){
PWATCH_ITEM_ROW record = watchItemBuffer.get(i);
watch_item::key k;
watch_item::value v;
k.wi_wl_id = record->WI_WL_ID;
k.wi_s_symb = record->WI_S_SYMB;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_watch_item(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseWatchListAndWatchItem();
watchItemBuffer.release();
watchListBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_company_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_company_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCompany();
while(companyBuffer.hasMoreToRead()){
companyBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCompany();
PCOMPANY_ROW record = pGenerateAndLoad->getCompanyRow();
companyBuffer.append(record);
} while((hasNext && companyBuffer.hasSpace()));
companyBuffer.setMoreToRead(hasNext);
int rows=companyBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMPANY_ROW record = companyBuffer.get(i);
company::key k;
company::value v;
co_name_index::key k_idx1;
co_name_index::value v_idx1;
co_in_id_index::key k_idx2;
co_in_id_index::value v_idx2;
k.co_id = record->CO_ID;
v.co_st_id = string(record->CO_ST_ID);
v.co_name = string(record->CO_NAME);
v.co_in_id = string(record->CO_IN_ID);
v.co_sp_rate = string(record->CO_SP_RATE);
v.co_ceo = string(record->CO_CEO);
v.co_ad_id = record->CO_AD_ID;
v.co_open_date = record->CO_OPEN_DATE.GetDate();
k_idx1.co_name = string(record->CO_NAME);
k_idx1.co_id = record->CO_ID;
k_idx2.co_in_id = string(record->CO_IN_ID);
k_idx2.co_id = record->CO_ID;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_company(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_co_name_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(tbl_co_in_id_index(1)->insert(txn, Encode(str(sizeof(k_idx2)), k_idx2), Encode(str(sizeof(v_idx2)), v_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCompany();
companyBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_company_competitor_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_company_competitor_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCompanyCompetitor();
while(companyCompetitorBuffer.hasMoreToRead()){
companyCompetitorBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCompanyCompetitor();
PCOMPANY_COMPETITOR_ROW record = pGenerateAndLoad->getCompanyCompetitorRow();
companyCompetitorBuffer.append(record);
} while((hasNext && companyCompetitorBuffer.hasSpace()));
companyCompetitorBuffer.setMoreToRead(hasNext);
int rows=companyCompetitorBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMPANY_COMPETITOR_ROW record = companyCompetitorBuffer.get(i);
company_competitor::key k;
company_competitor::value v;
k.cp_co_id = record->CP_CO_ID;
k.cp_comp_co_id = record->CP_COMP_CO_ID;
k.cp_in_id = string(record->CP_IN_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_company_competitor(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCompanyCompetitor();
companyCompetitorBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_daily_market_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_daily_market_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitDailyMarket();
while(dailyMarketBuffer.hasMoreToRead()){
dailyMarketBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextDailyMarket();
PDAILY_MARKET_ROW record = pGenerateAndLoad->getDailyMarketRow();
dailyMarketBuffer.append(record);
} while((hasNext && dailyMarketBuffer.hasSpace()));
dailyMarketBuffer.setMoreToRead(hasNext);
int rows=dailyMarketBuffer.getSize();
for(int i=0; i<rows; i++){
PDAILY_MARKET_ROW record = dailyMarketBuffer.get(i);
daily_market::key k;
daily_market::value v;
k.dm_s_symb = string(record->DM_S_SYMB);
k.dm_date = record->DM_DATE.GetDate();
v.dm_close = record->DM_CLOSE;
v.dm_high = record->DM_HIGH;
v.dm_low = record->DM_HIGH;
v.dm_vol = record->DM_VOL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_daily_market(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseDailyMarket();
dailyMarketBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_financial_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_financial_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitFinancial();
while(financialBuffer.hasMoreToRead()){
financialBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextFinancial();
PFINANCIAL_ROW record = pGenerateAndLoad->getFinancialRow();
financialBuffer.append(record);
} while((hasNext && financialBuffer.hasSpace()));
financialBuffer.setMoreToRead(hasNext);
int rows=financialBuffer.getSize();
for(int i=0; i<rows; i++){
PFINANCIAL_ROW record = financialBuffer.get(i);
financial::key k;
financial::value v;
k.fi_co_id = record->FI_CO_ID;
k.fi_year = record->FI_YEAR;
k.fi_qtr = record->FI_QTR;
v.fi_qtr_start_date = record->FI_QTR_START_DATE.GetDate();
v.fi_revenue = record->FI_REVENUE;
v.fi_net_earn = record->FI_NET_EARN;
v.fi_basic_eps = record->FI_BASIC_EPS;
v.fi_dilut_eps = record->FI_DILUT_EPS;
v.fi_margin = record->FI_MARGIN;
v.fi_inventory = record->FI_INVENTORY;
v.fi_assets = record->FI_ASSETS;
v.fi_liability = record->FI_LIABILITY;
v.fi_out_basic = record->FI_OUT_BASIC;
v.fi_out_dilut = record->FI_OUT_DILUT;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_financial(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseFinancial();
dailyMarketBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_last_trade_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_last_trade_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitLastTrade();
while(lastTradeBuffer.hasMoreToRead()){
lastTradeBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextLastTrade();
PLAST_TRADE_ROW record = pGenerateAndLoad->getLastTradeRow();
lastTradeBuffer.append(record);
} while((hasNext && lastTradeBuffer.hasSpace()));
lastTradeBuffer.setMoreToRead(hasNext);
int rows=lastTradeBuffer.getSize();
for(int i=0; i<rows; i++){
PLAST_TRADE_ROW record = lastTradeBuffer.get(i);
last_trade::key k;
last_trade::value v;
k.lt_s_symb = string( record->LT_S_SYMB );
v.lt_dts = record->LT_DTS.GetDate();
v.lt_price = record->LT_PRICE;
v.lt_open_price = record->LT_OPEN_PRICE;
v.lt_vol = record->LT_VOL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_last_trade(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseLastTrade();
lastTradeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_ni_and_nx_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_ni_and_nx_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitNewsItemAndNewsXRef();
while(newsItemBuffer.hasMoreToRead()){
newsItemBuffer.reset();
newsXRefBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextNewsItemAndNewsXRef();
PNEWS_ITEM_ROW record1 = pGenerateAndLoad->getNewsItemRow();
PNEWS_XREF_ROW record2 = pGenerateAndLoad->getNewsXRefRow();
newsItemBuffer.append(record1);
newsXRefBuffer.append(record2);
} while((hasNext && newsItemBuffer.hasSpace()));
newsItemBuffer.setMoreToRead(hasNext);
newsXRefBuffer.setMoreToRead(hasNext);
int rows=newsXRefBuffer.getSize();
for(int i=0; i<rows; i++){
PNEWS_XREF_ROW record = newsXRefBuffer.get(i);
news_xref::key k;
news_xref::value v;
k.nx_co_id = record->NX_CO_ID;
k.nx_ni_id = record->NX_NI_ID;
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_news_xref(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=newsItemBuffer.getSize();
for(int i=0; i<rows; i++){
PNEWS_ITEM_ROW record = newsItemBuffer.get(i);
news_item::key k;
news_item::value v;
k.ni_id = record->NI_ID;
v.ni_headline = string(record->NI_HEADLINE);
v.ni_summary = string(record->NI_SUMMARY);
v.ni_item = string(record->NI_ITEM);
v.ni_dts = record->NI_DTS.GetDate();
v.ni_source = string(record->NI_SOURCE);
v.ni_author = string(record->NI_AUTHOR);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_news_item(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseNewsItemAndNewsXRef();
newsItemBuffer.release();
newsXRefBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_security_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_security_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitSecurity();
while(securityBuffer.hasMoreToRead()){
securityBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextSecurity();
PSECURITY_ROW record = pGenerateAndLoad->getSecurityRow();
securityBuffer.append(record);
} while((hasNext && securityBuffer.hasSpace()));
securityBuffer.setMoreToRead(hasNext);
int rows=securityBuffer.getSize();
for(int i=0; i<rows; i++){
PSECURITY_ROW record = securityBuffer.get(i);
security::key k;
security::value v;
security_index::key k_idx;
security_index::value v_idx;
k.s_symb = string(record->S_SYMB);
v.s_issue = string(record->S_ISSUE);
v.s_st_id = string(record->S_ST_ID);
v.s_name = string(record->S_NAME);
v.s_ex_id = string(record->S_EX_ID);
v.s_co_id = record->S_CO_ID;
v.s_num_out = record->S_NUM_OUT;
v.s_start_date = record->S_START_DATE.GetDate();
v.s_exch_date = record->S_EXCH_DATE.GetDate();
v.s_pe = record->S_PE;
v.s_52wk_high = record->S_52WK_HIGH;
v.s_52wk_high_date= record->S_52WK_HIGH_DATE.GetDate();
v.s_52wk_low = record->S_52WK_LOW;
v.s_52wk_low_date = record->S_52WK_LOW_DATE.GetDate();
v.s_dividend = record->S_DIVIDEND;
v.s_yield = record->S_YIELD;
k_idx.s_co_id = record->S_CO_ID;
k_idx.s_issue = string(record->S_ISSUE);
k_idx.s_symb = string(record->S_SYMB);
v_idx.s_name = string(record->S_NAME);
v_idx.s_ex_id = string(record->S_EX_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_security(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_security_index(1)->insert(txn, Encode(str(sizeof(k_idx)), k_idx), Encode(str(sizeof(v_idx)), v_idx)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseSecurity();
securityBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_growing_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_growing_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitHoldingAndTrade();
do {
populate_unit_trade();
populate_broker();
populate_holding_summary();
populate_holding();
tradeBuffer.newLoadUnit();
tradeHistoryBuffer.newLoadUnit();
settlementBuffer.newLoadUnit();
cashTransactionBuffer.newLoadUnit();
holdingHistoryBuffer.newLoadUnit();
brokerBuffer.newLoadUnit();
holdingSummaryBuffer.newLoadUnit();
holdingBuffer.newLoadUnit();
} while(pGenerateAndLoad->hasNextLoadUnit());
pGenerateAndLoad->ReleaseHoldingAndTrade();
tradeBuffer.release();
tradeHistoryBuffer.release();
settlementBuffer.release();
cashTransactionBuffer.release();
holdingHistoryBuffer.release();
brokerBuffer.release();
holdingSummaryBuffer.release();
holdingBuffer.release();
}
private:
void populate_unit_trade()
{
while(tradeBuffer.hasMoreToRead()){
tradeBuffer.reset();
tradeHistoryBuffer.reset();
settlementBuffer.reset();
cashTransactionBuffer.reset();
holdingHistoryBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextTrade();
PTRADE_ROW row = pGenerateAndLoad->getTradeRow();
tradeBuffer.append(row);
int hist = pGenerateAndLoad->getTradeHistoryRowCount();
for(int i=0; i<hist; i++) {
PTRADE_HISTORY_ROW record = pGenerateAndLoad->getTradeHistoryRow(i);
tradeHistoryBuffer.append(record);
}
if(pGenerateAndLoad->shouldProcessSettlementRow()) {
PSETTLEMENT_ROW record = pGenerateAndLoad->getSettlementRow();
settlementBuffer.append(record);
}
if(pGenerateAndLoad->shouldProcessCashTransactionRow()) {
PCASH_TRANSACTION_ROW record=pGenerateAndLoad->getCashTransactionRow();
cashTransactionBuffer.append(record);
}
hist = pGenerateAndLoad->getHoldingHistoryRowCount();
for(int i=0; i<hist; i++) {
PHOLDING_HISTORY_ROW record=pGenerateAndLoad->getHoldingHistoryRow(i);
holdingHistoryBuffer.append(record);
}
} while((hasNext && tradeBuffer.hasSpace()));
tradeBuffer.setMoreToRead(hasNext);
int rows=tradeBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_ROW record = tradeBuffer.get(i);
trade::key k;
trade::value v;
k.t_id = record->T_ID ;
if( likely( record->T_ID > lastTradeId ) )
lastTradeId = record->T_ID ;
v.t_dts = record->T_DTS.GetDate();
v.t_st_id = string(record->T_ST_ID) ;
v.t_tt_id = string(record->T_TT_ID) ;
v.t_is_cash = record->T_IS_CASH ;
v.t_s_symb = string(record->T_S_SYMB);
v.t_qty = record->T_QTY ;
v.t_bid_price = record->T_BID_PRICE ;
v.t_ca_id = record->T_CA_ID ;
v.t_exec_name = string(record->T_EXEC_NAME);
v.t_trade_price = record->T_TRADE_PRICE ;
v.t_chrg = record->T_CHRG ;
v.t_comm = record->T_COMM ;
v.t_tax = record->T_TAX ;
v.t_lifo = record->T_LIFO ;
t_ca_id_index::key k_idx1;
t_ca_id_index::value v_idx1;
k_idx1.t_ca_id = record->T_CA_ID ;
k_idx1.t_dts = record->T_DTS.GetDate();
k_idx1.t_id = record->T_ID ;
v_idx1.t_st_id = string(record->T_ST_ID) ;
v_idx1.t_tt_id = string(record->T_TT_ID) ;
v_idx1.t_is_cash = record->T_IS_CASH ;
v_idx1.t_s_symb = string(record->T_S_SYMB);
v_idx1.t_qty = record->T_QTY ;
v_idx1.t_bid_price = record->T_BID_PRICE ;
v_idx1.t_exec_name = string(record->T_EXEC_NAME);
v_idx1.t_trade_price = record->T_TRADE_PRICE ;
v_idx1.t_chrg = record->T_CHRG ;
t_s_symb_index::key k_idx2;
t_s_symb_index::value v_idx2;
k_idx2.t_s_symb = string(record->T_S_SYMB);
k_idx2.t_dts = record->T_DTS.GetDate();
k_idx2.t_id = record->T_ID ;
v_idx2.t_ca_id = record->T_CA_ID ;
v_idx2.t_st_id = string(record->T_ST_ID) ;
v_idx2.t_tt_id = string(record->T_TT_ID) ;
v_idx2.t_is_cash = record->T_IS_CASH ;
v_idx2.t_qty = record->T_QTY ;
v_idx2.t_exec_name = string(record->T_EXEC_NAME);
v_idx2.t_trade_price = record->T_TRADE_PRICE ;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_t_ca_id_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(tbl_t_s_symb_index(1)->insert(txn, Encode(str(sizeof(k_idx2)), k_idx2), Encode(str(sizeof(v_idx2)), v_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=tradeHistoryBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_HISTORY_ROW record = tradeHistoryBuffer.get(i);
trade_history::key k;
trade_history::value v;
k.th_t_id = record->TH_T_ID;
k.th_dts = record->TH_DTS.GetDate();
k.th_st_id = string( record->TH_ST_ID );
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade_history(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=settlementBuffer.getSize();
for(int i=0; i<rows; i++){
PSETTLEMENT_ROW record = settlementBuffer.get(i);
settlement::key k;
settlement::value v;
k.se_t_id = record->SE_T_ID;
v.se_cash_type = string(record->SE_CASH_TYPE);
v.se_cash_due_date = record->SE_CASH_DUE_DATE.GetDate();
v.se_amt = record->SE_AMT;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_settlement(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=cashTransactionBuffer.getSize();
for(int i=0; i<rows; i++){
PCASH_TRANSACTION_ROW record = cashTransactionBuffer.get(i);
cash_transaction::key k;
cash_transaction::value v;
k.ct_t_id = record->CT_T_ID;
v.ct_dts = record->CT_DTS.GetDate();
v.ct_amt = record->CT_AMT;
v.ct_name = string(record->CT_NAME);
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_cash_transaction(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=holdingHistoryBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_HISTORY_ROW record = holdingHistoryBuffer.get(i);
holding_history::key k;
holding_history::value v;
k.hh_t_id = record->HH_T_ID;
k.hh_h_t_id = record->HH_H_T_ID;
v.hh_before_qty = record->HH_BEFORE_QTY;
v.hh_after_qty = record->HH_AFTER_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding_history(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_broker()
{
while(brokerBuffer.hasMoreToRead()) {
brokerBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextBroker();
PBROKER_ROW record = pGenerateAndLoad->getBrokerRow();
brokerBuffer.append(record);
} while((hasNext && brokerBuffer.hasSpace()));
brokerBuffer.setMoreToRead(hasNext);
int rows=brokerBuffer.getSize();
for(int i=0; i<rows; i++){
PBROKER_ROW record = brokerBuffer.get(i);
broker::key k;
broker::value v;
b_name_index::key k_idx;
b_name_index::value v_idx;
k.b_id = record->B_ID;
v.b_st_id = string(record->B_ST_ID);
v.b_name = string(record->B_NAME);
v.b_num_trades = record->B_NUM_TRADES;
v.b_comm_total = record->B_COMM_TOTAL;
k_idx.b_name = string(record->B_NAME );
k_idx.b_id = record->B_ID;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_broker(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_b_name_index(1)->insert(txn, Encode(str(sizeof(k_idx)), k_idx), Encode(str(sizeof(v_idx)), v_idx)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_holding_summary()
{
while(holdingSummaryBuffer.hasMoreToRead()){
holdingSummaryBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextHoldingSummary();
PHOLDING_SUMMARY_ROW record = pGenerateAndLoad->getHoldingSummaryRow();
holdingSummaryBuffer.append(record);
} while((hasNext && holdingSummaryBuffer.hasSpace()));
holdingSummaryBuffer.setMoreToRead(hasNext);
int rows=holdingSummaryBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_SUMMARY_ROW record = holdingSummaryBuffer.get(i);
holding_summary::key k;
holding_summary::value v;
k.hs_ca_id = record->HS_CA_ID;
k.hs_s_symb = string(record->HS_S_SYMB);
v.hs_qty = record->HS_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding_summary(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_holding()
{
while(holdingBuffer.hasMoreToRead()){
holdingBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextHolding();
PHOLDING_ROW record = pGenerateAndLoad->getHoldingRow();
holdingBuffer.append(record);
} while((hasNext && holdingBuffer.hasSpace()));
holdingBuffer.setMoreToRead(hasNext);
int rows=holdingBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_ROW record = holdingBuffer.get(i);
holding::key k;
holding::value v;
k.h_ca_id = record->H_CA_ID;
k.h_s_symb = string(record->H_S_SYMB);
k.h_dts = record->H_DTS.GetDate();
k.h_t_id = record->H_T_ID;
v.h_price = record->H_PRICE;
v.h_qty = record->H_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
private:
ssize_t partition_id;
};
class tpce_bench_runner : public bench_runner {
private:
static bool
IsTableReadOnly(const char *name)
{
// TODO.
return false;
}
static bool
IsTableAppendOnly(const char *name)
{
// TODO.
return true;
}
static vector<abstract_ordered_index *>
OpenTablesForTablespace(abstract_db *db, const char *name, size_t expected_size)
{
const string s_name(name);
vector<abstract_ordered_index *> ret(NumPartitions());
abstract_ordered_index *idx = db->open_index(s_name, expected_size, false );
for (size_t i = 0; i < NumPartitions(); i++)
ret[i] = idx;
return ret;
}
public:
tpce_bench_runner(abstract_db *db)
: bench_runner(db)
{
#define OPEN_TABLESPACE_X(x) \
partitions[#x] = OpenTablesForTablespace(db, #x, sizeof(x));
TPCE_TABLE_LIST(OPEN_TABLESPACE_X);
#undef OPEN_TABLESPACE_X
for (auto &t : partitions) {
auto v = unique_filter(t.second);
for (size_t i = 0; i < v.size(); i++)
open_tables[t.first + "_" + to_string(i)] = v[i];
}
}
protected:
virtual vector<bench_loader *>
make_loaders()
{
vector<bench_loader *> ret;
// FIXME. what seed values should be passed?
ret.push_back(new tpce_charge_loader(235443, db, open_tables, partitions, -1));
ret.push_back(new tpce_commission_rate_loader(89785943, db, open_tables, partitions, -1));
ret.push_back(new tpce_exchange_loader(129856349, db, open_tables, partitions, -1));
ret.push_back(new tpce_industry_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_sector_loader(2343352, db, open_tables, partitions, -1));
ret.push_back(new tpce_status_type_loader(235443, db, open_tables, partitions, -1));
ret.push_back(new tpce_tax_rate_loader(89785943, db, open_tables, partitions, -1));
ret.push_back(new tpce_trade_type_loader(129856349, db, open_tables, partitions, -1));
ret.push_back(new tpce_zip_code_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_address_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_customer_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_ca_and_ap_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_customer_taxrate_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_wl_and_wi_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_company_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_company_competitor_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_daily_market_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_financial_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_last_trade_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_ni_and_nx_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_security_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_growing_loader(923587856425, db, open_tables, partitions, -1));
return ret;
}
virtual vector<bench_worker *>
make_workers()
{
const unsigned alignment = coreid::num_cpus_online();
const int blockstart =
coreid::allocate_contiguous_aligned_block(nthreads, alignment);
ALWAYS_ASSERT(blockstart >= 0);
ALWAYS_ASSERT((blockstart % alignment) == 0);
fast_random r(23984543);
vector<bench_worker *> ret;
static bool const NO_PIN_WH = false;
if (NO_PIN_WH) {
for (size_t i = 0; i < nthreads; i++)
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b,
1, NumPartitions() + 1));
}
else if (NumPartitions() <= nthreads) {
for (size_t i = 0; i < nthreads; i++)
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b,
(i % NumPartitions()) + 1, (i % NumPartitions()) + 2));
} else {
auto N = NumPartitions();
auto T = nthreads;
// try this in python: [i*N//T for i in range(T+1)]
for (size_t i = 0; i < nthreads; i++) {
const unsigned wstart = i*N/T;
const unsigned wend = (i + 1)*N/T;
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b, wstart+1, wend+1));
}
}
return ret;
}
private:
map<string, vector<abstract_ordered_index *>> partitions;
};
// Benchmark entry function
void tpce_do_test(abstract_db *db, int argc, char **argv)
{
int customers = 0;
int working_days = 0;
int scaling_factor_tpce = scale_factor;
char* egen_dir = NULL;
char sfe_str[8], wd_str[8], cust_str[8];
memset(sfe_str,0,8);
memset(wd_str,0,8);
memset(cust_str,0,8);
sprintf(sfe_str, "%d",scaling_factor_tpce);
// parse options
optind = 1;
while (1) {
static struct option long_options[] =
{
{"workload-mix" , required_argument , 0 , 'w'} ,
{"egen-dir" , required_argument , 0 , 'e'} ,
{"customers" , required_argument , 0 , 'c'} ,
{"working-days" , required_argument , 0 , 'd'} ,
{"query-range" , required_argument , 0 , 'r'} ,
{0, 0, 0, 0}
};
int option_index = 0;
int c = getopt_long(argc, argv, "r:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
if (long_options[option_index].flag != 0)
break;
abort();
break;
case 'r':
long_query_scan_range = atoi( optarg );
ALWAYS_ASSERT( long_query_scan_range >= 0 or long_query_scan_range <= 100 );
break;
case 'c':
strncpy( cust_str, optarg, 8 );
customers = atoi(cust_str );
break;
case 'd':
strncpy( wd_str, optarg, 8 );
working_days = atoi(wd_str );
break;
case 'e':
egen_dir = optarg;
break;
case 'w':
{
const vector<string> toks = split(optarg, ',');
ALWAYS_ASSERT(toks.size() == ARRAY_NELEMS(g_txn_workload_mix));
double s = 0;
for (size_t i = 0; i < toks.size(); i++) {
double p = atof(toks[i].c_str());
ALWAYS_ASSERT(p >= 0.0 && p <= 100.0);
s += p;
g_txn_workload_mix[i] = p;
}
ALWAYS_ASSERT(s == 100.0);
}
break;
case '?':
/* getopt_long already printed an error message. */
exit(1);
default:
abort();
}
}
const char * params[] = {"to_skip", "-i", egen_dir, "-l", "NULL", "-f", sfe_str, "-w", wd_str, "-c", cust_str, "-t", cust_str };
egen_init(13, (char **)params);
//Initialize Client Transaction Input generator
m_TxnInputGenerator = transactions_input_init(customers, scaling_factor_tpce , working_days);
unsigned int seed = AutoRand();
setRNGSeeds(m_TxnInputGenerator, seed);
m_CDM = data_maintenance_init(customers, scaling_factor_tpce, working_days);
//Initialize Market side
for( unsigned int i = 0; i < nthreads; i++ )
{
auto mf_buf= new MFBuffer();
auto tr_buf= new TRBuffer();
MarketFeedInputBuffers.emplace_back( mf_buf );
TradeResultInputBuffers.emplace_back( tr_buf );
auto meesut = new CMEESUT();
meesut->setMFQueue(mf_buf);
meesut->setTRQueue(tr_buf);
auto mee = market_init( working_days*8, meesut, AutoRand());
mees.emplace_back( mee );
}
if (verbose) {
cerr << "tpce settings:" << endl;
cerr << " workload_mix : " <<
format_list(g_txn_workload_mix,
g_txn_workload_mix + ARRAY_NELEMS(g_txn_workload_mix)) << endl;
cerr << " scale factor :" << " " << sfe_str << endl;
cerr << " working days :" << " " << wd_str << endl;
cerr << " customers :" << " " << cust_str << endl;
cerr << " long query scan range :" << " " << long_query_scan_range << "%" << endl;
}
tpce_bench_runner r(db);
r.run();
}
TPC-E: fix security-detail.
#include <sys/time.h>
#include <string>
#include <ctype.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <vector>
#include "../txn.h"
#include "../macros.h"
#include "../scopedperf.hh"
#include "../spinlock.h"
#include "bench.h"
#include "tpce.h"
using namespace std;
using namespace util;
using namespace TPCE;
// TPC-E workload mix
int64_t lastTradeId;
int64_t last_list = 0;
int64_t min_ca_id = numeric_limits<int64_t>::max();
int64_t max_ca_id = 0;
static double g_txn_workload_mix[] = {4.9,13,1,18,14,8,10.1,10,19,2,0};
int64_t long_query_scan_range=20;
// Egen
int egen_init(int argc, char* argv[]);
void egen_release();
CCETxnInputGenerator* transactions_input_init(int customers, int sf, int wdays);
CDM* data_maintenance_init(int customers, int sf, int wdays);
CMEE* market_init(INT32 TradingTimeSoFar, CMEESUTInterface *pSUT, UINT32 UniqueId);
extern CGenerateAndLoad* pGenerateAndLoad;
CCETxnInputGenerator* m_TxnInputGenerator;
CDM* m_CDM;
//CMEESUT* meesut;
vector<CMEE*> mees;
vector<MFBuffer*> MarketFeedInputBuffers;
vector<TRBuffer*> TradeResultInputBuffers;
//Buffers
const int loadUnit = 1000;
AccountPermissionBuffer accountPermissionBuffer (3015);
CustomerBuffer customerBuffer (1005);
CustomerAccountBuffer customerAccountBuffer (1005);
CustomerTaxrateBuffer customerTaxrateBuffer (2010);
HoldingBuffer holdingBuffer(10000);
HoldingHistoryBuffer holdingHistoryBuffer(2*loadUnit);
HoldingSummaryBuffer holdingSummaryBuffer(6000);
WatchItemBuffer watchItemBuffer (iMaxItemsInWL*1020+5000);
WatchListBuffer watchListBuffer (1020);
BrokerBuffer brokerBuffer(100);
CashTransactionBuffer cashTransactionBuffer(loadUnit);
ChargeBuffer chargeBuffer(20);
CommissionRateBuffer commissionRateBuffer (245);
SettlementBuffer settlementBuffer(loadUnit);
TradeBuffer tradeBuffer(loadUnit);
TradeHistoryBuffer tradeHistoryBuffer(3*loadUnit);
TradeTypeBuffer tradeTypeBuffer (10);
CompanyBuffer companyBuffer (1000);
CompanyCompetitorBuffer companyCompetitorBuffer(3000);
DailyMarketBuffer dailyMarketBuffer(3000);
ExchangeBuffer exchangeBuffer(9);
FinancialBuffer financialBuffer (1500);
IndustryBuffer industryBuffer(107);
LastTradeBuffer lastTradeBuffer (1005);
NewsItemBuffer newsItemBuffer(200);
NewsXRefBuffer newsXRefBuffer(200);//big
SectorBuffer sectorBuffer(17);
SecurityBuffer securityBuffer(1005);
AddressBuffer addressBuffer(1005);
StatusTypeBuffer statusTypeBuffer (10);
TaxrateBuffer taxrateBuffer (325);
ZipCodeBuffer zipCodeBuffer (14850);
// Utils
class table_scanner: public abstract_ordered_index::scan_callback {
public:
table_scanner( str_arena* arena) : _arena(arena) {}
virtual bool invoke( const char *keyp, size_t keylen, const varstr &value)
{
varstr * const k = _arena->next(keylen);
INVARIANT(k);
k->copy_from(keyp, keylen);
output.emplace_back(k, &value);
return true;
}
std::vector<std::pair<varstr *, const varstr *>> output;
str_arena* _arena;
};
int64_t GetLastListID()
{
//TODO. decentralize, thread ID + local counter and TLS
auto ret = __sync_add_and_fetch(&last_list,1);
ALWAYS_ASSERT( ret );
return ret;
}
int64_t GetLastTradeID()
{
//TODO. decentralize, thread ID + local counter and TLS
auto ret = __sync_add_and_fetch(&lastTradeId,1);
ALWAYS_ASSERT( ret );
return ret;
}
static inline ALWAYS_INLINE size_t NumPartitions()
{
return (size_t) scale_factor;
}
void setRNGSeeds(CCETxnInputGenerator* gen, unsigned int UniqueId )
{
CDateTime Now;
INT32 BaseYear;
INT32 Tmp1, Tmp2;
Now.GetYMD( &BaseYear, &Tmp1, &Tmp2 );
// Set the base year to be the most recent year that was a multiple of 5.
BaseYear -= ( BaseYear % 5 );
CDateTime Base( BaseYear, 1, 1 ); // January 1st in the BaseYear
// Initialize the seed with the current time of day measured in 1/10's of a second.
// This will use up to 20 bits.
RNGSEED Seed;
Seed = Now.MSec() / 100;
// Now add in the number of days since the base time.
// The number of days in the 5 year period requires 11 bits.
// So shift up by that much to make room in the "lower" bits.
Seed <<= 11;
Seed += (RNGSEED)((INT64)Now.DayNo() - (INT64)Base.DayNo());
// So far, we've used up 31 bits.
// Save the "last" bit of the "upper" 32 for the RNG id.
// In addition, make room for the caller's 32-bit unique id.
// So shift a total of 33 bits.
Seed <<= 33;
// Now the "upper" 32-bits have been set with a value for RNG 0.
// Add in the sponsor's unique id for the "lower" 32-bits.
// Seed += UniqueId;
Seed += UniqueId;
// Set the TxnMixGenerator RNG to the unique seed.
gen->SetRNGSeed( Seed );
// m_DriverCESettings.cur.TxnMixRNGSeed = Seed;
// Set the RNG Id to 1 for the TxnInputGenerator.
Seed |= UINT64_CONST(0x0000000100000000);
gen->SetRNGSeed( Seed );
// m_DriverCESettings.cur.TxnInputRNGSeed = Seed;
}
unsigned int AutoRand()
{
struct timeval tv;
struct tm ltr;
gettimeofday(&tv, NULL);
struct tm* lt = localtime_r(&tv.tv_sec, <r);
return (((lt->tm_hour * MinutesPerHour + lt->tm_min) * SecondsPerMinute +
lt->tm_sec) * MsPerSecond + tv.tv_usec / 1000);
}
struct _dummy {}; // exists so we can inherit from it, so we can use a macro in
// an init list...
class tpce_worker_mixin : private _dummy {
#define DEFN_TBL_INIT_X(name) \
, tbl_ ## name ## _vec(partitions.at(#name))
public:
tpce_worker_mixin(const map<string, vector<abstract_ordered_index *>> &partitions) :
_dummy() // so hacky...
TPCE_TABLE_LIST(DEFN_TBL_INIT_X)
{
}
#undef DEFN_TBL_INIT_X
protected:
#define DEFN_TBL_ACCESSOR_X(name) \
private: \
vector<abstract_ordered_index *> tbl_ ## name ## _vec; \
protected: \
inline ALWAYS_INLINE abstract_ordered_index * \
tbl_ ## name (unsigned int pid) \
{ \
return tbl_ ## name ## _vec[pid - 1]; \
}
TPCE_TABLE_LIST(DEFN_TBL_ACCESSOR_X)
#undef DEFN_TBL_ACCESSOR_X
// only TPCE loaders need to call this- workers are automatically
// pinned by their worker id (which corresponds to partition id
// in TPCE)
//
// pins the *calling* thread
static void
PinToPartition(unsigned int pid)
{
}
public:
static inline uint32_t
GetCurrentTimeMillis()
{
//struct timeval tv;
//ALWAYS_ASSERT(gettimeofday(&tv, 0) == 0);
//return tv.tv_sec * 1000;
// XXX(stephentu): implement a scalable GetCurrentTimeMillis()
// for now, we just give each core an increasing number
static __thread uint32_t tl_hack = 0;
return tl_hack++;
}
// utils for generating random #s and strings
static inline ALWAYS_INLINE int
CheckBetweenInclusive(int v, int lower, int upper)
{
INVARIANT(v >= lower);
INVARIANT(v <= upper);
return v;
}
static inline ALWAYS_INLINE int
RandomNumber(fast_random &r, int min, int max)
{
return CheckBetweenInclusive((int) (r.next_uniform() * (max - min + 1) + min), min, max);
}
static inline ALWAYS_INLINE int
NonUniformRandom(fast_random &r, int A, int C, int min, int max)
{
return (((RandomNumber(r, 0, A) | RandomNumber(r, min, max)) + C) % (max - min + 1)) + min;
}
// following oltpbench, we really generate strings of len - 1...
static inline string
RandomStr(fast_random &r, uint len)
{
// this is a property of the oltpbench implementation...
if (!len)
return "";
uint i = 0;
string buf(len - 1, 0);
while (i < (len - 1)) {
const char c = (char) r.next_char();
// XXX(stephentu): oltpbench uses java's Character.isLetter(), which
// is a less restrictive filter than isalnum()
if (!isalnum(c))
continue;
buf[i++] = c;
}
return buf;
}
// RandomNStr() actually produces a string of length len
static inline string
RandomNStr(fast_random &r, uint len)
{
const char base = '0';
string buf(len, 0);
for (uint i = 0; i < len; i++)
buf[i] = (char)(base + (r.next() % 10));
return buf;
}
};
// TPCE workers implement TxnHarness interfaces
class tpce_worker :
public bench_worker,
public tpce_worker_mixin,
public CBrokerVolumeDBInterface,
public CCustomerPositionDBInterface,
public CMarketFeedDBInterface,
public CMarketWatchDBInterface,
public CSecurityDetailDBInterface,
public CTradeLookupDBInterface,
public CTradeOrderDBInterface,
public CTradeResultDBInterface,
public CTradeStatusDBInterface,
public CTradeUpdateDBInterface,
public CDataMaintenanceDBInterface,
public CTradeCleanupDBInterface,
public CSendToMarketInterface
{
public:
// resp for [partition_id_start, partition_id_end)
tpce_worker(unsigned int worker_id,
unsigned long seed, abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
spin_barrier *barrier_a, spin_barrier *barrier_b,
uint partition_id_start, uint partition_id_end)
: bench_worker(worker_id, true, seed, db,
open_tables, barrier_a, barrier_b),
tpce_worker_mixin(partitions),
partition_id_start(partition_id_start),
partition_id_end(partition_id_end)
{
INVARIANT(partition_id_start >= 1);
INVARIANT(partition_id_start <= NumPartitions());
INVARIANT(partition_id_end > partition_id_start);
INVARIANT(partition_id_end <= (NumPartitions() + 1));
if (verbose) {
cerr << "tpce: worker id " << worker_id
<< " => partitions [" << partition_id_start
<< ", " << partition_id_end << ")"
<< endl;
}
const unsigned base = coreid::num_cpus_online();
mee = mees[worker_id - base ];
MarketFeedInputBuffer = MarketFeedInputBuffers[worker_id - base ];
TradeResultInputBuffer = TradeResultInputBuffers[worker_id - base ];
ALWAYS_ASSERT( TradeResultInputBuffer and MarketFeedInputBuffer and mee );
}
// Market Interface
bool SendToMarket(TTradeRequest &trade_mes)
{
mee->SubmitTradeRequest(&trade_mes);
return true;
}
// BrokerVolume transaction
static bench_worker::txn_result BrokerVolume(bench_worker *w)
{
ANON_REGION("BrokerVolume:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->broker_volume();
}
bench_worker::txn_result broker_volume()
{
scoped_str_arena s_arena(arena);
TBrokerVolumeTxnInput input;
TBrokerVolumeTxnOutput output;
m_TxnInputGenerator->GenerateBrokerVolumeInput(input);
CBrokerVolume* harness= new CBrokerVolume(this);
auto ret = harness->DoTxn( (PBrokerVolumeTxnInput)&input, (PBrokerVolumeTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoBrokerVolumeFrame1(const TBrokerVolumeFrame1Input *pIn, TBrokerVolumeFrame1Output *pOut);
// CustomerPosition transaction
static bench_worker::txn_result CustomerPosition(bench_worker *w)
{
ANON_REGION("CustomerPosition:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->customer_position();
}
bench_worker::txn_result customer_position()
{
scoped_str_arena s_arena(arena);
TCustomerPositionTxnInput input;
TCustomerPositionTxnOutput output;
m_TxnInputGenerator->GenerateCustomerPositionInput(input);
CCustomerPosition* harness= new CCustomerPosition(this);
auto ret = harness->DoTxn( (PCustomerPositionTxnInput)&input, (PCustomerPositionTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoCustomerPositionFrame1(const TCustomerPositionFrame1Input *pIn, TCustomerPositionFrame1Output *pOut);
bench_worker::txn_result DoCustomerPositionFrame2(const TCustomerPositionFrame2Input *pIn, TCustomerPositionFrame2Output *pOut);
bench_worker::txn_result DoCustomerPositionFrame3(void );
// MarketFeed transaction
static bench_worker::txn_result MarketFeed(bench_worker *w)
{
ANON_REGION("MarketFeed:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->market_feed();
}
bench_worker::txn_result market_feed()
{
scoped_str_arena s_arena(arena);
TMarketFeedTxnInput* input= MarketFeedInputBuffer->get();
if( not input )
{
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0); // XXX. do we have to do this? MFQueue is empty, meaning no Trade-order submitted yet
}
TMarketFeedTxnOutput output;
CMarketFeed* harness= new CMarketFeed(this, this);
auto ret = harness->DoTxn( (PMarketFeedTxnInput)input, (PMarketFeedTxnOutput)&output);
delete input;
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoMarketFeedFrame1(const TMarketFeedFrame1Input *pIn, TMarketFeedFrame1Output *pOut, CSendToMarketInterface *pSendToMarket);
// MarketWatch
static bench_worker::txn_result MarketWatch(bench_worker *w)
{
ANON_REGION("MarketWatch:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->market_watch();
}
bench_worker::txn_result market_watch()
{
scoped_str_arena s_arena(arena);
TMarketWatchTxnInput input;
TMarketWatchTxnOutput output;
m_TxnInputGenerator->GenerateMarketWatchInput(input);
CMarketWatch* harness= new CMarketWatch(this);
auto ret = harness->DoTxn( (PMarketWatchTxnInput)&input, (PMarketWatchTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoMarketWatchFrame1 (const TMarketWatchFrame1Input *pIn, TMarketWatchFrame1Output *pOut);
// SecurityDetail
static bench_worker::txn_result SecurityDetail(bench_worker *w)
{
ANON_REGION("SecurityDetail:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->security_detail();
}
bench_worker::txn_result security_detail()
{
scoped_str_arena s_arena(arena);
TSecurityDetailTxnInput input;
TSecurityDetailTxnOutput output;
m_TxnInputGenerator->GenerateSecurityDetailInput(input);
CSecurityDetail* harness= new CSecurityDetail(this);
auto ret = harness->DoTxn( (PSecurityDetailTxnInput)&input, (PSecurityDetailTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoSecurityDetailFrame1(const TSecurityDetailFrame1Input *pIn, TSecurityDetailFrame1Output *pOut);
// TradeLookup
static bench_worker::txn_result TradeLookup(bench_worker *w)
{
ANON_REGION("TradeLookup:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_lookup();
}
bench_worker::txn_result trade_lookup()
{
scoped_str_arena s_arena(arena);
TTradeLookupTxnInput input;
TTradeLookupTxnOutput output;
m_TxnInputGenerator->GenerateTradeLookupInput(input);
CTradeLookup* harness= new CTradeLookup(this);
auto ret = harness->DoTxn( (PTradeLookupTxnInput)&input, (PTradeLookupTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeLookupFrame1(const TTradeLookupFrame1Input *pIn, TTradeLookupFrame1Output *pOut);
bench_worker::txn_result DoTradeLookupFrame2(const TTradeLookupFrame2Input *pIn, TTradeLookupFrame2Output *pOut);
bench_worker::txn_result DoTradeLookupFrame3(const TTradeLookupFrame3Input *pIn, TTradeLookupFrame3Output *pOut);
bench_worker::txn_result DoTradeLookupFrame4(const TTradeLookupFrame4Input *pIn, TTradeLookupFrame4Output *pOut);
// TradeOrder
static bench_worker::txn_result TradeOrder(bench_worker *w)
{
ANON_REGION("TradeOrder:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_order();
}
bench_worker::txn_result trade_order()
{
scoped_str_arena s_arena(arena);
TTradeOrderTxnInput input;
TTradeOrderTxnOutput output;
bool bExecutorIsAccountOwner;
int32_t iTradeType;
m_TxnInputGenerator->GenerateTradeOrderInput(input, iTradeType, bExecutorIsAccountOwner);
CTradeOrder* harness= new CTradeOrder(this, this);
auto ret = harness->DoTxn( (PTradeOrderTxnInput)&input, (PTradeOrderTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeOrderFrame1(const TTradeOrderFrame1Input *pIn, TTradeOrderFrame1Output *pOut);
bench_worker::txn_result DoTradeOrderFrame2(const TTradeOrderFrame2Input *pIn, TTradeOrderFrame2Output *pOut);
bench_worker::txn_result DoTradeOrderFrame3(const TTradeOrderFrame3Input *pIn, TTradeOrderFrame3Output *pOut);
bench_worker::txn_result DoTradeOrderFrame4(const TTradeOrderFrame4Input *pIn, TTradeOrderFrame4Output *pOut);
bench_worker::txn_result DoTradeOrderFrame5(void );
bench_worker::txn_result DoTradeOrderFrame6(void );
// TradeResult
static bench_worker::txn_result TradeResult(bench_worker *w)
{
ANON_REGION("TradeResult:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_result();
}
bench_worker::txn_result trade_result()
{
scoped_str_arena s_arena(arena);
TTradeResultTxnInput* input = TradeResultInputBuffer->get();
if( not input )
{
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0); // XXX. do we have to do this? TRQueue is empty, meaning no Trade-order submitted yet
}
TTradeResultTxnOutput output;
CTradeResult* harness= new CTradeResult(this);
auto ret = harness->DoTxn( (PTradeResultTxnInput)input, (PTradeResultTxnOutput)&output);
delete input;
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeResultFrame1(const TTradeResultFrame1Input *pIn, TTradeResultFrame1Output *pOut);
bench_worker::txn_result DoTradeResultFrame2(const TTradeResultFrame2Input *pIn, TTradeResultFrame2Output *pOut);
bench_worker::txn_result DoTradeResultFrame3(const TTradeResultFrame3Input *pIn, TTradeResultFrame3Output *pOut);
bench_worker::txn_result DoTradeResultFrame4(const TTradeResultFrame4Input *pIn, TTradeResultFrame4Output *pOut);
bench_worker::txn_result DoTradeResultFrame5(const TTradeResultFrame5Input *pIn );
bench_worker::txn_result DoTradeResultFrame6(const TTradeResultFrame6Input *pIn, TTradeResultFrame6Output *pOut);
// TradeStatus
static bench_worker::txn_result TradeStatus(bench_worker *w)
{
ANON_REGION("TradeStatus:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_status();
}
bench_worker::txn_result trade_status()
{
scoped_str_arena s_arena(arena);
TTradeStatusTxnInput input;
TTradeStatusTxnOutput output;
m_TxnInputGenerator->GenerateTradeStatusInput(input);
CTradeStatus* harness= new CTradeStatus(this);
auto ret = harness->DoTxn( (PTradeStatusTxnInput)&input, (PTradeStatusTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeStatusFrame1(const TTradeStatusFrame1Input *pIn, TTradeStatusFrame1Output *pOut);
// TradeUpdate
static bench_worker::txn_result TradeUpdate(bench_worker *w)
{
ANON_REGION("TradeUpdate:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_update();
}
bench_worker::txn_result trade_update()
{
scoped_str_arena s_arena(arena);
TTradeUpdateTxnInput input;
TTradeUpdateTxnOutput output;
m_TxnInputGenerator->GenerateTradeUpdateInput(input);
CTradeUpdate* harness= new CTradeUpdate(this);
auto ret = harness->DoTxn( (PTradeUpdateTxnInput)&input, (PTradeUpdateTxnOutput)&output);
if( ret.first )
{
if( output.status == 0 )
return txn_result(true, 0 );
else
{
inc_ntxn_user_aborts();
return txn_result(false, 0 ); // No DB aborts, TXN output isn't correct or user abort case
}
}
return txn_result(false, 0 );
}
bench_worker::txn_result DoTradeUpdateFrame1(const TTradeUpdateFrame1Input *pIn, TTradeUpdateFrame1Output *pOut);
bench_worker::txn_result DoTradeUpdateFrame2(const TTradeUpdateFrame2Input *pIn, TTradeUpdateFrame2Output *pOut);
bench_worker::txn_result DoTradeUpdateFrame3(const TTradeUpdateFrame3Input *pIn, TTradeUpdateFrame3Output *pOut);
// Long query
static bench_worker::txn_result LongQuery(bench_worker *w)
{
ANON_REGION("LongQuery:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->long_query();
}
bench_worker::txn_result long_query()
{
scoped_str_arena s_arena(arena);
return DoLongQueryFrame1();
}
bench_worker::txn_result DoLongQueryFrame1();
// DataMaintenance
static bench_worker::txn_result DataMaintenance(bench_worker *w)
{
ANON_REGION("DataMaintenance:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->data_maintenance();
}
bench_worker::txn_result data_maintenance()
{
scoped_str_arena s_arena(arena);
TDataMaintenanceTxnInput* input = m_CDM->createDMInput();
TDataMaintenanceTxnOutput output;
CDataMaintenance* harness= new CDataMaintenance(this);
// return harness->DoTxn( (PDataMaintenanceTxnInput)&input, (PDataMaintenanceTxnOutput)&output);
}
bench_worker::txn_result DoDataMaintenanceFrame1(const TDataMaintenanceFrame1Input *pIn);
// TradeCleanup
static bench_worker::txn_result TradeCleanup(bench_worker *w)
{
ANON_REGION("TradeCleanup:", &tpce_txn_cg);
return static_cast<tpce_worker *>(w)->trade_cleanup();
}
bench_worker::txn_result trade_cleanup()
{
scoped_str_arena s_arena(arena);
TTradeCleanupTxnInput* input = m_CDM->createTCInput();
TTradeCleanupTxnOutput output;
CTradeCleanup* harness= new CTradeCleanup(this);
// return harness->DoTxn( (PTradeCleanupTxnInput)&input, (PTradeCleanupTxnOutput)&output);
}
bench_worker::txn_result DoTradeCleanupFrame1(const TTradeCleanupFrame1Input *pIn);
virtual workload_desc_vec
get_workload() const
{
workload_desc_vec w;
double m = 0;
for (size_t i = 0; i < ARRAY_NELEMS(g_txn_workload_mix); i++)
m += g_txn_workload_mix[i];
ALWAYS_ASSERT(m == 100);
if (g_txn_workload_mix[0])
w.push_back(workload_desc("BrokerVolume", double(g_txn_workload_mix[0])/100.0, BrokerVolume));
if (g_txn_workload_mix[1])
w.push_back(workload_desc("CustomerPosition", double(g_txn_workload_mix[1])/100.0, CustomerPosition));
if (g_txn_workload_mix[2])
w.push_back(workload_desc("MarketFeed", double(g_txn_workload_mix[2])/100.0, MarketFeed));
if (g_txn_workload_mix[3])
w.push_back(workload_desc("MarketWatch", double(g_txn_workload_mix[3])/100.0, MarketWatch));
if (g_txn_workload_mix[4])
w.push_back(workload_desc("SecurityDetail", double(g_txn_workload_mix[4])/100.0, SecurityDetail));
if (g_txn_workload_mix[5])
w.push_back(workload_desc("TradeLookup", double(g_txn_workload_mix[5])/100.0, TradeLookup));
if (g_txn_workload_mix[6])
w.push_back(workload_desc("TradeOrder", double(g_txn_workload_mix[6])/100.0, TradeOrder));
if (g_txn_workload_mix[7])
w.push_back(workload_desc("TradeResult", double(g_txn_workload_mix[7])/100.0, TradeResult));
if (g_txn_workload_mix[8])
w.push_back(workload_desc("TradeStatus", double(g_txn_workload_mix[8])/100.0, TradeStatus));
if (g_txn_workload_mix[9])
w.push_back(workload_desc("TradeUpdate", double(g_txn_workload_mix[9])/100.0, TradeUpdate));
if (g_txn_workload_mix[10])
w.push_back(workload_desc("LongQuery", double(g_txn_workload_mix[10])/100.0, LongQuery));
// if (g_txn_workload_mix[10])
// w.push_back(workload_desc("DataMaintenance", double(g_txn_workload_mix[10])/100.0, DataMaintenance));
// if (g_txn_workload_mix[11])
// w.push_back(workload_desc("TradeCleanup", double(g_txn_workload_mix[11])/100.0, TradeCleanup));
return w;
}
protected:
virtual void
on_run_setup() OVERRIDE
{
if (!pin_cpus)
return;
const size_t a = worker_id % coreid::num_cpus_online();
const size_t b = a % nthreads;
RCU::pin_current_thread(b);
}
inline ALWAYS_INLINE varstr &
str(uint64_t size)
{
return *arena.next(size);
}
private:
void* txn;
const uint partition_id_start;
const uint partition_id_end;
// some scratch buffer space
varstr obj_key0;
varstr obj_key1;
varstr obj_v;
CMEE* mee; // thread-local MEE
MFBuffer* MarketFeedInputBuffer;
TRBuffer* TradeResultInputBuffer;
};
bench_worker::txn_result tpce_worker::DoBrokerVolumeFrame1(const TBrokerVolumeFrame1Input *pIn, TBrokerVolumeFrame1Output *pOut)
{
/* SQL
start transaction
// Should return 0 to 40 rows
select
broker_name[] = B_NAME,
volume[] = sum(TR_QTY * TR_BID_PRICE)
from
TRADE_REQUEST,
SECTOR,
INDUSTRY
COMPANY,
BROKER,
SECURITY
where
TR_B_ID = B_ID and
TR_S_SYMB = S_SYMB and
S_CO_ID = CO_ID and
CO_IN_ID = IN_ID and
SC_ID = IN_SC_ID and
B_NAME in (broker_list) and
SC_NAME = sector_name
group by
B_NAME
order by
2 DESC
// row_count will frequently be zero near the start of a Test Run when
// TRADE_REQUEST table is mostly empty.
list_len = row_count
commit transaction
*/
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
std::vector<std::pair<varstr *, const varstr *>> brokers;
for( auto i = 0; i < max_broker_list_len and pIn->broker_list[i] ; i++ )
{
const b_name_index::key k_b_0( string(pIn->broker_list[i]), MIN_VAL(k_b_0.b_id) );
const b_name_index::key k_b_1( string(pIn->broker_list[i]), MAX_VAL(k_b_1.b_id) );
table_scanner b_scanner(&arena);
try_catch(tbl_b_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_b_0)), k_b_0), &Encode(obj_key1=str(sizeof(k_b_1)), k_b_1), b_scanner, &arena));
if( not b_scanner.output.size())
continue;
for( auto &r_b : b_scanner.output )
brokers.push_back( r_b );
}
// NLJ
pOut->list_len = 0;
const sector::key k_sc_0( pIn->sector_name, string(cSC_ID_len, (char)0 ));
const sector::key k_sc_1( pIn->sector_name, string(cSC_ID_len, (char)255));
table_scanner sc_scanner(&arena);
try_catch(tbl_sector(1)->scan(txn, Encode(obj_key0=str(sizeof(k_sc_0)), k_sc_0), &Encode(obj_key1=str(sizeof(k_sc_1)), k_sc_1), sc_scanner, &arena));
ALWAYS_ASSERT(sc_scanner.output.size() == 1);
for( auto &r_sc: sc_scanner.output )
{
sector::key k_sc_temp;
const sector::key* k_sc = Decode(*r_sc.first, k_sc_temp );
// in_sc_id_index scan
const in_sc_id_index::key k_in_0( k_sc->sc_id, string(cIN_ID_len, (char)0) );
const in_sc_id_index::key k_in_1( k_sc->sc_id, string(cIN_ID_len, (char)255) );
table_scanner in_scanner(&arena);
try_catch(tbl_in_sc_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), in_scanner, &arena));
ALWAYS_ASSERT(in_scanner.output.size());
for( auto &r_in: in_scanner.output)
{
in_sc_id_index::key k_in_temp;
const in_sc_id_index::key* k_in = Decode(*r_in.first, k_in_temp );
// co_in_id_index scan
const co_in_id_index::key k_in_0( k_in->in_id, MIN_VAL(k_in_0.co_id) );
const co_in_id_index::key k_in_1( k_in->in_id, MAX_VAL(k_in_1.co_id) );
table_scanner co_scanner(&arena);
try_catch(tbl_co_in_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), co_scanner, &arena));
ALWAYS_ASSERT(co_scanner.output.size());
for( auto &r_co : co_scanner.output )
{
co_in_id_index::key k_co_temp;
const co_in_id_index::key* k_co = Decode(*r_co.first, k_co_temp );
// security_index scan
const security_index::key k_s_0( k_co->co_id, string(cS_ISSUE_len, (char)0) , string(cSYMBOL_len, (char)0) );
const security_index::key k_s_1( k_co->co_id, string(cS_ISSUE_len, (char)255), string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT(s_scanner.output.size());
for( auto &r_s : s_scanner.output )
{
security_index::key k_s_temp;
const security_index::key* k_s = Decode( *r_s.first, k_s_temp );
for( auto &r_b_idx : brokers )
{
if( pOut->list_len >= max_broker_list_len )
break;
b_name_index::key k_b_idx_temp;
const b_name_index::key* k_b_idx = Decode( *r_b_idx.first, k_b_idx_temp );
const trade_request::key k_tr_0( k_s->s_symb, k_b_idx->b_id, MIN_VAL(k_tr_0.tr_t_id) );
const trade_request::key k_tr_1( k_s->s_symb, k_b_idx->b_id, MAX_VAL(k_tr_1.tr_t_id) );
table_scanner tr_scanner(&arena);
try_catch(tbl_trade_request(1)->scan(txn, Encode(obj_key0=str(sizeof(k_tr_0)), k_tr_0), &Encode(obj_key1=str(sizeof(k_tr_1)), k_tr_1), tr_scanner, &arena));
// ALWAYS_ASSERT( tr_scanner.output.size() ); // XXX. If there's no previous trade, this can happen
for( auto &r_tr : tr_scanner.output )
{
trade_request::value v_tr_temp;
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
pOut->volume[pOut->list_len] += v_tr->tr_bid_price * v_tr->tr_qty;
}
memcpy(pOut->broker_name[pOut->list_len], k_b_idx->b_name.data(), k_b_idx->b_name.size());
// pOut->volume[pOut->list_len] = v_tr->tr_bid_price * v_tr->tr_qty;
pOut->list_len++;
}
}
}
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame1(const TCustomerPositionFrame1Input *pIn, TCustomerPositionFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
// Get c_id;
const c_tax_id_index::key k_c_0( pIn->tax_id, MIN_VAL(k_c_0.c_id) );
const c_tax_id_index::key k_c_1( pIn->tax_id, MAX_VAL(k_c_1.c_id) );
table_scanner c_scanner(&arena);
if(pIn->cust_id)
pOut->cust_id = pIn->cust_id;
else
{
try_catch(tbl_c_tax_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_c_0)), k_c_0), &Encode(obj_key1=str(sizeof(k_c_1)), k_c_1), c_scanner, &arena));
// XXX. input generator's tax_id doesn't exist. ???
if( not c_scanner.output.size())
{
// return;
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
c_tax_id_index::key k_c_temp;
const c_tax_id_index::key* k_c = Decode( *(c_scanner.output.front().first), k_c_temp );
pOut->cust_id = k_c->c_id;
}
ALWAYS_ASSERT( pOut->cust_id );
// probe Customers
const customers::key k_c(pOut->cust_id);
customers::value v_c_temp;
try_verify_strict(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
memcpy(pOut->c_st_id, v_c->c_st_id.data(), v_c->c_st_id.size() );
memcpy(pOut->c_l_name, v_c->c_l_name.data(), v_c->c_l_name.size());
memcpy(pOut->c_f_name, v_c->c_f_name.data(), v_c->c_f_name.size());
memcpy(pOut->c_m_name, v_c->c_m_name.data(), v_c->c_m_name.size());
pOut->c_gndr[0] = v_c->c_gndr; pOut->c_gndr[1] = 0;
pOut->c_tier = v_c->c_tier;
CDateTime(v_c->c_dob).GetTimeStamp(&pOut->c_dob );
pOut->c_ad_id = v_c->c_ad_id;
memcpy(pOut->c_ctry_1, v_c->c_ctry_1.data(), v_c->c_ctry_1.size());
memcpy(pOut->c_area_1, v_c->c_area_1.data(), v_c->c_area_1.size());
memcpy(pOut->c_local_1, v_c->c_local_1.data(), v_c->c_local_1.size());
memcpy(pOut->c_ext_1, v_c->c_ext_1.data(), v_c->c_ext_1.size());
memcpy(pOut->c_ctry_2, v_c->c_ctry_2.data(), v_c->c_ctry_2.size());
memcpy(pOut->c_area_2, v_c->c_area_2.data(), v_c->c_area_2.size());
memcpy(pOut->c_local_2, v_c->c_local_2.data(), v_c->c_local_2.size());
memcpy(pOut->c_ext_2, v_c->c_ext_2.data(), v_c->c_ext_2.size());
memcpy(pOut->c_ctry_3, v_c->c_ctry_3.data(), v_c->c_ctry_3.size());
memcpy(pOut->c_area_3, v_c->c_area_3.data(), v_c->c_area_3.size());
memcpy(pOut->c_local_3, v_c->c_local_3.data(), v_c->c_local_3.size());
memcpy(pOut->c_ext_3, v_c->c_ext_3.data(), v_c->c_ext_3.size());
memcpy(pOut->c_email_1, v_c->c_email_1.data(), v_c->c_email_1.size());
memcpy(pOut->c_email_2, v_c->c_email_2.data(), v_c->c_email_2.size());
// CustomerAccount scan
const ca_id_index::key k_ca_0( pOut->cust_id, MIN_VAL(k_ca_0.ca_id) );
const ca_id_index::key k_ca_1( pOut->cust_id, MAX_VAL(k_ca_1.ca_id) );
table_scanner ca_scanner(&arena);
try_catch(tbl_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_ca_0)), k_ca_0), &Encode(obj_key1=str(sizeof(k_ca_1)), k_ca_1), ca_scanner, &arena));
ALWAYS_ASSERT( ca_scanner.output.size() );
for( auto& r_ca : ca_scanner.output )
{
ca_id_index::key k_ca_temp;
ca_id_index::value v_ca_temp;
const ca_id_index::key* k_ca = Decode( *r_ca.first, k_ca_temp );
const ca_id_index::value* v_ca = Decode(*r_ca.second, v_ca_temp );
// HoldingSummary scan
const holding_summary::key k_hs_0( k_ca->ca_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( k_ca->ca_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
//ALWAYS_ASSERT( hs_scanner.output.size() ); // left-outer join. S table could be empty.
auto asset = 0;
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode(*r_hs.second, v_hs_temp );
// LastTrade probe & equi-join
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
asset += v_hs->hs_qty * v_lt->lt_price;
}
// TODO. sorting
// Since we are doing left outer join, non-join rows just emit 0 asset here.
pOut->acct_id[pOut->acct_len] = k_ca->ca_id;
pOut->cash_bal[pOut->acct_len] = v_ca->ca_bal;
pOut->asset_total[pOut->acct_len] = asset;
pOut->acct_len++;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame2(const TCustomerPositionFrame2Input *pIn, TCustomerPositionFrame2Output *pOut)
{
// XXX. If, CP frame 1 doesn't give output, then, we don't have valid input at here. so just return
if( not pIn->acct_id )
{
// try_catch(db->commit_txn(txn));
// return txn_result(true, 0);
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
// Trade scan and collect 10 TID
const t_ca_id_index::key k_t_0( pIn->acct_id, MIN_VAL(k_t_0.t_dts), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_0.t_dts), MAX_VAL(k_t_0.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
std::vector<std::pair<varstr *, const varstr *>> tids;
for( auto &r_t : t_scanner.output )
{
tids.push_back( r_t );
if( tids.size() >= 10 )
break;
}
reverse(tids.begin(), tids.end());
for( auto &r_t : tids )
{
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode(*r_t.second, v_t_temp );
// Join
const trade_history::key k_th_0( k_t->t_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( k_t->t_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
status_type::key k_st(k_th->th_st_id);
status_type::value v_st_temp;
try_verify_relax(tbl_status_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_st)), k_st), obj_v=str(sizeof(v_st_temp))));
const status_type::value *v_st = Decode(obj_v,v_st_temp);
// TODO. order by and grab 30 rows
pOut->trade_id[pOut->hist_len] = k_t->t_id;
pOut->qty[pOut->hist_len] = v_t->t_qty;
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->hist_dts[pOut->hist_len] );
memcpy(pOut->symbol[pOut->hist_len], v_t->t_s_symb.data(), v_t->t_s_symb.size());
memcpy(pOut->trade_status[pOut->hist_len], v_st->st_name.data(), v_st->st_name.size());
pOut->hist_len++;
if( pOut->hist_len >= max_hist_len )
goto commit;
}
}
commit:
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoCustomerPositionFrame3(void)
{
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoMarketFeedFrame1(const TMarketFeedFrame1Input *pIn, TMarketFeedFrame1Output *pOut, CSendToMarketInterface *pSendToMarket)
{
auto now_dts = CDateTime().GetDate();
vector<TTradeRequest> TradeRequestBuffer;
double req_price_quote = 0;
uint64_t req_trade_id = 0;
int32_t req_trade_qty = 0;
inline_str_fixed<cTT_ID_len> req_trade_type;
TStatusAndTradeType type = pIn->StatusAndTradeType;
for( int i = 0; i < max_feed_len; i++ )
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
TTickerEntry ticker = pIn->Entries[i];
last_trade::key k_lt(ticker.symbol);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
last_trade::value v_lt_new(*v_lt);
v_lt_new.lt_dts = now_dts;
v_lt_new.lt_price = v_lt->lt_price + ticker.price_quote;
v_lt_new.lt_vol = ticker.price_quote;
try_catch(tbl_last_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), Encode(obj_v=str(sizeof(v_lt_new)), v_lt_new)));
pOut->num_updated++;
const trade_request::key k_tr_0( string(ticker.symbol), MIN_VAL(k_tr_0.tr_b_id), MIN_VAL(k_tr_0.tr_t_id) );
const trade_request::key k_tr_1( string(ticker.symbol), MAX_VAL(k_tr_1.tr_b_id), MAX_VAL(k_tr_1.tr_t_id) );
table_scanner tr_scanner(&arena);
try_catch(tbl_trade_request(1)->scan(txn, Encode(obj_key0=str(sizeof(k_tr_0)), k_tr_0), &Encode(obj_key1=str(sizeof(k_tr_1)), k_tr_1), tr_scanner, &arena));
// ALWAYS_ASSERT( tr_scanner.output.size() ); // XXX. If there's no previous trade, this can happen. Higher initial trading days would enlarge this scan set
std::vector<std::pair<varstr *, const varstr *>> request_list_cursor;
for( auto &r_tr : tr_scanner.output )
{
trade_request::value v_tr_temp;
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
if( (v_tr->tr_tt_id == string(type.type_stop_loss) and v_tr->tr_bid_price >= ticker.price_quote) or
(v_tr->tr_tt_id == string(type.type_limit_sell) and v_tr->tr_bid_price <= ticker.price_quote) or
(v_tr->tr_tt_id == string(type.type_limit_buy) and v_tr->tr_bid_price >= ticker.price_quote) )
{
request_list_cursor.push_back( r_tr );
}
}
for( auto &r_tr : request_list_cursor )
{
trade_request::key k_tr_temp;
trade_request::value v_tr_temp;
const trade_request::key* k_tr = Decode( *r_tr.first, k_tr_temp );
const trade_request::value* v_tr = Decode(*r_tr.second, v_tr_temp );
req_trade_id = k_tr->tr_t_id;
req_price_quote = v_tr->tr_bid_price;
req_trade_type = v_tr->tr_tt_id;
req_trade_qty = v_tr->tr_qty;
const trade::key k_t(req_trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_dts = now_dts;
v_t_new.t_st_id = string(type.status_submitted);
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
// DTS field is updated. cascading update( actually insert after remove, because dts is included in PK )
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t->t_ca_id;
k_t_idx1.t_dts = v_t->t_dts;
k_t_idx1.t_id = k_t.t_id;
try_verify_relax(tbl_t_ca_id_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1)));
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t->t_s_symb;
k_t_idx2.t_dts = v_t->t_dts;
k_t_idx2.t_id = k_t.t_id;
try_verify_relax(tbl_t_s_symb_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2)));
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
trade_request::key k_tr_new(*k_tr);
try_verify_relax(tbl_trade_request(1)->remove(txn, Encode(obj_key0=str(sizeof(k_tr_new)), k_tr_new)));
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = req_trade_id;
k_th.th_dts = now_dts;
k_th.th_st_id = string(type.status_submitted);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
TTradeRequest request;
memset( &request, 0, sizeof(request));
memcpy(request.symbol, ticker.symbol, cSYMBOL_len+1);
request.trade_id = req_trade_id;
request.price_quote = req_price_quote;
request.trade_qty = req_trade_qty;
memcpy(request.trade_type_id, req_trade_type.data(), req_trade_type.size());
TradeRequestBuffer.emplace_back( request );
}
try_catch(db->commit_txn(txn));
pOut->send_len += request_list_cursor.size();
for( size_t i = 0; i < request_list_cursor.size(); i++ )
{
SendToMarketFromFrame(TradeRequestBuffer[i]);
}
TradeRequestBuffer.clear();
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoMarketWatchFrame1 (const TMarketWatchFrame1Input *pIn, TMarketWatchFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
std::vector<inline_str_fixed<cSYMBOL_len>> stock_list_cursor;
if( pIn->c_id )
{
const watch_list::key k_wl_0( pIn->c_id, MIN_VAL(k_wl_0.wl_id) );
const watch_list::key k_wl_1( pIn->c_id, MAX_VAL(k_wl_1.wl_id) );
table_scanner wl_scanner(&arena);
try_catch(tbl_watch_list(1)->scan(txn, Encode(obj_key0=str(sizeof(k_wl_0)), k_wl_0), &Encode(obj_key1=str(sizeof(k_wl_1)), k_wl_1), wl_scanner, &arena));
ALWAYS_ASSERT( wl_scanner.output.size() );
for( auto &r_wl: wl_scanner.output )
{
watch_list::key k_wl_temp;
const watch_list::key* k_wl = Decode( *r_wl.first, k_wl_temp );
const watch_item::key k_wi_0( k_wl->wl_id, string(cSYMBOL_len, (char)0 ) );
const watch_item::key k_wi_1( k_wl->wl_id, string(cSYMBOL_len, (char)255) );
table_scanner wi_scanner(&arena);
try_catch(tbl_watch_item(1)->scan(txn, Encode(obj_key0=str(sizeof(k_wi_0)), k_wi_0), &Encode(obj_key1=str(sizeof(k_wi_1)), k_wi_1), wi_scanner, &arena));
ALWAYS_ASSERT( wi_scanner.output.size() );
for( auto &r_wi : wi_scanner.output )
{
watch_item::key k_wi_temp;
const watch_item::key* k_wi = Decode( *r_wi.first, k_wi_temp );
stock_list_cursor.push_back( k_wi->wi_s_symb );
}
}
}
else if ( pIn->industry_name[0] )
{
const in_name_index::key k_in_0( string(pIn->industry_name), string(cIN_ID_len, (char)0 ) );
const in_name_index::key k_in_1( string(pIn->industry_name), string(cIN_ID_len, (char)255) );
table_scanner in_scanner(&arena);
try_catch(tbl_in_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_in_0)), k_in_0), &Encode(obj_key1=str(sizeof(k_in_1)), k_in_1), in_scanner, &arena));
ALWAYS_ASSERT( in_scanner.output.size() );
const company::key k_co_0( pIn->starting_co_id );
const company::key k_co_1( pIn->ending_co_id );
table_scanner co_scanner(&arena);
try_catch(tbl_company(1)->scan(txn, Encode(obj_key0=str(sizeof(k_co_0)), k_co_0), &Encode(obj_key1=str(sizeof(k_co_1)), k_co_1), co_scanner, &arena));
ALWAYS_ASSERT( co_scanner.output.size() );
const security::key k_s_0( string(cSYMBOL_len, (char)0 ));
const security::key k_s_1( string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT( s_scanner.output.size() );
for( auto &r_in : in_scanner.output )
{
in_name_index::key k_in_temp;
const in_name_index::key* k_in = Decode( *r_in.first, k_in_temp );
for( auto &r_co: co_scanner.output )
{
company::key k_co_temp;
company::value v_co_temp;
const company::key* k_co = Decode( *r_co.first, k_co_temp );
const company::value* v_co = Decode( *r_co.second, v_co_temp );
if( v_co->co_in_id != k_in->in_id )
continue;
for( auto &r_s : s_scanner.output )
{
security::key k_s_temp;
security::value v_s_temp;
const security::key* k_s = Decode( *r_s.first, k_s_temp );
const security::value* v_s = Decode( *r_s.second, v_s_temp );
if( v_s->s_co_id == k_co->co_id )
{
stock_list_cursor.push_back( k_s->s_symb );
}
}
}
}
}
else if( pIn->acct_id )
{
const holding_summary::key k_hs_0( pIn->acct_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( pIn->acct_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
// ALWAYS_ASSERT( hs_scanner.output.size() );
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
stock_list_cursor.push_back( k_hs->hs_s_symb );
}
}
else
ALWAYS_ASSERT(false);
double old_mkt_cap = 0;
double new_mkt_cap = 0;
for( auto &s : stock_list_cursor )
{
const last_trade::key k_lt(s);
last_trade::value v_lt_temp;
try_catch(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
const security::key k_s(s);
security::value v_s_temp;
try_catch(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
const daily_market::key k_dm(s, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_day).GetDate() );
daily_market::value v_dm_temp;
try_catch(tbl_daily_market(1)->get(txn, Encode(obj_key0=str(sizeof(k_dm)), k_dm), obj_v=str(sizeof(v_dm_temp))));
const daily_market::value *v_dm = Decode(obj_v,v_dm_temp);
auto s_num_out = v_s->s_num_out;
auto old_price = v_dm->dm_close;
auto new_price = v_lt->lt_price;
old_mkt_cap += s_num_out * old_price;
new_mkt_cap += s_num_out * new_price;
}
if( old_mkt_cap != 0 )
pOut->pct_change = 100 * (new_mkt_cap / old_mkt_cap - 1);
else
pOut->pct_change = 0;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoSecurityDetailFrame1(const TSecurityDetailFrame1Input *pIn, TSecurityDetailFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
int64_t co_id;
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
co_id = v_s->s_co_id;
const company::key k_co(co_id);
company::value v_co_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co)), k_co), obj_v=str(sizeof(v_co_temp))));
const company::value *v_co = Decode(obj_v,v_co_temp);
const address::key k_ca(v_co->co_ad_id);
address::value v_ca_temp;
try_verify_relax(tbl_address(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const address::value *v_ca = Decode(obj_v,v_ca_temp);
const zip_code::key k_zca(v_ca->ad_zc_code);
zip_code::value v_zca_temp;
try_verify_relax(tbl_zip_code(1)->get(txn, Encode(obj_key0=str(sizeof(k_zca)), k_zca), obj_v=str(sizeof(v_zca_temp))));
const zip_code::value *v_zca = Decode(obj_v,v_zca_temp);
const exchange::key k_ex(v_s->s_ex_id);
exchange::value v_ex_temp;
try_verify_relax(tbl_exchange(1)->get(txn, Encode(obj_key0=str(sizeof(k_ex)), k_ex), obj_v=str(sizeof(v_ex_temp))));
const exchange::value *v_ex = Decode(obj_v,v_ex_temp);
const address::key k_ea(v_ex->ex_ad_id);
address::value v_ea_temp;
try_verify_relax(tbl_address(1)->get(txn, Encode(obj_key0=str(sizeof(k_ea)), k_ea), obj_v=str(sizeof(v_ea_temp))));
const address::value *v_ea = Decode(obj_v,v_ea_temp);
const zip_code::key k_zea(v_ea->ad_zc_code);
zip_code::value v_zea_temp;
try_verify_relax(tbl_zip_code(1)->get(txn, Encode(obj_key0=str(sizeof(k_zea)), k_zea), obj_v=str(sizeof(v_zea_temp))));
const zip_code::value *v_zea = Decode(obj_v,v_zea_temp);
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size());
pOut->num_out = v_s->s_num_out;
CDateTime(v_s->s_start_date).GetTimeStamp(&pOut->start_date );
CDateTime(v_s->s_exch_date).GetTimeStamp(&pOut->ex_date);
pOut->pe_ratio = v_s->s_pe;
pOut->s52_wk_high = v_s->s_52wk_high;
CDateTime(v_s->s_52wk_high_date).GetTimeStamp(&pOut->s52_wk_high_date );
pOut->s52_wk_low = v_s->s_52wk_low;
CDateTime(v_s->s_52wk_low_date).GetTimeStamp(&pOut->s52_wk_low_date );
pOut->divid = v_s->s_dividend;
pOut->yield = v_s->s_yield;
memcpy(pOut->co_name, v_co->co_name.data(), v_co->co_name.size());
memcpy(pOut->sp_rate, v_co->co_sp_rate.data(), v_co->co_sp_rate.size());
memcpy(pOut->ceo_name, v_co->co_ceo.data(), v_co->co_ceo.size());
memcpy(pOut->co_desc, v_co->co_desc.data(), v_co->co_desc.size());
CDateTime(v_co->co_open_date).GetTimeStamp(&pOut->open_date );
memcpy(pOut->co_st_id, v_co->co_st_id.data(), v_co->co_st_id.size());
memcpy(pOut->co_ad_line1, v_ca->ad_line1.data(), v_ca->ad_line1.size());
memcpy(pOut->co_ad_line2, v_ca->ad_line2.data(), v_ca->ad_line2.size());
memcpy(pOut->co_ad_zip, v_ca->ad_zc_code.data(), v_ca->ad_zc_code.size());
memcpy(pOut->co_ad_cty, v_ca->ad_ctry.data(), v_ca->ad_ctry.size());
memcpy(pOut->ex_ad_line1, v_ea->ad_line1.data(), v_ea->ad_line1.size());
memcpy(pOut->ex_ad_line2, v_ea->ad_line2.data(), v_ea->ad_line2.size());
memcpy(pOut->ex_ad_zip, v_ea->ad_zc_code.data(), v_ea->ad_zc_code.size());
memcpy(pOut->ex_ad_cty, v_ea->ad_ctry.data(), v_ea->ad_ctry.size());
pOut->ex_open = v_ex->ex_open;
pOut->ex_close = v_ex->ex_close;
pOut->ex_num_symb = v_ex->ex_num_symb;
memcpy(pOut->ex_name, v_ex->ex_name.data(), v_ex->ex_name.size());
memcpy(pOut->ex_desc, v_ex->ex_desc.data(), v_ex->ex_desc.size());
memcpy(pOut->co_ad_town, v_zca->zc_town.data(), v_zca->zc_town.size());
memcpy(pOut->co_ad_div, v_zca->zc_div.data(), v_zca->zc_div.size());
memcpy(pOut->ex_ad_town, v_zea->zc_town.data(), v_zea->zc_town.size());
memcpy(pOut->ex_ad_div, v_zea->zc_div.data(), v_zea->zc_div.size());
const company_competitor::key k_cp_0( co_id, MIN_VAL(k_cp_0.cp_comp_co_id), string(cIN_ID_len, (char)0 ));
const company_competitor::key k_cp_1( co_id, MAX_VAL(k_cp_1.cp_comp_co_id), string(cIN_ID_len, (char)255));
table_scanner cp_scanner(&arena);
try_catch(tbl_company_competitor(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cp_0)), k_cp_0), &Encode(obj_key1=str(sizeof(k_cp_1)), k_cp_1), cp_scanner, &arena));
ALWAYS_ASSERT( cp_scanner.output.size() );
for(auto i = 0; i < max_comp_len; i++ )
{
auto &r_cp = cp_scanner.output[i];
company_competitor::key k_cp_temp;
const company_competitor::key* k_cp = Decode( *r_cp.first, k_cp_temp );
const company::key k_co3(k_cp->cp_comp_co_id);
company::value v_co3_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co3)), k_co3), obj_v=str(sizeof(v_co3_temp))));
const company::value *v_co3 = Decode(obj_v,v_co3_temp);
const industry::key k_in(k_cp->cp_in_id);
industry::value v_in_temp;
try_verify_relax(tbl_industry(1)->get(txn, Encode(obj_key0=str(sizeof(k_in)), k_in), obj_v=str(sizeof(v_in_temp))));
const industry::value *v_in = Decode(obj_v,v_in_temp);
memcpy( pOut->cp_co_name[i], v_co3->co_name.data(), v_co3->co_name.size() );
memcpy( pOut->cp_in_name[i], v_in->in_name.data(), v_in->in_name.size() );
}
const financial::key k_fi_0( co_id, MIN_VAL(k_fi_0.fi_year), MIN_VAL(k_fi_0.fi_qtr) );
const financial::key k_fi_1( co_id, MAX_VAL(k_fi_1.fi_year), MAX_VAL(k_fi_1.fi_qtr) );
table_scanner fi_scanner(&arena);
try_catch(tbl_financial(1)->scan(txn, Encode(obj_key0=str(sizeof(k_fi_0)), k_fi_0), &Encode(obj_key1=str(sizeof(k_fi_1)), k_fi_1), fi_scanner, &arena));
ALWAYS_ASSERT( fi_scanner.output.size() );
for( uint64_t i = 0; i < max_fin_len; i++ )
{
auto &r_fi = fi_scanner.output[i];
financial::key k_fi_temp;
financial::value v_fi_temp;
const financial::key* k_fi = Decode( *r_fi.first, k_fi_temp );
const financial::value* v_fi = Decode( *r_fi.second, v_fi_temp );
// TODO. order by
pOut->fin[i].year = k_fi->fi_year;
pOut->fin[i].qtr = k_fi->fi_qtr;
CDateTime(v_fi->fi_qtr_start_date).GetTimeStamp(&pOut->fin[i].start_date );
pOut->fin[i].rev = v_fi->fi_revenue;
pOut->fin[i].net_earn = v_fi->fi_net_earn;
pOut->fin[i].basic_eps = v_fi->fi_basic_eps;
pOut->fin[i].dilut_eps = v_fi->fi_dilut_eps;
pOut->fin[i].margin = v_fi->fi_margin;
pOut->fin[i].invent = v_fi->fi_inventory;
pOut->fin[i].assets = v_fi->fi_assets;
pOut->fin[i].liab = v_fi->fi_liability;
pOut->fin[i].out_basic = v_fi->fi_out_basic;
pOut->fin[i].out_dilut = v_fi->fi_out_dilut;
}
pOut->fin_len = max_fin_len;
const daily_market::key k_dm_0(string(pIn->symbol),CDateTime((TIMESTAMP_STRUCT*)&pIn->start_day).GetDate() );
const daily_market::key k_dm_1(string(pIn->symbol),MAX_VAL(k_dm_1.dm_date));
table_scanner dm_scanner(&arena);
try_catch(tbl_daily_market(1)->scan(txn, Encode(obj_key0=str(sizeof(k_dm_0)), k_dm_0), &Encode(obj_key1=str(sizeof(k_dm_1)), k_dm_1), dm_scanner, &arena));
ALWAYS_ASSERT( dm_scanner.output.size() );
for(size_t i=0; i < (size_t)pIn->max_rows_to_return and i< dm_scanner.output.size(); i++ )
{
auto &r_dm = dm_scanner.output[i];
daily_market::key k_dm_temp;
daily_market::value v_dm_temp;
const daily_market::key* k_dm = Decode( *r_dm.first, k_dm_temp );
const daily_market::value* v_dm = Decode( *r_dm.second, v_dm_temp );
CDateTime(k_dm->dm_date).GetTimeStamp(&pOut->day[i].date );
pOut->day[i].close = v_dm->dm_close;
pOut->day[i].high = v_dm->dm_high;
pOut->day[i].low = v_dm->dm_low;
pOut->day[i].vol = v_dm->dm_vol;
}
// TODO. order by
pOut->day_len = ((size_t)pIn->max_rows_to_return < dm_scanner.output.size()) ? pIn->max_rows_to_return : dm_scanner.output.size();
const last_trade::key k_lt(string(pIn->symbol));
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
pOut->last_price = v_lt->lt_price;
pOut->last_open = v_lt->lt_open_price;
pOut->last_vol = v_lt->lt_vol;
const news_xref::key k_nx_0( co_id , MIN_VAL(k_nx_0.nx_ni_id) );
const news_xref::key k_nx_1( co_id , MAX_VAL(k_nx_0.nx_ni_id) );
table_scanner nx_scanner(&arena);
try_catch(tbl_news_xref(1)->scan(txn, Encode(obj_key0=str(sizeof(k_nx_0)), k_nx_0), &Encode(obj_key1=str(sizeof(k_nx_1)), k_nx_1), nx_scanner, &arena));
ALWAYS_ASSERT( nx_scanner.output.size() );
for(int i = 0; i < max_news_len; i++ )
{
auto &r_nx = nx_scanner.output[i];
news_xref::key k_nx_temp;
const news_xref::key* k_nx = Decode( *r_nx.first, k_nx_temp );
const news_item::key k_ni(k_nx->nx_ni_id);
news_item::value v_ni_temp;
try_verify_relax(tbl_news_item(1)->get(txn, Encode(obj_key0=str(sizeof(k_ni)), k_ni), obj_v=str(sizeof(v_ni_temp))));
const news_item::value *v_ni = Decode(obj_v,v_ni_temp);
if( pIn->access_lob_flag )
{
memcpy(pOut->news[i].item, v_ni->ni_item.data(), v_ni->ni_item.size());
CDateTime(v_ni->ni_dts).GetTimeStamp(&pOut->news[i].dts );
memcpy(pOut->news[i].src , v_ni->ni_source.data(), v_ni->ni_source.size());
memcpy(pOut->news[i].auth , v_ni->ni_author.data(), v_ni->ni_author.size());
pOut->news[i].headline[0] = 0;
pOut->news[i].summary[0] = 0;
}
else
{
pOut->news[i].item[0] = 0;
CDateTime(v_ni->ni_dts).GetTimeStamp(&pOut->news[i].dts );
memcpy(pOut->news[i].src , v_ni->ni_source.data(), v_ni->ni_source.size());
memcpy(pOut->news[i].auth , v_ni->ni_author.data(), v_ni->ni_author.size());
memcpy(pOut->news[i].headline , v_ni->ni_headline.data(), v_ni->ni_headline.size());
memcpy(pOut->news[i].summary , v_ni->ni_summary.data(), v_ni->ni_summary.size());
}
}
pOut->news_len = ( max_news_len > nx_scanner.output.size() ) ? max_news_len : nx_scanner.output.size();
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame1(const TTradeLookupFrame1Input *pIn, TTradeLookupFrame1Output *pOut)
{
int i;
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
pOut->num_found = 0;
for( i = 0; i < pIn->max_trades; i++ )
{
const trade::key k_t(pIn->trade_id[i]);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->trade_info[i].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[i].is_cash= v_t->t_is_cash;
pOut->trade_info[i].is_market= v_tt->tt_is_mrkt;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
pOut->num_found++;
const settlement::key k_se(pIn->trade_id[i]);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pIn->trade_id[i]);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
// Scan
const trade_history::key k_th_0( pIn->trade_id[i], string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pIn->trade_id[i], string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame2(const TTradeLookupFrame2Input *pIn, TTradeLookupFrame2Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
auto num_found = 0;
for( auto &r_t : t_scanner.output )
{
if( num_found >= pIn->max_trades )
break;
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[num_found].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[num_found].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[num_found].is_cash = v_t->t_is_cash;
pOut->trade_info[num_found].trade_id= k_t->t_id;
pOut->trade_info[num_found].trade_price= v_t->t_trade_price;
num_found++;
}
pOut->num_found = num_found;
for( auto i = 0; i < num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame3(const TTradeLookupFrame3Input *pIn, TTradeLookupFrame3Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_s_symb_index::key k_t_0( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_s_symb_index::key k_t_1( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_s_symb_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
auto num_found = 0;
for( auto &r_t : t_scanner.output )
{
if( num_found >= pIn->max_trades )
break;
t_s_symb_index::key k_t_temp;
t_s_symb_index::value v_t_temp;
const t_s_symb_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_s_symb_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[num_found].acct_id = v_t->t_ca_id;
memcpy(pOut->trade_info[num_found].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->trade_info[num_found].is_cash = v_t->t_is_cash;
pOut->trade_info[num_found].price= v_t->t_trade_price;
pOut->trade_info[num_found].quantity = v_t->t_qty;
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_info[num_found].trade_dts );
pOut->trade_info[num_found].trade_id = k_t->t_id;
memcpy(pOut->trade_info[num_found].trade_type, v_t->t_tt_id.data(), v_t->t_tt_id.size() );
num_found++;
}
pOut->num_found = num_found;
for( int i = 0; i < num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date );
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size() );
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts );
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size() );
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_1.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
// TODO. order by
int th_cursor= 0;
for( auto &r_th : th_scanner.output )
{
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size() );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor] );
th_cursor++;
if( th_cursor >= TradeLookupMaxTradeHistoryRowsReturned )
break;
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeLookupFrame4(const TTradeLookupFrame4Input *pIn, TTradeLookupFrame4Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_1.t_dts), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
if( not t_scanner.output.size() ) // XXX. can happen? or something is wrong?
{
pOut->num_trades_found = 0;
db->abort_txn(txn);
inc_ntxn_user_aborts();
return txn_result(false, 0);
}
for( auto &r_t : t_scanner.output )
{
t_ca_id_index::key k_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
pOut->trade_id = k_t->t_id;
break;
}
pOut->num_trades_found = 1;
// XXX. holding_history PK isn't unique. combine T_ID and row ID.
const holding_history::key k_hh_0(pOut->trade_id, MIN_VAL(k_hh_0.hh_h_t_id));
const holding_history::key k_hh_1(pOut->trade_id, MAX_VAL(k_hh_1.hh_h_t_id));
table_scanner hh_scanner(&arena);
try_catch(tbl_holding_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hh_0)), k_hh_0), &Encode(obj_key1=str(sizeof(k_hh_1)), k_hh_1), hh_scanner, &arena));
ALWAYS_ASSERT( hh_scanner.output.size() ); // possible case. no holding for the customer
auto hh_cursor = 0;
for( auto& r_hh : hh_scanner.output )
{
holding_history::key k_hh_temp;
holding_history::value v_hh_temp;
const holding_history::key* k_hh = Decode( *r_hh.first, k_hh_temp );
const holding_history::value* v_hh = Decode( *r_hh.second, v_hh_temp );
pOut->trade_info[hh_cursor].holding_history_id = k_hh->hh_h_t_id;
pOut->trade_info[hh_cursor].holding_history_trade_id = k_hh->hh_t_id;
pOut->trade_info[hh_cursor].quantity_after = v_hh->hh_after_qty;
pOut->trade_info[hh_cursor].quantity_before = v_hh->hh_before_qty;
hh_cursor++;
if( hh_cursor >= TradeLookupFrame4MaxRows )
break;
}
pOut->num_found = hh_cursor;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame1(const TTradeOrderFrame1Input *pIn, TTradeOrderFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
memcpy( pOut->acct_name, v_ca->ca_name.data(), v_ca->ca_name.size() );
pOut->broker_id = v_ca->ca_b_id;
pOut->cust_id = v_ca->ca_c_id;
pOut->tax_status = v_ca->ca_tax_st;
pOut->num_found = 1;
const customers::key k_c(pOut->cust_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
memcpy( pOut->cust_f_name, v_c->c_f_name.data(), v_c->c_f_name.size() );
memcpy( pOut->cust_l_name, v_c->c_l_name.data(), v_c->c_l_name.size() );
pOut->cust_tier = v_c->c_tier;
memcpy(pOut->tax_id, v_c->c_tax_id.data(), v_c->c_tax_id.size() );
const broker::key k_b(pOut->broker_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
memcpy( pOut->broker_name, v_b->b_name.data(), v_b->b_name.size() );
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame2(const TTradeOrderFrame2Input *pIn, TTradeOrderFrame2Output *pOut)
{
const account_permission::key k_ap(pIn->acct_id, string(pIn->exec_tax_id) );
account_permission::value v_ap_temp;
rc_t ret;
try_catch( ret = tbl_account_permission(1)->get(txn, Encode(obj_key0=str(sizeof(k_ap)), k_ap), obj_v=str(sizeof(v_ap_temp))));
if( ret._val == RC_TRUE )
{
const account_permission::value *v_ap = Decode(obj_v,v_ap_temp);
if( v_ap->ap_f_name == string(pIn->exec_f_name) and v_ap->ap_l_name == string(pIn->exec_l_name) )
{
memcpy(pOut->ap_acl, v_ap->ap_acl.data(), v_ap->ap_acl.size() );
return bench_worker::txn_result(true, 0);
}
}
pOut->ap_acl[0] = '\0';
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame3(const TTradeOrderFrame3Input *pIn, TTradeOrderFrame3Output *pOut)
{
int64_t co_id = 0;
char exch_id[cEX_ID_len + 1]; // XXX. without "+1", gdb can be killed!
memset(exch_id, 0, cEX_ID_len + 1);
if( not pIn->symbol[0] )
{
const co_name_index::key k_co_0( string(pIn->co_name), MIN_VAL(k_co_0.co_id) );
const co_name_index::key k_co_1( string(pIn->co_name), MAX_VAL(k_co_1.co_id) );
table_scanner co_scanner(&arena);
try_catch(tbl_co_name_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_co_0)), k_co_0), &Encode(obj_key1=str(sizeof(k_co_1)), k_co_1), co_scanner, &arena));
ALWAYS_ASSERT( co_scanner.output.size() );
co_name_index::key k_co_temp;
const co_name_index::key* k_co = Decode( *co_scanner.output.front().first, k_co_temp );
co_id = k_co->co_id;
ALWAYS_ASSERT(co_id);
const security_index::key k_s_0( co_id, pIn->issue, string(cSYMBOL_len, (char)0) );
const security_index::key k_s_1( co_id, pIn->issue, string(cSYMBOL_len, (char)255));
table_scanner s_scanner(&arena);
try_catch(tbl_security_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_s_0)), k_s_0), &Encode(obj_key1=str(sizeof(k_s_1)), k_s_1), s_scanner, &arena));
ALWAYS_ASSERT(s_scanner.output.size());
for( auto &r_s : s_scanner.output )
{
security_index::key k_s_temp;
security_index::value v_s_temp;
const security_index::key* k_s = Decode( *r_s.first, k_s_temp );
const security_index::value* v_s = Decode( *r_s.second, v_s_temp );
memcpy(exch_id, v_s->s_ex_id.data(), v_s->s_ex_id.size() );
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
memcpy(pOut->symbol, k_s->s_symb.data(), k_s->s_symb.size() );
break;
}
}
else
{
memcpy(pOut->symbol, pIn->symbol, cSYMBOL_len);
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
co_id = v_s->s_co_id;
memcpy(exch_id, v_s->s_ex_id.data(), v_s->s_ex_id.size() );
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
const company::key k_co(co_id);
company::value v_co_temp;
try_verify_relax(tbl_company(1)->get(txn, Encode(obj_key0=str(sizeof(k_co)), k_co), obj_v=str(sizeof(v_co_temp))));
const company::value *v_co = Decode(obj_v,v_co_temp);
memcpy(pOut->co_name, v_co->co_name.data(), v_co->co_name.size() );
}
const last_trade::key k_lt(string(pOut->symbol));
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
pOut->market_price = v_lt->lt_price;
const trade_type::key k_tt(pIn->trade_type_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->type_is_market = v_tt->tt_is_mrkt;
pOut->type_is_sell = v_tt->tt_is_sell;
if( pOut->type_is_market )
{
pOut->requested_price = pOut->market_price;
}
else
pOut->requested_price = pIn->requested_price;
auto hold_qty = 0;
auto hold_price = 0.0;
auto hs_qty = 0;
auto buy_value = 0.0;
auto sell_value = 0.0;
auto needed_qty = pIn->trade_qty;
const holding_summary::key k_hs(pIn->acct_id, string(pOut->symbol));
holding_summary::value v_hs_temp;
rc_t ret;
try_catch(ret = tbl_holding_summary(1)->get(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), obj_v=str(sizeof(v_hs_temp))));
if( ret._val == RC_TRUE )
{
const holding_summary::value *v_hs = Decode(obj_v,v_hs_temp);
hs_qty = v_hs->hs_qty;
}
if( pOut->type_is_sell )
{
if( hs_qty > 0 )
{
vector<pair<int32_t, double>> hold_list;
const holding::key k_h_0( pIn->acct_id, string(pOut->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pOut->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // this set could be empty
for( auto &r_h : h_scanner.output )
{
holding::value v_h_temp;
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_list.push_back( make_pair(v_h->h_qty, v_h->h_price) );
}
if( pIn->is_lifo )
{
reverse(hold_list.begin(), hold_list.end());
}
for( auto& hold_list_cursor : hold_list )
{
if( not needed_qty )
break;
hold_qty = hold_list_cursor.first;
hold_price = hold_list_cursor.second;
if( hold_qty > needed_qty )
{
buy_value += needed_qty * hold_price;
sell_value += needed_qty * pOut->requested_price;
needed_qty = 0;
}
else
{
buy_value += hold_qty * hold_price;
sell_value += hold_qty * pOut->requested_price;
needed_qty -= hold_qty;
}
}
}
}
else
{
if( hs_qty < 0 )
{
vector<pair<int32_t, double>> hold_list;
const holding::key k_h_0( pIn->acct_id, string(pOut->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pOut->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // this set could be empty
for( auto &r_h : h_scanner.output )
{
holding::value v_h_temp;
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_list.push_back( make_pair(v_h->h_qty, v_h->h_price) );
}
if( pIn->is_lifo )
{
reverse(hold_list.begin(), hold_list.end());
}
for( auto& hold_list_cursor : hold_list )
{
if( not needed_qty )
break;
hold_qty = hold_list_cursor.first;
hold_price = hold_list_cursor.second;
if( hold_qty + needed_qty < 0 )
{
sell_value += needed_qty * hold_price;
buy_value += needed_qty * pOut->requested_price;
needed_qty = 0;
}
else
{
hold_qty -= hold_qty;
sell_value += hold_qty * hold_price;
buy_value += hold_qty * pOut->requested_price;
needed_qty -= hold_qty;
}
}
}
}
pOut->tax_amount = 0.0;
if( sell_value > buy_value and (pIn->tax_status == 1 or pIn->tax_status == 2 ))
{
const customer_taxrate::key k_cx_0( pIn->cust_id, string(cTX_ID_len, (char)0 ));
const customer_taxrate::key k_cx_1( pIn->cust_id, string(cTX_ID_len, (char)255));
table_scanner cx_scanner(&arena);
try_catch(tbl_customer_taxrate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cx_0)), k_cx_0), &Encode(obj_key1=str(sizeof(k_cx_1)), k_cx_1), cx_scanner, &arena));
ALWAYS_ASSERT( cx_scanner.output.size() );
auto tax_rates = 0.0;
for( auto &r_cx : cx_scanner.output )
{
customer_taxrate::key k_cx_temp;
const customer_taxrate::key* k_cx = Decode( *r_cx.first, k_cx_temp );
const tax_rate::key k_tx(k_cx->cx_tx_id);
tax_rate::value v_tx_temp;
try_verify_relax(tbl_tax_rate(1)->get(txn, Encode(obj_key0=str(sizeof(k_tx)), k_tx), obj_v=str(sizeof(v_tx_temp))));
const tax_rate::value *v_tx = Decode(obj_v,v_tx_temp);
tax_rates += v_tx->tx_rate;
}
pOut->tax_amount = (sell_value - buy_value) * tax_rates;
}
const commission_rate::key k_cr_0( pIn->cust_tier, string(pIn->trade_type_id), string(exch_id), 0 );
const commission_rate::key k_cr_1( pIn->cust_tier, string(pIn->trade_type_id), string(exch_id), pIn->trade_qty );
table_scanner cr_scanner(&arena);
try_catch(tbl_commission_rate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cr_0)), k_cr_0), &Encode(obj_key1=str(sizeof(k_cr_1)), k_cr_1), cr_scanner, &arena));
ALWAYS_ASSERT(cr_scanner.output.size());
for( auto &r_cr : cr_scanner.output )
{
commission_rate::value v_cr_temp;
const commission_rate::value* v_cr = Decode( *r_cr.second, v_cr_temp );
if( v_cr->cr_to_qty < pIn->trade_qty )
continue;
pOut->comm_rate = v_cr->cr_rate;
break;
}
const charge::key k_ch(pIn->trade_type_id, pIn->cust_tier );
charge::value v_ch_temp;
try_verify_relax(tbl_charge(1)->get(txn, Encode(obj_key0=str(sizeof(k_ch)), k_ch), obj_v=str(sizeof(v_ch_temp))));
const charge::value *v_ch = Decode(obj_v,v_ch_temp);
pOut->charge_amount = v_ch->ch_chrg;
double acct_bal = 0.0;
double hold_assets = 0.0;
pOut->acct_assets = 0.0;
if( pIn->type_is_margin )
{
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
acct_bal = v_ca->ca_bal;
const holding_summary::key k_hs_0( pIn->acct_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( pIn->acct_id, string(cSYMBOL_len, (char)255) );
table_scanner hs_scanner(&arena);
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
// ALWAYS_ASSERT( hs_scanner.output.size() ); // XXX. allowed?
for( auto &r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode( *r_hs.second, v_hs_temp );
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_verify_relax(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
hold_assets += v_hs->hs_qty * v_lt->lt_price;
}
if( not hold_assets )
pOut->acct_assets = acct_bal;
else
pOut->acct_assets = hold_assets + acct_bal;
}
if( pOut->type_is_market )
memcpy(pOut->status_id, pIn->st_submitted_id, cST_ID_len );
else
memcpy(pOut->status_id, pIn->st_pending_id, cST_ID_len );
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame4(const TTradeOrderFrame4Input *pIn, TTradeOrderFrame4Output *pOut)
{
auto now_dts = CDateTime().GetDate();
pOut->trade_id = GetLastTradeID();
trade::key k_t;
trade::value v_t;
k_t.t_id = pOut->trade_id;
v_t.t_dts = now_dts;
v_t.t_st_id = string(pIn->status_id);
v_t.t_tt_id = string(pIn->trade_type_id);
v_t.t_is_cash = pIn->is_cash;
v_t.t_s_symb = string(pIn->symbol);
v_t.t_qty = pIn->trade_qty;
v_t.t_bid_price = pIn->requested_price;
v_t.t_ca_id = pIn->acct_id;
v_t.t_exec_name = string(pIn->exec_name);
v_t.t_trade_price = 0;
v_t.t_chrg = pIn->charge_amount;
v_t.t_comm = pIn->comm_amount;
v_t.t_tax = 0;
v_t.t_lifo = pIn->is_lifo;
try_catch(tbl_trade(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t)), v_t)));
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t.t_ca_id;
k_t_idx1.t_dts = v_t.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t.t_st_id ;
v_t_idx1.t_tt_id = v_t.t_tt_id ;
v_t_idx1.t_is_cash = v_t.t_is_cash ;
v_t_idx1.t_s_symb = v_t.t_s_symb ;
v_t_idx1.t_qty = v_t.t_qty ;
v_t_idx1.t_bid_price = v_t.t_bid_price ;
v_t_idx1.t_exec_name = v_t.t_exec_name ;
v_t_idx1.t_trade_price = v_t.t_trade_price ;
v_t_idx1.t_chrg = v_t.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t.t_s_symb ;
k_t_idx2.t_dts = v_t.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t.t_ca_id;
v_t_idx2.t_st_id = v_t.t_st_id ;
v_t_idx2.t_tt_id = v_t.t_tt_id ;
v_t_idx2.t_is_cash = v_t.t_is_cash ;
v_t_idx2.t_qty = v_t.t_qty ;
v_t_idx2.t_exec_name = v_t.t_exec_name ;
v_t_idx2.t_trade_price = v_t.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
if( not pIn->type_is_market )
{
trade_request::key k_tr;
trade_request::value v_tr;
k_tr.tr_s_symb = string(pIn->symbol);
k_tr.tr_b_id = pIn->broker_id;
k_tr.tr_t_id = pOut->trade_id;
v_tr.tr_tt_id = string(pIn->trade_type_id);
v_tr.tr_qty = pIn->trade_qty;
v_tr.tr_bid_price = pIn->requested_price;
try_catch(tbl_trade_request(1)->insert(txn, Encode(obj_key0=str(sizeof(k_tr)), k_tr), Encode(obj_v=str(sizeof(v_tr)), v_tr)));
}
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = pOut->trade_id;
k_th.th_dts = now_dts;
k_th.th_st_id = string(pIn->status_id);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame5(void)
{
db->abort_txn(txn);
inc_ntxn_user_aborts();
return bench_worker::txn_result(false, 0);
}
bench_worker::txn_result tpce_worker::DoTradeOrderFrame6(void)
{
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame1(const TTradeResultFrame1Input *pIn, TTradeResultFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
pOut->acct_id = v_t->t_ca_id;
memcpy(pOut->type_id, v_t->t_tt_id.data(), v_t->t_tt_id.size());
memcpy(pOut->symbol, v_t->t_s_symb.data(), v_t->t_s_symb.size());
pOut->trade_qty = v_t->t_qty;
pOut->charge = v_t->t_chrg;
pOut->is_lifo = v_t->t_lifo;
pOut->trade_is_cash = v_t->t_is_cash;
pOut->num_found = 1;
const trade_type::key k_tt(pOut->type_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
memcpy(pOut->type_name, v_tt->tt_name.data(), v_tt->tt_name.size());
pOut->type_is_sell = v_tt->tt_is_sell;
pOut->type_is_market = v_tt->tt_is_mrkt;
pOut->hs_qty = 0;
const holding_summary::key k_hs(pOut->acct_id, string(pOut->symbol));
holding_summary::value v_hs_temp;
rc_t ret;
try_catch( ret = tbl_holding_summary(1)->get(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), obj_v=str(sizeof(v_hs_temp))));
if(ret._val == RC_TRUE )
{
const holding_summary::value *v_hs = Decode(obj_v,v_hs_temp);
pOut->hs_qty = v_hs->hs_qty;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame2(const TTradeResultFrame2Input *pIn, TTradeResultFrame2Output *pOut)
{
auto buy_value = 0.0;
auto sell_value = 0.0;
auto needed_qty = pIn->trade_qty;
uint64_t trade_dts = CDateTime().GetDate();
auto hold_id=0;
auto hold_price=0;
auto hold_qty=0;
CDateTime(trade_dts).GetTimeStamp(&pOut->trade_dts );
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
pOut->broker_id = v_ca->ca_b_id;
pOut->cust_id = v_ca->ca_c_id;
pOut->tax_status = v_ca->ca_tax_st;
if( pIn->type_is_sell )
{
if( pIn->hs_qty == 0 )
{
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = -1 * pIn->trade_qty;
try_catch(tbl_holding_summary(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
else
{
if( pIn->hs_qty != pIn->trade_qty )
{
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->hs_qty - pIn->trade_qty;
try_catch(tbl_holding_summary(1)->put(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
}
if( pIn->hs_qty > 0 )
{
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // guessing this could be empty set
if( pIn->is_lifo )
{
reverse(h_scanner.output.begin(), h_scanner.output.end());
}
for( auto& r_h : h_scanner.output )
{
if( needed_qty == 0 )
break;
holding::key k_h_temp;
holding::value v_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_id = k_h->h_t_id;
hold_qty = v_h->h_qty;
hold_price = v_h->h_price;
if( hold_qty > needed_qty )
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = hold_qty - needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// update with current holding cursor. use the same key
holding::key k_h_new(*k_h);
holding::value v_h_new(*v_h);
v_h_new.h_qty = hold_qty - needed_qty;
try_catch(tbl_holding(1)->put(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new), Encode(obj_v=str(sizeof(v_h_new)), v_h_new)));
buy_value += needed_qty * hold_price;
sell_value += needed_qty * pIn->trade_price;
needed_qty = 0;
}
else
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = 0;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
buy_value += hold_qty * hold_price;
sell_value += hold_qty * pIn->trade_price;
needed_qty -= hold_qty;
}
}
}
if( needed_qty > 0)
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = pIn->trade_id;
v_hh.hh_before_qty = 0;
v_hh.hh_after_qty = -1 * needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h;
holding::value v_h;
k_h.h_ca_id = pIn->acct_id;
k_h.h_s_symb = string(pIn->symbol);
k_h.h_dts = trade_dts;
k_h.h_t_id = pIn->trade_id;
v_h.h_price = pIn->trade_price;
v_h.h_qty = -1 * needed_qty;
try_catch(tbl_holding(1)->insert(txn, Encode(obj_key0=str(sizeof(k_h)), k_h), Encode(obj_v=str(sizeof(v_h)), v_h)));
}
else
{
if( pIn->hs_qty == pIn->trade_qty )
{
holding_summary::key k_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
try_catch(tbl_holding_summary(1)->remove(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs)));
// Cascade delete for FK integrity
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
for( auto& r_h : h_scanner.output )
{
holding::key k_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
}
}
}
}
else // BUY
{
if( pIn->hs_qty == 0 )
{
// HS insert
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->trade_qty;
try_catch(tbl_holding_summary(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
else if ( -1*pIn->hs_qty != pIn->trade_qty )
{
// HS update
holding_summary::key k_hs;
holding_summary::value v_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
v_hs.hs_qty = pIn->trade_qty + pIn->hs_qty;
try_catch(tbl_holding_summary(1)->put(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs), Encode(obj_v=str(sizeof(v_hs)), v_hs)));
}
if( pIn->hs_qty < 0 )
{
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
// ALWAYS_ASSERT( h_scanner.output.size() ); // XXX. guessing could be empty
if( pIn->is_lifo )
{
reverse(h_scanner.output.begin(), h_scanner.output.end());
}
// hold list cursor
for( auto& r_h : h_scanner.output )
{
if( needed_qty == 0 )
break;
holding::key k_h_temp;
holding::value v_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
const holding::value* v_h = Decode( *r_h.second, v_h_temp );
hold_id = k_h->h_t_id;
hold_qty = v_h->h_qty;
hold_price = v_h->h_price;
if( hold_qty + needed_qty < 0 )
{
// HH insert
// H update
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = hold_qty + needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// update with current holding cursor. use the same key
holding::key k_h_new(*k_h);
holding::value v_h_new(*v_h);
v_h_new.h_qty = hold_qty + needed_qty;
try_catch(tbl_holding(1)->put(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new), Encode(obj_v=str(sizeof(v_h_new)), v_h_new)));
sell_value += needed_qty * hold_price;
buy_value += needed_qty * pIn->trade_price;
needed_qty = 0;
}
else
{
// HH insert
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = hold_id;
v_hh.hh_before_qty = hold_qty;
v_hh.hh_after_qty = 0;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
// H delete
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
hold_qty *= -1;
sell_value += hold_qty * hold_price;
buy_value += hold_qty * pIn->trade_price;
needed_qty -= hold_qty;
}
}
}
if( needed_qty > 0 )
{
holding_history::key k_hh;
holding_history::value v_hh;
k_hh.hh_t_id = pIn->trade_id;
k_hh.hh_h_t_id = pIn->trade_id;
v_hh.hh_before_qty = 0;
v_hh.hh_after_qty = needed_qty;
try_catch(tbl_holding_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_hh)), k_hh), Encode(obj_v=str(sizeof(v_hh)), v_hh)));
holding::key k_h;
holding::value v_h;
k_h.h_ca_id = pIn->acct_id;
k_h.h_s_symb = string(pIn->symbol);
k_h.h_dts = trade_dts;
k_h.h_t_id = pIn->trade_id;
v_h.h_price = pIn->trade_price;
v_h.h_qty = needed_qty;
try_catch(tbl_holding(1)->insert(txn, Encode(obj_key0=str(sizeof(k_h)), k_h), Encode(obj_v=str(sizeof(v_h)), v_h)));
}
else if ( -1*pIn->hs_qty == pIn->trade_qty )
{
holding_summary::key k_hs;
k_hs.hs_ca_id = pIn->acct_id;
k_hs.hs_s_symb = string(pIn->symbol);
try_catch(tbl_holding_summary(1)->remove(txn, Encode(obj_key0=str(sizeof(k_hs)), k_hs)));
// Cascade delete for FK integrity
const holding::key k_h_0( pIn->acct_id, string(pIn->symbol), MIN_VAL(k_h_0.h_dts), MIN_VAL(k_h_0.h_t_id));
const holding::key k_h_1( pIn->acct_id, string(pIn->symbol), MAX_VAL(k_h_0.h_dts), MAX_VAL(k_h_0.h_t_id));
table_scanner h_scanner(&arena);
try_catch(tbl_holding(1)->scan(txn, Encode(obj_key0=str(sizeof(k_h_0)), k_h_0), &Encode(obj_key1=str(sizeof(k_h_1)), k_h_1), h_scanner, &arena));
for( auto& r_h : h_scanner.output )
{
holding::key k_h_temp;
const holding::key* k_h = Decode( *r_h.first, k_h_temp );
holding::key k_h_new(*k_h);
try_catch(tbl_holding(1)->remove(txn, Encode(obj_key0=str(sizeof(k_h_new)), k_h_new)));
}
}
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame3(const TTradeResultFrame3Input *pIn, TTradeResultFrame3Output *pOut)
{
const customer_taxrate::key k_cx_0( pIn->cust_id, string(cTX_ID_len, (char)0 ) );
const customer_taxrate::key k_cx_1( pIn->cust_id, string(cTX_ID_len, (char)255) );
table_scanner cx_scanner(&arena);
try_catch(tbl_customer_taxrate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cx_0)), k_cx_0), &Encode(obj_key1=str(sizeof(k_cx_1)), k_cx_1), cx_scanner, &arena));
ALWAYS_ASSERT( cx_scanner.output.size() );
double tax_rates = 0.0;
for( auto &r_cx : cx_scanner.output )
{
customer_taxrate::key k_cx_temp;
customer_taxrate::value v_cx_temp;
const customer_taxrate::key* k_cx = Decode( *r_cx.first, k_cx_temp );
const tax_rate::key k_tx(k_cx->cx_tx_id);
tax_rate::value v_tx_temp;
try_verify_relax(tbl_tax_rate(1)->get(txn, Encode(obj_key0=str(sizeof(k_tx)), k_tx), obj_v=str(sizeof(v_tx_temp))));
const tax_rate::value *v_tx = Decode(obj_v,v_tx_temp);
tax_rates += v_tx->tx_rate;
}
pOut->tax_amount = (pIn->sell_value - pIn->buy_value) * tax_rates;
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_tax = pOut->tax_amount; // secondary indices don't have t_tax field. no need for cascading update
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame4(const TTradeResultFrame4Input *pIn, TTradeResultFrame4Output *pOut)
{
const security::key k_s(string(pIn->symbol));
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
memcpy(pOut->s_name, v_s->s_name.data(), v_s->s_name.size() );
const customers::key k_c(pIn->cust_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
const commission_rate::key k_cr_0( v_c->c_tier, string(pIn->type_id), v_s->s_ex_id, 0);
const commission_rate::key k_cr_1( v_c->c_tier, string(pIn->type_id), v_s->s_ex_id, pIn->trade_qty );
table_scanner cr_scanner(&arena);
try_catch(tbl_commission_rate(1)->scan(txn, Encode(obj_key0=str(sizeof(k_cr_0)), k_cr_0), &Encode(obj_key1=str(sizeof(k_cr_1)), k_cr_1), cr_scanner, &arena));
ALWAYS_ASSERT(cr_scanner.output.size());
for( auto &r_cr : cr_scanner.output )
{
commission_rate::value v_cr_temp;
const commission_rate::value* v_cr = Decode( *r_cr.second, v_cr_temp );
if( v_cr->cr_to_qty < pIn->trade_qty )
continue;
pOut->comm_rate = v_cr->cr_rate;
break;
}
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame5(const TTradeResultFrame5Input *pIn )
{
const trade::key k_t(pIn->trade_id);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
trade::value v_t_new(*v_t);
v_t_new.t_comm = pIn->comm_amount;
v_t_new.t_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
v_t_new.t_st_id = string(pIn->st_completed_id);
v_t_new.t_trade_price = pIn->trade_price;
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
// DTS field is updated. cascading update( actually insert after remove, because dts is included in PK )
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t->t_ca_id;
k_t_idx1.t_dts = v_t->t_dts;
k_t_idx1.t_id = k_t.t_id;
try_verify_relax(tbl_t_ca_id_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1)));
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t->t_s_symb;
k_t_idx2.t_dts = v_t->t_dts;
k_t_idx2.t_id = k_t.t_id;
try_verify_relax(tbl_t_s_symb_index(1)->remove(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2)));
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->insert(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
trade_history::key k_th;
trade_history::value v_th;
k_th.th_t_id = pIn->trade_id;
k_th.th_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
k_th.th_st_id = string(pIn->st_completed_id);
try_catch(tbl_trade_history(1)->insert(txn, Encode(obj_key0=str(sizeof(k_th)), k_th), Encode(obj_v=str(sizeof(v_th)), v_th)));
const broker::key k_b(pIn->broker_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
broker::value v_b_new(*v_b);
v_b_new.b_comm_total += pIn->comm_amount;
v_b_new.b_num_trades += 1;
try_catch(tbl_broker(1)->put(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), Encode(obj_v=str(sizeof(v_b_new)), v_b_new)));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeResultFrame6(const TTradeResultFrame6Input *pIn, TTradeResultFrame6Output *pOut)
{
string cash_type;
if( pIn->trade_is_cash )
cash_type = "Cash Account";
else
cash_type = "Margin";
settlement::key k_se;
settlement::value v_se;
k_se.se_t_id = pIn->trade_id;
v_se.se_cash_type = cash_type;
v_se.se_cash_due_date = CDateTime((TIMESTAMP_STRUCT*)&pIn->due_date).GetDate();
v_se.se_amt = pIn->se_amount;
try_catch(tbl_settlement(1)->insert(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), Encode(obj_v=str(sizeof(v_se)), v_se)));
if( pIn->trade_is_cash )
{
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
customer_account::value v_ca_new(*v_ca);
v_ca_new.ca_bal += pIn->se_amount;
try_catch(tbl_customer_account(1)->put(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), Encode(obj_v=str(sizeof(v_ca_new)), v_ca_new)));
ca_id_index::key k_idx_ca;
ca_id_index::value v_idx_ca;
k_idx_ca.ca_id = k_ca.ca_id;
k_idx_ca.ca_c_id = v_ca_new.ca_c_id;
v_idx_ca.ca_bal = v_ca_new.ca_bal;
try_catch(tbl_ca_id_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_idx_ca)), k_idx_ca), Encode(obj_v=str(sizeof(v_idx_ca)), v_idx_ca)));
cash_transaction::key k_ct;
cash_transaction::value v_ct;
k_ct.ct_t_id = pIn->trade_id;
v_ct.ct_dts = CDateTime((TIMESTAMP_STRUCT*)&pIn->trade_dts).GetDate();
v_ct.ct_amt = pIn->se_amount;
v_ct.ct_name = string(pIn->type_name) + " " + to_string(pIn->trade_qty) + " shares of " + string(pIn->s_name);
try_catch(tbl_cash_transaction(1)->insert(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), Encode(obj_v=str(sizeof(v_ct)), v_ct)));
}
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
pOut->acct_bal = v_ca->ca_bal;
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeStatusFrame1(const TTradeStatusFrame1Input *pIn, TTradeStatusFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, MIN_VAL(k_t_0.t_dts), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, MAX_VAL(k_t_1.t_dts), MAX_VAL(k_t_1.t_id) );
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
int t_cursor = 0;
for( auto &r_t : t_scanner.output )
{
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
const status_type::key k_st(v_t->t_st_id);
status_type::value v_st_temp;
try_verify_relax(tbl_status_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_st)), k_st), obj_v=str(sizeof(v_st_temp))));
const status_type::value *v_st = Decode(obj_v,v_st_temp);
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
const security::key k_s(v_t->t_s_symb);
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
const exchange::key k_ex(v_s->s_ex_id);
exchange::value v_ex_temp;
try_verify_relax(tbl_exchange(1)->get(txn, Encode(obj_key0=str(sizeof(k_ex)), k_ex), obj_v=str(sizeof(v_ex_temp))));
const exchange::value *v_ex = Decode(obj_v,v_ex_temp);
pOut->trade_id[t_cursor] = k_t->t_id;
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_dts[t_cursor] );
memcpy(pOut->status_name[t_cursor], v_st->st_name.data(), v_st->st_name.size() );
memcpy(pOut->type_name[t_cursor], v_tt->tt_name.data(), v_tt->tt_name.size());
memcpy(pOut->symbol[t_cursor], v_t->t_s_symb.data(), v_t->t_s_symb.size() );
pOut->trade_qty[t_cursor] = v_t->t_qty;
memcpy(pOut->exec_name[t_cursor], v_t->t_exec_name.data(), v_t->t_exec_name.size() );
pOut->charge[t_cursor] = v_t->t_chrg;
memcpy(pOut->s_name[t_cursor], v_s->s_name.data(), v_s->s_name.size());
memcpy(pOut->ex_name[t_cursor], v_ex->ex_name.data(), v_ex->ex_name.size() );
t_cursor++;
if( t_cursor >= max_trade_status_len )
break;
}
pOut->num_found = t_cursor;
const customer_account::key k_ca(pIn->acct_id);
customer_account::value v_ca_temp;
try_verify_relax(tbl_customer_account(1)->get(txn, Encode(obj_key0=str(sizeof(k_ca)), k_ca), obj_v=str(sizeof(v_ca_temp))));
const customer_account::value *v_ca = Decode(obj_v,v_ca_temp);
const customers::key k_c(v_ca->ca_c_id);
customers::value v_c_temp;
try_verify_relax(tbl_customers(1)->get(txn, Encode(obj_key0=str(sizeof(k_c)), k_c), obj_v=str(sizeof(v_c_temp))));
const customers::value *v_c = Decode(obj_v,v_c_temp);
const broker::key k_b(v_ca->ca_b_id);
broker::value v_b_temp;
try_verify_relax(tbl_broker(1)->get(txn, Encode(obj_key0=str(sizeof(k_b)), k_b), obj_v=str(sizeof(v_b_temp))));
const broker::value *v_b = Decode(obj_v,v_b_temp);
memcpy(pOut->cust_f_name, v_c->c_f_name.data(), v_c->c_f_name.size() );
memcpy(pOut->cust_l_name, v_c->c_l_name.data(), v_c->c_l_name.size() );
memcpy(pOut->broker_name, v_b->b_name.data(), v_b->b_name.size() );
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame1(const TTradeUpdateFrame1Input *pIn, TTradeUpdateFrame1Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
for( auto i = 0; i < pIn->max_trades; i++ )
{
const trade::key k_t(pIn->trade_id[i]);
trade::value v_t_temp;
try_verify_relax(tbl_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), obj_v=str(sizeof(v_t_temp))));
const trade::value *v_t = Decode(obj_v,v_t_temp);
pOut->num_found++;
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
pOut->trade_info[i].bid_price = v_t->t_bid_price;
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].is_market = v_tt->tt_is_mrkt;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
if( pOut->num_updated < pIn->max_updates )
{
string temp_exec_name = v_t->t_exec_name.str();
size_t index = temp_exec_name.find(" X ");
if(index != string::npos){
temp_exec_name.replace(index, 3, " ");
} else {
index = temp_exec_name.find(" ");
temp_exec_name.replace(index, 3, " X ");
}
trade::value v_t_new(*v_t);
v_t_new.t_exec_name = temp_exec_name;
try_catch(tbl_trade(1)->put(txn, Encode(obj_key0=str(sizeof(k_t)), k_t), Encode(obj_v=str(sizeof(v_t_new)), v_t_new)));
t_ca_id_index::key k_t_idx1;
t_ca_id_index::value v_t_idx1;
k_t_idx1.t_ca_id = v_t_new.t_ca_id;
k_t_idx1.t_dts = v_t_new.t_dts;
k_t_idx1.t_id = k_t.t_id;
v_t_idx1.t_st_id = v_t_new.t_st_id ;
v_t_idx1.t_tt_id = v_t_new.t_tt_id ;
v_t_idx1.t_is_cash = v_t_new.t_is_cash ;
v_t_idx1.t_s_symb = v_t_new.t_s_symb ;
v_t_idx1.t_qty = v_t_new.t_qty ;
v_t_idx1.t_bid_price = v_t_new.t_bid_price ;
v_t_idx1.t_exec_name = v_t_new.t_exec_name ;
v_t_idx1.t_trade_price = v_t_new.t_trade_price ;
v_t_idx1.t_chrg = v_t_new.t_chrg ;
try_catch(tbl_t_ca_id_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_t_idx1)), k_t_idx1), Encode(obj_v=str(sizeof(v_t_idx1)), v_t_idx1)));
t_s_symb_index::key k_t_idx2;
t_s_symb_index::value v_t_idx2;
k_t_idx2.t_s_symb = v_t_new.t_s_symb ;
k_t_idx2.t_dts = v_t_new.t_dts;
k_t_idx2.t_id = k_t.t_id;
v_t_idx2.t_ca_id = v_t_new.t_ca_id;
v_t_idx2.t_st_id = v_t_new.t_st_id ;
v_t_idx2.t_tt_id = v_t_new.t_tt_id ;
v_t_idx2.t_is_cash = v_t_new.t_is_cash ;
v_t_idx2.t_qty = v_t_new.t_qty ;
v_t_idx2.t_exec_name = v_t_new.t_exec_name ;
v_t_idx2.t_trade_price = v_t_new.t_trade_price ;
try_catch(tbl_t_s_symb_index(1)->put(txn, Encode(obj_key0=str(sizeof(k_t_idx2)), k_t_idx2), Encode(obj_v=str(sizeof(v_t_idx2)), v_t_idx2)));
pOut->num_updated++;
memcpy(pOut->trade_info[i].exec_name, temp_exec_name.data(), temp_exec_name.size());
}
else
{
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
}
const settlement::key k_se(pIn->trade_id[i]);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date);
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size());
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pIn->trade_id[i]);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
const trade_history::key k_th_0( pIn->trade_id[i], string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pIn->trade_id[i], string(cST_ID_len, (char)255) , MIN_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame2(const TTradeUpdateFrame2Input *pIn, TTradeUpdateFrame2Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_ca_id_index::key k_t_0( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_ca_id_index::key k_t_1( pIn->acct_id, CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_0.t_id));
table_scanner t_scanner(&arena);
try_catch(tbl_t_ca_id_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() );
for( size_t i = 0; i < (size_t)pIn->max_trades and i < t_scanner.output.size(); i++ )
{
auto &r_t = t_scanner.output[i];
t_ca_id_index::key k_t_temp;
t_ca_id_index::value v_t_temp;
const t_ca_id_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_ca_id_index::value* v_t = Decode( *r_t.second, v_t_temp );
pOut->trade_info[i].bid_price = v_t->t_bid_price;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].trade_id= k_t->t_id;
pOut->trade_info[i].trade_price = v_t->t_trade_price;
pOut->num_found = i;
}
pOut->num_updated = 0;
for( int i = 0; i < pOut->num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
const settlement::value *v_se = Decode(obj_v,v_se_temp);
if( pOut->num_updated < pIn->max_updates )
{
settlement::value v_se_new(*v_se);
if( pOut->trade_info[i].is_cash ){
if( v_se_new.se_cash_type == "Cash Account")
v_se_new.se_cash_type = "Cash";
else
v_se_new.se_cash_type = "Cash Account";
}
else{
if( v_se_new.se_cash_type == "Margin Account")
v_se_new.se_cash_type = "Margin";
else
v_se_new.se_cash_type = "Margin Account";
}
try_catch(tbl_settlement(1)->put(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), Encode(obj_v=str(sizeof(v_se_new)), v_se_new)));
pOut->num_updated++;
}
pOut->trade_info[i].settlement_amount = v_se->se_amt;
CDateTime(v_se->se_cash_due_date).GetTimeStamp(&pOut->trade_info[i].settlement_cash_due_date);
memcpy(pOut->trade_info[i].settlement_cash_type, v_se->se_cash_type.data(), v_se->se_cash_type.size());
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoTradeUpdateFrame3(const TTradeUpdateFrame3Input *pIn, TTradeUpdateFrame3Output *pOut)
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
const t_s_symb_index::key k_t_0( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->start_trade_dts).GetDate(), MIN_VAL(k_t_0.t_id) );
const t_s_symb_index::key k_t_1( string(pIn->symbol), CDateTime((TIMESTAMP_STRUCT*)&pIn->end_trade_dts).GetDate(), MAX_VAL(k_t_0.t_id));
table_scanner t_scanner(&arena);
try_catch(tbl_t_s_symb_index(1)->scan(txn, Encode(obj_key0=str(sizeof(k_t_0)), k_t_0), &Encode(obj_key1=str(sizeof(k_t_1)), k_t_1), t_scanner, &arena));
ALWAYS_ASSERT( t_scanner.output.size() ); // XXX. short innitial trading day can make this case happening?
for( size_t i = 0; i < (size_t)pIn->max_trades and i < t_scanner.output.size() ; i++ )
{
auto &r_t = t_scanner.output[i];
t_s_symb_index::key k_t_temp;
t_s_symb_index::value v_t_temp;
const t_s_symb_index::key* k_t = Decode( *r_t.first, k_t_temp );
const t_s_symb_index::value* v_t = Decode( *r_t.second, v_t_temp );
const trade_type::key k_tt(v_t->t_tt_id);
trade_type::value v_tt_temp;
try_verify_relax(tbl_trade_type(1)->get(txn, Encode(obj_key0=str(sizeof(k_tt)), k_tt), obj_v=str(sizeof(v_tt_temp))));
const trade_type::value *v_tt = Decode(obj_v,v_tt_temp);
const security::key k_s(k_t->t_s_symb);
security::value v_s_temp;
try_verify_relax(tbl_security(1)->get(txn, Encode(obj_key0=str(sizeof(k_s)), k_s), obj_v=str(sizeof(v_s_temp))));
const security::value *v_s = Decode(obj_v,v_s_temp);
/*
acct_id[] = T_CA_ID,
exec_name[] = T_EXEC_NAME,
is_cash[] = T_IS_CASH,
price[] = T_TRADE_PRICE,
quantity[] = T_QTY,
s_name[] = S_NAME,
trade_dts[] = T_DTS,
trade_list[] = T_ID,
trade_type[] = T_TT_ID,
type_name[] = TT_NAME
*/
pOut->trade_info[i].acct_id = v_t->t_ca_id;
memcpy(pOut->trade_info[i].exec_name, v_t->t_exec_name.data(), v_t->t_exec_name.size());
pOut->trade_info[i].is_cash = v_t->t_is_cash;
pOut->trade_info[i].price = v_t->t_trade_price;
pOut->trade_info[i].quantity = v_t->t_qty;
memcpy(pOut->trade_info[i].s_name, v_s->s_name.data(), v_s->s_name.size());
CDateTime(k_t->t_dts).GetTimeStamp(&pOut->trade_info[i].trade_dts);
pOut->trade_info[i].trade_id = k_t->t_id;
memcpy(pOut->trade_info[i].trade_type, v_t->t_tt_id.data(), v_t->t_tt_id.size());
memcpy(pOut->trade_info[i].type_name, v_tt->tt_name.data(), v_tt->tt_name.size());
pOut->num_found = i;
}
pOut->num_updated = 0;
for( int i = 0; i < pOut->num_found; i++ )
{
const settlement::key k_se(pOut->trade_info[i].trade_id);
settlement::value v_se_temp;
try_verify_relax(tbl_settlement(1)->get(txn, Encode(obj_key0=str(sizeof(k_se)), k_se), obj_v=str(sizeof(v_se_temp))));
if( pOut->trade_info[i].is_cash )
{
const cash_transaction::key k_ct(pOut->trade_info[i].trade_id);
cash_transaction::value v_ct_temp;
try_verify_relax(tbl_cash_transaction(1)->get(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), obj_v=str(sizeof(v_ct_temp))));
const cash_transaction::value *v_ct = Decode(obj_v,v_ct_temp);
if( pOut->num_updated < pIn->max_updates )
{
string temp_ct_name = v_ct->ct_name.str();
size_t index = temp_ct_name.find(" shares of ");
if(index != string::npos){
stringstream ss;
ss << pOut->trade_info[i].type_name << " " << pOut->trade_info[i].quantity
<< " Shares of " << pOut->trade_info[i].s_name;
temp_ct_name = ss.str();
} else {
stringstream ss;
ss << pOut->trade_info[i].type_name << " " << pOut->trade_info[i].quantity
<< " shares of " << pOut->trade_info[i].s_name;
temp_ct_name = ss.str();
}
cash_transaction::value v_ct_new(*v_ct);
v_ct_new.ct_name = temp_ct_name;
try_catch(tbl_cash_transaction(1)->put(txn, Encode(obj_key0=str(sizeof(k_ct)), k_ct), Encode(obj_v=str(sizeof(v_ct_new)), v_ct_new)));
pOut->num_updated++;
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct_new.ct_name.data(), v_ct_new.ct_name.size());
}
else
{
memcpy(pOut->trade_info[i].cash_transaction_name, v_ct->ct_name.data(), v_ct->ct_name.size());
}
pOut->trade_info[i].cash_transaction_amount = v_ct->ct_amt;
CDateTime(v_ct->ct_dts).GetTimeStamp(&pOut->trade_info[i].cash_transaction_dts);
}
const trade_history::key k_th_0( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)0) , MIN_VAL(k_th_0.th_dts));
const trade_history::key k_th_1( pOut->trade_info[i].trade_id, string(cST_ID_len, (char)255) , MAX_VAL(k_th_0.th_dts));
table_scanner th_scanner(&arena);
try_catch(tbl_trade_history(1)->scan(txn, Encode(obj_key0=str(sizeof(k_th_0)), k_th_0), &Encode(obj_key1=str(sizeof(k_th_1)), k_th_1), th_scanner, &arena));
ALWAYS_ASSERT( th_scanner.output.size() );
for( size_t th_cursor = 0; th_cursor < 3 and th_cursor < th_scanner.output.size(); th_cursor++ )
{
auto& r_th = th_scanner.output[th_cursor];
trade_history::key k_th_temp;
const trade_history::key* k_th = Decode( *r_th.first, k_th_temp );
CDateTime(k_th->th_dts).GetTimeStamp(&pOut->trade_info[i].trade_history_dts[th_cursor]);
memcpy( pOut->trade_info[i].trade_history_status_id[th_cursor], k_th->th_st_id.data(), k_th->th_st_id.size());
}
}
try_catch(db->commit_txn(txn));
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoLongQueryFrame1()
{
txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
auto total_range = max_ca_id - min_ca_id;
auto scan_range_size = (max_ca_id - min_ca_id) / 100 * long_query_scan_range;
auto start_pos = min_ca_id + RandomNumber( r, 0, total_range - scan_range_size );
auto end_pos = start_pos + scan_range_size;
const customer_account::key k_ca_0( start_pos);
const customer_account::key k_ca_1( end_pos );
table_scanner ca_scanner(&arena);
try_catch(tbl_customer_account(1)->scan(txn, Encode(obj_key0=str(sizeof(k_ca_0)), k_ca_0), &Encode(obj_key1=str(sizeof(k_ca_1)), k_ca_1), ca_scanner, &arena));
ALWAYS_ASSERT( ca_scanner.output.size() );
auto asset = 0;
for( auto& r_ca : ca_scanner.output )
{
customer_account::key k_ca_temp;
const customer_account::key* k_ca = Decode( *r_ca.first, k_ca_temp );
const holding_summary::key k_hs_0( k_ca->ca_id, string(cSYMBOL_len, (char)0 ) );
const holding_summary::key k_hs_1( k_ca->ca_id, string(cSYMBOL_len, (char)255) );
static __thread table_scanner hs_scanner(&arena);
hs_scanner.output.clear();
try_catch(tbl_holding_summary(1)->scan(txn, Encode(obj_key0=str(sizeof(k_hs_0)), k_hs_0), &Encode(obj_key1=str(sizeof(k_hs_1)), k_hs_1), hs_scanner, &arena));
for( auto& r_hs : hs_scanner.output )
{
holding_summary::key k_hs_temp;
holding_summary::value v_hs_temp;
const holding_summary::key* k_hs = Decode( *r_hs.first, k_hs_temp );
const holding_summary::value* v_hs = Decode(*r_hs.second, v_hs_temp );
// LastTrade probe & equi-join
const last_trade::key k_lt(k_hs->hs_s_symb);
last_trade::value v_lt_temp;
try_catch(tbl_last_trade(1)->get(txn, Encode(obj_key0=str(sizeof(k_lt)), k_lt), obj_v=str(sizeof(v_lt_temp))));
const last_trade::value *v_lt = Decode(obj_v,v_lt_temp);
asset += v_hs->hs_qty * v_lt->lt_price;
}
}
assets_history::key k_ah;
assets_history::value v_ah;
k_ah.ah_id = GetLastListID();
v_ah.start_ca_id = start_pos;
v_ah.end_ca_id = start_pos;
v_ah.total_assets = asset;
try_catch(tbl_assets_history(1)->insert(txn, Encode(str(sizeof(k_ah)), k_ah), Encode(str(sizeof(v_ah)), v_ah)));
// nothing to do actually. just bothering writers.
try_catch(db->commit_txn(txn));
inc_ntxn_query_commits();
return bench_worker::txn_result(true, 0);
}
bench_worker::txn_result tpce_worker::DoDataMaintenanceFrame1(const TDataMaintenanceFrame1Input *pIn){}
bench_worker::txn_result tpce_worker::DoTradeCleanupFrame1(const TTradeCleanupFrame1Input *pIn){}
class tpce_charge_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_charge_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCharge();
bool isLast = pGenerateAndLoad->isLastCharge();
while(!isLast) {
PCHARGE_ROW record = pGenerateAndLoad->getChargeRow();
chargeBuffer.append(record);
isLast= pGenerateAndLoad->isLastCharge();
}
chargeBuffer.setMoreToRead(false);
int rows=chargeBuffer.getSize();
for(int i=0; i<rows; i++){
PCHARGE_ROW record = chargeBuffer.get(i);
charge::key k;
charge::value v;
k.ch_tt_id = string( record->CH_TT_ID );
k.ch_c_tier = record->CH_C_TIER;
v.ch_chrg = record->CH_CHRG;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_charge(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
// TODO. sanity check
// Partitioning by customer?
}
pGenerateAndLoad->ReleaseCharge();
chargeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_commission_rate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_commission_rate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCommissionRate();
bool isLast = pGenerateAndLoad->isLastCommissionRate();
while(!isLast) {
PCOMMISSION_RATE_ROW record = pGenerateAndLoad->getCommissionRateRow();
commissionRateBuffer.append(record);
isLast= pGenerateAndLoad->isLastCommissionRate();
}
commissionRateBuffer.setMoreToRead(false);
int rows=commissionRateBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMMISSION_RATE_ROW record = commissionRateBuffer.get(i);
commission_rate::key k;
commission_rate::value v;
k.cr_c_tier = record->CR_C_TIER;
k.cr_tt_id = string(record->CR_TT_ID);
k.cr_ex_id = string(record->CR_EX_ID);
k.cr_from_qty = record->CR_FROM_QTY;
v.cr_to_qty = record->CR_TO_QTY;
v.cr_rate = record->CR_RATE;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_commission_rate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseCommissionRate();
commissionRateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_exchange_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_exchange_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions)
{}
protected:
virtual void
load()
{
pGenerateAndLoad->InitExchange();
bool isLast = pGenerateAndLoad->isLastExchange();
while(!isLast) {
PEXCHANGE_ROW record = pGenerateAndLoad->getExchangeRow();
exchangeBuffer.append(record);
isLast= pGenerateAndLoad->isLastExchange();
}
exchangeBuffer.setMoreToRead(false);
int rows=exchangeBuffer.getSize();
for(int i=0; i<rows; i++){
PEXCHANGE_ROW record = exchangeBuffer.get(i);
exchange::key k;
exchange::value v;
k.ex_id = string(record->EX_ID);
v.ex_name = string(record->EX_NAME);
v.ex_num_symb = record->EX_NUM_SYMB;
v.ex_open= record->EX_OPEN;
v.ex_close= record->EX_CLOSE;
v.ex_desc = string(record->EX_DESC);
v.ex_ad_id= record->EX_AD_ID;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_exchange(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseExchange();
exchangeBuffer.release();
}
};
class tpce_industry_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_industry_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitIndustry();
bool isLast = pGenerateAndLoad->isLastIndustry();
while(!isLast) {
PINDUSTRY_ROW record = pGenerateAndLoad->getIndustryRow();
industryBuffer.append(record);
isLast= pGenerateAndLoad->isLastIndustry();
}
industryBuffer.setMoreToRead(false);
int rows=industryBuffer.getSize();
for(int i=0; i<rows; i++){
PINDUSTRY_ROW record = industryBuffer.get(i);
industry::key k_in;
industry::value v_in;
in_name_index::key k_in_idx1;
in_name_index::value v_in_idx1;
in_sc_id_index::key k_in_idx2;
in_sc_id_index::value v_in_idx2;
k_in.in_id = string(record->IN_ID);
v_in.in_name = string(record->IN_NAME);
v_in.in_sc_id = string(record->IN_SC_ID);
k_in_idx1.in_name = string(record->IN_NAME);
k_in_idx1.in_id = string(record->IN_ID);
k_in_idx2.in_sc_id = string(record->IN_SC_ID);
k_in_idx2.in_id = string(record->IN_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_industry(1)->insert(txn, Encode(str(sizeof(k_in)), k_in), Encode(str(sizeof(v_in)), v_in)));
try_verify_strict(tbl_in_name_index(1)->insert(txn, Encode(str(sizeof(k_in_idx1)), k_in_idx1), Encode(str(sizeof(v_in_idx1)), v_in_idx1)));
try_verify_strict(tbl_in_sc_id_index(1)->insert(txn, Encode(str(sizeof(k_in_idx2)), k_in_idx2), Encode(str(sizeof(v_in_idx2)), v_in_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseIndustry();
industryBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_sector_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_sector_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitSector();
bool isLast = pGenerateAndLoad->isLastSector();
while(!isLast) {
PSECTOR_ROW record = pGenerateAndLoad->getSectorRow();
sectorBuffer.append(record);
isLast= pGenerateAndLoad->isLastSector();
}
sectorBuffer.setMoreToRead(false);
int rows=sectorBuffer.getSize();
for(int i=0; i<rows; i++){
PSECTOR_ROW record = sectorBuffer.get(i);
sector::key k;
sector::value v;
k.sc_name= string(record->SC_NAME);
k.sc_id= string(record->SC_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_sector(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseSector();
sectorBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_status_type_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_status_type_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitStatusType();
bool isLast = pGenerateAndLoad->isLastStatusType();
while(!isLast) {
PSTATUS_TYPE_ROW record = pGenerateAndLoad->getStatusTypeRow();
statusTypeBuffer.append(record);
isLast= pGenerateAndLoad->isLastStatusType();
}
statusTypeBuffer.setMoreToRead(false);
int rows=statusTypeBuffer.getSize();
for(int i=0; i<rows; i++){
PSTATUS_TYPE_ROW record = statusTypeBuffer.get(i);
status_type::key k;
status_type::value v;
k.st_id = string(record->ST_ID);
v.st_name = string(record->ST_NAME );
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_status_type(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseStatusType();
statusTypeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_tax_rate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_tax_rate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitTaxrate();
bool hasNext;
do{
hasNext= pGenerateAndLoad->hasNextTaxrate();
PTAXRATE_ROW record = pGenerateAndLoad->getTaxrateRow();
taxrateBuffer.append(record);
} while(hasNext);
taxrateBuffer.setMoreToRead(false);
int rows=taxrateBuffer.getSize();
for(int i=0; i<rows; i++){
PTAXRATE_ROW record = taxrateBuffer.get(i);
tax_rate::key k;
tax_rate::value v;
k.tx_id = string(record->TX_ID);
v.tx_name = string(record->TX_NAME );
v.tx_rate = record->TX_RATE;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_tax_rate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseTaxrate();
taxrateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_trade_type_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_trade_type_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
size_t
NumOrderLinesPerCustomer()
{
return RandomNumber(r, 5, 15);
}
virtual void
load()
{
pGenerateAndLoad->InitTradeType();
bool isLast = pGenerateAndLoad->isLastTradeType();
while(!isLast) {
PTRADE_TYPE_ROW record = pGenerateAndLoad->getTradeTypeRow();
tradeTypeBuffer.append(record);
isLast= pGenerateAndLoad->isLastTradeType();
}
tradeTypeBuffer.setMoreToRead(false);
int rows=tradeTypeBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_TYPE_ROW record = tradeTypeBuffer.get(i);
trade_type::key k;
trade_type::value v;
k.tt_id = string(record->TT_ID);
v.tt_name = string(record->TT_NAME );
v.tt_is_sell = record->TT_IS_SELL;
v.tt_is_mrkt = record->TT_IS_MRKT;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade_type(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseTradeType();
tradeTypeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_zip_code_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_zip_code_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitZipCode();
bool hasNext = pGenerateAndLoad->hasNextZipCode();
while(hasNext) {
PZIP_CODE_ROW record = pGenerateAndLoad->getZipCodeRow();
zipCodeBuffer.append(record);
hasNext= pGenerateAndLoad->hasNextZipCode();
}
zipCodeBuffer.setMoreToRead(false);
int rows=zipCodeBuffer.getSize();
for(int i=0; i<rows; i++){
PZIP_CODE_ROW record = zipCodeBuffer.get(i);
zip_code::key k;
zip_code::value v;
k.zc_code = string(record->ZC_CODE);
v.zc_town = string(record->ZC_TOWN);
v.zc_div = string(record->ZC_DIV);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_zip_code(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
pGenerateAndLoad->ReleaseZipCode();
zipCodeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_address_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_address_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitAddress();
while(addressBuffer.hasMoreToRead()){
addressBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextAddress();
PADDRESS_ROW record = pGenerateAndLoad->getAddressRow();
addressBuffer.append(record);
} while((hasNext && addressBuffer.hasSpace()));
addressBuffer.setMoreToRead(hasNext);
int rows=addressBuffer.getSize();
for(int i=0; i<rows; i++){
PADDRESS_ROW record = addressBuffer.get(i);
address::key k;
address::value v;
k.ad_id = record->AD_ID;
v.ad_line1 = string(record->AD_LINE1);
v.ad_line2 = string(record->AD_LINE2);
v.ad_zc_code = string(record->AD_ZC_CODE );
v.ad_ctry = string(record->AD_CTRY );
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_address(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseAddress();
addressBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_customer_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_customer_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomer();
while(customerBuffer.hasMoreToRead()){
customerBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCustomer();
PCUSTOMER_ROW record = pGenerateAndLoad->getCustomerRow();
customerBuffer.append(record);
} while((hasNext && customerBuffer.hasSpace()));
customerBuffer.setMoreToRead(hasNext);
int rows=customerBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_ROW record = customerBuffer.get(i);
customers::key k;
customers::value v;
k.c_id = record->C_ID;
v.c_tax_id = string(record->C_TAX_ID);
v.c_st_id = string(record->C_ST_ID);
v.c_l_name = string(record->C_L_NAME);
v.c_f_name = string(record->C_F_NAME);
v.c_m_name = string(record->C_M_NAME);
v.c_gndr = record->C_GNDR;
v.c_tier = record->C_TIER;
v.c_dob = record->C_DOB.GetDate();
v.c_ad_id = record->C_AD_ID;
v.c_ctry_1 = string(record->C_CTRY_1);
v.c_area_1 = string(record->C_AREA_1);
v.c_local_1 = string(record->C_LOCAL_1);
v.c_ext_1 = string(record->C_EXT_1);
v.c_ctry_2 = string(record->C_CTRY_2);
v.c_area_2 = string(record->C_AREA_2);
v.c_local_2 = string(record->C_LOCAL_2);
v.c_ext_2 = string(record->C_EXT_2);
v.c_ctry_3 = string(record->C_CTRY_3);
v.c_area_3 = string(record->C_AREA_3);
v.c_local_3 = string(record->C_LOCAL_3);
v.c_ext_3 = string(record->C_EXT_3);
v.c_email_1 = string(record->C_EMAIL_1);
v.c_email_2 = string(record->C_EMAIL_2);
c_tax_id_index::key k_idx_tax_id;
c_tax_id_index::value v_idx_tax_id;
k_idx_tax_id.c_id = record->C_ID;
k_idx_tax_id.c_tax_id = string(record->C_TAX_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customers(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_c_tax_id_index(1)->insert(txn, Encode(str(sizeof(k_idx_tax_id)), k_idx_tax_id), Encode(str(sizeof(v_idx_tax_id)), v_idx_tax_id)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomer();
customerBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_ca_and_ap_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_ca_and_ap_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomerAccountAndAccountPermission();
while(customerAccountBuffer.hasMoreToRead()){
customerAccountBuffer.reset();
accountPermissionBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCustomerAccount();
PCUSTOMER_ACCOUNT_ROW record = pGenerateAndLoad->getCustomerAccountRow();
customerAccountBuffer.append(record);
int perms = pGenerateAndLoad->PermissionsPerCustomer();
for(int i=0; i<perms; i++) {
PACCOUNT_PERMISSION_ROW row =
pGenerateAndLoad->getAccountPermissionRow(i);
accountPermissionBuffer.append(row);
}
} while((hasNext && customerAccountBuffer.hasSpace()));
customerAccountBuffer.setMoreToRead(hasNext);
int rows=customerAccountBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_ACCOUNT_ROW record = customerAccountBuffer.get(i);
customer_account::key k;
customer_account::value v;
ca_id_index::key k_idx1;
ca_id_index::value v_idx1;
k.ca_id = record->CA_ID;
if( likely( record->CA_ID > max_ca_id ) )
max_ca_id = record->CA_ID;
if( unlikely( record->CA_ID < min_ca_id ) )
min_ca_id = record->CA_ID;
v.ca_b_id = record->CA_B_ID;
v.ca_c_id = record->CA_C_ID;
v.ca_name = string(record->CA_NAME);
v.ca_tax_st = record->CA_TAX_ST;
v.ca_bal = record->CA_BAL;
k_idx1.ca_id = record->CA_ID;
k_idx1.ca_c_id = record->CA_C_ID;
v_idx1.ca_bal = record->CA_BAL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customer_account(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_ca_id_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=customerAccountBuffer.getSize();
for(int i=0; i<rows; i++){
PACCOUNT_PERMISSION_ROW record = accountPermissionBuffer.get(i);
account_permission::key k;
account_permission::value v;
k.ap_ca_id = record->AP_CA_ID;
k.ap_tax_id = string(record->AP_TAX_ID);
v.ap_acl = string(record->AP_ACL);
v.ap_l_name = string(record->AP_L_NAME);
v.ap_f_name = string(record->AP_F_NAME);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_account_permission(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomerAccountAndAccountPermission();
customerAccountBuffer.release();
accountPermissionBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_customer_taxrate_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_customer_taxrate_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCustomerTaxrate();
while(customerTaxrateBuffer.hasMoreToRead()){
customerTaxrateBuffer.reset();
bool hasNext;
int taxrates=pGenerateAndLoad->getTaxratesCount();
do {
hasNext= pGenerateAndLoad->hasNextCustomerTaxrate();
for(int i=0; i<taxrates; i++) {
PCUSTOMER_TAXRATE_ROW record = pGenerateAndLoad->getCustomerTaxrateRow(i);
customerTaxrateBuffer.append(record);
}
} while((hasNext && customerTaxrateBuffer.hasSpace()));
customerTaxrateBuffer.setMoreToRead(hasNext);
int rows=customerTaxrateBuffer.getSize();
for(int i=0; i<rows; i++){
PCUSTOMER_TAXRATE_ROW record = customerTaxrateBuffer.get(i);
customer_taxrate::key k;
customer_taxrate::value v;
k.cx_c_id = record->CX_C_ID;
k.cx_tx_id = string(record->CX_TX_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_customer_taxrate(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCustomerTaxrate();
customerTaxrateBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_wl_and_wi_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_wl_and_wi_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitWatchListAndWatchItem();
while(watchListBuffer.hasMoreToRead()){
watchItemBuffer.reset();
watchListBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextWatchList();
PWATCH_LIST_ROW record = pGenerateAndLoad->getWatchListRow();
watchListBuffer.append(record);
int items = pGenerateAndLoad->ItemsPerWatchList();
for(int i=0; i<items; i++) {
PWATCH_ITEM_ROW row = pGenerateAndLoad->getWatchItemRow(i);
watchItemBuffer.append(row);
}
} while(hasNext && watchListBuffer.hasSpace());
watchListBuffer.setMoreToRead(hasNext);
int rows=watchListBuffer.getSize();
for(int i=0; i<rows; i++){
PWATCH_LIST_ROW record = watchListBuffer.get(i);
watch_list::key k;
watch_list::value v;
k.wl_c_id = record->WL_C_ID;
k.wl_id = record->WL_ID;
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_watch_list(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=watchItemBuffer.getSize();
for(int i=0; i<rows; i++){
PWATCH_ITEM_ROW record = watchItemBuffer.get(i);
watch_item::key k;
watch_item::value v;
k.wi_wl_id = record->WI_WL_ID;
k.wi_s_symb = record->WI_S_SYMB;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_watch_item(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseWatchListAndWatchItem();
watchItemBuffer.release();
watchListBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_company_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_company_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCompany();
while(companyBuffer.hasMoreToRead()){
companyBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCompany();
PCOMPANY_ROW record = pGenerateAndLoad->getCompanyRow();
companyBuffer.append(record);
} while((hasNext && companyBuffer.hasSpace()));
companyBuffer.setMoreToRead(hasNext);
int rows=companyBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMPANY_ROW record = companyBuffer.get(i);
company::key k;
company::value v;
co_name_index::key k_idx1;
co_name_index::value v_idx1;
co_in_id_index::key k_idx2;
co_in_id_index::value v_idx2;
k.co_id = record->CO_ID;
v.co_st_id = string(record->CO_ST_ID);
v.co_name = string(record->CO_NAME);
v.co_in_id = string(record->CO_IN_ID);
v.co_sp_rate = string(record->CO_SP_RATE);
v.co_ceo = string(record->CO_CEO);
v.co_ad_id = record->CO_AD_ID;
v.co_open_date = record->CO_OPEN_DATE.GetDate();
k_idx1.co_name = string(record->CO_NAME);
k_idx1.co_id = record->CO_ID;
k_idx2.co_in_id = string(record->CO_IN_ID);
k_idx2.co_id = record->CO_ID;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_company(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_co_name_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(tbl_co_in_id_index(1)->insert(txn, Encode(str(sizeof(k_idx2)), k_idx2), Encode(str(sizeof(v_idx2)), v_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCompany();
companyBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_company_competitor_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_company_competitor_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitCompanyCompetitor();
while(companyCompetitorBuffer.hasMoreToRead()){
companyCompetitorBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextCompanyCompetitor();
PCOMPANY_COMPETITOR_ROW record = pGenerateAndLoad->getCompanyCompetitorRow();
companyCompetitorBuffer.append(record);
} while((hasNext && companyCompetitorBuffer.hasSpace()));
companyCompetitorBuffer.setMoreToRead(hasNext);
int rows=companyCompetitorBuffer.getSize();
for(int i=0; i<rows; i++){
PCOMPANY_COMPETITOR_ROW record = companyCompetitorBuffer.get(i);
company_competitor::key k;
company_competitor::value v;
k.cp_co_id = record->CP_CO_ID;
k.cp_comp_co_id = record->CP_COMP_CO_ID;
k.cp_in_id = string(record->CP_IN_ID);
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_company_competitor(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseCompanyCompetitor();
companyCompetitorBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_daily_market_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_daily_market_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitDailyMarket();
while(dailyMarketBuffer.hasMoreToRead()){
dailyMarketBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextDailyMarket();
PDAILY_MARKET_ROW record = pGenerateAndLoad->getDailyMarketRow();
dailyMarketBuffer.append(record);
} while((hasNext && dailyMarketBuffer.hasSpace()));
dailyMarketBuffer.setMoreToRead(hasNext);
int rows=dailyMarketBuffer.getSize();
for(int i=0; i<rows; i++){
PDAILY_MARKET_ROW record = dailyMarketBuffer.get(i);
daily_market::key k;
daily_market::value v;
k.dm_s_symb = string(record->DM_S_SYMB);
k.dm_date = record->DM_DATE.GetDate();
v.dm_close = record->DM_CLOSE;
v.dm_high = record->DM_HIGH;
v.dm_low = record->DM_HIGH;
v.dm_vol = record->DM_VOL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_daily_market(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseDailyMarket();
dailyMarketBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_financial_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_financial_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitFinancial();
while(financialBuffer.hasMoreToRead()){
financialBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextFinancial();
PFINANCIAL_ROW record = pGenerateAndLoad->getFinancialRow();
financialBuffer.append(record);
} while((hasNext && financialBuffer.hasSpace()));
financialBuffer.setMoreToRead(hasNext);
int rows=financialBuffer.getSize();
for(int i=0; i<rows; i++){
PFINANCIAL_ROW record = financialBuffer.get(i);
financial::key k;
financial::value v;
k.fi_co_id = record->FI_CO_ID;
k.fi_year = record->FI_YEAR;
k.fi_qtr = record->FI_QTR;
v.fi_qtr_start_date = record->FI_QTR_START_DATE.GetDate();
v.fi_revenue = record->FI_REVENUE;
v.fi_net_earn = record->FI_NET_EARN;
v.fi_basic_eps = record->FI_BASIC_EPS;
v.fi_dilut_eps = record->FI_DILUT_EPS;
v.fi_margin = record->FI_MARGIN;
v.fi_inventory = record->FI_INVENTORY;
v.fi_assets = record->FI_ASSETS;
v.fi_liability = record->FI_LIABILITY;
v.fi_out_basic = record->FI_OUT_BASIC;
v.fi_out_dilut = record->FI_OUT_DILUT;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_financial(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseFinancial();
dailyMarketBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_last_trade_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_last_trade_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitLastTrade();
while(lastTradeBuffer.hasMoreToRead()){
lastTradeBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextLastTrade();
PLAST_TRADE_ROW record = pGenerateAndLoad->getLastTradeRow();
lastTradeBuffer.append(record);
} while((hasNext && lastTradeBuffer.hasSpace()));
lastTradeBuffer.setMoreToRead(hasNext);
int rows=lastTradeBuffer.getSize();
for(int i=0; i<rows; i++){
PLAST_TRADE_ROW record = lastTradeBuffer.get(i);
last_trade::key k;
last_trade::value v;
k.lt_s_symb = string( record->LT_S_SYMB );
v.lt_dts = record->LT_DTS.GetDate();
v.lt_price = record->LT_PRICE;
v.lt_open_price = record->LT_OPEN_PRICE;
v.lt_vol = record->LT_VOL;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_last_trade(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseLastTrade();
lastTradeBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_ni_and_nx_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_ni_and_nx_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitNewsItemAndNewsXRef();
while(newsItemBuffer.hasMoreToRead()){
newsItemBuffer.reset();
newsXRefBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextNewsItemAndNewsXRef();
PNEWS_ITEM_ROW record1 = pGenerateAndLoad->getNewsItemRow();
PNEWS_XREF_ROW record2 = pGenerateAndLoad->getNewsXRefRow();
newsItemBuffer.append(record1);
newsXRefBuffer.append(record2);
} while((hasNext && newsItemBuffer.hasSpace()));
newsItemBuffer.setMoreToRead(hasNext);
newsXRefBuffer.setMoreToRead(hasNext);
int rows=newsXRefBuffer.getSize();
for(int i=0; i<rows; i++){
PNEWS_XREF_ROW record = newsXRefBuffer.get(i);
news_xref::key k;
news_xref::value v;
k.nx_co_id = record->NX_CO_ID;
k.nx_ni_id = record->NX_NI_ID;
v.dummy = true;
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_news_xref(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=newsItemBuffer.getSize();
for(int i=0; i<rows; i++){
PNEWS_ITEM_ROW record = newsItemBuffer.get(i);
news_item::key k;
news_item::value v;
k.ni_id = record->NI_ID;
v.ni_headline = string(record->NI_HEADLINE);
v.ni_summary = string(record->NI_SUMMARY);
v.ni_item = string(record->NI_ITEM);
v.ni_dts = record->NI_DTS.GetDate();
v.ni_source = string(record->NI_SOURCE);
v.ni_author = string(record->NI_AUTHOR);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_news_item(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseNewsItemAndNewsXRef();
newsItemBuffer.release();
newsXRefBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_security_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_security_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitSecurity();
while(securityBuffer.hasMoreToRead()){
securityBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextSecurity();
PSECURITY_ROW record = pGenerateAndLoad->getSecurityRow();
securityBuffer.append(record);
} while((hasNext && securityBuffer.hasSpace()));
securityBuffer.setMoreToRead(hasNext);
int rows=securityBuffer.getSize();
for(int i=0; i<rows; i++){
PSECURITY_ROW record = securityBuffer.get(i);
security::key k;
security::value v;
security_index::key k_idx;
security_index::value v_idx;
k.s_symb = string(record->S_SYMB);
v.s_issue = string(record->S_ISSUE);
v.s_st_id = string(record->S_ST_ID);
v.s_name = string(record->S_NAME);
v.s_ex_id = string(record->S_EX_ID);
v.s_co_id = record->S_CO_ID;
v.s_num_out = record->S_NUM_OUT;
v.s_start_date = record->S_START_DATE.GetDate();
v.s_exch_date = record->S_EXCH_DATE.GetDate();
v.s_pe = record->S_PE;
v.s_52wk_high = record->S_52WK_HIGH;
v.s_52wk_high_date= record->S_52WK_HIGH_DATE.GetDate();
v.s_52wk_low = record->S_52WK_LOW;
v.s_52wk_low_date = record->S_52WK_LOW_DATE.GetDate();
v.s_dividend = record->S_DIVIDEND;
v.s_yield = record->S_YIELD;
k_idx.s_co_id = record->S_CO_ID;
k_idx.s_issue = string(record->S_ISSUE);
k_idx.s_symb = string(record->S_SYMB);
v_idx.s_name = string(record->S_NAME);
v_idx.s_ex_id = string(record->S_EX_ID);
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_security(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_security_index(1)->insert(txn, Encode(str(sizeof(k_idx)), k_idx), Encode(str(sizeof(v_idx)), v_idx)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
pGenerateAndLoad->ReleaseSecurity();
securityBuffer.release();
}
private:
ssize_t partition_id;
};
class tpce_growing_loader : public bench_loader, public tpce_worker_mixin {
public:
tpce_growing_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t partition_id)
: bench_loader(seed, db, open_tables),
tpce_worker_mixin(partitions),
partition_id(partition_id)
{
ALWAYS_ASSERT(partition_id == -1 ||
(partition_id >= 1 &&
static_cast<size_t>(partition_id) <= NumPartitions()));
}
protected:
virtual void
load()
{
pGenerateAndLoad->InitHoldingAndTrade();
do {
populate_unit_trade();
populate_broker();
populate_holding_summary();
populate_holding();
tradeBuffer.newLoadUnit();
tradeHistoryBuffer.newLoadUnit();
settlementBuffer.newLoadUnit();
cashTransactionBuffer.newLoadUnit();
holdingHistoryBuffer.newLoadUnit();
brokerBuffer.newLoadUnit();
holdingSummaryBuffer.newLoadUnit();
holdingBuffer.newLoadUnit();
} while(pGenerateAndLoad->hasNextLoadUnit());
pGenerateAndLoad->ReleaseHoldingAndTrade();
tradeBuffer.release();
tradeHistoryBuffer.release();
settlementBuffer.release();
cashTransactionBuffer.release();
holdingHistoryBuffer.release();
brokerBuffer.release();
holdingSummaryBuffer.release();
holdingBuffer.release();
}
private:
void populate_unit_trade()
{
while(tradeBuffer.hasMoreToRead()){
tradeBuffer.reset();
tradeHistoryBuffer.reset();
settlementBuffer.reset();
cashTransactionBuffer.reset();
holdingHistoryBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextTrade();
PTRADE_ROW row = pGenerateAndLoad->getTradeRow();
tradeBuffer.append(row);
int hist = pGenerateAndLoad->getTradeHistoryRowCount();
for(int i=0; i<hist; i++) {
PTRADE_HISTORY_ROW record = pGenerateAndLoad->getTradeHistoryRow(i);
tradeHistoryBuffer.append(record);
}
if(pGenerateAndLoad->shouldProcessSettlementRow()) {
PSETTLEMENT_ROW record = pGenerateAndLoad->getSettlementRow();
settlementBuffer.append(record);
}
if(pGenerateAndLoad->shouldProcessCashTransactionRow()) {
PCASH_TRANSACTION_ROW record=pGenerateAndLoad->getCashTransactionRow();
cashTransactionBuffer.append(record);
}
hist = pGenerateAndLoad->getHoldingHistoryRowCount();
for(int i=0; i<hist; i++) {
PHOLDING_HISTORY_ROW record=pGenerateAndLoad->getHoldingHistoryRow(i);
holdingHistoryBuffer.append(record);
}
} while((hasNext && tradeBuffer.hasSpace()));
tradeBuffer.setMoreToRead(hasNext);
int rows=tradeBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_ROW record = tradeBuffer.get(i);
trade::key k;
trade::value v;
k.t_id = record->T_ID ;
if( likely( record->T_ID > lastTradeId ) )
lastTradeId = record->T_ID ;
v.t_dts = record->T_DTS.GetDate();
v.t_st_id = string(record->T_ST_ID) ;
v.t_tt_id = string(record->T_TT_ID) ;
v.t_is_cash = record->T_IS_CASH ;
v.t_s_symb = string(record->T_S_SYMB);
v.t_qty = record->T_QTY ;
v.t_bid_price = record->T_BID_PRICE ;
v.t_ca_id = record->T_CA_ID ;
v.t_exec_name = string(record->T_EXEC_NAME);
v.t_trade_price = record->T_TRADE_PRICE ;
v.t_chrg = record->T_CHRG ;
v.t_comm = record->T_COMM ;
v.t_tax = record->T_TAX ;
v.t_lifo = record->T_LIFO ;
t_ca_id_index::key k_idx1;
t_ca_id_index::value v_idx1;
k_idx1.t_ca_id = record->T_CA_ID ;
k_idx1.t_dts = record->T_DTS.GetDate();
k_idx1.t_id = record->T_ID ;
v_idx1.t_st_id = string(record->T_ST_ID) ;
v_idx1.t_tt_id = string(record->T_TT_ID) ;
v_idx1.t_is_cash = record->T_IS_CASH ;
v_idx1.t_s_symb = string(record->T_S_SYMB);
v_idx1.t_qty = record->T_QTY ;
v_idx1.t_bid_price = record->T_BID_PRICE ;
v_idx1.t_exec_name = string(record->T_EXEC_NAME);
v_idx1.t_trade_price = record->T_TRADE_PRICE ;
v_idx1.t_chrg = record->T_CHRG ;
t_s_symb_index::key k_idx2;
t_s_symb_index::value v_idx2;
k_idx2.t_s_symb = string(record->T_S_SYMB);
k_idx2.t_dts = record->T_DTS.GetDate();
k_idx2.t_id = record->T_ID ;
v_idx2.t_ca_id = record->T_CA_ID ;
v_idx2.t_st_id = string(record->T_ST_ID) ;
v_idx2.t_tt_id = string(record->T_TT_ID) ;
v_idx2.t_is_cash = record->T_IS_CASH ;
v_idx2.t_qty = record->T_QTY ;
v_idx2.t_exec_name = string(record->T_EXEC_NAME);
v_idx2.t_trade_price = record->T_TRADE_PRICE ;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_t_ca_id_index(1)->insert(txn, Encode(str(sizeof(k_idx1)), k_idx1), Encode(str(sizeof(v_idx1)), v_idx1)));
try_verify_strict(tbl_t_s_symb_index(1)->insert(txn, Encode(str(sizeof(k_idx2)), k_idx2), Encode(str(sizeof(v_idx2)), v_idx2)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=tradeHistoryBuffer.getSize();
for(int i=0; i<rows; i++){
PTRADE_HISTORY_ROW record = tradeHistoryBuffer.get(i);
trade_history::key k;
trade_history::value v;
k.th_t_id = record->TH_T_ID;
k.th_dts = record->TH_DTS.GetDate();
k.th_st_id = string( record->TH_ST_ID );
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_trade_history(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=settlementBuffer.getSize();
for(int i=0; i<rows; i++){
PSETTLEMENT_ROW record = settlementBuffer.get(i);
settlement::key k;
settlement::value v;
k.se_t_id = record->SE_T_ID;
v.se_cash_type = string(record->SE_CASH_TYPE);
v.se_cash_due_date = record->SE_CASH_DUE_DATE.GetDate();
v.se_amt = record->SE_AMT;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_settlement(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=cashTransactionBuffer.getSize();
for(int i=0; i<rows; i++){
PCASH_TRANSACTION_ROW record = cashTransactionBuffer.get(i);
cash_transaction::key k;
cash_transaction::value v;
k.ct_t_id = record->CT_T_ID;
v.ct_dts = record->CT_DTS.GetDate();
v.ct_amt = record->CT_AMT;
v.ct_name = string(record->CT_NAME);
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_cash_transaction(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
rows=holdingHistoryBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_HISTORY_ROW record = holdingHistoryBuffer.get(i);
holding_history::key k;
holding_history::value v;
k.hh_t_id = record->HH_T_ID;
k.hh_h_t_id = record->HH_H_T_ID;
v.hh_before_qty = record->HH_BEFORE_QTY;
v.hh_after_qty = record->HH_AFTER_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding_history(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_broker()
{
while(brokerBuffer.hasMoreToRead()) {
brokerBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextBroker();
PBROKER_ROW record = pGenerateAndLoad->getBrokerRow();
brokerBuffer.append(record);
} while((hasNext && brokerBuffer.hasSpace()));
brokerBuffer.setMoreToRead(hasNext);
int rows=brokerBuffer.getSize();
for(int i=0; i<rows; i++){
PBROKER_ROW record = brokerBuffer.get(i);
broker::key k;
broker::value v;
b_name_index::key k_idx;
b_name_index::value v_idx;
k.b_id = record->B_ID;
v.b_st_id = string(record->B_ST_ID);
v.b_name = string(record->B_NAME);
v.b_num_trades = record->B_NUM_TRADES;
v.b_comm_total = record->B_COMM_TOTAL;
k_idx.b_name = string(record->B_NAME );
k_idx.b_id = record->B_ID;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_broker(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(tbl_b_name_index(1)->insert(txn, Encode(str(sizeof(k_idx)), k_idx), Encode(str(sizeof(v_idx)), v_idx)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_holding_summary()
{
while(holdingSummaryBuffer.hasMoreToRead()){
holdingSummaryBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextHoldingSummary();
PHOLDING_SUMMARY_ROW record = pGenerateAndLoad->getHoldingSummaryRow();
holdingSummaryBuffer.append(record);
} while((hasNext && holdingSummaryBuffer.hasSpace()));
holdingSummaryBuffer.setMoreToRead(hasNext);
int rows=holdingSummaryBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_SUMMARY_ROW record = holdingSummaryBuffer.get(i);
holding_summary::key k;
holding_summary::value v;
k.hs_ca_id = record->HS_CA_ID;
k.hs_s_symb = string(record->HS_S_SYMB);
v.hs_qty = record->HS_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding_summary(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
void populate_holding()
{
while(holdingBuffer.hasMoreToRead()){
holdingBuffer.reset();
bool hasNext;
do {
hasNext= pGenerateAndLoad->hasNextHolding();
PHOLDING_ROW record = pGenerateAndLoad->getHoldingRow();
holdingBuffer.append(record);
} while((hasNext && holdingBuffer.hasSpace()));
holdingBuffer.setMoreToRead(hasNext);
int rows=holdingBuffer.getSize();
for(int i=0; i<rows; i++){
PHOLDING_ROW record = holdingBuffer.get(i);
holding::key k;
holding::value v;
k.h_ca_id = record->H_CA_ID;
k.h_s_symb = string(record->H_S_SYMB);
k.h_dts = record->H_DTS.GetDate();
k.h_t_id = record->H_T_ID;
v.h_price = record->H_PRICE;
v.h_qty = record->H_QTY;
void* txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_DEFAULT);
try_verify_strict(tbl_holding(1)->insert(txn, Encode(str(sizeof(k)), k), Encode(str(sizeof(v)), v)));
try_verify_strict(db->commit_txn(txn));
arena.reset();
}
}
}
private:
ssize_t partition_id;
};
class tpce_bench_runner : public bench_runner {
private:
static bool
IsTableReadOnly(const char *name)
{
// TODO.
return false;
}
static bool
IsTableAppendOnly(const char *name)
{
// TODO.
return true;
}
static vector<abstract_ordered_index *>
OpenTablesForTablespace(abstract_db *db, const char *name, size_t expected_size)
{
const string s_name(name);
vector<abstract_ordered_index *> ret(NumPartitions());
abstract_ordered_index *idx = db->open_index(s_name, expected_size, false );
for (size_t i = 0; i < NumPartitions(); i++)
ret[i] = idx;
return ret;
}
public:
tpce_bench_runner(abstract_db *db)
: bench_runner(db)
{
#define OPEN_TABLESPACE_X(x) \
partitions[#x] = OpenTablesForTablespace(db, #x, sizeof(x));
TPCE_TABLE_LIST(OPEN_TABLESPACE_X);
#undef OPEN_TABLESPACE_X
for (auto &t : partitions) {
auto v = unique_filter(t.second);
for (size_t i = 0; i < v.size(); i++)
open_tables[t.first + "_" + to_string(i)] = v[i];
}
}
protected:
virtual vector<bench_loader *>
make_loaders()
{
vector<bench_loader *> ret;
// FIXME. what seed values should be passed?
ret.push_back(new tpce_charge_loader(235443, db, open_tables, partitions, -1));
ret.push_back(new tpce_commission_rate_loader(89785943, db, open_tables, partitions, -1));
ret.push_back(new tpce_exchange_loader(129856349, db, open_tables, partitions, -1));
ret.push_back(new tpce_industry_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_sector_loader(2343352, db, open_tables, partitions, -1));
ret.push_back(new tpce_status_type_loader(235443, db, open_tables, partitions, -1));
ret.push_back(new tpce_tax_rate_loader(89785943, db, open_tables, partitions, -1));
ret.push_back(new tpce_trade_type_loader(129856349, db, open_tables, partitions, -1));
ret.push_back(new tpce_zip_code_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_address_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_customer_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_ca_and_ap_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_customer_taxrate_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_wl_and_wi_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_company_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_company_competitor_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_daily_market_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_financial_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_last_trade_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_ni_and_nx_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_security_loader(923587856425, db, open_tables, partitions, -1));
ret.push_back(new tpce_growing_loader(923587856425, db, open_tables, partitions, -1));
return ret;
}
virtual vector<bench_worker *>
make_workers()
{
const unsigned alignment = coreid::num_cpus_online();
const int blockstart =
coreid::allocate_contiguous_aligned_block(nthreads, alignment);
ALWAYS_ASSERT(blockstart >= 0);
ALWAYS_ASSERT((blockstart % alignment) == 0);
fast_random r(23984543);
vector<bench_worker *> ret;
static bool const NO_PIN_WH = false;
if (NO_PIN_WH) {
for (size_t i = 0; i < nthreads; i++)
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b,
1, NumPartitions() + 1));
}
else if (NumPartitions() <= nthreads) {
for (size_t i = 0; i < nthreads; i++)
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b,
(i % NumPartitions()) + 1, (i % NumPartitions()) + 2));
} else {
auto N = NumPartitions();
auto T = nthreads;
// try this in python: [i*N//T for i in range(T+1)]
for (size_t i = 0; i < nthreads; i++) {
const unsigned wstart = i*N/T;
const unsigned wend = (i + 1)*N/T;
ret.push_back(
new tpce_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b, wstart+1, wend+1));
}
}
return ret;
}
private:
map<string, vector<abstract_ordered_index *>> partitions;
};
// Benchmark entry function
void tpce_do_test(abstract_db *db, int argc, char **argv)
{
int customers = 0;
int working_days = 0;
int scaling_factor_tpce = scale_factor;
char* egen_dir = NULL;
char sfe_str[8], wd_str[8], cust_str[8];
memset(sfe_str,0,8);
memset(wd_str,0,8);
memset(cust_str,0,8);
sprintf(sfe_str, "%d",scaling_factor_tpce);
// parse options
optind = 1;
while (1) {
static struct option long_options[] =
{
{"workload-mix" , required_argument , 0 , 'w'} ,
{"egen-dir" , required_argument , 0 , 'e'} ,
{"customers" , required_argument , 0 , 'c'} ,
{"working-days" , required_argument , 0 , 'd'} ,
{"query-range" , required_argument , 0 , 'r'} ,
{0, 0, 0, 0}
};
int option_index = 0;
int c = getopt_long(argc, argv, "r:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
if (long_options[option_index].flag != 0)
break;
abort();
break;
case 'r':
long_query_scan_range = atoi( optarg );
ALWAYS_ASSERT( long_query_scan_range >= 0 or long_query_scan_range <= 100 );
break;
case 'c':
strncpy( cust_str, optarg, 8 );
customers = atoi(cust_str );
break;
case 'd':
strncpy( wd_str, optarg, 8 );
working_days = atoi(wd_str );
break;
case 'e':
egen_dir = optarg;
break;
case 'w':
{
const vector<string> toks = split(optarg, ',');
ALWAYS_ASSERT(toks.size() == ARRAY_NELEMS(g_txn_workload_mix));
double s = 0;
for (size_t i = 0; i < toks.size(); i++) {
double p = atof(toks[i].c_str());
ALWAYS_ASSERT(p >= 0.0 && p <= 100.0);
s += p;
g_txn_workload_mix[i] = p;
}
ALWAYS_ASSERT(s == 100.0);
}
break;
case '?':
/* getopt_long already printed an error message. */
exit(1);
default:
abort();
}
}
const char * params[] = {"to_skip", "-i", egen_dir, "-l", "NULL", "-f", sfe_str, "-w", wd_str, "-c", cust_str, "-t", cust_str };
egen_init(13, (char **)params);
//Initialize Client Transaction Input generator
m_TxnInputGenerator = transactions_input_init(customers, scaling_factor_tpce , working_days);
unsigned int seed = AutoRand();
setRNGSeeds(m_TxnInputGenerator, seed);
m_CDM = data_maintenance_init(customers, scaling_factor_tpce, working_days);
//Initialize Market side
for( unsigned int i = 0; i < nthreads; i++ )
{
auto mf_buf= new MFBuffer();
auto tr_buf= new TRBuffer();
MarketFeedInputBuffers.emplace_back( mf_buf );
TradeResultInputBuffers.emplace_back( tr_buf );
auto meesut = new CMEESUT();
meesut->setMFQueue(mf_buf);
meesut->setTRQueue(tr_buf);
auto mee = market_init( working_days*8, meesut, AutoRand());
mees.emplace_back( mee );
}
if (verbose) {
cerr << "tpce settings:" << endl;
cerr << " workload_mix : " <<
format_list(g_txn_workload_mix,
g_txn_workload_mix + ARRAY_NELEMS(g_txn_workload_mix)) << endl;
cerr << " scale factor :" << " " << sfe_str << endl;
cerr << " working days :" << " " << wd_str << endl;
cerr << " customers :" << " " << cust_str << endl;
cerr << " long query scan range :" << " " << long_query_scan_range << "%" << endl;
}
tpce_bench_runner r(db);
r.run();
}
|
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
setOgreViewportDimensions(area);
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
// Now with updated code from OpenGL renderer
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
d_viewDistance = midx / (aspect * 0.267949192431123f);
const float nearZ = d_viewDistance * 0.5f;
const float farZ = d_viewDistance * 2.0f;
const float nr_sub_far = nearZ - farZ;
Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
tmp[0][0] = 3.732050808f / aspect;
tmp[0][3] = -d_viewDistance;
tmp[1][1] = -3.732050808f;
tmp[1][3] = d_viewDistance;
tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
tmp[3][2] = 1.0f;
tmp[3][3] = d_viewDistance;
d_renderSystem._convertProjectionMatrix(tmp, d_matrix);
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
MOD: Adding missing activationCounter reset
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_matrix(Ogre::Matrix4::IDENTITY),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
delete d_viewport;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
setOgreViewportDimensions(area);
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setProjectionMatrix(d_matrix);
d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);
RenderTarget::activate();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const glm::vec2& p_in,
glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.x;
in.y = p_in.y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0f;
p_out.x = static_cast<float>(r1.x - rv.x * tmp);
p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
// Now with updated code from OpenGL renderer
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
d_viewDistance = midx / (aspect * 0.267949192431123f);
const float nearZ = d_viewDistance * 0.5f;
const float farZ = d_viewDistance * 2.0f;
const float nr_sub_far = nearZ - farZ;
Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
tmp[0][0] = 3.732050808f / aspect;
tmp[0][3] = -d_viewDistance;
tmp[1][1] = -3.732050808f;
tmp[1][3] = d_viewDistance;
tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
tmp[3][2] = 1.0f;
tmp[3][3] = d_viewDistance;
d_renderSystem._convertProjectionMatrix(tmp, d_matrix);
d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
RenderTarget::d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
return d_owner;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_renderTargetUpdated(false),
#else
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_matrix(Ogre::Matrix3::ZERO),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
delete d_viewport;
#endif // CEGUI_USE_OGRE_COMPOSITOR2
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
setOgreViewportDimensions(area);
#endif
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
#endif
//----------------------------------------------------------------------------//
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
#endif
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
d_renderSystem._setViewport(d_viewport);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_owner.setProjectionMatrix(d_matrix);
d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const Vector2f& p_in,
Vector2f& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(gb.getMatrix() * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.d_x;
in.y = p_in.d_y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0;
p_out.d_x = static_cast<float>(r1.x - rv.x * tmp);
p_out.d_y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
const float aspect = w / h;
const float midx = w * 0.5f;
d_viewDistance = midx / (aspect * 0.267949192431123f);
const float nearZ = d_viewDistance * 0.5f;
const float farZ = d_viewDistance * 2.0f;
const float nr_sub_far = nearZ - farZ;
Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
tmp[0][0] = 3.732050808f / aspect;
tmp[0][3] = -d_viewDistance;
tmp[1][1] = -3.732050808f;
tmp[1][3] = d_viewDistance;
tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
tmp[3][2] = 1.0f;
tmp[3][3] = d_viewDistance;
d_renderSystem._convertProjectionMatrix(tmp, d_matrix);
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
if (!d_viewport)
{
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
Removed duplicate new lines.
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_area(0, 0, 0, 0),
d_renderTarget(0),
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_renderTargetUpdated(false),
#else
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_matrix(Ogre::Matrix3::ZERO),
d_matrixValid(false),
d_viewportValid(false),
d_viewDistance(0)
{
}
//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
delete d_viewport;
#endif // CEGUI_USE_OGRE_COMPOSITOR2
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
d_area = area;
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
setOgreViewportDimensions(area);
#endif
d_matrixValid = false;
RenderTargetEventArgs args(this);
T::fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
#endif
//----------------------------------------------------------------------------//
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
#endif
//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
if (!d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
d_renderSystem._setViewport(d_viewport);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_owner.setProjectionMatrix(d_matrix);
d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
// currently nothing to do in the basic case
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
const Vector2f& p_in,
Vector2f& p_out) const
{
if (!d_matrixValid)
updateMatrix();
const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);
const Ogre::Real midx = d_area.getWidth() * 0.5f;
const Ogre::Real midy = d_area.getHeight() * 0.5f;
// viewport matrix
const Ogre::Matrix4 vpmat(
midx, 0, 0, d_area.left() + midx,
0, -midy, 0, d_area.top() + midy,
0, 0, 1, 0,
0, 0, 0, 1
);
// matrices used for projecting and unprojecting points
const Ogre::Matrix4 proj(gb.getMatrix() * d_matrix * vpmat);
const Ogre::Matrix4 unproj(proj.inverse());
Ogre::Vector3 in;
// unproject the ends of the ray
in.x = midx;
in.y = midy;
in.z = -d_viewDistance;
const Ogre::Vector3 r1(unproj * in);
in.x = p_in.d_x;
in.y = p_in.d_y;
in.z = 0;
// calculate vector of picking ray
const Ogre::Vector3 rv(r1 - unproj * in);
// project points to orientate them with GeometryBuffer plane
in.x = 0.0;
in.y = 0.0;
const Ogre::Vector3 p1(proj * in);
in.x = 1.0;
in.y = 0.0;
const Ogre::Vector3 p2(proj * in);
in.x = 0.0;
in.y = 1.0;
const Ogre::Vector3 p3(proj * in);
// calculate the plane normal
const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
// calculate distance from origin
const Ogre::Real plen = pn.length();
const Ogre::Real dist = -(p1.x * (pn.x / plen) +
p1.y * (pn.y / plen) +
p1.z * (pn.z / plen));
// calculate intersection of ray and plane
const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
const Ogre::Real tmp = pn_dot_rv != 0.0 ?
(pn.dotProduct(r1) + dist) / pn_dot_rv :
0.0;
p_out.d_x = static_cast<float>(r1.x - rv.x * tmp);
p_out.d_y = static_cast<float>(r1.y - rv.y * tmp);
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
const float aspect = w / h;
const float midx = w * 0.5f;
d_viewDistance = midx / (aspect * 0.267949192431123f);
const float nearZ = d_viewDistance * 0.5f;
const float farZ = d_viewDistance * 2.0f;
const float nr_sub_far = nearZ - farZ;
Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
tmp[0][0] = 3.732050808f / aspect;
tmp[0][3] = -d_viewDistance;
tmp[1][1] = -3.732050808f;
tmp[1][3] = d_viewDistance;
tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
tmp[3][2] = 1.0f;
tmp[3][3] = d_viewDistance;
d_renderSystem._convertProjectionMatrix(tmp, d_matrix);
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
#if !defined(CEGUI_USE_OGRE_COMPOSITOR2)
if (!d_viewport)
{
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
#endif // CEGUI_USE_OGRE_COMPOSITOR2
d_viewportValid = true;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
|
// 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 "build/build_config.h"
#include "app/keyboard_codes.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_operation_notification_details.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
const char kTestingPage[] = "files/keyevents_test.html";
const wchar_t kSuppressEventJS[] =
L"window.domAutomationController.send(setDefaultAction('%ls', %ls));";
const wchar_t kGetResultJS[] =
L"window.domAutomationController.send(keyEventResult[%d]);";
const wchar_t kGetResultLengthJS[] =
L"window.domAutomationController.send(keyEventResult.length);";
const wchar_t kGetFocusedElementJS[] =
L"window.domAutomationController.send(focusedElement);";
const wchar_t kSetFocusedElementJS[] =
L"window.domAutomationController.send(setFocusedElement('%ls'));";
const wchar_t kGetTextBoxValueJS[] =
L"window.domAutomationController.send("
L"document.getElementById('%ls').value);";
const wchar_t kSetTextBoxValueJS[] =
L"window.domAutomationController.send("
L"document.getElementById('%ls').value = '%ls');";
const wchar_t kStartTestJS[] =
L"window.domAutomationController.send(startTest(%d));";
// Maximum lenght of the result array in KeyEventTestData structure.
const size_t kMaxResultLength = 10;
// A structure holding test data of a keyboard event.
// Each keyboard event may generate multiple result strings representing
// the result of keydown, keypress, keyup and textInput events.
// For keydown, keypress and keyup events, the format of the result string is:
// <type> <keyCode> <charCode> <ctrlKey> <shiftKey> <altKey> <commandKey>
// where <type> may be 'D' (keydown), 'P' (keypress) or 'U' (keyup).
// <ctrlKey>, <shiftKey> <altKey> and <commandKey> are boolean value indicating
// the state of corresponding modifier key.
// For textInput event, the format is: T <text>, where <text> is the text to be
// input.
// Please refer to chrome/test/data/keyevents_test.html for details.
struct KeyEventTestData {
app::KeyboardCode key;
bool ctrl;
bool shift;
bool alt;
bool command;
bool suppress_keydown;
bool suppress_keypress;
bool suppress_keyup;
bool suppress_textinput;
int result_length;
const char* const result[kMaxResultLength];
};
const wchar_t* GetBoolString(bool value) {
return value ? L"true" : L"false";
}
// A class to help wait for the finish of a key event test.
class TestFinishObserver : public NotificationObserver {
public:
explicit TestFinishObserver(RenderViewHost* render_view_host)
: finished_(false), waiting_(false) {
registrar_.Add(this, NotificationType::DOM_OPERATION_RESPONSE,
Source<RenderViewHost>(render_view_host));
}
bool WaitForFinish() {
if (!finished_) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
waiting_ = false;
}
return finished_;
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::DOM_OPERATION_RESPONSE);
Details<DomOperationNotificationDetails> dom_op_details(details);
// We might receive responses for other script execution, but we only
// care about the test finished message.
if (dom_op_details->json() == "\"FINISHED\"") {
finished_ = true;
if (waiting_)
MessageLoopForUI::current()->Quit();
}
}
private:
bool finished_;
bool waiting_;
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(TestFinishObserver);
};
class BrowserKeyEventsTest : public InProcessBrowserTest {
public:
BrowserKeyEventsTest() {
set_show_window(true);
EnableDOMAutomation();
}
void GetNativeWindow(gfx::NativeWindow* native_window) {
BrowserWindow* window = browser()->window();
ASSERT_TRUE(window);
*native_window = window->GetNativeHandle();
ASSERT_TRUE(*native_window);
}
void BringBrowserWindowToFront() {
gfx::NativeWindow window = NULL;
ASSERT_NO_FATAL_FAILURE(GetNativeWindow(&window));
ui_test_utils::ShowAndFocusNativeWindow(window);
}
void SendKey(app::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
gfx::NativeWindow window = NULL;
ASSERT_NO_FATAL_FAILURE(GetNativeWindow(&window));
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
window, key, control, shift, alt, command));
}
bool IsViewFocused(ViewID vid) {
return ui_test_utils::IsViewFocused(browser(), vid);
}
void ClickOnView(ViewID vid) {
ui_test_utils::ClickOnView(browser(), vid);
}
// Set the suppress flag of an event specified by |type|. If |suppress| is
// true then the web page will suppress all events with |type|. Following
// event types are supported: keydown, keypress, keyup and textInput.
void SuppressEventByType(int tab_index, const wchar_t* type, bool suppress) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSuppressEventJS, type, GetBoolString(!suppress)),
&actual));
ASSERT_EQ(!suppress, actual);
}
void SuppressEvents(int tab_index, bool keydown, bool keypress,
bool keyup, bool textinput) {
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keydown", keydown));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keypress", keypress));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keyup", keyup));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"textInput", textinput));
}
void SuppressAllEvents(int tab_index, bool suppress) {
SuppressEvents(tab_index, suppress, suppress, suppress, suppress);
}
void GetResultLength(int tab_index, int* length) {
ASSERT_LT(tab_index, browser()->tab_count());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", kGetResultLengthJS, length));
}
void CheckResult(int tab_index, int length, const char* const result[]) {
ASSERT_LT(tab_index, browser()->tab_count());
int actual_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(tab_index, &actual_length));
ASSERT_GE(actual_length, length);
for (int i = 0; i < actual_length; ++i) {
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", StringPrintf(kGetResultJS, i), &actual));
// If more events were received than expected, then the additional events
// must be keyup events.
if (i < length)
ASSERT_STREQ(result[i], actual.c_str());
else
ASSERT_EQ('U', actual[0]);
}
}
void CheckFocusedElement(int tab_index, const wchar_t* focused) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", kGetFocusedElementJS, &actual));
ASSERT_EQ(WideToUTF8(focused), actual);
}
void SetFocusedElement(int tab_index, const wchar_t* focused) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSetFocusedElementJS, focused),
&actual));
ASSERT_TRUE(actual);
}
void CheckTextBoxValue(int tab_index, const wchar_t* id,
const wchar_t* value) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kGetTextBoxValueJS, id),
&actual));
ASSERT_EQ(WideToUTF8(value), actual);
}
void SetTextBoxValue(int tab_index, const wchar_t* id,
const wchar_t* value) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSetTextBoxValueJS, id, value),
&actual));
ASSERT_EQ(WideToUTF8(value), actual);
}
void StartTest(int tab_index, int result_length) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", StringPrintf(kStartTestJS, result_length), &actual));
ASSERT_TRUE(actual);
}
void TestKeyEvent(int tab_index, const KeyEventTestData& test) {
ASSERT_LT(tab_index, browser()->tab_count());
ASSERT_EQ(tab_index, browser()->selected_index());
// Inform our testing web page that we are about to start testing a key
// event.
ASSERT_NO_FATAL_FAILURE(StartTest(tab_index, test.result_length));
ASSERT_NO_FATAL_FAILURE(SuppressEvents(
tab_index, test.suppress_keydown, test.suppress_keypress,
test.suppress_keyup, test.suppress_textinput));
// We need to create a finish observer before sending the key event,
// because the test finished message might be arrived before returning
// from the SendKey() method.
TestFinishObserver finish_observer(
browser()->GetTabContentsAt(tab_index)->render_view_host());
ASSERT_NO_FATAL_FAILURE(
SendKey(test.key, test.ctrl, test.shift, test.alt, test.command));
ASSERT_TRUE(finish_observer.WaitForFinish());
ASSERT_NO_FATAL_FAILURE(CheckResult(
tab_index, test.result_length, test.result));
}
std::string GetTestDataDescription(const KeyEventTestData& data) {
std::string desc = StringPrintf(
" VKEY:0x%02x, ctrl:%d, shift:%d, alt:%d, command:%d\n"
" Suppress: keydown:%d, keypress:%d, keyup:%d, textInput:%d\n"
" Expected results(%d):\n",
data.key, data.ctrl, data.shift, data.alt, data.command,
data.suppress_keydown, data.suppress_keypress, data.suppress_keyup,
data.suppress_textinput, data.result_length);
for (int i = 0; i < data.result_length; ++i) {
desc.append(" ");
desc.append(data.result[i]);
desc.append("\n");
}
return desc;
}
};
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, NormalKeyEvents) {
static const KeyEventTestData kTestNoInput[] = {
// a
{ app::VKEY_A, false, false, false, false,
false, false, false, false, 3,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"U 65 0 false false false false" } },
// shift-a
{ app::VKEY_A, false, true, false, false,
false, false, false, false, 5,
{ "D 16 0 false true false false",
"D 65 0 false true false false",
"P 65 65 false true false false",
"U 65 0 false true false false",
"U 16 0 false true false false" } },
// a, suppress keydown
{ app::VKEY_A, false, false, false, false,
true, false, false, false, 2,
{ "D 65 0 false false false false",
"U 65 0 false false false false" } },
};
static const KeyEventTestData kTestWithInput[] = {
// a
{ app::VKEY_A, false, false, false, false,
false, false, false, false, 4,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"T a",
"U 65 0 false false false false" } },
// shift-a
{ app::VKEY_A, false, true, false, false,
false, false, false, false, 6,
{ "D 16 0 false true false false",
"D 65 0 false true false false",
"P 65 65 false true false false",
"T A",
"U 65 0 false true false false",
"U 16 0 false true false false" } },
// a, suppress keydown
{ app::VKEY_A, false, false, false, false,
true, false, false, false, 2,
{ "D 65 0 false false false false",
"U 65 0 false false false false" } },
// a, suppress keypress
{ app::VKEY_A, false, false, false, false,
false, true, false, false, 3,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"U 65 0 false false false false" } },
// a, suppress textInput
{ app::VKEY_A, false, false, false, false,
false, false, false, true, 4,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"T a",
"U 65 0 false false false false" } },
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
for (size_t i = 0; i < arraysize(kTestNoInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestNoInput[i]))
<< "kTestNoInput[" << i << "] failed:\n"
<< GetTestDataDescription(kTestNoInput[i]);
}
// Input in normal text box.
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
for (size_t i = 0; i < arraysize(kTestWithInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestWithInput[i]))
<< "kTestWithInput[" << i << "] in text box failed:\n"
<< GetTestDataDescription(kTestWithInput[i]);
}
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L"aA"));
// Input in password box.
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"B"));
for (size_t i = 0; i < arraysize(kTestWithInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestWithInput[i]))
<< "kTestWithInput[" << i << "] in password box failed:\n"
<< GetTestDataDescription(kTestWithInput[i]);
}
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"B", L"aA"));
}
#if defined(OS_WIN) || defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, CtrlKeyEvents) {
static const KeyEventTestData kTestCtrlF = {
app::VKEY_F, true, false, false, false,
false, false, false, false, 2,
{ "D 17 0 true false false false",
"D 70 0 true false false false" }
};
static const KeyEventTestData kTestCtrlFSuppressKeyDown = {
app::VKEY_F, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 70 0 true false false false",
"U 70 0 true false false false",
"U 17 0 true false false false" }
};
// Ctrl+Z doesn't bind to any accelerators, which then should generate a
// keypress event with charCode=26.
static const KeyEventTestData kTestCtrlZ = {
app::VKEY_Z, true, false, false, false,
false, false, false, false, 5,
{ "D 17 0 true false false false",
"D 90 0 true false false false",
"P 26 26 true false false false",
"U 90 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlZSuppressKeyDown = {
app::VKEY_Z, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 90 0 true false false false",
"U 90 0 true false false false",
"U 17 0 true false false false" }
};
// Ctrl+Enter shall generate a keypress event with charCode=10 (LF).
static const KeyEventTestData kTestCtrlEnter = {
app::VKEY_RETURN, true, false, false, false,
false, false, false, false, 5,
{ "D 17 0 true false false false",
"D 13 0 true false false false",
"P 10 10 true false false false",
"U 13 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press Ctrl+F, which will make the Find box open and request focus.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlF));
EXPECT_TRUE(IsViewFocused(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Press Escape to close the Find box and move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(
SendKey(app::VKEY_ESCAPE, false, false, false, false));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Press Ctrl+F with keydown suppressed shall not open the find box.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlFSuppressKeyDown));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlZ));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlZSuppressKeyDown));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlEnter));
}
#elif defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, CommandKeyEvents) {
static const KeyEventTestData kTestCmdF = {
app::VKEY_F, false, false, false, true,
false, false, false, false, 2,
{ "D 91 0 false false false true",
"D 70 0 false false false true" }
};
// On Mac we don't send key up events when command modifier is down.
static const KeyEventTestData kTestCmdFSuppressKeyDown = {
app::VKEY_F, false, false, false, true,
true, false, false, false, 3,
{ "D 91 0 false false false true",
"D 70 0 false false false true",
"U 91 0 false false false true" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press Cmd+F, which will make the Find box open and request focus.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCmdF));
EXPECT_TRUE(IsViewFocused(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Press Escape to close the Find box and move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(
SendKey(app::VKEY_ESCAPE, false, false, false, false));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Press Cmd+F with keydown suppressed shall not open the find box.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCmdFSuppressKeyDown));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
}
#endif
#if defined(OS_WIN)
// Tests may fail on windows: http://crbug.com/55713
#define MAYBE_AccessKeys FLAKY_AccessKeys
#else
#define MAYBE_AccessKeys AccessKeys
#end
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, MAYBE_AccessKeys) {
#if defined(OS_MACOSX)
// On Mac, access keys use ctrl+alt modifiers.
static const KeyEventTestData kTestAccessA = {
app::VKEY_A, true, false, true, false,
false, false, false, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 65 0 true false true false",
"U 65 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestAccessDSuppress = {
app::VKEY_D, true, false, true, false,
true, true, true, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 68 0 true false true false",
"U 68 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestAccess1 = {
app::VKEY_1, true, false, true, false,
false, false, false, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 49 0 true false true false",
"U 49 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
#else
static const KeyEventTestData kTestAccessA = {
app::VKEY_A, false, false, true, false,
false, false, false, false, 4,
{ "D 18 0 false false true false",
"D 65 0 false false true false",
"U 65 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAccessD = {
app::VKEY_D, false, false, true, false,
false, false, false, false, 2,
{ "D 18 0 false false true false",
"D 68 0 false false true false" }
};
static const KeyEventTestData kTestAccessDSuppress = {
app::VKEY_D, false, false, true, false,
true, true, true, false, 4,
{ "D 18 0 false false true false",
"D 68 0 false false true false",
"U 68 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAccess1 = {
app::VKEY_1, false, false, true, false,
false, false, false, false, 4,
{ "D 18 0 false false true false",
"D 49 0 false false true false",
"U 49 0 false false true false",
"U 18 0 false false true false" }
};
#endif
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ui_test_utils::RunAllPendingInMessageLoop();
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
// Alt+A should focus the element with accesskey = "A".
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessA));
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"A"));
// Blur the focused element.
EXPECT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L""));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#if !defined(OS_MACOSX)
// Alt+D should move the focus to the location entry.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessD));
EXPECT_TRUE(IsViewFocused(VIEW_ID_LOCATION_BAR));
// No element should be focused, as Alt+D was handled by the browser.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
// Move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#endif
// If the keydown event is suppressed, then Alt+D should be handled as an
// accesskey rather than an accelerator key. Activation of an accesskey is not
// a part of the default action of the key event, so it should not be
// suppressed at all.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessDSuppress));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"D"));
// Blur the focused element.
EXPECT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L""));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccess1));
#if defined(TOOLKIT_GTK)
// On GTK, alt-0..9 are assigned as tab selection accelerators, so they can
// not be used as accesskeys.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#else
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"1"));
#endif
}
#if defined(OS_MACOSX)
// See http://crbug.com/50447 for details.
#define MAYBE_ReservedAccelerators FLAKY_ReservedAccelerators
#else
#define MAYBE_ReservedAccelerators ReservedAccelerators
#endif
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, MAYBE_ReservedAccelerators) {
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
static const KeyEventTestData kTestCtrlT = {
app::VKEY_T, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
ASSERT_EQ(1, browser()->tab_count());
// Press Ctrl+T, which will open a new tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlT));
EXPECT_EQ(2, browser()->tab_count());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
int result_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(0, &result_length));
EXPECT_EQ(1, result_length);
// Reserved accelerators can't be suppressed.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
// Press Ctrl+W, which will close the tab.
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_W, true, false, false, false));
EXPECT_EQ(1, browser()->tab_count());
#elif defined(OS_MACOSX)
static const KeyEventTestData kTestCmdT = {
app::VKEY_T, false, false, false, true,
true, false, false, false, 1,
{ "D 91 0 false false false true" }
};
ASSERT_EQ(1, browser()->tab_count());
// Press Cmd+T, which will open a new tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCmdT));
EXPECT_EQ(2, browser()->tab_count());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
int result_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(0, &result_length));
EXPECT_EQ(1, result_length);
// Reserved accelerators can't be suppressed.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
// Press Cmd+W, which will close the tab.
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_W, false, false, false, true));
EXPECT_EQ(1, browser()->tab_count());
#elif defined(TOOLKIT_GTK)
// Ctrl-[a-z] are not treated as reserved accelerators on GTK.
static const KeyEventTestData kTestCtrlT = {
app::VKEY_T, true, false, false, false,
false, false, false, false, 2,
{ "D 17 0 true false false false",
"D 84 0 true false false false" }
};
static const KeyEventTestData kTestCtrlPageDown = {
app::VKEY_NEXT, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlTab = {
app::VKEY_TAB, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlTBlocked = {
app::VKEY_T, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 84 0 true false false false",
"U 84 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlWBlocked = {
app::VKEY_W, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 87 0 true false false false",
"U 87 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_EQ(1, browser()->tab_count());
// Ctrl+T should be blockable.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlTBlocked));
ASSERT_EQ(1, browser()->tab_count());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlT));
ASSERT_EQ(2, browser()->tab_count());
ASSERT_EQ(1, browser()->selected_index());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
// Ctrl+PageDown and Ctrl+Tab switches to the next tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlPageDown));
ASSERT_EQ(1, browser()->selected_index());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlTab));
ASSERT_EQ(1, browser()->selected_index());
// Ctrl+W should be blockable.
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlWBlocked));
ASSERT_EQ(2, browser()->tab_count());
// Ctrl+F4 to close the tab.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_F4, true, false, false, false));
ASSERT_EQ(1, browser()->tab_count());
#endif
}
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, EditorKeyBindings) {
static const KeyEventTestData kTestCtrlA = {
app::VKEY_A, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 65 0 true false false false",
"U 65 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlF = {
app::VKEY_F, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 70 0 true false false false",
"U 70 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlK = {
app::VKEY_K, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 75 0 true false false false",
"U 75 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
ASSERT_NO_FATAL_FAILURE(SetTextBoxValue(tab_index, L"A", L"Hello"));
// Move the caret to the beginning of the line.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlA));
// Forward one character
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlF));
// Delete to the end of the line.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlK));
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L"H"));
}
#endif
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, PageUpDownKeys) {
static const KeyEventTestData kTestPageUp = {
app::VKEY_PRIOR, false, false, false, false,
false, false, false, false, 2,
{ "D 33 0 false false false false",
"U 33 0 false false false false" }
};
static const KeyEventTestData kTestPageDown = {
app::VKEY_NEXT, false, false, false, false,
false, false, false, false, 2,
{ "D 34 0 false false false false",
"U 34 0 false false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestPageUp));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestPageDown));
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L""));
}
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, FocusMenuBarByAltKey) {
static const KeyEventTestData kTestAltKey = {
app::VKEY_MENU, false, false, false, false,
false, false, false, false, 2,
{ "D 18 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAltKeySuppress = {
app::VKEY_MENU, false, false, false, false,
true, false, false, false, 2,
{ "D 18 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestCtrlAltKey = {
app::VKEY_MENU, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press and release Alt key to focus wrench menu button.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAltKey));
EXPECT_TRUE(IsViewFocused(VIEW_ID_APP_MENU));
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Alt key can be suppressed.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAltKeySuppress));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Ctrl+Alt should have no effect.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlAltKey));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
}
#endif
} // namespace
Fix type that broke build
TBR=suzhe@chromium.org
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@59504 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "build/build_config.h"
#include "app/keyboard_codes.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_operation_notification_details.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
const char kTestingPage[] = "files/keyevents_test.html";
const wchar_t kSuppressEventJS[] =
L"window.domAutomationController.send(setDefaultAction('%ls', %ls));";
const wchar_t kGetResultJS[] =
L"window.domAutomationController.send(keyEventResult[%d]);";
const wchar_t kGetResultLengthJS[] =
L"window.domAutomationController.send(keyEventResult.length);";
const wchar_t kGetFocusedElementJS[] =
L"window.domAutomationController.send(focusedElement);";
const wchar_t kSetFocusedElementJS[] =
L"window.domAutomationController.send(setFocusedElement('%ls'));";
const wchar_t kGetTextBoxValueJS[] =
L"window.domAutomationController.send("
L"document.getElementById('%ls').value);";
const wchar_t kSetTextBoxValueJS[] =
L"window.domAutomationController.send("
L"document.getElementById('%ls').value = '%ls');";
const wchar_t kStartTestJS[] =
L"window.domAutomationController.send(startTest(%d));";
// Maximum lenght of the result array in KeyEventTestData structure.
const size_t kMaxResultLength = 10;
// A structure holding test data of a keyboard event.
// Each keyboard event may generate multiple result strings representing
// the result of keydown, keypress, keyup and textInput events.
// For keydown, keypress and keyup events, the format of the result string is:
// <type> <keyCode> <charCode> <ctrlKey> <shiftKey> <altKey> <commandKey>
// where <type> may be 'D' (keydown), 'P' (keypress) or 'U' (keyup).
// <ctrlKey>, <shiftKey> <altKey> and <commandKey> are boolean value indicating
// the state of corresponding modifier key.
// For textInput event, the format is: T <text>, where <text> is the text to be
// input.
// Please refer to chrome/test/data/keyevents_test.html for details.
struct KeyEventTestData {
app::KeyboardCode key;
bool ctrl;
bool shift;
bool alt;
bool command;
bool suppress_keydown;
bool suppress_keypress;
bool suppress_keyup;
bool suppress_textinput;
int result_length;
const char* const result[kMaxResultLength];
};
const wchar_t* GetBoolString(bool value) {
return value ? L"true" : L"false";
}
// A class to help wait for the finish of a key event test.
class TestFinishObserver : public NotificationObserver {
public:
explicit TestFinishObserver(RenderViewHost* render_view_host)
: finished_(false), waiting_(false) {
registrar_.Add(this, NotificationType::DOM_OPERATION_RESPONSE,
Source<RenderViewHost>(render_view_host));
}
bool WaitForFinish() {
if (!finished_) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
waiting_ = false;
}
return finished_;
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::DOM_OPERATION_RESPONSE);
Details<DomOperationNotificationDetails> dom_op_details(details);
// We might receive responses for other script execution, but we only
// care about the test finished message.
if (dom_op_details->json() == "\"FINISHED\"") {
finished_ = true;
if (waiting_)
MessageLoopForUI::current()->Quit();
}
}
private:
bool finished_;
bool waiting_;
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(TestFinishObserver);
};
class BrowserKeyEventsTest : public InProcessBrowserTest {
public:
BrowserKeyEventsTest() {
set_show_window(true);
EnableDOMAutomation();
}
void GetNativeWindow(gfx::NativeWindow* native_window) {
BrowserWindow* window = browser()->window();
ASSERT_TRUE(window);
*native_window = window->GetNativeHandle();
ASSERT_TRUE(*native_window);
}
void BringBrowserWindowToFront() {
gfx::NativeWindow window = NULL;
ASSERT_NO_FATAL_FAILURE(GetNativeWindow(&window));
ui_test_utils::ShowAndFocusNativeWindow(window);
}
void SendKey(app::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
gfx::NativeWindow window = NULL;
ASSERT_NO_FATAL_FAILURE(GetNativeWindow(&window));
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
window, key, control, shift, alt, command));
}
bool IsViewFocused(ViewID vid) {
return ui_test_utils::IsViewFocused(browser(), vid);
}
void ClickOnView(ViewID vid) {
ui_test_utils::ClickOnView(browser(), vid);
}
// Set the suppress flag of an event specified by |type|. If |suppress| is
// true then the web page will suppress all events with |type|. Following
// event types are supported: keydown, keypress, keyup and textInput.
void SuppressEventByType(int tab_index, const wchar_t* type, bool suppress) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSuppressEventJS, type, GetBoolString(!suppress)),
&actual));
ASSERT_EQ(!suppress, actual);
}
void SuppressEvents(int tab_index, bool keydown, bool keypress,
bool keyup, bool textinput) {
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keydown", keydown));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keypress", keypress));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"keyup", keyup));
ASSERT_NO_FATAL_FAILURE(
SuppressEventByType(tab_index, L"textInput", textinput));
}
void SuppressAllEvents(int tab_index, bool suppress) {
SuppressEvents(tab_index, suppress, suppress, suppress, suppress);
}
void GetResultLength(int tab_index, int* length) {
ASSERT_LT(tab_index, browser()->tab_count());
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", kGetResultLengthJS, length));
}
void CheckResult(int tab_index, int length, const char* const result[]) {
ASSERT_LT(tab_index, browser()->tab_count());
int actual_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(tab_index, &actual_length));
ASSERT_GE(actual_length, length);
for (int i = 0; i < actual_length; ++i) {
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", StringPrintf(kGetResultJS, i), &actual));
// If more events were received than expected, then the additional events
// must be keyup events.
if (i < length)
ASSERT_STREQ(result[i], actual.c_str());
else
ASSERT_EQ('U', actual[0]);
}
}
void CheckFocusedElement(int tab_index, const wchar_t* focused) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", kGetFocusedElementJS, &actual));
ASSERT_EQ(WideToUTF8(focused), actual);
}
void SetFocusedElement(int tab_index, const wchar_t* focused) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSetFocusedElementJS, focused),
&actual));
ASSERT_TRUE(actual);
}
void CheckTextBoxValue(int tab_index, const wchar_t* id,
const wchar_t* value) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kGetTextBoxValueJS, id),
&actual));
ASSERT_EQ(WideToUTF8(value), actual);
}
void SetTextBoxValue(int tab_index, const wchar_t* id,
const wchar_t* value) {
ASSERT_LT(tab_index, browser()->tab_count());
std::string actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"",
StringPrintf(kSetTextBoxValueJS, id, value),
&actual));
ASSERT_EQ(WideToUTF8(value), actual);
}
void StartTest(int tab_index, int result_length) {
ASSERT_LT(tab_index, browser()->tab_count());
bool actual;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetTabContentsAt(tab_index)->render_view_host(),
L"", StringPrintf(kStartTestJS, result_length), &actual));
ASSERT_TRUE(actual);
}
void TestKeyEvent(int tab_index, const KeyEventTestData& test) {
ASSERT_LT(tab_index, browser()->tab_count());
ASSERT_EQ(tab_index, browser()->selected_index());
// Inform our testing web page that we are about to start testing a key
// event.
ASSERT_NO_FATAL_FAILURE(StartTest(tab_index, test.result_length));
ASSERT_NO_FATAL_FAILURE(SuppressEvents(
tab_index, test.suppress_keydown, test.suppress_keypress,
test.suppress_keyup, test.suppress_textinput));
// We need to create a finish observer before sending the key event,
// because the test finished message might be arrived before returning
// from the SendKey() method.
TestFinishObserver finish_observer(
browser()->GetTabContentsAt(tab_index)->render_view_host());
ASSERT_NO_FATAL_FAILURE(
SendKey(test.key, test.ctrl, test.shift, test.alt, test.command));
ASSERT_TRUE(finish_observer.WaitForFinish());
ASSERT_NO_FATAL_FAILURE(CheckResult(
tab_index, test.result_length, test.result));
}
std::string GetTestDataDescription(const KeyEventTestData& data) {
std::string desc = StringPrintf(
" VKEY:0x%02x, ctrl:%d, shift:%d, alt:%d, command:%d\n"
" Suppress: keydown:%d, keypress:%d, keyup:%d, textInput:%d\n"
" Expected results(%d):\n",
data.key, data.ctrl, data.shift, data.alt, data.command,
data.suppress_keydown, data.suppress_keypress, data.suppress_keyup,
data.suppress_textinput, data.result_length);
for (int i = 0; i < data.result_length; ++i) {
desc.append(" ");
desc.append(data.result[i]);
desc.append("\n");
}
return desc;
}
};
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, NormalKeyEvents) {
static const KeyEventTestData kTestNoInput[] = {
// a
{ app::VKEY_A, false, false, false, false,
false, false, false, false, 3,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"U 65 0 false false false false" } },
// shift-a
{ app::VKEY_A, false, true, false, false,
false, false, false, false, 5,
{ "D 16 0 false true false false",
"D 65 0 false true false false",
"P 65 65 false true false false",
"U 65 0 false true false false",
"U 16 0 false true false false" } },
// a, suppress keydown
{ app::VKEY_A, false, false, false, false,
true, false, false, false, 2,
{ "D 65 0 false false false false",
"U 65 0 false false false false" } },
};
static const KeyEventTestData kTestWithInput[] = {
// a
{ app::VKEY_A, false, false, false, false,
false, false, false, false, 4,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"T a",
"U 65 0 false false false false" } },
// shift-a
{ app::VKEY_A, false, true, false, false,
false, false, false, false, 6,
{ "D 16 0 false true false false",
"D 65 0 false true false false",
"P 65 65 false true false false",
"T A",
"U 65 0 false true false false",
"U 16 0 false true false false" } },
// a, suppress keydown
{ app::VKEY_A, false, false, false, false,
true, false, false, false, 2,
{ "D 65 0 false false false false",
"U 65 0 false false false false" } },
// a, suppress keypress
{ app::VKEY_A, false, false, false, false,
false, true, false, false, 3,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"U 65 0 false false false false" } },
// a, suppress textInput
{ app::VKEY_A, false, false, false, false,
false, false, false, true, 4,
{ "D 65 0 false false false false",
"P 97 97 false false false false",
"T a",
"U 65 0 false false false false" } },
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
for (size_t i = 0; i < arraysize(kTestNoInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestNoInput[i]))
<< "kTestNoInput[" << i << "] failed:\n"
<< GetTestDataDescription(kTestNoInput[i]);
}
// Input in normal text box.
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
for (size_t i = 0; i < arraysize(kTestWithInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestWithInput[i]))
<< "kTestWithInput[" << i << "] in text box failed:\n"
<< GetTestDataDescription(kTestWithInput[i]);
}
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L"aA"));
// Input in password box.
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"B"));
for (size_t i = 0; i < arraysize(kTestWithInput); ++i) {
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestWithInput[i]))
<< "kTestWithInput[" << i << "] in password box failed:\n"
<< GetTestDataDescription(kTestWithInput[i]);
}
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"B", L"aA"));
}
#if defined(OS_WIN) || defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, CtrlKeyEvents) {
static const KeyEventTestData kTestCtrlF = {
app::VKEY_F, true, false, false, false,
false, false, false, false, 2,
{ "D 17 0 true false false false",
"D 70 0 true false false false" }
};
static const KeyEventTestData kTestCtrlFSuppressKeyDown = {
app::VKEY_F, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 70 0 true false false false",
"U 70 0 true false false false",
"U 17 0 true false false false" }
};
// Ctrl+Z doesn't bind to any accelerators, which then should generate a
// keypress event with charCode=26.
static const KeyEventTestData kTestCtrlZ = {
app::VKEY_Z, true, false, false, false,
false, false, false, false, 5,
{ "D 17 0 true false false false",
"D 90 0 true false false false",
"P 26 26 true false false false",
"U 90 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlZSuppressKeyDown = {
app::VKEY_Z, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 90 0 true false false false",
"U 90 0 true false false false",
"U 17 0 true false false false" }
};
// Ctrl+Enter shall generate a keypress event with charCode=10 (LF).
static const KeyEventTestData kTestCtrlEnter = {
app::VKEY_RETURN, true, false, false, false,
false, false, false, false, 5,
{ "D 17 0 true false false false",
"D 13 0 true false false false",
"P 10 10 true false false false",
"U 13 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press Ctrl+F, which will make the Find box open and request focus.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlF));
EXPECT_TRUE(IsViewFocused(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Press Escape to close the Find box and move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(
SendKey(app::VKEY_ESCAPE, false, false, false, false));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Press Ctrl+F with keydown suppressed shall not open the find box.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlFSuppressKeyDown));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlZ));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlZSuppressKeyDown));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlEnter));
}
#elif defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, CommandKeyEvents) {
static const KeyEventTestData kTestCmdF = {
app::VKEY_F, false, false, false, true,
false, false, false, false, 2,
{ "D 91 0 false false false true",
"D 70 0 false false false true" }
};
// On Mac we don't send key up events when command modifier is down.
static const KeyEventTestData kTestCmdFSuppressKeyDown = {
app::VKEY_F, false, false, false, true,
true, false, false, false, 3,
{ "D 91 0 false false false true",
"D 70 0 false false false true",
"U 91 0 false false false true" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press Cmd+F, which will make the Find box open and request focus.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCmdF));
EXPECT_TRUE(IsViewFocused(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Press Escape to close the Find box and move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(
SendKey(app::VKEY_ESCAPE, false, false, false, false));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Press Cmd+F with keydown suppressed shall not open the find box.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCmdFSuppressKeyDown));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
}
#endif
#if defined(OS_WIN)
// Tests may fail on windows: http://crbug.com/55713
#define MAYBE_AccessKeys FLAKY_AccessKeys
#else
#define MAYBE_AccessKeys AccessKeys
#endif
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, MAYBE_AccessKeys) {
#if defined(OS_MACOSX)
// On Mac, access keys use ctrl+alt modifiers.
static const KeyEventTestData kTestAccessA = {
app::VKEY_A, true, false, true, false,
false, false, false, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 65 0 true false true false",
"U 65 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestAccessDSuppress = {
app::VKEY_D, true, false, true, false,
true, true, true, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 68 0 true false true false",
"U 68 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestAccess1 = {
app::VKEY_1, true, false, true, false,
false, false, false, false, 6,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"D 49 0 true false true false",
"U 49 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
#else
static const KeyEventTestData kTestAccessA = {
app::VKEY_A, false, false, true, false,
false, false, false, false, 4,
{ "D 18 0 false false true false",
"D 65 0 false false true false",
"U 65 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAccessD = {
app::VKEY_D, false, false, true, false,
false, false, false, false, 2,
{ "D 18 0 false false true false",
"D 68 0 false false true false" }
};
static const KeyEventTestData kTestAccessDSuppress = {
app::VKEY_D, false, false, true, false,
true, true, true, false, 4,
{ "D 18 0 false false true false",
"D 68 0 false false true false",
"U 68 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAccess1 = {
app::VKEY_1, false, false, true, false,
false, false, false, false, 4,
{ "D 18 0 false false true false",
"D 49 0 false false true false",
"U 49 0 false false true false",
"U 18 0 false false true false" }
};
#endif
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ui_test_utils::RunAllPendingInMessageLoop();
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
// Alt+A should focus the element with accesskey = "A".
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessA));
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"A"));
// Blur the focused element.
EXPECT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L""));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#if !defined(OS_MACOSX)
// Alt+D should move the focus to the location entry.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessD));
EXPECT_TRUE(IsViewFocused(VIEW_ID_LOCATION_BAR));
// No element should be focused, as Alt+D was handled by the browser.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
// Move the focus back to the web page.
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#endif
// If the keydown event is suppressed, then Alt+D should be handled as an
// accesskey rather than an accelerator key. Activation of an accesskey is not
// a part of the default action of the key event, so it should not be
// suppressed at all.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccessDSuppress));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"D"));
// Blur the focused element.
EXPECT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L""));
// Make sure no element is focused.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAccess1));
#if defined(TOOLKIT_GTK)
// On GTK, alt-0..9 are assigned as tab selection accelerators, so they can
// not be used as accesskeys.
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L""));
#else
EXPECT_NO_FATAL_FAILURE(CheckFocusedElement(tab_index, L"1"));
#endif
}
#if defined(OS_MACOSX)
// See http://crbug.com/50447 for details.
#define MAYBE_ReservedAccelerators FLAKY_ReservedAccelerators
#else
#define MAYBE_ReservedAccelerators ReservedAccelerators
#endif
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, MAYBE_ReservedAccelerators) {
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
static const KeyEventTestData kTestCtrlT = {
app::VKEY_T, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
ASSERT_EQ(1, browser()->tab_count());
// Press Ctrl+T, which will open a new tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlT));
EXPECT_EQ(2, browser()->tab_count());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
int result_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(0, &result_length));
EXPECT_EQ(1, result_length);
// Reserved accelerators can't be suppressed.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
// Press Ctrl+W, which will close the tab.
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_W, true, false, false, false));
EXPECT_EQ(1, browser()->tab_count());
#elif defined(OS_MACOSX)
static const KeyEventTestData kTestCmdT = {
app::VKEY_T, false, false, false, true,
true, false, false, false, 1,
{ "D 91 0 false false false true" }
};
ASSERT_EQ(1, browser()->tab_count());
// Press Cmd+T, which will open a new tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCmdT));
EXPECT_EQ(2, browser()->tab_count());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
int result_length;
ASSERT_NO_FATAL_FAILURE(GetResultLength(0, &result_length));
EXPECT_EQ(1, result_length);
// Reserved accelerators can't be suppressed.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
// Press Cmd+W, which will close the tab.
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_W, false, false, false, true));
EXPECT_EQ(1, browser()->tab_count());
#elif defined(TOOLKIT_GTK)
// Ctrl-[a-z] are not treated as reserved accelerators on GTK.
static const KeyEventTestData kTestCtrlT = {
app::VKEY_T, true, false, false, false,
false, false, false, false, 2,
{ "D 17 0 true false false false",
"D 84 0 true false false false" }
};
static const KeyEventTestData kTestCtrlPageDown = {
app::VKEY_NEXT, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlTab = {
app::VKEY_TAB, true, false, false, false,
true, false, false, false, 1,
{ "D 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlTBlocked = {
app::VKEY_T, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 84 0 true false false false",
"U 84 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlWBlocked = {
app::VKEY_W, true, false, false, false,
true, false, false, false, 4,
{ "D 17 0 true false false false",
"D 87 0 true false false false",
"U 87 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_EQ(1, browser()->tab_count());
// Ctrl+T should be blockable.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlTBlocked));
ASSERT_EQ(1, browser()->tab_count());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlT));
ASSERT_EQ(2, browser()->tab_count());
ASSERT_EQ(1, browser()->selected_index());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
// Ctrl+PageDown and Ctrl+Tab switches to the next tab.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlPageDown));
ASSERT_EQ(1, browser()->selected_index());
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlTab));
ASSERT_EQ(1, browser()->selected_index());
// Ctrl+W should be blockable.
browser()->SelectNumberedTab(0);
ASSERT_EQ(0, browser()->selected_index());
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(0, kTestCtrlWBlocked));
ASSERT_EQ(2, browser()->tab_count());
// Ctrl+F4 to close the tab.
ASSERT_NO_FATAL_FAILURE(SuppressAllEvents(0, true));
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_F4, true, false, false, false));
ASSERT_EQ(1, browser()->tab_count());
#endif
}
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, EditorKeyBindings) {
static const KeyEventTestData kTestCtrlA = {
app::VKEY_A, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 65 0 true false false false",
"U 65 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlF = {
app::VKEY_F, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 70 0 true false false false",
"U 70 0 true false false false",
"U 17 0 true false false false" }
};
static const KeyEventTestData kTestCtrlK = {
app::VKEY_K, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 75 0 true false false false",
"U 75 0 true false false false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
ASSERT_NO_FATAL_FAILURE(SetTextBoxValue(tab_index, L"A", L"Hello"));
// Move the caret to the beginning of the line.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlA));
// Forward one character
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlF));
// Delete to the end of the line.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlK));
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L"H"));
}
#endif
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, PageUpDownKeys) {
static const KeyEventTestData kTestPageUp = {
app::VKEY_PRIOR, false, false, false, false,
false, false, false, false, 2,
{ "D 33 0 false false false false",
"U 33 0 false false false false" }
};
static const KeyEventTestData kTestPageDown = {
app::VKEY_NEXT, false, false, false, false,
false, false, false, false, 2,
{ "D 34 0 false false false false",
"U 34 0 false false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
ASSERT_NO_FATAL_FAILURE(SetFocusedElement(tab_index, L"A"));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestPageUp));
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestPageDown));
EXPECT_NO_FATAL_FAILURE(CheckTextBoxValue(tab_index, L"A", L""));
}
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
IN_PROC_BROWSER_TEST_F(BrowserKeyEventsTest, FocusMenuBarByAltKey) {
static const KeyEventTestData kTestAltKey = {
app::VKEY_MENU, false, false, false, false,
false, false, false, false, 2,
{ "D 18 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestAltKeySuppress = {
app::VKEY_MENU, false, false, false, false,
true, false, false, false, 2,
{ "D 18 0 false false true false",
"U 18 0 false false true false" }
};
static const KeyEventTestData kTestCtrlAltKey = {
app::VKEY_MENU, true, false, false, false,
false, false, false, false, 4,
{ "D 17 0 true false false false",
"D 18 0 true false true false",
"U 18 0 true false true false",
"U 17 0 true false false false" }
};
ASSERT_TRUE(test_server()->Start());
BringBrowserWindowToFront();
GURL url = test_server()->GetURL(kTestingPage);
ui_test_utils::NavigateToURL(browser(), url);
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
int tab_index = browser()->selected_index();
// Press and release Alt key to focus wrench menu button.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAltKey));
EXPECT_TRUE(IsViewFocused(VIEW_ID_APP_MENU));
ASSERT_NO_FATAL_FAILURE(ClickOnView(VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Alt key can be suppressed.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestAltKeySuppress));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Ctrl+Alt should have no effect.
EXPECT_NO_FATAL_FAILURE(TestKeyEvent(tab_index, kTestCtrlAltKey));
ASSERT_TRUE(IsViewFocused(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
}
#endif
} // namespace
|
#include <iostream>
/**
* Exercise that (I) changes the value of a pointer and (II) changes the value
* to which the pointer points.
*/
int main ()
{
int i1 = 1;
int i2 = 1;
int *p = &i1;
std::cout << "p = " << p << " *p = " << *p << std::endl;
std::cout << "Let's change p by pointing somewhere else." << std::endl;
p = &i2;
std::cout << "p = " << p << " *p = " << *p << std::endl;
std::cout << "Let's change the value of what p points at." << std::endl;
*p = 2;
std::cout << "p = " << p << " *p = " << *p << std::endl;
return 0;
}
Committing exercise 2.18.
#include <iostream>
/**
* Exercise that (I) changes the value of a pointer and (II) changes the value
* to which the pointer points.
*/
int main ()
{
int i1 = 1;
int i2 = 1;
int* p = &i1;
std::cout << "p = " << p << " *p = " << *p << std::endl;
std::cout << "Let's change p by pointing somewhere else." << std::endl;
p = &i2;
std::cout << "p = " << p << " *p = " << *p << std::endl;
std::cout << "Let's change the value of what p points at." << std::endl;
*p = 2;
std::cout << "p = " << p << " *p = " << *p << std::endl;
return 0;
}
|
// 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/chromeos/cros/network_library.h"
#include <algorithm>
#include <map>
#include "base/i18n/time_formatting.h"
#include "base/metrics/histogram.h"
#include "base/stl_util-inl.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/network_login_observer.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/common/time_format.h"
#include "content/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
////////////////////////////////////////////////////////////////////////////////
// Implementation notes.
// NetworkLibraryImpl manages a series of classes that describe network devices
// and services:
//
// NetworkDevice: e.g. ethernet, wifi modem, cellular modem
// device_map_: canonical map<name,NetworkDevice*> for devices
//
// Network: a network service ("network").
// network_map_: canonical map<name,Network*> for all visible networks.
// EthernetNetwork
// ethernet_: EthernetNetwork* to the active ethernet network in network_map_.
// WirelessNetwork: a Wifi or Cellular Network.
// WifiNetwork
// active_wifi_: WifiNetwork* to the active wifi network in network_map_.
// wifi_networks_: ordered vector of WifiNetwork* entries in network_map_,
// in descending order of importance.
// CellularNetwork
// active_cellular_: Cellular version of wifi_.
// cellular_networks_: Cellular version of wifi_.
// remembered_network_map_: a canonical map<name,Network*> for all networks
// remembered in the active Profile ("favorites").
// remembered_wifi_networks_: ordered vector of WifiNetwork* entries in
// remembered_network_map_, in descending order of preference.
//
// network_manager_monitor_: a handle to the libcros network Manager handler.
// NetworkManagerStatusChanged: This handles all messages from the Manager.
// Messages are parsed here and the appropriate updates are then requested.
//
// UpdateNetworkServiceList: This is the primary Manager handler. It handles
// the "Services" message which list all visible networks. The handler
// rebuilds the network lists without destroying existing Network structures,
// then requests neccessary updates to be fetched asynchronously from
// libcros (RequestNetworkServiceInfo).
//
// TODO(stevenjb): Document cellular data plan handlers.
//
// AddNetworkObserver: Adds an observer for a specific network.
// NetworkObserverList: A monitor and list of observers of a network.
// network_monitor_: a handle to the libcros network Service handler.
// UpdateNetworkStatus: This handles changes to a monitored service, typically
// changes to transient states like Strength. (Note: also updates State).
//
////////////////////////////////////////////////////////////////////////////////
namespace chromeos {
// Local constants.
namespace {
// Only send network change notifications to observers once every 50ms.
const int kNetworkNotifyDelayMs = 50;
// How long we should remember that cellular plan payment was received.
const int kRecentPlanPaymentHours = 6;
// D-Bus interface string constants.
// Flimflam property names.
const char* kSecurityProperty = "Security";
const char* kPassphraseProperty = "Passphrase";
const char* kIdentityProperty = "Identity";
const char* kCertPathProperty = "CertPath";
const char* kPassphraseRequiredProperty = "PassphraseRequired";
const char* kProfilesProperty = "Profiles";
const char* kServicesProperty = "Services";
const char* kServiceWatchListProperty = "ServiceWatchList";
const char* kAvailableTechnologiesProperty = "AvailableTechnologies";
const char* kEnabledTechnologiesProperty = "EnabledTechnologies";
const char* kConnectedTechnologiesProperty = "ConnectedTechnologies";
const char* kDefaultTechnologyProperty = "DefaultTechnology";
const char* kOfflineModeProperty = "OfflineMode";
const char* kSignalStrengthProperty = "Strength";
const char* kNameProperty = "Name";
const char* kStateProperty = "State";
const char* kConnectivityStateProperty = "ConnectivityState";
const char* kTypeProperty = "Type";
const char* kDeviceProperty = "Device";
const char* kActivationStateProperty = "Cellular.ActivationState";
const char* kNetworkTechnologyProperty = "Cellular.NetworkTechnology";
const char* kRoamingStateProperty = "Cellular.RoamingState";
const char* kOperatorNameProperty = "Cellular.OperatorName";
const char* kOperatorCodeProperty = "Cellular.OperatorCode";
const char* kPaymentURLProperty = "Cellular.OlpUrl";
const char* kUsageURLProperty = "Cellular.UsageUrl";
const char* kFavoriteProperty = "Favorite";
const char* kConnectableProperty = "Connectable";
const char* kAutoConnectProperty = "AutoConnect";
const char* kIsActiveProperty = "IsActive";
const char* kModeProperty = "Mode";
const char* kErrorProperty = "Error";
const char* kActiveProfileProperty = "ActiveProfile";
const char* kEntriesProperty = "Entries";
const char* kDevicesProperty = "Devices";
// Flimflam device info property names.
const char* kScanningProperty = "Scanning";
const char* kCarrierProperty = "Cellular.Carrier";
const char* kMeidProperty = "Cellular.MEID";
const char* kImeiProperty = "Cellular.IMEI";
const char* kImsiProperty = "Cellular.IMSI";
const char* kEsnProperty = "Cellular.ESN";
const char* kMdnProperty = "Cellular.MDN";
const char* kMinProperty = "Cellular.MIN";
const char* kModelIDProperty = "Cellular.ModelID";
const char* kManufacturerProperty = "Cellular.Manufacturer";
const char* kFirmwareRevisionProperty = "Cellular.FirmwareRevision";
const char* kHardwareRevisionProperty = "Cellular.HardwareRevision";
const char* kLastDeviceUpdateProperty = "Cellular.LastDeviceUpdate";
const char* kPRLVersionProperty = "Cellular.PRLVersion"; // (INT16)
// Flimflam type options.
const char* kTypeEthernet = "ethernet";
const char* kTypeWifi = "wifi";
const char* kTypeWimax = "wimax";
const char* kTypeBluetooth = "bluetooth";
const char* kTypeCellular = "cellular";
const char* kTypeVPN = "vpn";
// Flimflam mode options.
const char* kModeManaged = "managed";
const char* kModeAdhoc = "adhoc";
// Flimflam security options.
const char* kSecurityWpa = "wpa";
const char* kSecurityWep = "wep";
const char* kSecurityRsn = "rsn";
const char* kSecurity8021x = "802_1x";
const char* kSecurityNone = "none";
// Flimflam EAP property names.
const char* kEapIdentityProperty = "EAP.Identity";
const char* kEapMethodProperty = "EAP.EAP";
const char* kEapPhase2AuthProperty = "EAP.InnerEAP";
const char* kEapAnonymousIdentityProperty = "EAP.AnonymousIdentity";
const char* kEapClientCertProperty = "EAP.ClientCert";
const char* kEapCertIDProperty = "EAP.CertID";
const char* kEapPrivateKeyProperty = "EAP.PrivateKey";
const char* kEapPrivateKeyPasswordProperty = "EAP.PrivateKeyPassword";
const char* kEapKeyIDProperty = "EAP.KeyID";
const char* kEapCACertProperty = "EAP.CACert";
const char* kEapCACertIDProperty = "EAP.CACertID";
const char* kEapUseSystemCAsProperty = "EAP.UseSystemCAs";
const char* kEapPinProperty = "EAP.PIN";
const char* kEapPasswordProperty = "EAP.Password";
const char* kEapKeyMgmtProperty = "EAP.KeyMgmt";
// Flimflam EAP method options.
const std::string& kEapMethodPEAP = "PEAP";
const std::string& kEapMethodTLS = "TLS";
const std::string& kEapMethodTTLS = "TTLS";
const std::string& kEapMethodLEAP = "LEAP";
// Flimflam EAP phase 2 auth options.
const std::string& kEapPhase2AuthPEAPMD5 = "auth=MD5";
const std::string& kEapPhase2AuthPEAPMSCHAPV2 = "auth=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMD5 = "autheap=MD5";
const std::string& kEapPhase2AuthTTLSMSCHAPV2 = "autheap=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMSCHAP = "autheap=MSCHAP";
const std::string& kEapPhase2AuthTTLSPAP = "autheap=PAP";
const std::string& kEapPhase2AuthTTLSCHAP = "autheap=CHAP";
// Flimflam state options.
const char* kStateIdle = "idle";
const char* kStateCarrier = "carrier";
const char* kStateAssociation = "association";
const char* kStateConfiguration = "configuration";
const char* kStateReady = "ready";
const char* kStateDisconnect = "disconnect";
const char* kStateFailure = "failure";
const char* kStateActivationFailure = "activation-failure";
// Flimflam connectivity state options.
const char* kConnStateUnrestricted = "unrestricted";
const char* kConnStateRestricted = "restricted";
const char* kConnStateNone = "none";
// Flimflam network technology options.
const char* kNetworkTechnology1Xrtt = "1xRTT";
const char* kNetworkTechnologyEvdo = "EVDO";
const char* kNetworkTechnologyGprs = "GPRS";
const char* kNetworkTechnologyEdge = "EDGE";
const char* kNetworkTechnologyUmts = "UMTS";
const char* kNetworkTechnologyHspa = "HSPA";
const char* kNetworkTechnologyHspaPlus = "HSPA+";
const char* kNetworkTechnologyLte = "LTE";
const char* kNetworkTechnologyLteAdvanced = "LTE Advanced";
// Flimflam roaming state options
const char* kRoamingStateHome = "home";
const char* kRoamingStateRoaming = "roaming";
const char* kRoamingStateUnknown = "unknown";
// Flimflam activation state options
const char* kActivationStateActivated = "activated";
const char* kActivationStateActivating = "activating";
const char* kActivationStateNotActivated = "not-activated";
const char* kActivationStatePartiallyActivated = "partially-activated";
const char* kActivationStateUnknown = "unknown";
// Flimflam error options.
const char* kErrorOutOfRange = "out-of-range";
const char* kErrorPinMissing = "pin-missing";
const char* kErrorDhcpFailed = "dhcp-failed";
const char* kErrorConnectFailed = "connect-failed";
const char* kErrorBadPassphrase = "bad-passphrase";
const char* kErrorBadWEPKey = "bad-wepkey";
const char* kErrorActivationFailed = "activation-failed";
const char* kErrorNeedEvdo = "need-evdo";
const char* kErrorNeedHomeNetwork = "need-home-network";
const char* kErrorOtaspFailed = "otasp-failed";
const char* kErrorAaaFailed = "aaa-failed";
// Flimflam error messages.
const char* kErrorPassphraseRequiredMsg = "Passphrase required";
const char* kUnknownString = "UNKNOWN";
////////////////////////////////////////////////////////////////////////////
static const char* ConnectionTypeToString(ConnectionType type) {
switch (type) {
case TYPE_UNKNOWN:
break;
case TYPE_ETHERNET:
return kTypeEthernet;
case TYPE_WIFI:
return kTypeWifi;
case TYPE_WIMAX:
return kTypeWimax;
case TYPE_BLUETOOTH:
return kTypeBluetooth;
case TYPE_CELLULAR:
return kTypeCellular;
case TYPE_VPN:
return kTypeVPN;
}
LOG(ERROR) << "ConnectionTypeToString called with unknown type: " << type;
return kUnknownString;
}
// TODO(stevenjb/njw): Deprecate in favor of setting EAP properties.
static const char* SecurityToString(ConnectionSecurity security) {
switch (security) {
case SECURITY_UNKNOWN:
break;
case SECURITY_8021X:
return kSecurity8021x;
case SECURITY_RSN:
return kSecurityRsn;
case SECURITY_WPA:
return kSecurityWpa;
case SECURITY_WEP:
return kSecurityWep;
case SECURITY_NONE:
return kSecurityNone;
}
LOG(ERROR) << "SecurityToString called with unknown type: " << security;
return kUnknownString;
}
////////////////////////////////////////////////////////////////////////////
// Helper class to cache maps of strings to enums.
template <typename Type>
class StringToEnum {
public:
struct Pair {
const char* key;
const Type value;
};
explicit StringToEnum(const Pair* list, size_t num_entries, Type unknown)
: unknown_value_(unknown) {
for (size_t i = 0; i < num_entries; ++i, ++list)
enum_map_[list->key] = list->value;
}
Type Get(const std::string& type) const {
EnumMapConstIter iter = enum_map_.find(type);
if (iter != enum_map_.end())
return iter->second;
return unknown_value_;
}
private:
typedef typename std::map<std::string, Type> EnumMap;
typedef typename std::map<std::string, Type>::const_iterator EnumMapConstIter;
EnumMap enum_map_;
Type unknown_value_;
DISALLOW_COPY_AND_ASSIGN(StringToEnum);
};
////////////////////////////////////////////////////////////////////////////
enum PropertyIndex {
PROPERTY_INDEX_ACTIVATION_STATE,
PROPERTY_INDEX_ACTIVE_PROFILE,
PROPERTY_INDEX_AUTO_CONNECT,
PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES,
PROPERTY_INDEX_CARRIER,
PROPERTY_INDEX_CERT_PATH,
PROPERTY_INDEX_CONNECTABLE,
PROPERTY_INDEX_CONNECTED_TECHNOLOGIES,
PROPERTY_INDEX_CONNECTIVITY_STATE,
PROPERTY_INDEX_DEFAULT_TECHNOLOGY,
PROPERTY_INDEX_DEVICE,
PROPERTY_INDEX_DEVICES,
PROPERTY_INDEX_EAP_IDENTITY,
PROPERTY_INDEX_EAP_METHOD,
PROPERTY_INDEX_EAP_PHASE_2_AUTH,
PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY,
PROPERTY_INDEX_EAP_CLIENT_CERT,
PROPERTY_INDEX_EAP_CERT_ID,
PROPERTY_INDEX_EAP_PRIVATE_KEY,
PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD,
PROPERTY_INDEX_EAP_KEY_ID,
PROPERTY_INDEX_EAP_CA_CERT,
PROPERTY_INDEX_EAP_CA_CERT_ID,
PROPERTY_INDEX_EAP_USE_SYSTEM_CAS,
PROPERTY_INDEX_EAP_PIN,
PROPERTY_INDEX_EAP_PASSWORD,
PROPERTY_INDEX_EAP_KEY_MGMT,
PROPERTY_INDEX_ENABLED_TECHNOLOGIES,
PROPERTY_INDEX_ERROR,
PROPERTY_INDEX_ESN,
PROPERTY_INDEX_FAVORITE,
PROPERTY_INDEX_FIRMWARE_REVISION,
PROPERTY_INDEX_HARDWARE_REVISION,
PROPERTY_INDEX_IDENTITY,
PROPERTY_INDEX_IMEI,
PROPERTY_INDEX_IMSI,
PROPERTY_INDEX_IS_ACTIVE,
PROPERTY_INDEX_LAST_DEVICE_UPDATE,
PROPERTY_INDEX_MANUFACTURER,
PROPERTY_INDEX_MDN,
PROPERTY_INDEX_MEID,
PROPERTY_INDEX_MIN,
PROPERTY_INDEX_MODE,
PROPERTY_INDEX_MODEL_ID,
PROPERTY_INDEX_NAME,
PROPERTY_INDEX_NETWORK_TECHNOLOGY,
PROPERTY_INDEX_OFFLINE_MODE,
PROPERTY_INDEX_OPERATOR_CODE,
PROPERTY_INDEX_OPERATOR_NAME,
PROPERTY_INDEX_PASSPHRASE,
PROPERTY_INDEX_PASSPHRASE_REQUIRED,
PROPERTY_INDEX_PAYMENT_URL,
PROPERTY_INDEX_PRL_VERSION,
PROPERTY_INDEX_PROFILES,
PROPERTY_INDEX_ROAMING_STATE,
PROPERTY_INDEX_SCANNING,
PROPERTY_INDEX_SECURITY,
PROPERTY_INDEX_SERVICES,
PROPERTY_INDEX_SERVICE_WATCH_LIST,
PROPERTY_INDEX_SIGNAL_STRENGTH,
PROPERTY_INDEX_STATE,
PROPERTY_INDEX_TYPE,
PROPERTY_INDEX_UNKNOWN,
PROPERTY_INDEX_USAGE_URL,
};
StringToEnum<PropertyIndex>::Pair property_index_table[] = {
{ kActivationStateProperty, PROPERTY_INDEX_ACTIVATION_STATE },
{ kActiveProfileProperty, PROPERTY_INDEX_ACTIVE_PROFILE },
{ kAutoConnectProperty, PROPERTY_INDEX_AUTO_CONNECT },
{ kAvailableTechnologiesProperty, PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES },
{ kCarrierProperty, PROPERTY_INDEX_CARRIER },
{ kCertPathProperty, PROPERTY_INDEX_CERT_PATH },
{ kConnectableProperty, PROPERTY_INDEX_CONNECTABLE },
{ kConnectedTechnologiesProperty, PROPERTY_INDEX_CONNECTED_TECHNOLOGIES },
{ kConnectivityStateProperty, PROPERTY_INDEX_CONNECTIVITY_STATE },
{ kDefaultTechnologyProperty, PROPERTY_INDEX_DEFAULT_TECHNOLOGY },
{ kDeviceProperty, PROPERTY_INDEX_DEVICE },
{ kDevicesProperty, PROPERTY_INDEX_DEVICES },
{ kEapIdentityProperty, PROPERTY_INDEX_EAP_IDENTITY },
{ kEapMethodProperty, PROPERTY_INDEX_EAP_METHOD },
{ kEapPhase2AuthProperty, PROPERTY_INDEX_EAP_PHASE_2_AUTH },
{ kEapAnonymousIdentityProperty, PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY },
{ kEapClientCertProperty, PROPERTY_INDEX_EAP_CLIENT_CERT },
{ kEapCertIDProperty, PROPERTY_INDEX_EAP_CERT_ID },
{ kEapPrivateKeyProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY },
{ kEapPrivateKeyPasswordProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD },
{ kEapKeyIDProperty, PROPERTY_INDEX_EAP_KEY_ID },
{ kEapCACertProperty, PROPERTY_INDEX_EAP_CA_CERT },
{ kEapCACertIDProperty, PROPERTY_INDEX_EAP_CA_CERT_ID },
{ kEapUseSystemCAsProperty, PROPERTY_INDEX_EAP_USE_SYSTEM_CAS },
{ kEapPinProperty, PROPERTY_INDEX_EAP_PIN },
{ kEapPasswordProperty, PROPERTY_INDEX_EAP_PASSWORD },
{ kEapKeyMgmtProperty, PROPERTY_INDEX_EAP_KEY_MGMT },
{ kEnabledTechnologiesProperty, PROPERTY_INDEX_ENABLED_TECHNOLOGIES },
{ kErrorProperty, PROPERTY_INDEX_ERROR },
{ kEsnProperty, PROPERTY_INDEX_ESN },
{ kFavoriteProperty, PROPERTY_INDEX_FAVORITE },
{ kFirmwareRevisionProperty, PROPERTY_INDEX_FIRMWARE_REVISION },
{ kHardwareRevisionProperty, PROPERTY_INDEX_HARDWARE_REVISION },
{ kIdentityProperty, PROPERTY_INDEX_IDENTITY },
{ kImeiProperty, PROPERTY_INDEX_IMEI },
{ kImsiProperty, PROPERTY_INDEX_IMSI },
{ kIsActiveProperty, PROPERTY_INDEX_IS_ACTIVE },
{ kLastDeviceUpdateProperty, PROPERTY_INDEX_LAST_DEVICE_UPDATE },
{ kManufacturerProperty, PROPERTY_INDEX_MANUFACTURER },
{ kMdnProperty, PROPERTY_INDEX_MDN },
{ kMeidProperty, PROPERTY_INDEX_MEID },
{ kMinProperty, PROPERTY_INDEX_MIN },
{ kModeProperty, PROPERTY_INDEX_MODE },
{ kModelIDProperty, PROPERTY_INDEX_MODEL_ID },
{ kNameProperty, PROPERTY_INDEX_NAME },
{ kNetworkTechnologyProperty, PROPERTY_INDEX_NETWORK_TECHNOLOGY },
{ kOfflineModeProperty, PROPERTY_INDEX_OFFLINE_MODE },
{ kOperatorCodeProperty, PROPERTY_INDEX_OPERATOR_CODE },
{ kOperatorNameProperty, PROPERTY_INDEX_OPERATOR_NAME },
{ kPRLVersionProperty, PROPERTY_INDEX_PRL_VERSION },
{ kPassphraseProperty, PROPERTY_INDEX_PASSPHRASE },
{ kPassphraseRequiredProperty, PROPERTY_INDEX_PASSPHRASE_REQUIRED },
{ kPaymentURLProperty, PROPERTY_INDEX_PAYMENT_URL },
{ kProfilesProperty, PROPERTY_INDEX_PROFILES },
{ kRoamingStateProperty, PROPERTY_INDEX_ROAMING_STATE },
{ kScanningProperty, PROPERTY_INDEX_SCANNING },
{ kSecurityProperty, PROPERTY_INDEX_SECURITY },
{ kServiceWatchListProperty, PROPERTY_INDEX_SERVICE_WATCH_LIST },
{ kServicesProperty, PROPERTY_INDEX_SERVICES },
{ kSignalStrengthProperty, PROPERTY_INDEX_SIGNAL_STRENGTH },
{ kStateProperty, PROPERTY_INDEX_STATE },
{ kTypeProperty, PROPERTY_INDEX_TYPE },
{ kUsageURLProperty, PROPERTY_INDEX_USAGE_URL },
};
StringToEnum<PropertyIndex>& property_index_parser() {
static StringToEnum<PropertyIndex> parser(property_index_table,
arraysize(property_index_table),
PROPERTY_INDEX_UNKNOWN);
return parser;
}
////////////////////////////////////////////////////////////////////////////
// Parse strings from libcros.
// Network.
static ConnectionType ParseType(const std::string& type) {
static StringToEnum<ConnectionType>::Pair table[] = {
{ kTypeEthernet, TYPE_ETHERNET },
{ kTypeWifi, TYPE_WIFI },
{ kTypeWimax, TYPE_WIMAX },
{ kTypeBluetooth, TYPE_BLUETOOTH },
{ kTypeCellular, TYPE_CELLULAR },
{ kTypeVPN, TYPE_VPN },
};
static StringToEnum<ConnectionType> parser(
table, arraysize(table), TYPE_UNKNOWN);
return parser.Get(type);
}
ConnectionType ParseTypeFromDictionary(const DictionaryValue* info) {
std::string type_string;
info->GetString(kTypeProperty, &type_string);
return ParseType(type_string);
}
static ConnectionMode ParseMode(const std::string& mode) {
static StringToEnum<ConnectionMode>::Pair table[] = {
{ kModeManaged, MODE_MANAGED },
{ kModeAdhoc, MODE_ADHOC },
};
static StringToEnum<ConnectionMode> parser(
table, arraysize(table), MODE_UNKNOWN);
return parser.Get(mode);
}
static ConnectionState ParseState(const std::string& state) {
static StringToEnum<ConnectionState>::Pair table[] = {
{ kStateIdle, STATE_IDLE },
{ kStateCarrier, STATE_CARRIER },
{ kStateAssociation, STATE_ASSOCIATION },
{ kStateConfiguration, STATE_CONFIGURATION },
{ kStateReady, STATE_READY },
{ kStateDisconnect, STATE_DISCONNECT },
{ kStateFailure, STATE_FAILURE },
{ kStateActivationFailure, STATE_ACTIVATION_FAILURE },
};
static StringToEnum<ConnectionState> parser(
table, arraysize(table), STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectionError ParseError(const std::string& error) {
static StringToEnum<ConnectionError>::Pair table[] = {
{ kErrorOutOfRange, ERROR_OUT_OF_RANGE },
{ kErrorPinMissing, ERROR_PIN_MISSING },
{ kErrorDhcpFailed, ERROR_DHCP_FAILED },
{ kErrorConnectFailed, ERROR_CONNECT_FAILED },
{ kErrorBadPassphrase, ERROR_BAD_PASSPHRASE },
{ kErrorBadWEPKey, ERROR_BAD_WEPKEY },
{ kErrorActivationFailed, ERROR_ACTIVATION_FAILED },
{ kErrorNeedEvdo, ERROR_NEED_EVDO },
{ kErrorNeedHomeNetwork, ERROR_NEED_HOME_NETWORK },
{ kErrorOtaspFailed, ERROR_OTASP_FAILED },
{ kErrorAaaFailed, ERROR_AAA_FAILED },
};
static StringToEnum<ConnectionError> parser(
table, arraysize(table), ERROR_UNKNOWN);
return parser.Get(error);
}
// CellularNetwork.
static ActivationState ParseActivationState(const std::string& state) {
static StringToEnum<ActivationState>::Pair table[] = {
{ kActivationStateActivated, ACTIVATION_STATE_ACTIVATED },
{ kActivationStateActivating, ACTIVATION_STATE_ACTIVATING },
{ kActivationStateNotActivated, ACTIVATION_STATE_NOT_ACTIVATED },
{ kActivationStatePartiallyActivated, ACTIVATION_STATE_PARTIALLY_ACTIVATED},
{ kActivationStateUnknown, ACTIVATION_STATE_UNKNOWN},
};
static StringToEnum<ActivationState> parser(
table, arraysize(table), ACTIVATION_STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectivityState ParseConnectivityState(const std::string& state) {
static StringToEnum<ConnectivityState>::Pair table[] = {
{ kConnStateUnrestricted, CONN_STATE_UNRESTRICTED },
{ kConnStateRestricted, CONN_STATE_RESTRICTED },
{ kConnStateNone, CONN_STATE_NONE },
};
static StringToEnum<ConnectivityState> parser(
table, arraysize(table), CONN_STATE_UNKNOWN);
return parser.Get(state);
}
static NetworkTechnology ParseNetworkTechnology(const std::string& technology) {
static StringToEnum<NetworkTechnology>::Pair table[] = {
{ kNetworkTechnology1Xrtt, NETWORK_TECHNOLOGY_1XRTT },
{ kNetworkTechnologyEvdo, NETWORK_TECHNOLOGY_EVDO },
{ kNetworkTechnologyGprs, NETWORK_TECHNOLOGY_GPRS },
{ kNetworkTechnologyEdge, NETWORK_TECHNOLOGY_EDGE },
{ kNetworkTechnologyUmts, NETWORK_TECHNOLOGY_UMTS },
{ kNetworkTechnologyHspa, NETWORK_TECHNOLOGY_HSPA },
{ kNetworkTechnologyHspaPlus, NETWORK_TECHNOLOGY_HSPA_PLUS },
{ kNetworkTechnologyLte, NETWORK_TECHNOLOGY_LTE },
{ kNetworkTechnologyLteAdvanced, NETWORK_TECHNOLOGY_LTE_ADVANCED },
};
static StringToEnum<NetworkTechnology> parser(
table, arraysize(table), NETWORK_TECHNOLOGY_UNKNOWN);
return parser.Get(technology);
}
static NetworkRoamingState ParseRoamingState(const std::string& roaming_state) {
static StringToEnum<NetworkRoamingState>::Pair table[] = {
{ kRoamingStateHome, ROAMING_STATE_HOME },
{ kRoamingStateRoaming, ROAMING_STATE_ROAMING },
{ kRoamingStateUnknown, ROAMING_STATE_UNKNOWN },
};
static StringToEnum<NetworkRoamingState> parser(
table, arraysize(table), ROAMING_STATE_UNKNOWN);
return parser.Get(roaming_state);
}
// WifiNetwork
static ConnectionSecurity ParseSecurity(const std::string& security) {
static StringToEnum<ConnectionSecurity>::Pair table[] = {
{ kSecurity8021x, SECURITY_8021X },
{ kSecurityRsn, SECURITY_RSN },
{ kSecurityWpa, SECURITY_WPA },
{ kSecurityWep, SECURITY_WEP },
{ kSecurityNone, SECURITY_NONE },
};
static StringToEnum<ConnectionSecurity> parser(
table, arraysize(table), SECURITY_UNKNOWN);
return parser.Get(security);
}
static EAPMethod ParseEAPMethod(const std::string& method) {
static StringToEnum<EAPMethod>::Pair table[] = {
{ kEapMethodPEAP.c_str(), EAP_METHOD_PEAP },
{ kEapMethodTLS.c_str(), EAP_METHOD_TLS },
{ kEapMethodTTLS.c_str(), EAP_METHOD_TTLS },
{ kEapMethodLEAP.c_str(), EAP_METHOD_LEAP },
};
static StringToEnum<EAPMethod> parser(
table, arraysize(table), EAP_METHOD_UNKNOWN);
return parser.Get(method);
}
static EAPPhase2Auth ParseEAPPhase2Auth(const std::string& auth) {
static StringToEnum<EAPPhase2Auth>::Pair table[] = {
{ kEapPhase2AuthPEAPMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthPEAPMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthTTLSMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMSCHAP.c_str(), EAP_PHASE_2_AUTH_MSCHAP },
{ kEapPhase2AuthTTLSPAP.c_str(), EAP_PHASE_2_AUTH_PAP },
{ kEapPhase2AuthTTLSCHAP.c_str(), EAP_PHASE_2_AUTH_CHAP },
};
static StringToEnum<EAPPhase2Auth> parser(
table, arraysize(table), EAP_PHASE_2_AUTH_AUTO);
return parser.Get(auth);
}
////////////////////////////////////////////////////////////////////////////
// Html output helper functions
// Helper function to wrap Html with <th> tag.
static std::string WrapWithTH(std::string text) {
return "<th>" + text + "</th>";
}
// Helper function to wrap Html with <td> tag.
static std::string WrapWithTD(std::string text) {
return "<td>" + text + "</td>";
}
// Helper function to create an Html table header for a Network.
static std::string ToHtmlTableHeader(Network* network) {
std::string str;
if (network->type() == TYPE_ETHERNET) {
str += WrapWithTH("Active");
} else if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
str += WrapWithTH("Name") + WrapWithTH("Active") +
WrapWithTH("Auto-Connect") + WrapWithTH("Strength");
if (network->type() == TYPE_WIFI)
str += WrapWithTH("Encryption") + WrapWithTH("Passphrase") +
WrapWithTH("Identity") + WrapWithTH("Certificate");
}
str += WrapWithTH("State") + WrapWithTH("Error") + WrapWithTH("IP Address");
return str;
}
// Helper function to create an Html table row for a Network.
static std::string ToHtmlTableRow(Network* network) {
std::string str;
if (network->type() == TYPE_ETHERNET) {
str += WrapWithTD(base::IntToString(network->is_active()));
} else if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
WirelessNetwork* wireless = static_cast<WirelessNetwork*>(network);
str += WrapWithTD(wireless->name()) +
WrapWithTD(base::IntToString(network->is_active())) +
WrapWithTD(base::IntToString(wireless->auto_connect())) +
WrapWithTD(base::IntToString(wireless->strength()));
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
str += WrapWithTD(wifi->GetEncryptionString()) +
WrapWithTD(std::string(wifi->passphrase().length(), '*')) +
WrapWithTD(wifi->identity()) + WrapWithTD(wifi->cert_path());
}
}
str += WrapWithTD(network->GetStateString()) +
WrapWithTD(network->failed() ? network->GetErrorString() : "") +
WrapWithTD(network->ip_address());
return str;
}
////////////////////////////////////////////////////////////////////////////////
// Misc.
// Safe string constructor since we can't rely on non NULL pointers
// for string values from libcros.
static std::string SafeString(const char* s) {
return s ? std::string(s) : std::string();
}
static bool EnsureCrosLoaded() {
if (!CrosLibrary::Get()->EnsureLoaded()) {
return false;
} else {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "chromeos_library calls made from non UI thread!";
NOTREACHED();
}
return true;
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// NetworkDevice
NetworkDevice::NetworkDevice(const std::string& device_path)
: device_path_(device_path),
type_(TYPE_UNKNOWN),
scanning_(false),
PRL_version_(0) {
}
bool NetworkDevice::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
type_ = ParseType(type_string);
return true;
}
break;
}
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_SCANNING:
return value->GetAsBoolean(&scanning_);
case PROPERTY_INDEX_CARRIER:
return value->GetAsString(&carrier_);
case PROPERTY_INDEX_MEID:
return value->GetAsString(&MEID_);
case PROPERTY_INDEX_IMEI:
return value->GetAsString(&IMEI_);
case PROPERTY_INDEX_IMSI:
return value->GetAsString(&IMSI_);
case PROPERTY_INDEX_ESN:
return value->GetAsString(&ESN_);
case PROPERTY_INDEX_MDN:
return value->GetAsString(&MDN_);
case PROPERTY_INDEX_MIN:
return value->GetAsString(&MIN_);
case PROPERTY_INDEX_MODEL_ID:
return value->GetAsString(&model_id_);
case PROPERTY_INDEX_MANUFACTURER:
return value->GetAsString(&manufacturer_);
case PROPERTY_INDEX_FIRMWARE_REVISION:
return value->GetAsString(&firmware_revision_);
case PROPERTY_INDEX_HARDWARE_REVISION:
return value->GetAsString(&hardware_revision_);
case PROPERTY_INDEX_LAST_DEVICE_UPDATE:
return value->GetAsString(&last_update_);
case PROPERTY_INDEX_PRL_VERSION:
return value->GetAsInteger(&PRL_version_);
default:
break;
}
return false;
}
void NetworkDevice::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
CHECK(res);
int index = property_index_parser().Get(key);
if (!ParseValue(index, value))
VLOG(1) << "NetworkDevice: Unhandled key: " << key;
}
}
////////////////////////////////////////////////////////////////////////////////
// Network
bool Network::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
ConnectionType type = ParseType(type_string);
LOG_IF(ERROR, type != type_)
<< "Network with mismatched type: " << service_path_
<< " " << type << " != " << type_;
return true;
}
break;
}
case PROPERTY_INDEX_DEVICE:
return value->GetAsString(&device_path_);
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_STATE: {
std::string state_string;
if (value->GetAsString(&state_string)) {
ConnectionState prev_state = state_;
state_ = ParseState(state_string);
if (state_ != prev_state) {
// State changed, so refresh IP address.
// Note: blocking DBus call. TODO(stevenjb): refactor this.
InitIPAddress();
}
return true;
}
break;
}
case PROPERTY_INDEX_MODE: {
std::string mode_string;
if (value->GetAsString(&mode_string)) {
mode_ = ParseMode(mode_string);
return true;
}
break;
}
case PROPERTY_INDEX_ERROR: {
std::string error_string;
if (value->GetAsString(&error_string)) {
error_ = ParseError(error_string);
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTABLE:
return value->GetAsBoolean(&connectable_);
case PROPERTY_INDEX_IS_ACTIVE:
return value->GetAsBoolean(&is_active_);
case PROPERTY_INDEX_FAVORITE:
return value->GetAsBoolean(&favorite_);
case PROPERTY_INDEX_AUTO_CONNECT:
return value->GetAsBoolean(&auto_connect_);
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
std::string connectivity_state_string;
if (value->GetAsString(&connectivity_state_string)) {
connectivity_state_ = ParseConnectivityState(connectivity_state_string);
return true;
}
break;
}
default:
break;
}
return false;
}
void Network::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
CHECK(res);
int index = property_index_parser().Get(key);
if (!ParseValue(index, value)) // virtual.
VLOG(1) << "Network: Type: " << type_ << " Unhandled key: " << key;
}
}
void Network::SetAutoConnect(bool auto_connect) {
auto_connect_ = auto_connect;
SetBooleanProperty(kAutoConnectProperty, auto_connect);
}
void Network::SetStringProperty(const char* prop, const std::string& str) {
scoped_ptr<Value> value(Value::CreateStringValue(str));
SetValueProperty(prop, value.get());
}
void Network::SetBooleanProperty(const char* prop, bool b) {
scoped_ptr<Value> value(Value::CreateBooleanValue(b));
SetValueProperty(prop, value.get());
}
void Network::SetIntegerProperty(const char* prop, int i) {
scoped_ptr<Value> value(Value::CreateIntegerValue(i));
SetValueProperty(prop, value.get());
}
void Network::ClearProperty(const char* prop) {
// TODO(chocobo): Need to expose async method to clear service property.
DCHECK(prop);
if (!EnsureCrosLoaded())
return;
// ClearNetworkServiceProperty(service_path_.c_str(), prop);
}
void Network::SetOrClearStringProperty(const char* prop,
const std::string& str) {
if (str.empty())
ClearProperty(prop);
else
SetStringProperty(prop, str);
}
void Network::SetValueProperty(const char* prop, Value* val) {
DCHECK(prop);
DCHECK(val);
if (!EnsureCrosLoaded())
return;
SetNetworkServiceProperty(service_path_.c_str(), prop, val);
}
// Used by GetHtmlInfo() which is called from the about:network handler.
std::string Network::GetStateString() const {
switch (state_) {
case STATE_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN);
case STATE_IDLE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE);
case STATE_CARRIER:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER);
case STATE_ASSOCIATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION);
case STATE_CONFIGURATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION);
case STATE_READY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY);
case STATE_DISCONNECT:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT);
case STATE_FAILURE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE);
case STATE_ACTIVATION_FAILURE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE);
default:
// Usually no default, but changes to libcros may add states.
break;
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
std::string Network::GetErrorString() const {
switch (error_) {
case ERROR_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
case ERROR_OUT_OF_RANGE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE);
case ERROR_PIN_MISSING:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING);
case ERROR_DHCP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED);
case ERROR_CONNECT_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED);
case ERROR_BAD_PASSPHRASE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE);
case ERROR_BAD_WEPKEY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY);
case ERROR_ACTIVATION_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED);
case ERROR_NEED_EVDO:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO);
case ERROR_NEED_HOME_NETWORK:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK);
case ERROR_OTASP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED);
case ERROR_AAA_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED);
default:
// Usually no default, but changes to libcros may add errors.
break;
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
void Network::InitIPAddress() {
ip_address_.clear();
// If connected, get ip config.
if (EnsureCrosLoaded() && connected() && !device_path_.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path_.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0) {
ip_address_ = ipconfig.address;
break;
}
}
FreeIPConfigStatus(ipconfig_status);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// WirelessNetwork
bool WirelessNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SIGNAL_STRENGTH:
return value->GetAsInteger(&strength_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// CellularDataPlan
string16 CellularDataPlan::GetPlanDesciption() const {
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_UNLIMITED_DATA,
base::TimeFormatFriendlyDate(plan_start_time));
break;
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_RECEIVED_FREE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
default:
break;
}
}
return string16();
}
string16 CellularDataPlan::GetRemainingWarning() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
if (remaining_time().InSeconds() <= chromeos::kCellularDataVeryLowSecs) {
return GetPlanExpiration();
}
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
if (remaining_data() <= chromeos::kCellularDataVeryLowBytes) {
int64 remaining_mbytes = remaining_data() / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
}
return string16();
}
string16 CellularDataPlan::GetDataRemainingDesciption() const {
int64 remaining_bytes = remaining_data();
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_UNLIMITED);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
default:
break;
}
return string16();
}
string16 CellularDataPlan::GetUsageInfo() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
return GetPlanExpiration();
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
int64 remaining_bytes = remaining_data();
if (remaining_bytes == 0) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_NONE_AVAILABLE_MESSAGE);
} else if (remaining_bytes < 1024 * 1024) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_LESS_THAN_ONE_MB_AVAILABLE_MESSAGE);
} else {
int64 remaining_mb = remaining_bytes / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_MB_AVAILABLE_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mb)));
}
}
return string16();
}
std::string CellularDataPlan::GetUniqueIdentifier() const {
// A cellular plan is uniquely described by the union of name, type,
// start time, end time, and max bytes.
// So we just return a union of all these variables.
return plan_name + "|" +
base::Int64ToString(plan_type) + "|" +
base::Int64ToString(plan_start_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_end_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_data_bytes);
}
base::TimeDelta CellularDataPlan::remaining_time() const {
base::TimeDelta time = plan_end_time - base::Time::Now();
return time.InMicroseconds() < 0 ? base::TimeDelta() : time;
}
int64 CellularDataPlan::remaining_minutes() const {
return remaining_time().InMinutes();
}
int64 CellularDataPlan::remaining_data() const {
int64 data = plan_data_bytes - data_bytes_used;
return data < 0 ? 0 : data;
}
string16 CellularDataPlan::GetPlanExpiration() const {
return TimeFormat::TimeRemaining(remaining_time());
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork
CellularNetwork::~CellularNetwork() {
}
bool CellularNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_ACTIVATION_STATE: {
std::string activation_state_string;
if (value->GetAsString(&activation_state_string)) {
ActivationState prev_state = activation_state_;
activation_state_ = ParseActivationState(activation_state_string);
if (activation_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_NETWORK_TECHNOLOGY: {
std::string network_technology_string;
if (value->GetAsString(&network_technology_string)) {
network_technology_ = ParseNetworkTechnology(network_technology_string);
return true;
}
break;
}
case PROPERTY_INDEX_ROAMING_STATE: {
std::string roaming_state_string;
if (value->GetAsString(&roaming_state_string)) {
roaming_state_ = ParseRoamingState(roaming_state_string);
return true;
}
break;
}
case PROPERTY_INDEX_OPERATOR_NAME:
return value->GetAsString(&operator_name_);
case PROPERTY_INDEX_OPERATOR_CODE:
return value->GetAsString(&operator_code_);
case PROPERTY_INDEX_PAYMENT_URL:
return value->GetAsString(&payment_url_);
case PROPERTY_INDEX_USAGE_URL:
return value->GetAsString(&usage_url_);
case PROPERTY_INDEX_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectionState prev_state = state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectivityState prev_state = connectivity_state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (connectivity_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
bool CellularNetwork::StartActivation() const {
if (!EnsureCrosLoaded())
return false;
return ActivateCellularModem(service_path().c_str(), NULL);
}
void CellularNetwork::RefreshDataPlansIfNeeded() const {
if (!EnsureCrosLoaded())
return;
if (connected() && activated())
RequestCellularDataPlanUpdate(service_path().c_str());
}
std::string CellularNetwork::GetNetworkTechnologyString() const {
// No need to localize these cellular technology abbreviations.
switch (network_technology_) {
case NETWORK_TECHNOLOGY_1XRTT:
return "1xRTT";
break;
case NETWORK_TECHNOLOGY_EVDO:
return "EVDO";
break;
case NETWORK_TECHNOLOGY_GPRS:
return "GPRS";
break;
case NETWORK_TECHNOLOGY_EDGE:
return "EDGE";
break;
case NETWORK_TECHNOLOGY_UMTS:
return "UMTS";
break;
case NETWORK_TECHNOLOGY_HSPA:
return "HSPA";
break;
case NETWORK_TECHNOLOGY_HSPA_PLUS:
return "HSPA Plus";
break;
case NETWORK_TECHNOLOGY_LTE:
return "LTE";
break;
case NETWORK_TECHNOLOGY_LTE_ADVANCED:
return "LTE Advanced";
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_CELLULAR_TECHNOLOGY_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetConnectivityStateString() const {
// These strings do not appear in the UI, so no need to localize them
switch (connectivity_state_) {
case CONN_STATE_UNRESTRICTED:
return "unrestricted";
break;
case CONN_STATE_RESTRICTED:
return "restricted";
break;
case CONN_STATE_NONE:
return "none";
break;
case CONN_STATE_UNKNOWN:
default:
return "unknown";
}
}
std::string CellularNetwork::ActivationStateToString(
ActivationState activation_state) {
switch (activation_state) {
case ACTIVATION_STATE_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED);
break;
case ACTIVATION_STATE_ACTIVATING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING);
break;
case ACTIVATION_STATE_NOT_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED);
break;
case ACTIVATION_STATE_PARTIALLY_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetActivationStateString() const {
return ActivationStateToString(this->activation_state_);
}
std::string CellularNetwork::GetRoamingStateString() const {
switch (this->roaming_state_) {
case ROAMING_STATE_HOME:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME);
break;
case ROAMING_STATE_ROAMING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WifiNetwork
bool WifiNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SECURITY: {
std::string security_string;
if (value->GetAsString(&security_string)) {
encryption_ = ParseSecurity(security_string);
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE: {
std::string passphrase;
if (value->GetAsString(&passphrase)) {
// Only store the passphrase if we are the owner.
// TODO(stevenjb): Remove this when chromium-os:12948 is resolved.
if (chromeos::UserManager::Get()->current_user_is_owner())
passphrase_ = passphrase;
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE_REQUIRED:
return value->GetAsBoolean(&passphrase_required_);
case PROPERTY_INDEX_IDENTITY:
return value->GetAsString(&identity_);
case PROPERTY_INDEX_CERT_PATH:
return value->GetAsString(&cert_path_);
case PROPERTY_INDEX_EAP_METHOD: {
std::string method;
if (value->GetAsString(&method)) {
eap_method_ = ParseEAPMethod(method);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_PHASE_2_AUTH: {
std::string auth;
if (value->GetAsString(&auth)) {
eap_phase_2_auth_ = ParseEAPPhase2Auth(auth);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_IDENTITY:
return value->GetAsString(&eap_identity_);
case PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY:
return value->GetAsString(&eap_anonymous_identity_);
case PROPERTY_INDEX_EAP_CLIENT_CERT:
return value->GetAsString(&eap_client_cert_path_);
case PROPERTY_INDEX_EAP_CA_CERT:
return value->GetAsString(&eap_server_ca_cert_path_);
case PROPERTY_INDEX_EAP_PASSWORD:
return value->GetAsString(&eap_passphrase_);
case PROPERTY_INDEX_EAP_USE_SYSTEM_CAS:
return value->GetAsBoolean(&eap_use_system_cas_);
case PROPERTY_INDEX_EAP_CERT_ID:
case PROPERTY_INDEX_EAP_PRIVATE_KEY:
case PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD:
case PROPERTY_INDEX_EAP_KEY_ID:
case PROPERTY_INDEX_EAP_CA_CERT_ID:
case PROPERTY_INDEX_EAP_PIN:
case PROPERTY_INDEX_EAP_KEY_MGMT:
// These properties are currently not used in the UI.
return true;
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
const std::string& WifiNetwork::GetPassphrase() const {
if (!user_passphrase_.empty())
return user_passphrase_;
return passphrase_;
}
void WifiNetwork::SetPassphrase(const std::string& passphrase) {
// Set the user_passphrase_ only; passphrase_ stores the flimflam value.
// If the user sets an empty passphrase, restore it to the passphrase
// remembered by flimflam.
if (!passphrase.empty())
user_passphrase_ = passphrase;
else
user_passphrase_ = passphrase_;
// Send the change to flimflam. If the format is valid, it will propagate to
// passphrase_ with a service update.
SetStringProperty(kPassphraseProperty, passphrase);
}
void WifiNetwork::SetIdentity(const std::string& identity) {
identity_ = identity;
SetStringProperty(kIdentityProperty, identity);
}
void WifiNetwork::SetCertPath(const std::string& cert_path) {
cert_path_ = cert_path;
SetStringProperty(kCertPathProperty, cert_path);
}
void WifiNetwork::SetEAPMethod(EAPMethod method) {
eap_method_ = method;
switch (method) {
case EAP_METHOD_PEAP:
SetStringProperty(kEapMethodProperty, kEapMethodPEAP);
break;
case EAP_METHOD_TLS:
SetStringProperty(kEapMethodProperty, kEapMethodTLS);
break;
case EAP_METHOD_TTLS:
SetStringProperty(kEapMethodProperty, kEapMethodTTLS);
break;
case EAP_METHOD_LEAP:
SetStringProperty(kEapMethodProperty, kEapMethodLEAP);
break;
default:
ClearProperty(kEapMethodProperty);
break;
}
}
void WifiNetwork::SetEAPPhase2Auth(EAPPhase2Auth auth) {
eap_phase_2_auth_ = auth;
bool is_peap = (eap_method_ == EAP_METHOD_PEAP);
switch (auth) {
case EAP_PHASE_2_AUTH_AUTO:
ClearProperty(kEapPhase2AuthProperty);
break;
case EAP_PHASE_2_AUTH_MD5:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMD5
: kEapPhase2AuthTTLSMD5);
break;
case EAP_PHASE_2_AUTH_MSCHAPV2:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMSCHAPV2
: kEapPhase2AuthTTLSMSCHAPV2);
break;
case EAP_PHASE_2_AUTH_MSCHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSMSCHAP);
break;
case EAP_PHASE_2_AUTH_PAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSPAP);
break;
case EAP_PHASE_2_AUTH_CHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSCHAP);
break;
}
}
void WifiNetwork::SetEAPServerCACert(const std::string& cert_path) {
eap_server_ca_cert_path_ = cert_path;
SetOrClearStringProperty(kEapCACertProperty, cert_path);
}
void WifiNetwork::SetEAPClientCert(const std::string& cert_path) {
eap_client_cert_path_ = cert_path;
SetOrClearStringProperty(kEapClientCertProperty, cert_path);
}
void WifiNetwork::SetEAPUseSystemCAs(bool use_system_cas) {
eap_use_system_cas_ = use_system_cas;
SetBooleanProperty(kEapUseSystemCAsProperty, use_system_cas);
}
void WifiNetwork::SetEAPIdentity(const std::string& identity) {
eap_identity_ = identity;
SetOrClearStringProperty(kEapIdentityProperty, identity);
}
void WifiNetwork::SetEAPAnonymousIdentity(const std::string& identity) {
eap_anonymous_identity_ = identity;
SetOrClearStringProperty(kEapAnonymousIdentityProperty, identity);
}
void WifiNetwork::SetEAPPassphrase(const std::string& passphrase) {
eap_passphrase_ = passphrase;
SetOrClearStringProperty(kEapPasswordProperty, passphrase);
}
std::string WifiNetwork::GetEncryptionString() {
switch (encryption_) {
case SECURITY_UNKNOWN:
break;
case SECURITY_NONE:
return "";
case SECURITY_WEP:
return "WEP";
case SECURITY_WPA:
return "WPA";
case SECURITY_RSN:
return "RSN";
case SECURITY_8021X:
return "8021X";
}
return "Unknown";
}
bool WifiNetwork::IsPassphraseRequired() const {
// TODO(stevenjb): Remove error_ tests when fixed in flimflam
// (http://crosbug.com/10135).
if (error_ == ERROR_BAD_PASSPHRASE || error_ == ERROR_BAD_WEPKEY)
return true;
// For 802.1x networks, configuration is required if connectable is false.
if (encryption_ == SECURITY_8021X)
return !connectable_;
return passphrase_required_;
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
bool WifiNetwork::IsCertificateLoaded() const {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (cert_path_.find(settings_string) == 0) {
std::string::size_type idx = cert_path_.find(pkcs11_key);
if (idx != std::string::npos)
idx = cert_path_.find_first_not_of(kWhitespaceASCII,
idx + pkcs11_key.length());
if (idx != std::string::npos && cert_path_[idx] == '=')
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
class NetworkLibraryImpl : public NetworkLibrary {
public:
NetworkLibraryImpl()
: network_manager_monitor_(NULL),
data_plan_monitor_(NULL),
ethernet_(NULL),
active_wifi_(NULL),
active_cellular_(NULL),
active_virtual_(NULL),
available_devices_(0),
enabled_devices_(0),
connected_devices_(0),
wifi_scanning_(false),
offline_mode_(false),
is_locked_(false),
notify_task_(NULL) {
if (EnsureCrosLoaded()) {
Init();
network_manager_monitor_ =
MonitorNetworkManager(&NetworkManagerStatusChangedHandler,
this);
data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler,
this);
network_login_observer_.reset(new NetworkLoginObserver(this));
} else {
InitTestData();
}
}
virtual ~NetworkLibraryImpl() {
network_manager_observers_.Clear();
if (network_manager_monitor_)
DisconnectPropertyChangeMonitor(network_manager_monitor_);
data_plan_observers_.Clear();
if (data_plan_monitor_)
DisconnectDataPlanUpdateMonitor(data_plan_monitor_);
STLDeleteValues(&network_observers_);
ClearNetworks(true /*delete networks*/);
ClearRememberedNetworks(true /*delete networks*/);
STLDeleteValues(&data_plan_map_);
}
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {
if (!network_manager_observers_.HasObserver(observer))
network_manager_observers_.AddObserver(observer);
}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {
network_manager_observers_.RemoveObserver(observer);
}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkObserverMap::iterator iter = network_observers_.find(service_path);
NetworkObserverList* oblist;
if (iter != network_observers_.end()) {
oblist = iter->second;
} else {
std::pair<NetworkObserverMap::iterator, bool> inserted =
network_observers_.insert(
std::make_pair<std::string, NetworkObserverList*>(
service_path,
new NetworkObserverList(this, service_path)));
oblist = inserted.first->second;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
DCHECK(service_path.size());
NetworkObserverMap::iterator map_iter =
network_observers_.find(service_path);
if (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
}
}
}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {
DCHECK(observer);
NetworkObserverMap::iterator map_iter = network_observers_.begin();
while (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
} else {
++map_iter;
}
}
}
virtual void Lock() {
if (is_locked_)
return;
is_locked_ = true;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual void Unlock() {
DCHECK(is_locked_);
if (!is_locked_)
return;
is_locked_ = false;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool IsLocked() {
return is_locked_;
}
virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) {
if (!data_plan_observers_.HasObserver(observer))
data_plan_observers_.AddObserver(observer);
}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {
data_plan_observers_.RemoveObserver(observer);
}
virtual void AddUserActionObserver(UserActionObserver* observer) {
if (!user_action_observers_.HasObserver(observer))
user_action_observers_.AddObserver(observer);
}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {
user_action_observers_.RemoveObserver(observer);
}
virtual const EthernetNetwork* ethernet_network() const { return ethernet_; }
virtual bool ethernet_connecting() const {
return ethernet_ ? ethernet_->connecting() : false;
}
virtual bool ethernet_connected() const {
return ethernet_ ? ethernet_->connected() : false;
}
virtual const WifiNetwork* wifi_network() const { return active_wifi_; }
virtual bool wifi_connecting() const {
return active_wifi_ ? active_wifi_->connecting() : false;
}
virtual bool wifi_connected() const {
return active_wifi_ ? active_wifi_->connected() : false;
}
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const {
return active_cellular_ ? active_cellular_->connecting() : false;
}
virtual bool cellular_connected() const {
return active_cellular_ ? active_cellular_->connected() : false;
}
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const {
return active_virtual_ ? active_virtual_->connecting() : false;
}
virtual bool virtual_network_connected() const {
return active_virtual_ ? active_virtual_->connected() : false;
}
bool Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& IPAddress() const {
// Returns IP address for the active network.
const Network* result = active_network();
if (active_virtual_ && active_virtual_->is_active() &&
(!result || active_virtual_->priority_ > result->priority_))
result = active_virtual_;
if (!result)
result = ethernet_; // Use non active ethernet addr if no active network.
if (result)
return result->ip_address();
static std::string null_address("0.0.0.0");
return null_address;
}
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return remembered_wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const {
NetworkDeviceMap::const_iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
virtual Network* FindNetworkByPath(const std::string& path) const {
NetworkMap::const_iterator iter = network_map_.find(path);
if (iter != network_map_.end())
return iter->second;
return NULL;
}
WirelessNetwork* FindWirelessNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network &&
(network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR))
return static_cast<WirelessNetwork*>(network);
return NULL;
}
virtual WifiNetwork* FindWifiNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_WIFI)
return static_cast<WifiNetwork*>(network);
return NULL;
}
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_CELLULAR)
return static_cast<CellularNetwork*>(network);
return NULL;
}
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const {
CellularDataPlanMap::const_iterator iter = data_plan_map_.find(path);
if (iter != data_plan_map_.end())
return iter->second;
return NULL;
}
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const {
const CellularDataPlanVector* plans = GetDataPlans(path);
if (plans)
return GetSignificantDataPlanFromVector(plans);
return NULL;
}
virtual void RequestNetworkScan() {
if (EnsureCrosLoaded()) {
if (wifi_enabled()) {
wifi_scanning_ = true; // Cleared when updates are received.
chromeos::RequestNetworkScan(kTypeWifi);
RequestRememberedNetworksUpdate();
}
if (cellular_network())
cellular_network()->RefreshDataPlansIfNeeded();
}
}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
if (!EnsureCrosLoaded())
return false;
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeviceNetworkList* network_list = GetDeviceNetworkList();
if (network_list == NULL)
return false;
result->clear();
result->reserve(network_list->network_size);
const base::Time now = base::Time::Now();
for (size_t i = 0; i < network_list->network_size; ++i) {
DCHECK(network_list->networks[i].address);
DCHECK(network_list->networks[i].name);
WifiAccessPoint ap;
ap.mac_address = SafeString(network_list->networks[i].address);
ap.name = SafeString(network_list->networks[i].name);
ap.timestamp = now -
base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds);
ap.signal_strength = network_list->networks[i].strength;
ap.channel = network_list->networks[i].channel;
result->push_back(ap);
}
FreeDeviceNetworkList(network_list);
return true;
}
static void WirelessConnectCallback(void *object,
const char *path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
WirelessNetwork* wireless = networklib->FindWirelessNetworkByPath(path);
if (!wireless) {
LOG(ERROR) << "No wireless network for path: " << path;
return;
}
if (error != NETWORK_METHOD_ERROR_NONE) {
if (error_message &&
strcmp(error_message, kErrorPassphraseRequiredMsg) == 0) {
// This will trigger the connection failed notification.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
wireless->set_state(STATE_FAILURE);
wireless->set_error(ERROR_BAD_PASSPHRASE);
networklib->NotifyNetworkManagerChanged(true); // Forced update.
} else {
LOG(WARNING) << "Error from ServiceConnect callback: "
<< error_message;
}
return;
}
// Update local cache and notify listeners.
if (wireless->type() == TYPE_WIFI)
networklib->active_wifi_ = static_cast<WifiNetwork *>(wireless);
else if (wireless->type() == TYPE_CELLULAR)
networklib->active_cellular_ = static_cast<CellularNetwork *>(wireless);
else
LOG(ERROR) << "Network of unexpected type: " << wireless->type();
// If we succeed, this network will be remembered; request an update.
// TODO(stevenjb): flimflam should do this automatically.
networklib->RequestRememberedNetworksUpdate();
// Notify observers.
networklib->NotifyNetworkManagerChanged(false); // Not forced.
networklib->NotifyUserConnectionInitiated(wireless);
}
void CallConnectToNetworkForWifi(WifiNetwork* wifi) {
// If we haven't correctly set the parameters (e.g. passphrase), flimflam
// might fail without attempting a connection. In order to trigger any
// notifications, set the state locally and notify observers.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
wifi->set_connecting(true);
NotifyNetworkManagerChanged(true); // Forced update.
RequestNetworkServiceConnect(wifi->service_path().c_str(),
WirelessConnectCallback, this);
}
virtual void ConnectToWifiNetwork(WifiNetwork* wifi) {
DCHECK(wifi);
if (!EnsureCrosLoaded() || !wifi)
return;
CallConnectToNetworkForWifi(wifi);
}
// Use this to connect to a wifi network by service path.
virtual void ConnectToWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
WifiNetwork* wifi = FindWifiNetworkByPath(service_path);
if (!wifi) {
LOG(WARNING) << "Attempt to connect to non existing network: "
<< service_path;
return;
}
CallConnectToNetworkForWifi(wifi);
}
// Use this to connect to an unlisted wifi network.
// This needs to request information about the named service.
// The connection attempt will occur in the callback.
virtual void ConnectToWifiNetwork(ConnectionSecurity security,
const std::string& ssid,
const std::string& passphrase,
const std::string& identity,
const std::string& certpath,
bool auto_connect) {
if (!EnsureCrosLoaded())
return;
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(security),
WifiServiceUpdateAndConnect,
this);
// Store the connection data to be used by the callback.
connect_data_.SetData(ssid, passphrase, identity, certpath, auto_connect);
}
// Callback
static void WifiServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
// Blocking DBus call. TODO(stevenjb): make async.
networklib->ConnectToNetworkUsingConnectData(network);
}
}
void ConnectToNetworkUsingConnectData(Network* network) {
ConnectData& data = connect_data_;
if (network->name() != data.name) {
LOG(WARNING) << "Network name does not match ConnectData: "
<< network->name() << " != " << data.name;
return;
}
WifiNetwork *wifi = static_cast<WifiNetwork *>(network);
if (!data.passphrase.empty())
wifi->SetPassphrase(data.passphrase);
if (!data.identity.empty())
wifi->SetIdentity(data.identity);
if (!data.certpath.empty())
wifi->SetCertPath(data.certpath);
wifi->SetAutoConnect(data.auto_connect);
CallConnectToNetworkForWifi(wifi);
}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
RequestNetworkServiceConnect(network->service_path().c_str(),
WirelessConnectCallback, this);
}
// Records information that cellular play payment had happened.
virtual void SignalCellularPlanPayment() {
DCHECK(!HasRecentCellularPlanPayment());
cellular_plan_payment_time_ = base::Time::Now();
}
// Returns true if cellular plan payment had been recorded recently.
virtual bool HasRecentCellularPlanPayment() {
return (base::Time::Now() -
cellular_plan_payment_time_).InHours() < kRecentPlanPaymentHours;
}
virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
if (DisconnectFromNetwork(network->service_path().c_str())) {
// Update local cache and notify listeners.
WirelessNetwork* wireless =
FindWirelessNetworkByPath(network->service_path());
if (wireless) {
wireless->set_connected(false);
if (wireless == active_wifi_)
active_wifi_ = NULL;
else if (wireless == active_cellular_)
active_cellular_ = NULL;
}
NotifyNetworkManagerChanged(false); // Not forced.
}
}
virtual void ForgetWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
// NOTE: service paths for remembered wifi networks do not match the
// service paths in wifi_networks_; calling a libcros funtion that
// operates on the wifi_networks_ list with this service_path will
// trigger a crash because the DBUS path does not exist.
// TODO(stevenjb): modify libcros to warn and fail instead of crash.
// https://crosbug.com/9295
if (DeleteRememberedService(service_path.c_str())) {
DeleteRememberedNetwork(service_path);
NotifyNetworkManagerChanged(false); // Not forced.
}
}
virtual bool ethernet_available() const {
return available_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_available() const {
return available_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_available() const {
return available_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool ethernet_enabled() const {
return enabled_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_enabled() const {
return enabled_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_enabled() const {
return enabled_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool wifi_scanning() const {
return wifi_scanning_;
}
virtual bool offline_mode() const { return offline_mode_; }
// Note: This does not include any virtual networks.
virtual const Network* active_network() const {
// Use flimflam's ordering of the services to determine what the active
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->is_active())
result = ethernet_;
if (active_wifi_ && active_wifi_->is_active() &&
(!result || active_wifi_->priority_ > result->priority_))
result = active_wifi_;
if (active_cellular_ && active_cellular_->is_active() &&
(!result || active_cellular_->priority_ > result->priority_))
result = active_cellular_;
return result;
}
virtual void EnableEthernetNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_ETHERNET, enable);
}
virtual void EnableWifiNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_WIFI, enable);
}
virtual void EnableCellularNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_CELLULAR, enable);
}
virtual void EnableOfflineMode(bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
VLOG(1) << "Trying to enable offline mode when it's already enabled.";
return;
}
if (!enable && !offline_mode_) {
VLOG(1) << "Trying to disable offline mode when it's already disabled.";
return;
}
if (SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address) {
hardware_address->clear();
NetworkIPConfigVector ipconfig_vector;
if (EnsureCrosLoaded() && !device_path.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
*hardware_address = ipconfig_status->hardware_address;
FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
return ipconfig_vector;
}
virtual std::string GetHtmlInfo(int refresh) {
std::string output;
output.append("<html><head><title>About Network</title>");
if (refresh > 0)
output.append("<meta http-equiv=\"refresh\" content=\"" +
base::IntToString(refresh) + "\"/>");
output.append("</head><body>");
if (refresh > 0) {
output.append("(Auto-refreshing page every " +
base::IntToString(refresh) + "s)");
} else {
output.append("(To auto-refresh this page: about:network/<secs>)");
}
if (ethernet_enabled()) {
output.append("<h3>Ethernet:</h3><table border=1>");
if (ethernet_) {
output.append("<tr>" + ToHtmlTableHeader(ethernet_) + "</tr>");
output.append("<tr>" + ToHtmlTableRow(ethernet_) + "</tr>");
}
}
if (wifi_enabled()) {
output.append("</table><h3>Wifi:</h3><table border=1>");
for (size_t i = 0; i < wifi_networks_.size(); ++i) {
if (i == 0)
output.append("<tr>" + ToHtmlTableHeader(wifi_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(wifi_networks_[i]) + "</tr>");
}
}
if (cellular_enabled()) {
output.append("</table><h3>Cellular:</h3><table border=1>");
for (size_t i = 0; i < cellular_networks_.size(); ++i) {
if (i == 0)
output.append("<tr>" + ToHtmlTableHeader(cellular_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(cellular_networks_[i]) + "</tr>");
}
}
output.append("</table><h3>Remembered Wifi:</h3><table border=1>");
for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) {
if (i == 0)
output.append(
"<tr>" + ToHtmlTableHeader(remembered_wifi_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(remembered_wifi_networks_[i]) +
"</tr>");
}
output.append("</table></body></html>");
return output;
}
private:
typedef std::map<std::string, Network*> NetworkMap;
typedef std::map<std::string, int> PriorityMap;
typedef std::map<std::string, NetworkDevice*> NetworkDeviceMap;
typedef std::map<std::string, CellularDataPlanVector*> CellularDataPlanMap;
class NetworkObserverList : public ObserverList<NetworkObserver> {
public:
NetworkObserverList(NetworkLibraryImpl* library,
const std::string& service_path) {
network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler,
service_path.c_str(),
library);
}
virtual ~NetworkObserverList() {
if (network_monitor_)
DisconnectPropertyChangeMonitor(network_monitor_);
}
private:
static void NetworkStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkStatus(path, key, value);
}
PropertyChangeMonitor network_monitor_;
};
typedef std::map<std::string, NetworkObserverList*> NetworkObserverMap;
////////////////////////////////////////////////////////////////////////////
// Callbacks.
static void NetworkManagerStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->NetworkManagerStatusChanged(key, value);
}
// This processes all Manager update messages.
void NetworkManagerStatusChanged(const char* key, const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::TimeTicks start = base::TimeTicks::Now();
VLOG(1) << "NetworkManagerStatusChanged: KEY=" << key;
if (!key)
return;
int index = property_index_parser().Get(std::string(key));
switch (index) {
case PROPERTY_INDEX_STATE:
// Currently we ignore the network manager state.
break;
case PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateAvailableTechnologies(vlist);
break;
}
case PROPERTY_INDEX_ENABLED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateEnabledTechnologies(vlist);
break;
}
case PROPERTY_INDEX_CONNECTED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateConnectedTechnologies(vlist);
break;
}
case PROPERTY_INDEX_DEFAULT_TECHNOLOGY:
// Currently we ignore DefaultTechnology.
break;
case PROPERTY_INDEX_OFFLINE_MODE: {
DCHECK_EQ(value->GetType(), Value::TYPE_BOOLEAN);
value->GetAsBoolean(&offline_mode_);
NotifyNetworkManagerChanged(false); // Not forced.
break;
}
case PROPERTY_INDEX_ACTIVE_PROFILE: {
DCHECK_EQ(value->GetType(), Value::TYPE_STRING);
value->GetAsString(&active_profile_path_);
RequestRememberedNetworksUpdate();
break;
}
case PROPERTY_INDEX_PROFILES:
// Currently we ignore Profiles (list of all profiles).
break;
case PROPERTY_INDEX_SERVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_SERVICE_WATCH_LIST: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateWatchedNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_DEVICE:
case PROPERTY_INDEX_DEVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkDeviceList(vlist);
break;
}
default:
LOG(WARNING) << "Unhandled key: " << key;
break;
}
base::TimeDelta delta = base::TimeTicks::Now() - start;
VLOG(1) << " time: " << delta.InMilliseconds() << " ms.";
HISTOGRAM_TIMES("CROS_NETWORK_UPDATE", delta);
}
static void NetworkManagerUpdate(void* object,
const char* manager_path,
const Value* info) {
VLOG(1) << "Received NetworkManagerUpdate.";
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
DCHECK(info);
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkManager(dict);
}
void ParseNetworkManager(const DictionaryValue* dict) {
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = dict->GetWithoutPathExpansion(key, &value);
CHECK(res);
NetworkManagerStatusChanged(key.c_str(), value);
}
}
static void ProfileUpdate(void* object,
const char* profile_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
DCHECK(info);
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
ListValue* entries(NULL);
dict->GetList(kEntriesProperty, &entries);
DCHECK(entries);
networklib->UpdateRememberedServiceList(profile_path, entries);
}
static void NetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Network no longer exists.
networklib->DeleteNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetwork(std::string(service_path), dict);
}
}
}
static void RememberedNetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Remembered network no longer exists.
networklib->DeleteRememberedNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseRememberedNetwork(std::string(service_path), dict);
}
}
}
static void NetworkDeviceUpdate(void* object,
const char* device_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (device_path) {
if (!info) {
// device no longer exists.
networklib->DeleteDevice(std::string(device_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkDevice(std::string(device_path), dict);
}
}
}
static void DataPlanUpdateHandler(void* object,
const char* modem_service_path,
const CellularDataPlanList* dataplan) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (modem_service_path && dataplan) {
networklib->UpdateCellularDataPlan(std::string(modem_service_path),
dataplan);
}
}
////////////////////////////////////////////////////////////////////////////
// Network technology functions.
void UpdateTechnologies(const ListValue* technologies, int* bitfieldp) {
DCHECK(bitfieldp);
if (!technologies)
return;
int bitfield = 0;
for (ListValue::const_iterator iter = technologies->begin();
iter != technologies->end(); ++iter) {
std::string technology;
(*iter)->GetAsString(&technology);
if (!technology.empty()) {
ConnectionType type = ParseType(technology);
bitfield |= 1 << type;
}
}
*bitfieldp = bitfield;
NotifyNetworkManagerChanged(false); // Not forced.
}
void UpdateAvailableTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &available_devices_);
}
void UpdateEnabledTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &enabled_devices_);
if (!ethernet_enabled())
ethernet_ = NULL;
if (!wifi_enabled()) {
active_wifi_ = NULL;
wifi_networks_.clear();
}
if (!cellular_enabled()) {
active_cellular_ = NULL;
cellular_networks_.clear();
}
}
void UpdateConnectedTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &connected_devices_);
}
////////////////////////////////////////////////////////////////////////////
// Network list management functions.
// Note: sometimes flimflam still returns networks when the device type is
// disabled. Always check the appropriate enabled() state before adding
// networks to a list or setting an active network so that we do not show them
// in the UI.
// This relies on services being requested from flimflam in priority order,
// and the updates getting processed and received in order.
void UpdateActiveNetwork(Network* network) {
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (ethernet_enabled()) {
// Set ethernet_ to the first connected ethernet service, or the first
// disconnected ethernet service if none are connected.
if (ethernet_ == NULL || !ethernet_->connected())
ethernet_ = static_cast<EthernetNetwork*>(network);
}
} else if (type == TYPE_WIFI) {
if (wifi_enabled()) {
// Set active_wifi_ to the first connected or connecting wifi service.
if (active_wifi_ == NULL && network->connecting_or_connected())
active_wifi_ = static_cast<WifiNetwork*>(network);
}
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled()) {
// Set active_cellular_ to first connected/connecting celluar service.
if (active_cellular_ == NULL && network->connecting_or_connected())
active_cellular_ = static_cast<CellularNetwork*>(network);
}
} else if (type == TYPE_VPN) {
// Set active_virtual_ to the first connected or connecting vpn service.
if (active_virtual_ == NULL && network->connecting_or_connected())
active_virtual_ = static_cast<VirtualNetwork*>(network);
}
}
void AddNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
network_map_.insert(std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
ConnectionType type(network->type());
if (type == TYPE_WIFI) {
if (wifi_enabled())
wifi_networks_.push_back(static_cast<WifiNetwork*>(network));
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled())
cellular_networks_.push_back(static_cast<CellularNetwork*>(network));
} else if (type == TYPE_VPN) {
virtual_networks_.push_back(static_cast<VirtualNetwork*>(network));
}
// Do not set the active network here. Wait until we parse the network.
}
// This only gets called when NetworkServiceUpdate receives a NULL update
// for an existing network, e.g. an error occurred while fetching a network.
void DeleteNetwork(const std::string& service_path) {
NetworkMap::iterator found = network_map_.find(service_path);
if (found == network_map_.end()) {
// This occurs when we receive an update request followed by a disconnect
// which triggers another update. See UpdateNetworkServiceList.
return;
}
Network* network = found->second;
network_map_.erase(found);
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (network == ethernet_) {
// This should never happen.
LOG(ERROR) << "Deleting active ethernet network: " << service_path;
ethernet_ = NULL;
}
} else if (type == TYPE_WIFI) {
WifiNetworkVector::iterator iter = std::find(
wifi_networks_.begin(), wifi_networks_.end(), network);
if (iter != wifi_networks_.end())
wifi_networks_.erase(iter);
if (network == active_wifi_) {
// This should never happen.
LOG(ERROR) << "Deleting active wifi network: " << service_path;
active_wifi_ = NULL;
}
} else if (type == TYPE_CELLULAR) {
CellularNetworkVector::iterator iter = std::find(
cellular_networks_.begin(), cellular_networks_.end(), network);
if (iter != cellular_networks_.end())
cellular_networks_.erase(iter);
if (network == active_cellular_) {
// This should never happen.
LOG(ERROR) << "Deleting active cellular network: " << service_path;
active_cellular_ = NULL;
}
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
CellularDataPlanVector* data_plans = found->second;
delete data_plans;
data_plan_map_.erase(found);
}
} else if (type == TYPE_VPN) {
VirtualNetworkVector::iterator iter = std::find(
virtual_networks_.begin(), virtual_networks_.end(), network);
if (iter != virtual_networks_.end())
virtual_networks_.erase(iter);
if (network == active_virtual_) {
// This should never happen.
LOG(ERROR) << "Deleting active virtual network: " << service_path;
active_virtual_ = NULL;
}
}
delete network;
}
void AddRememberedNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
remembered_network_map_.insert(
std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
remembered_wifi_networks_.push_back(wifi);
}
}
void DeleteRememberedNetwork(const std::string& service_path) {
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found == remembered_network_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant remembered network: "
<< service_path;
return;
}
Network* remembered_network = found->second;
remembered_network_map_.erase(found);
WifiNetworkVector::iterator iter = std::find(
remembered_wifi_networks_.begin(), remembered_wifi_networks_.end(),
remembered_network);
if (iter != remembered_wifi_networks_.end())
remembered_wifi_networks_.erase(iter);
delete remembered_network;
}
// Update all network lists, and request associated service updates.
void UpdateNetworkServiceList(const ListValue* services) {
// TODO(stevenjb): Wait for wifi_scanning_ to be false.
// Copy the list of existing networks to "old" and clear the map and lists.
NetworkMap old_network_map = network_map_;
ClearNetworks(false /*don't delete*/);
// Clear the list of update requests.
int network_priority = 0;
network_update_requests_.clear();
// wifi_scanning_ will remain false unless we request a network update.
wifi_scanning_ = false;
// |services| represents a complete list of visible networks.
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and lists. Otherwise it will get added when NetworkServiceUpdate
// calls ParseNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddNetwork(found->second);
old_network_map.erase(found);
}
// Always request network updates.
// TODO(stevenjb): Investigate why we are missing updates then
// rely on watched network updates and only request updates here for
// new networks.
// Use update_request map to store network priority.
network_update_requests_[service_path] = network_priority++;
wifi_scanning_ = true;
RequestNetworkServiceInfo(service_path.c_str(),
&NetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
// Request updates for watched networks. Does not affect network lists.
// Existing networks will be updated. There should not be any new networks
// in this list, but if there are they will be added appropriately.
void UpdateWatchedNetworkServiceList(const ListValue* services) {
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
VLOG(1) << "Watched Service: " << service_path;
RequestNetworkServiceInfo(
service_path.c_str(), &NetworkServiceUpdate, this);
}
}
}
// Request the active profile which lists the remembered networks.
void RequestRememberedNetworksUpdate() {
RequestNetworkProfile(
active_profile_path_.c_str(), &ProfileUpdate, this);
}
// Update the list of remembered (profile) networks, and request associated
// service updates.
void UpdateRememberedServiceList(const char* profile_path,
const ListValue* profile_entries) {
// Copy the list of existing networks to "old" and clear the map and list.
NetworkMap old_network_map = remembered_network_map_;
ClearRememberedNetworks(false /*don't delete*/);
// |profile_entries| represents a complete list of remembered networks.
for (ListValue::const_iterator iter = profile_entries->begin();
iter != profile_entries->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and list. Otherwise it will get added when
// RememberedNetworkServiceUpdate calls ParseRememberedNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddRememberedNetwork(found->second);
old_network_map.erase(found);
}
// Always request updates for remembered networks.
RequestNetworkProfileEntry(profile_path,
service_path.c_str(),
&RememberedNetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
Network* CreateNewNetwork(ConnectionType type,
const std::string& service_path) {
switch (type) {
case TYPE_ETHERNET: {
EthernetNetwork* ethernet = new EthernetNetwork(service_path);
return ethernet;
}
case TYPE_WIFI: {
WifiNetwork* wifi = new WifiNetwork(service_path);
return wifi;
}
case TYPE_CELLULAR: {
CellularNetwork* cellular = new CellularNetwork(service_path);
return cellular;
}
case TYPE_VPN: {
VirtualNetwork* vpn = new VirtualNetwork(service_path);
return vpn;
}
default: {
LOG(WARNING) << "Unknown service type: " << type;
return new Network(service_path, type);
}
}
}
Network* ParseNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network = FindNetworkByPath(service_path);
if (!network) {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddNetwork(network);
}
network->ParseInfo(info); // virtual.
UpdateActiveNetwork(network);
// Find and erase entry in update_requests, and set network priority.
PriorityMap::iterator found2 = network_update_requests_.find(service_path);
if (found2 != network_update_requests_.end()) {
network->priority_ = found2->second;
network_update_requests_.erase(found2);
if (network_update_requests_.empty()) {
// Clear wifi_scanning_ when we have no pending requests.
wifi_scanning_ = false;
}
} else {
// TODO(stevenjb): Enable warning once UpdateNetworkServiceList is fixed.
// LOG(WARNING) << "ParseNetwork called with no update request entry: "
// << service_path;
}
VLOG(1) << "ParseNetwork:" << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
Network* ParseRememberedNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network;
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found != remembered_network_map_.end()) {
network = found->second;
} else {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddRememberedNetwork(network);
}
network->ParseInfo(info); // virtual.
VLOG(1) << "ParseRememberedNetwork:" << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
void ClearNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&network_map_);
network_map_.clear();
ethernet_ = NULL;
active_wifi_ = NULL;
active_cellular_ = NULL;
active_virtual_ = NULL;
wifi_networks_.clear();
cellular_networks_.clear();
virtual_networks_.clear();
}
void ClearRememberedNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&remembered_network_map_);
remembered_network_map_.clear();
remembered_wifi_networks_.clear();
}
////////////////////////////////////////////////////////////////////////////
// NetworkDevice list management functions.
// Update device list, and request associated device updates.
// |devices| represents a complete list of devices.
void UpdateNetworkDeviceList(const ListValue* devices) {
NetworkDeviceMap old_device_map = device_map_;
device_map_.clear();
VLOG(2) << "Updating Device List.";
for (ListValue::const_iterator iter = devices->begin();
iter != devices->end(); ++iter) {
std::string device_path;
(*iter)->GetAsString(&device_path);
if (!device_path.empty()) {
NetworkDeviceMap::iterator found = old_device_map.find(device_path);
if (found != old_device_map.end()) {
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = found->second;
old_device_map.erase(found);
}
RequestNetworkDeviceInfo(
device_path.c_str(), &NetworkDeviceUpdate, this);
}
}
// Delete any old devices that no longer exist.
for (NetworkDeviceMap::iterator iter = old_device_map.begin();
iter != old_device_map.end(); ++iter) {
delete iter->second;
}
}
void DeleteDevice(const std::string& device_path) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
if (found == device_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant device: "
<< device_path;
return;
}
VLOG(2) << " Deleting device: " << device_path;
NetworkDevice* device = found->second;
device_map_.erase(found);
delete device;
}
void ParseNetworkDevice(const std::string& device_path,
const DictionaryValue* info) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
NetworkDevice* device;
if (found != device_map_.end()) {
device = found->second;
} else {
device = new NetworkDevice(device_path);
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = device;
}
device->ParseInfo(info);
VLOG(1) << "ParseNetworkDevice:" << device->name();
NotifyNetworkManagerChanged(false); // Not forced.
}
////////////////////////////////////////////////////////////////////////////
void EnableNetworkDeviceType(ConnectionType device, bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to enable a device that's already enabled: "
<< device;
return;
}
if (!enable && !(enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to disable a device that's already disabled: "
<< device;
return;
}
RequestNetworkDeviceEnable(ConnectionTypeToString(device), enable);
}
////////////////////////////////////////////////////////////////////////////
// Notifications.
// We call this any time something in NetworkLibrary changes.
// TODO(stevenjb): We should consider breaking this into multiplie
// notifications, e.g. connection state, devices, services, etc.
void NotifyNetworkManagerChanged(bool force_update) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Cancel any pending signals.
if (notify_task_) {
notify_task_->Cancel();
notify_task_ = NULL;
}
if (force_update) {
// Signal observers now.
SignalNetworkManagerObservers();
} else {
// Schedule a deleayed signal to limit the frequency of notifications.
notify_task_ = NewRunnableMethod(
this, &NetworkLibraryImpl::SignalNetworkManagerObservers);
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, notify_task_,
kNetworkNotifyDelayMs);
}
}
void SignalNetworkManagerObservers() {
notify_task_ = NULL;
FOR_EACH_OBSERVER(NetworkManagerObserver,
network_manager_observers_,
OnNetworkManagerChanged(this));
}
void NotifyNetworkChanged(Network* network) {
DCHECK(network);
NetworkObserverMap::const_iterator iter = network_observers_.find(
network->service_path());
if (iter != network_observers_.end()) {
FOR_EACH_OBSERVER(NetworkObserver,
*(iter->second),
OnNetworkChanged(this, network));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
network->service_path();
}
}
void NotifyCellularDataPlanChanged() {
FOR_EACH_OBSERVER(CellularDataPlanObserver,
data_plan_observers_,
OnCellularDataPlanChanged(this));
}
void NotifyUserConnectionInitiated(const Network* network) {
FOR_EACH_OBSERVER(UserActionObserver,
user_action_observers_,
OnConnectionInitiated(this, network));
}
////////////////////////////////////////////////////////////////////////////
// Service updates.
void UpdateNetworkStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
Network* network = FindNetworkByPath(path);
if (network) {
VLOG(1) << "UpdateNetworkStatus: " << network->name() << "." << key;
// Note: ParseValue is virtual.
int index = property_index_parser().Get(std::string(key));
if (!network->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkStatus: Error parsing: "
<< path << "." << key;
}
NotifyNetworkChanged(network);
// Anything observing the manager needs to know about any service change.
NotifyNetworkManagerChanged(false); // Not forced.
}
}
////////////////////////////////////////////////////////////////////////////
// Data Plans.
const CellularDataPlan* GetSignificantDataPlanFromVector(
const CellularDataPlanVector* plans) const {
const CellularDataPlan* significant = NULL;
for (CellularDataPlanVector::const_iterator iter = plans->begin();
iter != plans->end(); ++iter) {
// Set significant to the first plan or to first non metered base plan.
if (significant == NULL ||
significant->plan_type == CELLULAR_DATA_PLAN_METERED_BASE)
significant = *iter;
}
return significant;
}
CellularNetwork::DataLeft GetDataLeft(
CellularDataPlanVector* data_plans) {
const CellularDataPlan* plan = GetSignificantDataPlanFromVector(data_plans);
if (!plan)
return CellularNetwork::DATA_UNKNOWN;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
base::TimeDelta remaining = plan->remaining_time();
if (remaining <= base::TimeDelta::FromSeconds(0))
return CellularNetwork::DATA_NONE;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs))
return CellularNetwork::DATA_VERY_LOW;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs))
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
} else if (plan->plan_type == CELLULAR_DATA_PLAN_METERED_PAID ||
plan->plan_type == CELLULAR_DATA_PLAN_METERED_BASE) {
int64 remaining = plan->remaining_data();
if (remaining <= 0)
return CellularNetwork::DATA_NONE;
if (remaining <= kCellularDataVeryLowBytes)
return CellularNetwork::DATA_VERY_LOW;
// For base plans, we do not care about low data.
if (remaining <= kCellularDataLowBytes &&
plan->plan_type != CELLULAR_DATA_PLAN_METERED_BASE)
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
}
return CellularNetwork::DATA_UNKNOWN;
}
void UpdateCellularDataPlan(const std::string& service_path,
const CellularDataPlanList* data_plan_list) {
VLOG(1) << "Updating cellular data plans for: " << service_path;
CellularDataPlanVector* data_plans = NULL;
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
data_plans = found->second;
data_plans->reset(); // This will delete existing data plans.
} else {
data_plans = new CellularDataPlanVector;
data_plan_map_[service_path] = data_plans;
}
for (size_t i = 0; i < data_plan_list->plans_size; i++) {
const CellularDataPlanInfo* info(data_plan_list->GetCellularDataPlan(i));
CellularDataPlan* plan = new CellularDataPlan(*info);
data_plans->push_back(plan);
VLOG(2) << " Plan: " << plan->GetPlanDesciption()
<< " : " << plan->GetDataRemainingDesciption();
}
// Now, update any matching cellular network's cached data
CellularNetwork* cellular = FindCellularNetworkByPath(service_path);
if (cellular) {
CellularNetwork::DataLeft data_left;
// If the network needs a new plan, then there's no data.
if (cellular->needs_new_plan())
data_left = CellularNetwork::DATA_NONE;
else
data_left = GetDataLeft(data_plans);
VLOG(2) << " Data left: " << data_left
<< " Need plan: " << cellular->needs_new_plan();
cellular->set_data_left(data_left);
}
NotifyCellularDataPlanChanged();
}
////////////////////////////////////////////////////////////////////////////
void Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
if (EnsureCrosLoaded()) {
VLOG(1) << "Requesting initial network manager info from libcros.";
RequestNetworkManagerInfo(&NetworkManagerUpdate, this);
}
}
void InitTestData() {
is_locked_ = false;
// Devices
int devices =
(1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR);
available_devices_ = devices;
enabled_devices_ = devices;
connected_devices_ = devices;
// Networks
ClearNetworks(true /*delete networks*/);
ethernet_ = new EthernetNetwork("eth1");
ethernet_->set_connected(true);
AddNetwork(ethernet_);
WifiNetwork* wifi1 = new WifiNetwork("fw1");
wifi1->set_name("Fake Wifi Connected");
wifi1->set_strength(90);
wifi1->set_connected(true);
wifi1->set_encryption(SECURITY_NONE);
AddNetwork(wifi1);
WifiNetwork* wifi2 = new WifiNetwork("fw2");
wifi2->set_name("Fake Wifi");
wifi2->set_strength(70);
wifi2->set_connected(false);
wifi2->set_encryption(SECURITY_NONE);
AddNetwork(wifi2);
WifiNetwork* wifi3 = new WifiNetwork("fw3");
wifi3->set_name("Fake Wifi Encrypted");
wifi3->set_strength(60);
wifi3->set_connected(false);
wifi3->set_encryption(SECURITY_WEP);
wifi3->set_passphrase_required(true);
AddNetwork(wifi3);
WifiNetwork* wifi4 = new WifiNetwork("fw4");
wifi4->set_name("Fake Wifi 802.1x");
wifi4->set_strength(50);
wifi4->set_connected(false);
wifi4->set_connectable(false);
wifi4->set_encryption(SECURITY_8021X);
wifi4->set_identity("nobody@google.com");
wifi4->set_cert_path("SETTINGS:key_id=3,cert_id=3,pin=111111");
AddNetwork(wifi4);
active_wifi_ = wifi1;
CellularNetwork* cellular1 = new CellularNetwork("fc1");
cellular1->set_name("Fake Cellular");
cellular1->set_strength(70);
cellular1->set_connected(false);
cellular1->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular1->set_payment_url(std::string("http://www.google.com"));
cellular1->set_usage_url(std::string("http://www.google.com"));
cellular1->set_network_technology(NETWORK_TECHNOLOGY_EVDO);
cellular1->set_roaming_state(ROAMING_STATE_ROAMING);
CellularDataPlan* base_plan = new CellularDataPlan();
base_plan->plan_name = "Base plan";
base_plan->plan_type = CELLULAR_DATA_PLAN_METERED_BASE;
base_plan->plan_data_bytes = 100ll * 1024 * 1024;
base_plan->data_bytes_used = 75ll * 1024 * 1024;
CellularDataPlanVector* data_plans = new CellularDataPlanVector();
data_plan_map_[cellular1->service_path()] = data_plans;
data_plans->push_back(base_plan);
CellularDataPlan* paid_plan = new CellularDataPlan();
paid_plan->plan_name = "Paid plan";
paid_plan->plan_type = CELLULAR_DATA_PLAN_METERED_PAID;
paid_plan->plan_data_bytes = 5ll * 1024 * 1024 * 1024;
paid_plan->data_bytes_used = 3ll * 1024 * 1024 * 1024;
data_plans->push_back(paid_plan);
AddNetwork(cellular1);
active_cellular_ = cellular1;
// Remembered Networks
ClearRememberedNetworks(true /*delete networks*/);
WifiNetwork* remembered_wifi2 = new WifiNetwork("fw2");
remembered_wifi2->set_name("Fake Wifi 2");
remembered_wifi2->set_strength(70);
remembered_wifi2->set_connected(true);
remembered_wifi2->set_encryption(SECURITY_WEP);
AddRememberedNetwork(remembered_wifi2);
wifi_scanning_ = false;
offline_mode_ = false;
}
// Network manager observer list
ObserverList<NetworkManagerObserver> network_manager_observers_;
// Cellular data plan observer list
ObserverList<CellularDataPlanObserver> data_plan_observers_;
// User action observer list
ObserverList<UserActionObserver> user_action_observers_;
// Network observer map
NetworkObserverMap network_observers_;
// For monitoring network manager status changes.
PropertyChangeMonitor network_manager_monitor_;
// For monitoring data plan changes to the connected cellular network.
DataPlanUpdateMonitor data_plan_monitor_;
// Network login observer.
scoped_ptr<NetworkLoginObserver> network_login_observer_;
// A service path based map of all Networks.
NetworkMap network_map_;
// A service path based map of all remembered Networks.
NetworkMap remembered_network_map_;
// A list of services that we are awaiting updates for.
PriorityMap network_update_requests_;
// A device path based map of all NetworkDevices.
NetworkDeviceMap device_map_;
// A network service path based map of all CellularDataPlanVectors.
CellularDataPlanMap data_plan_map_;
// The ethernet network.
EthernetNetwork* ethernet_;
// The list of available wifi networks.
WifiNetworkVector wifi_networks_;
// The current connected (or connecting) wifi network.
WifiNetwork* active_wifi_;
// The remembered wifi networks.
WifiNetworkVector remembered_wifi_networks_;
// The list of available cellular networks.
CellularNetworkVector cellular_networks_;
// The current connected (or connecting) cellular network.
CellularNetwork* active_cellular_;
// The list of available virtual networks.
VirtualNetworkVector virtual_networks_;
// The current connected (or connecting) virtual network.
VirtualNetwork* active_virtual_;
// The path of the active profile (for retrieving remembered services).
std::string active_profile_path_;
// The current available network devices. Bitwise flag of ConnectionTypes.
int available_devices_;
// The current enabled network devices. Bitwise flag of ConnectionTypes.
int enabled_devices_;
// The current connected network devices. Bitwise flag of ConnectionTypes.
int connected_devices_;
// True if we are currently scanning for wifi networks.
bool wifi_scanning_;
// Currently not implemented. TODO: implement or eliminate.
bool offline_mode_;
// True if access network library is locked.
bool is_locked_;
// Delayed task to notify a network change.
CancelableTask* notify_task_;
// Cellular plan payment time.
base::Time cellular_plan_payment_time_;
// Temporary connection data for async connect calls.
struct ConnectData {
ConnectData() : auto_connect(false) {}
void SetData(const std::string& n,
const std::string& p,
const std::string& id,
const std::string& cert,
bool autocon) {
name = n;
passphrase = p;
identity = id;
certpath = cert;
auto_connect = autocon;
}
std::string name;
std::string passphrase;
std::string identity;
std::string certpath;
bool auto_connect;
};
ConnectData connect_data_;
DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl);
};
class NetworkLibraryStubImpl : public NetworkLibrary {
public:
NetworkLibraryStubImpl()
: ip_address_("1.1.1.1"),
ethernet_(new EthernetNetwork("eth0")),
active_wifi_(NULL),
active_cellular_(NULL) {
}
~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; }
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {}
virtual void Lock() {}
virtual void Unlock() {}
virtual bool IsLocked() { return true; }
virtual void AddCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void AddUserActionObserver(UserActionObserver* observer) {}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {}
virtual const EthernetNetwork* ethernet_network() const {
return ethernet_;
}
virtual bool ethernet_connecting() const { return false; }
virtual bool ethernet_connected() const { return true; }
virtual const WifiNetwork* wifi_network() const {
return active_wifi_;
}
virtual bool wifi_connecting() const { return false; }
virtual bool wifi_connected() const { return false; }
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const { return false; }
virtual bool cellular_connected() const { return false; }
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const { return false; }
virtual bool virtual_network_connected() const { return false; }
bool Connected() const { return true; }
bool Connecting() const { return false; }
const std::string& IPAddress() const { return ip_address_; }
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
virtual bool has_cellular_networks() const {
return cellular_networks_.begin() != cellular_networks_.end();
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const { return NULL; }
virtual Network* FindNetworkByPath(
const std::string& path) const { return NULL; }
virtual WifiNetwork* FindWifiNetworkByPath(
const std::string& path) const { return NULL; }
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const { return NULL; }
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const { return NULL; }
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const { return NULL; }
virtual void RequestNetworkScan() {}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
return false;
}
virtual void ConnectToWifiNetwork(WifiNetwork* network) {}
virtual void ConnectToWifiNetwork(const std::string& service_path) {}
virtual void ConnectToWifiNetwork(ConnectionSecurity security,
const std::string& ssid,
const std::string& passphrase,
const std::string& identity,
const std::string& certpath,
bool auto_connect) {}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {}
virtual void SignalCellularPlanPayment() {}
virtual bool HasRecentCellularPlanPayment() { return false; }
virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {}
virtual void ForgetWifiNetwork(const std::string& service_path) {}
virtual bool ethernet_available() const { return true; }
virtual bool wifi_available() const { return false; }
virtual bool cellular_available() const { return false; }
virtual bool ethernet_enabled() const { return true; }
virtual bool wifi_enabled() const { return false; }
virtual bool cellular_enabled() const { return false; }
virtual bool wifi_scanning() const { return false; }
virtual const Network* active_network() const { return NULL; }
virtual bool offline_mode() const { return false; }
virtual void EnableEthernetNetworkDevice(bool enable) {}
virtual void EnableWifiNetworkDevice(bool enable) {}
virtual void EnableCellularNetworkDevice(bool enable) {}
virtual void EnableOfflineMode(bool enable) {}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address) {
hardware_address->clear();
return NetworkIPConfigVector();
}
virtual std::string GetHtmlInfo(int refresh) { return std::string(); }
private:
std::string ip_address_;
EthernetNetwork* ethernet_;
WifiNetwork* active_wifi_;
CellularNetwork* active_cellular_;
VirtualNetwork* active_virtual_;
WifiNetworkVector wifi_networks_;
CellularNetworkVector cellular_networks_;
VirtualNetworkVector virtual_networks_;
};
// static
NetworkLibrary* NetworkLibrary::GetImpl(bool stub) {
if (stub)
return new NetworkLibraryStubImpl();
else
return new NetworkLibraryImpl();
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl);
Use ClearNetworkServiceProperty from libcros to clear network properties.
BUG=chromium-os:11412
TEST=make sure you can connect to 802.1x networks.
Review URL: http://codereview.chromium.org/6749005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@79458 0039d316-1c4b-4281-b951-d872f2087c98
// 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/chromeos/cros/network_library.h"
#include <algorithm>
#include <map>
#include "base/i18n/time_formatting.h"
#include "base/metrics/histogram.h"
#include "base/stl_util-inl.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/network_login_observer.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/common/time_format.h"
#include "content/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
////////////////////////////////////////////////////////////////////////////////
// Implementation notes.
// NetworkLibraryImpl manages a series of classes that describe network devices
// and services:
//
// NetworkDevice: e.g. ethernet, wifi modem, cellular modem
// device_map_: canonical map<name,NetworkDevice*> for devices
//
// Network: a network service ("network").
// network_map_: canonical map<name,Network*> for all visible networks.
// EthernetNetwork
// ethernet_: EthernetNetwork* to the active ethernet network in network_map_.
// WirelessNetwork: a Wifi or Cellular Network.
// WifiNetwork
// active_wifi_: WifiNetwork* to the active wifi network in network_map_.
// wifi_networks_: ordered vector of WifiNetwork* entries in network_map_,
// in descending order of importance.
// CellularNetwork
// active_cellular_: Cellular version of wifi_.
// cellular_networks_: Cellular version of wifi_.
// remembered_network_map_: a canonical map<name,Network*> for all networks
// remembered in the active Profile ("favorites").
// remembered_wifi_networks_: ordered vector of WifiNetwork* entries in
// remembered_network_map_, in descending order of preference.
//
// network_manager_monitor_: a handle to the libcros network Manager handler.
// NetworkManagerStatusChanged: This handles all messages from the Manager.
// Messages are parsed here and the appropriate updates are then requested.
//
// UpdateNetworkServiceList: This is the primary Manager handler. It handles
// the "Services" message which list all visible networks. The handler
// rebuilds the network lists without destroying existing Network structures,
// then requests neccessary updates to be fetched asynchronously from
// libcros (RequestNetworkServiceInfo).
//
// TODO(stevenjb): Document cellular data plan handlers.
//
// AddNetworkObserver: Adds an observer for a specific network.
// NetworkObserverList: A monitor and list of observers of a network.
// network_monitor_: a handle to the libcros network Service handler.
// UpdateNetworkStatus: This handles changes to a monitored service, typically
// changes to transient states like Strength. (Note: also updates State).
//
////////////////////////////////////////////////////////////////////////////////
namespace chromeos {
// Local constants.
namespace {
// Only send network change notifications to observers once every 50ms.
const int kNetworkNotifyDelayMs = 50;
// How long we should remember that cellular plan payment was received.
const int kRecentPlanPaymentHours = 6;
// D-Bus interface string constants.
// Flimflam property names.
const char* kSecurityProperty = "Security";
const char* kPassphraseProperty = "Passphrase";
const char* kIdentityProperty = "Identity";
const char* kCertPathProperty = "CertPath";
const char* kPassphraseRequiredProperty = "PassphraseRequired";
const char* kProfilesProperty = "Profiles";
const char* kServicesProperty = "Services";
const char* kServiceWatchListProperty = "ServiceWatchList";
const char* kAvailableTechnologiesProperty = "AvailableTechnologies";
const char* kEnabledTechnologiesProperty = "EnabledTechnologies";
const char* kConnectedTechnologiesProperty = "ConnectedTechnologies";
const char* kDefaultTechnologyProperty = "DefaultTechnology";
const char* kOfflineModeProperty = "OfflineMode";
const char* kSignalStrengthProperty = "Strength";
const char* kNameProperty = "Name";
const char* kStateProperty = "State";
const char* kConnectivityStateProperty = "ConnectivityState";
const char* kTypeProperty = "Type";
const char* kDeviceProperty = "Device";
const char* kActivationStateProperty = "Cellular.ActivationState";
const char* kNetworkTechnologyProperty = "Cellular.NetworkTechnology";
const char* kRoamingStateProperty = "Cellular.RoamingState";
const char* kOperatorNameProperty = "Cellular.OperatorName";
const char* kOperatorCodeProperty = "Cellular.OperatorCode";
const char* kPaymentURLProperty = "Cellular.OlpUrl";
const char* kUsageURLProperty = "Cellular.UsageUrl";
const char* kFavoriteProperty = "Favorite";
const char* kConnectableProperty = "Connectable";
const char* kAutoConnectProperty = "AutoConnect";
const char* kIsActiveProperty = "IsActive";
const char* kModeProperty = "Mode";
const char* kErrorProperty = "Error";
const char* kActiveProfileProperty = "ActiveProfile";
const char* kEntriesProperty = "Entries";
const char* kDevicesProperty = "Devices";
// Flimflam device info property names.
const char* kScanningProperty = "Scanning";
const char* kCarrierProperty = "Cellular.Carrier";
const char* kMeidProperty = "Cellular.MEID";
const char* kImeiProperty = "Cellular.IMEI";
const char* kImsiProperty = "Cellular.IMSI";
const char* kEsnProperty = "Cellular.ESN";
const char* kMdnProperty = "Cellular.MDN";
const char* kMinProperty = "Cellular.MIN";
const char* kModelIDProperty = "Cellular.ModelID";
const char* kManufacturerProperty = "Cellular.Manufacturer";
const char* kFirmwareRevisionProperty = "Cellular.FirmwareRevision";
const char* kHardwareRevisionProperty = "Cellular.HardwareRevision";
const char* kLastDeviceUpdateProperty = "Cellular.LastDeviceUpdate";
const char* kPRLVersionProperty = "Cellular.PRLVersion"; // (INT16)
// Flimflam type options.
const char* kTypeEthernet = "ethernet";
const char* kTypeWifi = "wifi";
const char* kTypeWimax = "wimax";
const char* kTypeBluetooth = "bluetooth";
const char* kTypeCellular = "cellular";
const char* kTypeVPN = "vpn";
// Flimflam mode options.
const char* kModeManaged = "managed";
const char* kModeAdhoc = "adhoc";
// Flimflam security options.
const char* kSecurityWpa = "wpa";
const char* kSecurityWep = "wep";
const char* kSecurityRsn = "rsn";
const char* kSecurity8021x = "802_1x";
const char* kSecurityNone = "none";
// Flimflam EAP property names.
const char* kEapIdentityProperty = "EAP.Identity";
const char* kEapMethodProperty = "EAP.EAP";
const char* kEapPhase2AuthProperty = "EAP.InnerEAP";
const char* kEapAnonymousIdentityProperty = "EAP.AnonymousIdentity";
const char* kEapClientCertProperty = "EAP.ClientCert";
const char* kEapCertIDProperty = "EAP.CertID";
const char* kEapPrivateKeyProperty = "EAP.PrivateKey";
const char* kEapPrivateKeyPasswordProperty = "EAP.PrivateKeyPassword";
const char* kEapKeyIDProperty = "EAP.KeyID";
const char* kEapCACertProperty = "EAP.CACert";
const char* kEapCACertIDProperty = "EAP.CACertID";
const char* kEapUseSystemCAsProperty = "EAP.UseSystemCAs";
const char* kEapPinProperty = "EAP.PIN";
const char* kEapPasswordProperty = "EAP.Password";
const char* kEapKeyMgmtProperty = "EAP.KeyMgmt";
// Flimflam EAP method options.
const std::string& kEapMethodPEAP = "PEAP";
const std::string& kEapMethodTLS = "TLS";
const std::string& kEapMethodTTLS = "TTLS";
const std::string& kEapMethodLEAP = "LEAP";
// Flimflam EAP phase 2 auth options.
const std::string& kEapPhase2AuthPEAPMD5 = "auth=MD5";
const std::string& kEapPhase2AuthPEAPMSCHAPV2 = "auth=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMD5 = "autheap=MD5";
const std::string& kEapPhase2AuthTTLSMSCHAPV2 = "autheap=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMSCHAP = "autheap=MSCHAP";
const std::string& kEapPhase2AuthTTLSPAP = "autheap=PAP";
const std::string& kEapPhase2AuthTTLSCHAP = "autheap=CHAP";
// Flimflam state options.
const char* kStateIdle = "idle";
const char* kStateCarrier = "carrier";
const char* kStateAssociation = "association";
const char* kStateConfiguration = "configuration";
const char* kStateReady = "ready";
const char* kStateDisconnect = "disconnect";
const char* kStateFailure = "failure";
const char* kStateActivationFailure = "activation-failure";
// Flimflam connectivity state options.
const char* kConnStateUnrestricted = "unrestricted";
const char* kConnStateRestricted = "restricted";
const char* kConnStateNone = "none";
// Flimflam network technology options.
const char* kNetworkTechnology1Xrtt = "1xRTT";
const char* kNetworkTechnologyEvdo = "EVDO";
const char* kNetworkTechnologyGprs = "GPRS";
const char* kNetworkTechnologyEdge = "EDGE";
const char* kNetworkTechnologyUmts = "UMTS";
const char* kNetworkTechnologyHspa = "HSPA";
const char* kNetworkTechnologyHspaPlus = "HSPA+";
const char* kNetworkTechnologyLte = "LTE";
const char* kNetworkTechnologyLteAdvanced = "LTE Advanced";
// Flimflam roaming state options
const char* kRoamingStateHome = "home";
const char* kRoamingStateRoaming = "roaming";
const char* kRoamingStateUnknown = "unknown";
// Flimflam activation state options
const char* kActivationStateActivated = "activated";
const char* kActivationStateActivating = "activating";
const char* kActivationStateNotActivated = "not-activated";
const char* kActivationStatePartiallyActivated = "partially-activated";
const char* kActivationStateUnknown = "unknown";
// Flimflam error options.
const char* kErrorOutOfRange = "out-of-range";
const char* kErrorPinMissing = "pin-missing";
const char* kErrorDhcpFailed = "dhcp-failed";
const char* kErrorConnectFailed = "connect-failed";
const char* kErrorBadPassphrase = "bad-passphrase";
const char* kErrorBadWEPKey = "bad-wepkey";
const char* kErrorActivationFailed = "activation-failed";
const char* kErrorNeedEvdo = "need-evdo";
const char* kErrorNeedHomeNetwork = "need-home-network";
const char* kErrorOtaspFailed = "otasp-failed";
const char* kErrorAaaFailed = "aaa-failed";
// Flimflam error messages.
const char* kErrorPassphraseRequiredMsg = "Passphrase required";
const char* kUnknownString = "UNKNOWN";
////////////////////////////////////////////////////////////////////////////
static const char* ConnectionTypeToString(ConnectionType type) {
switch (type) {
case TYPE_UNKNOWN:
break;
case TYPE_ETHERNET:
return kTypeEthernet;
case TYPE_WIFI:
return kTypeWifi;
case TYPE_WIMAX:
return kTypeWimax;
case TYPE_BLUETOOTH:
return kTypeBluetooth;
case TYPE_CELLULAR:
return kTypeCellular;
case TYPE_VPN:
return kTypeVPN;
}
LOG(ERROR) << "ConnectionTypeToString called with unknown type: " << type;
return kUnknownString;
}
// TODO(stevenjb/njw): Deprecate in favor of setting EAP properties.
static const char* SecurityToString(ConnectionSecurity security) {
switch (security) {
case SECURITY_UNKNOWN:
break;
case SECURITY_8021X:
return kSecurity8021x;
case SECURITY_RSN:
return kSecurityRsn;
case SECURITY_WPA:
return kSecurityWpa;
case SECURITY_WEP:
return kSecurityWep;
case SECURITY_NONE:
return kSecurityNone;
}
LOG(ERROR) << "SecurityToString called with unknown type: " << security;
return kUnknownString;
}
////////////////////////////////////////////////////////////////////////////
// Helper class to cache maps of strings to enums.
template <typename Type>
class StringToEnum {
public:
struct Pair {
const char* key;
const Type value;
};
explicit StringToEnum(const Pair* list, size_t num_entries, Type unknown)
: unknown_value_(unknown) {
for (size_t i = 0; i < num_entries; ++i, ++list)
enum_map_[list->key] = list->value;
}
Type Get(const std::string& type) const {
EnumMapConstIter iter = enum_map_.find(type);
if (iter != enum_map_.end())
return iter->second;
return unknown_value_;
}
private:
typedef typename std::map<std::string, Type> EnumMap;
typedef typename std::map<std::string, Type>::const_iterator EnumMapConstIter;
EnumMap enum_map_;
Type unknown_value_;
DISALLOW_COPY_AND_ASSIGN(StringToEnum);
};
////////////////////////////////////////////////////////////////////////////
enum PropertyIndex {
PROPERTY_INDEX_ACTIVATION_STATE,
PROPERTY_INDEX_ACTIVE_PROFILE,
PROPERTY_INDEX_AUTO_CONNECT,
PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES,
PROPERTY_INDEX_CARRIER,
PROPERTY_INDEX_CERT_PATH,
PROPERTY_INDEX_CONNECTABLE,
PROPERTY_INDEX_CONNECTED_TECHNOLOGIES,
PROPERTY_INDEX_CONNECTIVITY_STATE,
PROPERTY_INDEX_DEFAULT_TECHNOLOGY,
PROPERTY_INDEX_DEVICE,
PROPERTY_INDEX_DEVICES,
PROPERTY_INDEX_EAP_IDENTITY,
PROPERTY_INDEX_EAP_METHOD,
PROPERTY_INDEX_EAP_PHASE_2_AUTH,
PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY,
PROPERTY_INDEX_EAP_CLIENT_CERT,
PROPERTY_INDEX_EAP_CERT_ID,
PROPERTY_INDEX_EAP_PRIVATE_KEY,
PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD,
PROPERTY_INDEX_EAP_KEY_ID,
PROPERTY_INDEX_EAP_CA_CERT,
PROPERTY_INDEX_EAP_CA_CERT_ID,
PROPERTY_INDEX_EAP_USE_SYSTEM_CAS,
PROPERTY_INDEX_EAP_PIN,
PROPERTY_INDEX_EAP_PASSWORD,
PROPERTY_INDEX_EAP_KEY_MGMT,
PROPERTY_INDEX_ENABLED_TECHNOLOGIES,
PROPERTY_INDEX_ERROR,
PROPERTY_INDEX_ESN,
PROPERTY_INDEX_FAVORITE,
PROPERTY_INDEX_FIRMWARE_REVISION,
PROPERTY_INDEX_HARDWARE_REVISION,
PROPERTY_INDEX_IDENTITY,
PROPERTY_INDEX_IMEI,
PROPERTY_INDEX_IMSI,
PROPERTY_INDEX_IS_ACTIVE,
PROPERTY_INDEX_LAST_DEVICE_UPDATE,
PROPERTY_INDEX_MANUFACTURER,
PROPERTY_INDEX_MDN,
PROPERTY_INDEX_MEID,
PROPERTY_INDEX_MIN,
PROPERTY_INDEX_MODE,
PROPERTY_INDEX_MODEL_ID,
PROPERTY_INDEX_NAME,
PROPERTY_INDEX_NETWORK_TECHNOLOGY,
PROPERTY_INDEX_OFFLINE_MODE,
PROPERTY_INDEX_OPERATOR_CODE,
PROPERTY_INDEX_OPERATOR_NAME,
PROPERTY_INDEX_PASSPHRASE,
PROPERTY_INDEX_PASSPHRASE_REQUIRED,
PROPERTY_INDEX_PAYMENT_URL,
PROPERTY_INDEX_PRL_VERSION,
PROPERTY_INDEX_PROFILES,
PROPERTY_INDEX_ROAMING_STATE,
PROPERTY_INDEX_SCANNING,
PROPERTY_INDEX_SECURITY,
PROPERTY_INDEX_SERVICES,
PROPERTY_INDEX_SERVICE_WATCH_LIST,
PROPERTY_INDEX_SIGNAL_STRENGTH,
PROPERTY_INDEX_STATE,
PROPERTY_INDEX_TYPE,
PROPERTY_INDEX_UNKNOWN,
PROPERTY_INDEX_USAGE_URL,
};
StringToEnum<PropertyIndex>::Pair property_index_table[] = {
{ kActivationStateProperty, PROPERTY_INDEX_ACTIVATION_STATE },
{ kActiveProfileProperty, PROPERTY_INDEX_ACTIVE_PROFILE },
{ kAutoConnectProperty, PROPERTY_INDEX_AUTO_CONNECT },
{ kAvailableTechnologiesProperty, PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES },
{ kCarrierProperty, PROPERTY_INDEX_CARRIER },
{ kCertPathProperty, PROPERTY_INDEX_CERT_PATH },
{ kConnectableProperty, PROPERTY_INDEX_CONNECTABLE },
{ kConnectedTechnologiesProperty, PROPERTY_INDEX_CONNECTED_TECHNOLOGIES },
{ kConnectivityStateProperty, PROPERTY_INDEX_CONNECTIVITY_STATE },
{ kDefaultTechnologyProperty, PROPERTY_INDEX_DEFAULT_TECHNOLOGY },
{ kDeviceProperty, PROPERTY_INDEX_DEVICE },
{ kDevicesProperty, PROPERTY_INDEX_DEVICES },
{ kEapIdentityProperty, PROPERTY_INDEX_EAP_IDENTITY },
{ kEapMethodProperty, PROPERTY_INDEX_EAP_METHOD },
{ kEapPhase2AuthProperty, PROPERTY_INDEX_EAP_PHASE_2_AUTH },
{ kEapAnonymousIdentityProperty, PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY },
{ kEapClientCertProperty, PROPERTY_INDEX_EAP_CLIENT_CERT },
{ kEapCertIDProperty, PROPERTY_INDEX_EAP_CERT_ID },
{ kEapPrivateKeyProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY },
{ kEapPrivateKeyPasswordProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD },
{ kEapKeyIDProperty, PROPERTY_INDEX_EAP_KEY_ID },
{ kEapCACertProperty, PROPERTY_INDEX_EAP_CA_CERT },
{ kEapCACertIDProperty, PROPERTY_INDEX_EAP_CA_CERT_ID },
{ kEapUseSystemCAsProperty, PROPERTY_INDEX_EAP_USE_SYSTEM_CAS },
{ kEapPinProperty, PROPERTY_INDEX_EAP_PIN },
{ kEapPasswordProperty, PROPERTY_INDEX_EAP_PASSWORD },
{ kEapKeyMgmtProperty, PROPERTY_INDEX_EAP_KEY_MGMT },
{ kEnabledTechnologiesProperty, PROPERTY_INDEX_ENABLED_TECHNOLOGIES },
{ kErrorProperty, PROPERTY_INDEX_ERROR },
{ kEsnProperty, PROPERTY_INDEX_ESN },
{ kFavoriteProperty, PROPERTY_INDEX_FAVORITE },
{ kFirmwareRevisionProperty, PROPERTY_INDEX_FIRMWARE_REVISION },
{ kHardwareRevisionProperty, PROPERTY_INDEX_HARDWARE_REVISION },
{ kIdentityProperty, PROPERTY_INDEX_IDENTITY },
{ kImeiProperty, PROPERTY_INDEX_IMEI },
{ kImsiProperty, PROPERTY_INDEX_IMSI },
{ kIsActiveProperty, PROPERTY_INDEX_IS_ACTIVE },
{ kLastDeviceUpdateProperty, PROPERTY_INDEX_LAST_DEVICE_UPDATE },
{ kManufacturerProperty, PROPERTY_INDEX_MANUFACTURER },
{ kMdnProperty, PROPERTY_INDEX_MDN },
{ kMeidProperty, PROPERTY_INDEX_MEID },
{ kMinProperty, PROPERTY_INDEX_MIN },
{ kModeProperty, PROPERTY_INDEX_MODE },
{ kModelIDProperty, PROPERTY_INDEX_MODEL_ID },
{ kNameProperty, PROPERTY_INDEX_NAME },
{ kNetworkTechnologyProperty, PROPERTY_INDEX_NETWORK_TECHNOLOGY },
{ kOfflineModeProperty, PROPERTY_INDEX_OFFLINE_MODE },
{ kOperatorCodeProperty, PROPERTY_INDEX_OPERATOR_CODE },
{ kOperatorNameProperty, PROPERTY_INDEX_OPERATOR_NAME },
{ kPRLVersionProperty, PROPERTY_INDEX_PRL_VERSION },
{ kPassphraseProperty, PROPERTY_INDEX_PASSPHRASE },
{ kPassphraseRequiredProperty, PROPERTY_INDEX_PASSPHRASE_REQUIRED },
{ kPaymentURLProperty, PROPERTY_INDEX_PAYMENT_URL },
{ kProfilesProperty, PROPERTY_INDEX_PROFILES },
{ kRoamingStateProperty, PROPERTY_INDEX_ROAMING_STATE },
{ kScanningProperty, PROPERTY_INDEX_SCANNING },
{ kSecurityProperty, PROPERTY_INDEX_SECURITY },
{ kServiceWatchListProperty, PROPERTY_INDEX_SERVICE_WATCH_LIST },
{ kServicesProperty, PROPERTY_INDEX_SERVICES },
{ kSignalStrengthProperty, PROPERTY_INDEX_SIGNAL_STRENGTH },
{ kStateProperty, PROPERTY_INDEX_STATE },
{ kTypeProperty, PROPERTY_INDEX_TYPE },
{ kUsageURLProperty, PROPERTY_INDEX_USAGE_URL },
};
StringToEnum<PropertyIndex>& property_index_parser() {
static StringToEnum<PropertyIndex> parser(property_index_table,
arraysize(property_index_table),
PROPERTY_INDEX_UNKNOWN);
return parser;
}
////////////////////////////////////////////////////////////////////////////
// Parse strings from libcros.
// Network.
static ConnectionType ParseType(const std::string& type) {
static StringToEnum<ConnectionType>::Pair table[] = {
{ kTypeEthernet, TYPE_ETHERNET },
{ kTypeWifi, TYPE_WIFI },
{ kTypeWimax, TYPE_WIMAX },
{ kTypeBluetooth, TYPE_BLUETOOTH },
{ kTypeCellular, TYPE_CELLULAR },
{ kTypeVPN, TYPE_VPN },
};
static StringToEnum<ConnectionType> parser(
table, arraysize(table), TYPE_UNKNOWN);
return parser.Get(type);
}
ConnectionType ParseTypeFromDictionary(const DictionaryValue* info) {
std::string type_string;
info->GetString(kTypeProperty, &type_string);
return ParseType(type_string);
}
static ConnectionMode ParseMode(const std::string& mode) {
static StringToEnum<ConnectionMode>::Pair table[] = {
{ kModeManaged, MODE_MANAGED },
{ kModeAdhoc, MODE_ADHOC },
};
static StringToEnum<ConnectionMode> parser(
table, arraysize(table), MODE_UNKNOWN);
return parser.Get(mode);
}
static ConnectionState ParseState(const std::string& state) {
static StringToEnum<ConnectionState>::Pair table[] = {
{ kStateIdle, STATE_IDLE },
{ kStateCarrier, STATE_CARRIER },
{ kStateAssociation, STATE_ASSOCIATION },
{ kStateConfiguration, STATE_CONFIGURATION },
{ kStateReady, STATE_READY },
{ kStateDisconnect, STATE_DISCONNECT },
{ kStateFailure, STATE_FAILURE },
{ kStateActivationFailure, STATE_ACTIVATION_FAILURE },
};
static StringToEnum<ConnectionState> parser(
table, arraysize(table), STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectionError ParseError(const std::string& error) {
static StringToEnum<ConnectionError>::Pair table[] = {
{ kErrorOutOfRange, ERROR_OUT_OF_RANGE },
{ kErrorPinMissing, ERROR_PIN_MISSING },
{ kErrorDhcpFailed, ERROR_DHCP_FAILED },
{ kErrorConnectFailed, ERROR_CONNECT_FAILED },
{ kErrorBadPassphrase, ERROR_BAD_PASSPHRASE },
{ kErrorBadWEPKey, ERROR_BAD_WEPKEY },
{ kErrorActivationFailed, ERROR_ACTIVATION_FAILED },
{ kErrorNeedEvdo, ERROR_NEED_EVDO },
{ kErrorNeedHomeNetwork, ERROR_NEED_HOME_NETWORK },
{ kErrorOtaspFailed, ERROR_OTASP_FAILED },
{ kErrorAaaFailed, ERROR_AAA_FAILED },
};
static StringToEnum<ConnectionError> parser(
table, arraysize(table), ERROR_UNKNOWN);
return parser.Get(error);
}
// CellularNetwork.
static ActivationState ParseActivationState(const std::string& state) {
static StringToEnum<ActivationState>::Pair table[] = {
{ kActivationStateActivated, ACTIVATION_STATE_ACTIVATED },
{ kActivationStateActivating, ACTIVATION_STATE_ACTIVATING },
{ kActivationStateNotActivated, ACTIVATION_STATE_NOT_ACTIVATED },
{ kActivationStatePartiallyActivated, ACTIVATION_STATE_PARTIALLY_ACTIVATED},
{ kActivationStateUnknown, ACTIVATION_STATE_UNKNOWN},
};
static StringToEnum<ActivationState> parser(
table, arraysize(table), ACTIVATION_STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectivityState ParseConnectivityState(const std::string& state) {
static StringToEnum<ConnectivityState>::Pair table[] = {
{ kConnStateUnrestricted, CONN_STATE_UNRESTRICTED },
{ kConnStateRestricted, CONN_STATE_RESTRICTED },
{ kConnStateNone, CONN_STATE_NONE },
};
static StringToEnum<ConnectivityState> parser(
table, arraysize(table), CONN_STATE_UNKNOWN);
return parser.Get(state);
}
static NetworkTechnology ParseNetworkTechnology(const std::string& technology) {
static StringToEnum<NetworkTechnology>::Pair table[] = {
{ kNetworkTechnology1Xrtt, NETWORK_TECHNOLOGY_1XRTT },
{ kNetworkTechnologyEvdo, NETWORK_TECHNOLOGY_EVDO },
{ kNetworkTechnologyGprs, NETWORK_TECHNOLOGY_GPRS },
{ kNetworkTechnologyEdge, NETWORK_TECHNOLOGY_EDGE },
{ kNetworkTechnologyUmts, NETWORK_TECHNOLOGY_UMTS },
{ kNetworkTechnologyHspa, NETWORK_TECHNOLOGY_HSPA },
{ kNetworkTechnologyHspaPlus, NETWORK_TECHNOLOGY_HSPA_PLUS },
{ kNetworkTechnologyLte, NETWORK_TECHNOLOGY_LTE },
{ kNetworkTechnologyLteAdvanced, NETWORK_TECHNOLOGY_LTE_ADVANCED },
};
static StringToEnum<NetworkTechnology> parser(
table, arraysize(table), NETWORK_TECHNOLOGY_UNKNOWN);
return parser.Get(technology);
}
static NetworkRoamingState ParseRoamingState(const std::string& roaming_state) {
static StringToEnum<NetworkRoamingState>::Pair table[] = {
{ kRoamingStateHome, ROAMING_STATE_HOME },
{ kRoamingStateRoaming, ROAMING_STATE_ROAMING },
{ kRoamingStateUnknown, ROAMING_STATE_UNKNOWN },
};
static StringToEnum<NetworkRoamingState> parser(
table, arraysize(table), ROAMING_STATE_UNKNOWN);
return parser.Get(roaming_state);
}
// WifiNetwork
static ConnectionSecurity ParseSecurity(const std::string& security) {
static StringToEnum<ConnectionSecurity>::Pair table[] = {
{ kSecurity8021x, SECURITY_8021X },
{ kSecurityRsn, SECURITY_RSN },
{ kSecurityWpa, SECURITY_WPA },
{ kSecurityWep, SECURITY_WEP },
{ kSecurityNone, SECURITY_NONE },
};
static StringToEnum<ConnectionSecurity> parser(
table, arraysize(table), SECURITY_UNKNOWN);
return parser.Get(security);
}
static EAPMethod ParseEAPMethod(const std::string& method) {
static StringToEnum<EAPMethod>::Pair table[] = {
{ kEapMethodPEAP.c_str(), EAP_METHOD_PEAP },
{ kEapMethodTLS.c_str(), EAP_METHOD_TLS },
{ kEapMethodTTLS.c_str(), EAP_METHOD_TTLS },
{ kEapMethodLEAP.c_str(), EAP_METHOD_LEAP },
};
static StringToEnum<EAPMethod> parser(
table, arraysize(table), EAP_METHOD_UNKNOWN);
return parser.Get(method);
}
static EAPPhase2Auth ParseEAPPhase2Auth(const std::string& auth) {
static StringToEnum<EAPPhase2Auth>::Pair table[] = {
{ kEapPhase2AuthPEAPMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthPEAPMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthTTLSMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMSCHAP.c_str(), EAP_PHASE_2_AUTH_MSCHAP },
{ kEapPhase2AuthTTLSPAP.c_str(), EAP_PHASE_2_AUTH_PAP },
{ kEapPhase2AuthTTLSCHAP.c_str(), EAP_PHASE_2_AUTH_CHAP },
};
static StringToEnum<EAPPhase2Auth> parser(
table, arraysize(table), EAP_PHASE_2_AUTH_AUTO);
return parser.Get(auth);
}
////////////////////////////////////////////////////////////////////////////
// Html output helper functions
// Helper function to wrap Html with <th> tag.
static std::string WrapWithTH(std::string text) {
return "<th>" + text + "</th>";
}
// Helper function to wrap Html with <td> tag.
static std::string WrapWithTD(std::string text) {
return "<td>" + text + "</td>";
}
// Helper function to create an Html table header for a Network.
static std::string ToHtmlTableHeader(Network* network) {
std::string str;
if (network->type() == TYPE_ETHERNET) {
str += WrapWithTH("Active");
} else if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
str += WrapWithTH("Name") + WrapWithTH("Active") +
WrapWithTH("Auto-Connect") + WrapWithTH("Strength");
if (network->type() == TYPE_WIFI)
str += WrapWithTH("Encryption") + WrapWithTH("Passphrase") +
WrapWithTH("Identity") + WrapWithTH("Certificate");
}
str += WrapWithTH("State") + WrapWithTH("Error") + WrapWithTH("IP Address");
return str;
}
// Helper function to create an Html table row for a Network.
static std::string ToHtmlTableRow(Network* network) {
std::string str;
if (network->type() == TYPE_ETHERNET) {
str += WrapWithTD(base::IntToString(network->is_active()));
} else if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
WirelessNetwork* wireless = static_cast<WirelessNetwork*>(network);
str += WrapWithTD(wireless->name()) +
WrapWithTD(base::IntToString(network->is_active())) +
WrapWithTD(base::IntToString(wireless->auto_connect())) +
WrapWithTD(base::IntToString(wireless->strength()));
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
str += WrapWithTD(wifi->GetEncryptionString()) +
WrapWithTD(std::string(wifi->passphrase().length(), '*')) +
WrapWithTD(wifi->identity()) + WrapWithTD(wifi->cert_path());
}
}
str += WrapWithTD(network->GetStateString()) +
WrapWithTD(network->failed() ? network->GetErrorString() : "") +
WrapWithTD(network->ip_address());
return str;
}
////////////////////////////////////////////////////////////////////////////////
// Misc.
// Safe string constructor since we can't rely on non NULL pointers
// for string values from libcros.
static std::string SafeString(const char* s) {
return s ? std::string(s) : std::string();
}
static bool EnsureCrosLoaded() {
if (!CrosLibrary::Get()->EnsureLoaded()) {
return false;
} else {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "chromeos_library calls made from non UI thread!";
NOTREACHED();
}
return true;
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// NetworkDevice
NetworkDevice::NetworkDevice(const std::string& device_path)
: device_path_(device_path),
type_(TYPE_UNKNOWN),
scanning_(false),
PRL_version_(0) {
}
bool NetworkDevice::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
type_ = ParseType(type_string);
return true;
}
break;
}
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_SCANNING:
return value->GetAsBoolean(&scanning_);
case PROPERTY_INDEX_CARRIER:
return value->GetAsString(&carrier_);
case PROPERTY_INDEX_MEID:
return value->GetAsString(&MEID_);
case PROPERTY_INDEX_IMEI:
return value->GetAsString(&IMEI_);
case PROPERTY_INDEX_IMSI:
return value->GetAsString(&IMSI_);
case PROPERTY_INDEX_ESN:
return value->GetAsString(&ESN_);
case PROPERTY_INDEX_MDN:
return value->GetAsString(&MDN_);
case PROPERTY_INDEX_MIN:
return value->GetAsString(&MIN_);
case PROPERTY_INDEX_MODEL_ID:
return value->GetAsString(&model_id_);
case PROPERTY_INDEX_MANUFACTURER:
return value->GetAsString(&manufacturer_);
case PROPERTY_INDEX_FIRMWARE_REVISION:
return value->GetAsString(&firmware_revision_);
case PROPERTY_INDEX_HARDWARE_REVISION:
return value->GetAsString(&hardware_revision_);
case PROPERTY_INDEX_LAST_DEVICE_UPDATE:
return value->GetAsString(&last_update_);
case PROPERTY_INDEX_PRL_VERSION:
return value->GetAsInteger(&PRL_version_);
default:
break;
}
return false;
}
void NetworkDevice::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
CHECK(res);
int index = property_index_parser().Get(key);
if (!ParseValue(index, value))
VLOG(1) << "NetworkDevice: Unhandled key: " << key;
}
}
////////////////////////////////////////////////////////////////////////////////
// Network
bool Network::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
ConnectionType type = ParseType(type_string);
LOG_IF(ERROR, type != type_)
<< "Network with mismatched type: " << service_path_
<< " " << type << " != " << type_;
return true;
}
break;
}
case PROPERTY_INDEX_DEVICE:
return value->GetAsString(&device_path_);
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_STATE: {
std::string state_string;
if (value->GetAsString(&state_string)) {
ConnectionState prev_state = state_;
state_ = ParseState(state_string);
if (state_ != prev_state) {
// State changed, so refresh IP address.
// Note: blocking DBus call. TODO(stevenjb): refactor this.
InitIPAddress();
}
return true;
}
break;
}
case PROPERTY_INDEX_MODE: {
std::string mode_string;
if (value->GetAsString(&mode_string)) {
mode_ = ParseMode(mode_string);
return true;
}
break;
}
case PROPERTY_INDEX_ERROR: {
std::string error_string;
if (value->GetAsString(&error_string)) {
error_ = ParseError(error_string);
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTABLE:
return value->GetAsBoolean(&connectable_);
case PROPERTY_INDEX_IS_ACTIVE:
return value->GetAsBoolean(&is_active_);
case PROPERTY_INDEX_FAVORITE:
return value->GetAsBoolean(&favorite_);
case PROPERTY_INDEX_AUTO_CONNECT:
return value->GetAsBoolean(&auto_connect_);
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
std::string connectivity_state_string;
if (value->GetAsString(&connectivity_state_string)) {
connectivity_state_ = ParseConnectivityState(connectivity_state_string);
return true;
}
break;
}
default:
break;
}
return false;
}
void Network::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
CHECK(res);
int index = property_index_parser().Get(key);
if (!ParseValue(index, value)) // virtual.
VLOG(1) << "Network: Type: " << type_ << " Unhandled key: " << key;
}
}
void Network::SetAutoConnect(bool auto_connect) {
auto_connect_ = auto_connect;
SetBooleanProperty(kAutoConnectProperty, auto_connect);
}
void Network::SetStringProperty(const char* prop, const std::string& str) {
scoped_ptr<Value> value(Value::CreateStringValue(str));
SetValueProperty(prop, value.get());
}
void Network::SetBooleanProperty(const char* prop, bool b) {
scoped_ptr<Value> value(Value::CreateBooleanValue(b));
SetValueProperty(prop, value.get());
}
void Network::SetIntegerProperty(const char* prop, int i) {
scoped_ptr<Value> value(Value::CreateIntegerValue(i));
SetValueProperty(prop, value.get());
}
void Network::ClearProperty(const char* prop) {
DCHECK(prop);
if (!EnsureCrosLoaded())
return;
ClearNetworkServiceProperty(service_path_.c_str(), prop);
}
void Network::SetOrClearStringProperty(const char* prop,
const std::string& str) {
if (str.empty())
ClearProperty(prop);
else
SetStringProperty(prop, str);
}
void Network::SetValueProperty(const char* prop, Value* val) {
DCHECK(prop);
DCHECK(val);
if (!EnsureCrosLoaded())
return;
SetNetworkServiceProperty(service_path_.c_str(), prop, val);
}
// Used by GetHtmlInfo() which is called from the about:network handler.
std::string Network::GetStateString() const {
switch (state_) {
case STATE_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN);
case STATE_IDLE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE);
case STATE_CARRIER:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER);
case STATE_ASSOCIATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION);
case STATE_CONFIGURATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION);
case STATE_READY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY);
case STATE_DISCONNECT:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT);
case STATE_FAILURE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE);
case STATE_ACTIVATION_FAILURE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE);
default:
// Usually no default, but changes to libcros may add states.
break;
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
std::string Network::GetErrorString() const {
switch (error_) {
case ERROR_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
case ERROR_OUT_OF_RANGE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE);
case ERROR_PIN_MISSING:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING);
case ERROR_DHCP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED);
case ERROR_CONNECT_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED);
case ERROR_BAD_PASSPHRASE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE);
case ERROR_BAD_WEPKEY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY);
case ERROR_ACTIVATION_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED);
case ERROR_NEED_EVDO:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO);
case ERROR_NEED_HOME_NETWORK:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK);
case ERROR_OTASP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED);
case ERROR_AAA_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED);
default:
// Usually no default, but changes to libcros may add errors.
break;
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
void Network::InitIPAddress() {
ip_address_.clear();
// If connected, get ip config.
if (EnsureCrosLoaded() && connected() && !device_path_.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path_.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0) {
ip_address_ = ipconfig.address;
break;
}
}
FreeIPConfigStatus(ipconfig_status);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// WirelessNetwork
bool WirelessNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SIGNAL_STRENGTH:
return value->GetAsInteger(&strength_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// CellularDataPlan
string16 CellularDataPlan::GetPlanDesciption() const {
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_UNLIMITED_DATA,
base::TimeFormatFriendlyDate(plan_start_time));
break;
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_RECEIVED_FREE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
default:
break;
}
}
return string16();
}
string16 CellularDataPlan::GetRemainingWarning() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
if (remaining_time().InSeconds() <= chromeos::kCellularDataVeryLowSecs) {
return GetPlanExpiration();
}
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
if (remaining_data() <= chromeos::kCellularDataVeryLowBytes) {
int64 remaining_mbytes = remaining_data() / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
}
return string16();
}
string16 CellularDataPlan::GetDataRemainingDesciption() const {
int64 remaining_bytes = remaining_data();
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_UNLIMITED);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
default:
break;
}
return string16();
}
string16 CellularDataPlan::GetUsageInfo() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
return GetPlanExpiration();
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
int64 remaining_bytes = remaining_data();
if (remaining_bytes == 0) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_NONE_AVAILABLE_MESSAGE);
} else if (remaining_bytes < 1024 * 1024) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_LESS_THAN_ONE_MB_AVAILABLE_MESSAGE);
} else {
int64 remaining_mb = remaining_bytes / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_MB_AVAILABLE_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mb)));
}
}
return string16();
}
std::string CellularDataPlan::GetUniqueIdentifier() const {
// A cellular plan is uniquely described by the union of name, type,
// start time, end time, and max bytes.
// So we just return a union of all these variables.
return plan_name + "|" +
base::Int64ToString(plan_type) + "|" +
base::Int64ToString(plan_start_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_end_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_data_bytes);
}
base::TimeDelta CellularDataPlan::remaining_time() const {
base::TimeDelta time = plan_end_time - base::Time::Now();
return time.InMicroseconds() < 0 ? base::TimeDelta() : time;
}
int64 CellularDataPlan::remaining_minutes() const {
return remaining_time().InMinutes();
}
int64 CellularDataPlan::remaining_data() const {
int64 data = plan_data_bytes - data_bytes_used;
return data < 0 ? 0 : data;
}
string16 CellularDataPlan::GetPlanExpiration() const {
return TimeFormat::TimeRemaining(remaining_time());
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork
CellularNetwork::~CellularNetwork() {
}
bool CellularNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_ACTIVATION_STATE: {
std::string activation_state_string;
if (value->GetAsString(&activation_state_string)) {
ActivationState prev_state = activation_state_;
activation_state_ = ParseActivationState(activation_state_string);
if (activation_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_NETWORK_TECHNOLOGY: {
std::string network_technology_string;
if (value->GetAsString(&network_technology_string)) {
network_technology_ = ParseNetworkTechnology(network_technology_string);
return true;
}
break;
}
case PROPERTY_INDEX_ROAMING_STATE: {
std::string roaming_state_string;
if (value->GetAsString(&roaming_state_string)) {
roaming_state_ = ParseRoamingState(roaming_state_string);
return true;
}
break;
}
case PROPERTY_INDEX_OPERATOR_NAME:
return value->GetAsString(&operator_name_);
case PROPERTY_INDEX_OPERATOR_CODE:
return value->GetAsString(&operator_code_);
case PROPERTY_INDEX_PAYMENT_URL:
return value->GetAsString(&payment_url_);
case PROPERTY_INDEX_USAGE_URL:
return value->GetAsString(&usage_url_);
case PROPERTY_INDEX_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectionState prev_state = state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectivityState prev_state = connectivity_state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (connectivity_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
bool CellularNetwork::StartActivation() const {
if (!EnsureCrosLoaded())
return false;
return ActivateCellularModem(service_path().c_str(), NULL);
}
void CellularNetwork::RefreshDataPlansIfNeeded() const {
if (!EnsureCrosLoaded())
return;
if (connected() && activated())
RequestCellularDataPlanUpdate(service_path().c_str());
}
std::string CellularNetwork::GetNetworkTechnologyString() const {
// No need to localize these cellular technology abbreviations.
switch (network_technology_) {
case NETWORK_TECHNOLOGY_1XRTT:
return "1xRTT";
break;
case NETWORK_TECHNOLOGY_EVDO:
return "EVDO";
break;
case NETWORK_TECHNOLOGY_GPRS:
return "GPRS";
break;
case NETWORK_TECHNOLOGY_EDGE:
return "EDGE";
break;
case NETWORK_TECHNOLOGY_UMTS:
return "UMTS";
break;
case NETWORK_TECHNOLOGY_HSPA:
return "HSPA";
break;
case NETWORK_TECHNOLOGY_HSPA_PLUS:
return "HSPA Plus";
break;
case NETWORK_TECHNOLOGY_LTE:
return "LTE";
break;
case NETWORK_TECHNOLOGY_LTE_ADVANCED:
return "LTE Advanced";
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_CELLULAR_TECHNOLOGY_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetConnectivityStateString() const {
// These strings do not appear in the UI, so no need to localize them
switch (connectivity_state_) {
case CONN_STATE_UNRESTRICTED:
return "unrestricted";
break;
case CONN_STATE_RESTRICTED:
return "restricted";
break;
case CONN_STATE_NONE:
return "none";
break;
case CONN_STATE_UNKNOWN:
default:
return "unknown";
}
}
std::string CellularNetwork::ActivationStateToString(
ActivationState activation_state) {
switch (activation_state) {
case ACTIVATION_STATE_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED);
break;
case ACTIVATION_STATE_ACTIVATING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING);
break;
case ACTIVATION_STATE_NOT_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED);
break;
case ACTIVATION_STATE_PARTIALLY_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetActivationStateString() const {
return ActivationStateToString(this->activation_state_);
}
std::string CellularNetwork::GetRoamingStateString() const {
switch (this->roaming_state_) {
case ROAMING_STATE_HOME:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME);
break;
case ROAMING_STATE_ROAMING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WifiNetwork
bool WifiNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SECURITY: {
std::string security_string;
if (value->GetAsString(&security_string)) {
encryption_ = ParseSecurity(security_string);
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE: {
std::string passphrase;
if (value->GetAsString(&passphrase)) {
// Only store the passphrase if we are the owner.
// TODO(stevenjb): Remove this when chromium-os:12948 is resolved.
if (chromeos::UserManager::Get()->current_user_is_owner())
passphrase_ = passphrase;
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE_REQUIRED:
return value->GetAsBoolean(&passphrase_required_);
case PROPERTY_INDEX_IDENTITY:
return value->GetAsString(&identity_);
case PROPERTY_INDEX_CERT_PATH:
return value->GetAsString(&cert_path_);
case PROPERTY_INDEX_EAP_METHOD: {
std::string method;
if (value->GetAsString(&method)) {
eap_method_ = ParseEAPMethod(method);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_PHASE_2_AUTH: {
std::string auth;
if (value->GetAsString(&auth)) {
eap_phase_2_auth_ = ParseEAPPhase2Auth(auth);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_IDENTITY:
return value->GetAsString(&eap_identity_);
case PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY:
return value->GetAsString(&eap_anonymous_identity_);
case PROPERTY_INDEX_EAP_CLIENT_CERT:
return value->GetAsString(&eap_client_cert_path_);
case PROPERTY_INDEX_EAP_CA_CERT:
return value->GetAsString(&eap_server_ca_cert_path_);
case PROPERTY_INDEX_EAP_PASSWORD:
return value->GetAsString(&eap_passphrase_);
case PROPERTY_INDEX_EAP_USE_SYSTEM_CAS:
return value->GetAsBoolean(&eap_use_system_cas_);
case PROPERTY_INDEX_EAP_CERT_ID:
case PROPERTY_INDEX_EAP_PRIVATE_KEY:
case PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD:
case PROPERTY_INDEX_EAP_KEY_ID:
case PROPERTY_INDEX_EAP_CA_CERT_ID:
case PROPERTY_INDEX_EAP_PIN:
case PROPERTY_INDEX_EAP_KEY_MGMT:
// These properties are currently not used in the UI.
return true;
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
const std::string& WifiNetwork::GetPassphrase() const {
if (!user_passphrase_.empty())
return user_passphrase_;
return passphrase_;
}
void WifiNetwork::SetPassphrase(const std::string& passphrase) {
// Set the user_passphrase_ only; passphrase_ stores the flimflam value.
// If the user sets an empty passphrase, restore it to the passphrase
// remembered by flimflam.
if (!passphrase.empty())
user_passphrase_ = passphrase;
else
user_passphrase_ = passphrase_;
// Send the change to flimflam. If the format is valid, it will propagate to
// passphrase_ with a service update.
SetStringProperty(kPassphraseProperty, passphrase);
}
void WifiNetwork::SetIdentity(const std::string& identity) {
identity_ = identity;
SetStringProperty(kIdentityProperty, identity);
}
void WifiNetwork::SetCertPath(const std::string& cert_path) {
cert_path_ = cert_path;
SetStringProperty(kCertPathProperty, cert_path);
}
void WifiNetwork::SetEAPMethod(EAPMethod method) {
eap_method_ = method;
switch (method) {
case EAP_METHOD_PEAP:
SetStringProperty(kEapMethodProperty, kEapMethodPEAP);
break;
case EAP_METHOD_TLS:
SetStringProperty(kEapMethodProperty, kEapMethodTLS);
break;
case EAP_METHOD_TTLS:
SetStringProperty(kEapMethodProperty, kEapMethodTTLS);
break;
case EAP_METHOD_LEAP:
SetStringProperty(kEapMethodProperty, kEapMethodLEAP);
break;
default:
ClearProperty(kEapMethodProperty);
break;
}
}
void WifiNetwork::SetEAPPhase2Auth(EAPPhase2Auth auth) {
eap_phase_2_auth_ = auth;
bool is_peap = (eap_method_ == EAP_METHOD_PEAP);
switch (auth) {
case EAP_PHASE_2_AUTH_AUTO:
ClearProperty(kEapPhase2AuthProperty);
break;
case EAP_PHASE_2_AUTH_MD5:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMD5
: kEapPhase2AuthTTLSMD5);
break;
case EAP_PHASE_2_AUTH_MSCHAPV2:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMSCHAPV2
: kEapPhase2AuthTTLSMSCHAPV2);
break;
case EAP_PHASE_2_AUTH_MSCHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSMSCHAP);
break;
case EAP_PHASE_2_AUTH_PAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSPAP);
break;
case EAP_PHASE_2_AUTH_CHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSCHAP);
break;
}
}
void WifiNetwork::SetEAPServerCACert(const std::string& cert_path) {
eap_server_ca_cert_path_ = cert_path;
SetOrClearStringProperty(kEapCACertProperty, cert_path);
}
void WifiNetwork::SetEAPClientCert(const std::string& cert_path) {
eap_client_cert_path_ = cert_path;
SetOrClearStringProperty(kEapClientCertProperty, cert_path);
}
void WifiNetwork::SetEAPUseSystemCAs(bool use_system_cas) {
eap_use_system_cas_ = use_system_cas;
SetBooleanProperty(kEapUseSystemCAsProperty, use_system_cas);
}
void WifiNetwork::SetEAPIdentity(const std::string& identity) {
eap_identity_ = identity;
SetOrClearStringProperty(kEapIdentityProperty, identity);
}
void WifiNetwork::SetEAPAnonymousIdentity(const std::string& identity) {
eap_anonymous_identity_ = identity;
SetOrClearStringProperty(kEapAnonymousIdentityProperty, identity);
}
void WifiNetwork::SetEAPPassphrase(const std::string& passphrase) {
eap_passphrase_ = passphrase;
SetOrClearStringProperty(kEapPasswordProperty, passphrase);
}
std::string WifiNetwork::GetEncryptionString() {
switch (encryption_) {
case SECURITY_UNKNOWN:
break;
case SECURITY_NONE:
return "";
case SECURITY_WEP:
return "WEP";
case SECURITY_WPA:
return "WPA";
case SECURITY_RSN:
return "RSN";
case SECURITY_8021X:
return "8021X";
}
return "Unknown";
}
bool WifiNetwork::IsPassphraseRequired() const {
// TODO(stevenjb): Remove error_ tests when fixed in flimflam
// (http://crosbug.com/10135).
if (error_ == ERROR_BAD_PASSPHRASE || error_ == ERROR_BAD_WEPKEY)
return true;
// For 802.1x networks, configuration is required if connectable is false.
if (encryption_ == SECURITY_8021X)
return !connectable_;
return passphrase_required_;
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
bool WifiNetwork::IsCertificateLoaded() const {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (cert_path_.find(settings_string) == 0) {
std::string::size_type idx = cert_path_.find(pkcs11_key);
if (idx != std::string::npos)
idx = cert_path_.find_first_not_of(kWhitespaceASCII,
idx + pkcs11_key.length());
if (idx != std::string::npos && cert_path_[idx] == '=')
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
class NetworkLibraryImpl : public NetworkLibrary {
public:
NetworkLibraryImpl()
: network_manager_monitor_(NULL),
data_plan_monitor_(NULL),
ethernet_(NULL),
active_wifi_(NULL),
active_cellular_(NULL),
active_virtual_(NULL),
available_devices_(0),
enabled_devices_(0),
connected_devices_(0),
wifi_scanning_(false),
offline_mode_(false),
is_locked_(false),
notify_task_(NULL) {
if (EnsureCrosLoaded()) {
Init();
network_manager_monitor_ =
MonitorNetworkManager(&NetworkManagerStatusChangedHandler,
this);
data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler,
this);
network_login_observer_.reset(new NetworkLoginObserver(this));
} else {
InitTestData();
}
}
virtual ~NetworkLibraryImpl() {
network_manager_observers_.Clear();
if (network_manager_monitor_)
DisconnectPropertyChangeMonitor(network_manager_monitor_);
data_plan_observers_.Clear();
if (data_plan_monitor_)
DisconnectDataPlanUpdateMonitor(data_plan_monitor_);
STLDeleteValues(&network_observers_);
ClearNetworks(true /*delete networks*/);
ClearRememberedNetworks(true /*delete networks*/);
STLDeleteValues(&data_plan_map_);
}
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {
if (!network_manager_observers_.HasObserver(observer))
network_manager_observers_.AddObserver(observer);
}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {
network_manager_observers_.RemoveObserver(observer);
}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkObserverMap::iterator iter = network_observers_.find(service_path);
NetworkObserverList* oblist;
if (iter != network_observers_.end()) {
oblist = iter->second;
} else {
std::pair<NetworkObserverMap::iterator, bool> inserted =
network_observers_.insert(
std::make_pair<std::string, NetworkObserverList*>(
service_path,
new NetworkObserverList(this, service_path)));
oblist = inserted.first->second;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
DCHECK(service_path.size());
NetworkObserverMap::iterator map_iter =
network_observers_.find(service_path);
if (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
}
}
}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {
DCHECK(observer);
NetworkObserverMap::iterator map_iter = network_observers_.begin();
while (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
} else {
++map_iter;
}
}
}
virtual void Lock() {
if (is_locked_)
return;
is_locked_ = true;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual void Unlock() {
DCHECK(is_locked_);
if (!is_locked_)
return;
is_locked_ = false;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool IsLocked() {
return is_locked_;
}
virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) {
if (!data_plan_observers_.HasObserver(observer))
data_plan_observers_.AddObserver(observer);
}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {
data_plan_observers_.RemoveObserver(observer);
}
virtual void AddUserActionObserver(UserActionObserver* observer) {
if (!user_action_observers_.HasObserver(observer))
user_action_observers_.AddObserver(observer);
}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {
user_action_observers_.RemoveObserver(observer);
}
virtual const EthernetNetwork* ethernet_network() const { return ethernet_; }
virtual bool ethernet_connecting() const {
return ethernet_ ? ethernet_->connecting() : false;
}
virtual bool ethernet_connected() const {
return ethernet_ ? ethernet_->connected() : false;
}
virtual const WifiNetwork* wifi_network() const { return active_wifi_; }
virtual bool wifi_connecting() const {
return active_wifi_ ? active_wifi_->connecting() : false;
}
virtual bool wifi_connected() const {
return active_wifi_ ? active_wifi_->connected() : false;
}
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const {
return active_cellular_ ? active_cellular_->connecting() : false;
}
virtual bool cellular_connected() const {
return active_cellular_ ? active_cellular_->connected() : false;
}
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const {
return active_virtual_ ? active_virtual_->connecting() : false;
}
virtual bool virtual_network_connected() const {
return active_virtual_ ? active_virtual_->connected() : false;
}
bool Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& IPAddress() const {
// Returns IP address for the active network.
const Network* result = active_network();
if (active_virtual_ && active_virtual_->is_active() &&
(!result || active_virtual_->priority_ > result->priority_))
result = active_virtual_;
if (!result)
result = ethernet_; // Use non active ethernet addr if no active network.
if (result)
return result->ip_address();
static std::string null_address("0.0.0.0");
return null_address;
}
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return remembered_wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const {
NetworkDeviceMap::const_iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
virtual Network* FindNetworkByPath(const std::string& path) const {
NetworkMap::const_iterator iter = network_map_.find(path);
if (iter != network_map_.end())
return iter->second;
return NULL;
}
WirelessNetwork* FindWirelessNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network &&
(network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR))
return static_cast<WirelessNetwork*>(network);
return NULL;
}
virtual WifiNetwork* FindWifiNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_WIFI)
return static_cast<WifiNetwork*>(network);
return NULL;
}
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_CELLULAR)
return static_cast<CellularNetwork*>(network);
return NULL;
}
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const {
CellularDataPlanMap::const_iterator iter = data_plan_map_.find(path);
if (iter != data_plan_map_.end())
return iter->second;
return NULL;
}
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const {
const CellularDataPlanVector* plans = GetDataPlans(path);
if (plans)
return GetSignificantDataPlanFromVector(plans);
return NULL;
}
virtual void RequestNetworkScan() {
if (EnsureCrosLoaded()) {
if (wifi_enabled()) {
wifi_scanning_ = true; // Cleared when updates are received.
chromeos::RequestNetworkScan(kTypeWifi);
RequestRememberedNetworksUpdate();
}
if (cellular_network())
cellular_network()->RefreshDataPlansIfNeeded();
}
}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
if (!EnsureCrosLoaded())
return false;
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeviceNetworkList* network_list = GetDeviceNetworkList();
if (network_list == NULL)
return false;
result->clear();
result->reserve(network_list->network_size);
const base::Time now = base::Time::Now();
for (size_t i = 0; i < network_list->network_size; ++i) {
DCHECK(network_list->networks[i].address);
DCHECK(network_list->networks[i].name);
WifiAccessPoint ap;
ap.mac_address = SafeString(network_list->networks[i].address);
ap.name = SafeString(network_list->networks[i].name);
ap.timestamp = now -
base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds);
ap.signal_strength = network_list->networks[i].strength;
ap.channel = network_list->networks[i].channel;
result->push_back(ap);
}
FreeDeviceNetworkList(network_list);
return true;
}
static void WirelessConnectCallback(void *object,
const char *path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
WirelessNetwork* wireless = networklib->FindWirelessNetworkByPath(path);
if (!wireless) {
LOG(ERROR) << "No wireless network for path: " << path;
return;
}
if (error != NETWORK_METHOD_ERROR_NONE) {
if (error_message &&
strcmp(error_message, kErrorPassphraseRequiredMsg) == 0) {
// This will trigger the connection failed notification.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
wireless->set_state(STATE_FAILURE);
wireless->set_error(ERROR_BAD_PASSPHRASE);
networklib->NotifyNetworkManagerChanged(true); // Forced update.
} else {
LOG(WARNING) << "Error from ServiceConnect callback: "
<< error_message;
}
return;
}
// Update local cache and notify listeners.
if (wireless->type() == TYPE_WIFI)
networklib->active_wifi_ = static_cast<WifiNetwork *>(wireless);
else if (wireless->type() == TYPE_CELLULAR)
networklib->active_cellular_ = static_cast<CellularNetwork *>(wireless);
else
LOG(ERROR) << "Network of unexpected type: " << wireless->type();
// If we succeed, this network will be remembered; request an update.
// TODO(stevenjb): flimflam should do this automatically.
networklib->RequestRememberedNetworksUpdate();
// Notify observers.
networklib->NotifyNetworkManagerChanged(false); // Not forced.
networklib->NotifyUserConnectionInitiated(wireless);
}
void CallConnectToNetworkForWifi(WifiNetwork* wifi) {
// If we haven't correctly set the parameters (e.g. passphrase), flimflam
// might fail without attempting a connection. In order to trigger any
// notifications, set the state locally and notify observers.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
wifi->set_connecting(true);
NotifyNetworkManagerChanged(true); // Forced update.
RequestNetworkServiceConnect(wifi->service_path().c_str(),
WirelessConnectCallback, this);
}
virtual void ConnectToWifiNetwork(WifiNetwork* wifi) {
DCHECK(wifi);
if (!EnsureCrosLoaded() || !wifi)
return;
CallConnectToNetworkForWifi(wifi);
}
// Use this to connect to a wifi network by service path.
virtual void ConnectToWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
WifiNetwork* wifi = FindWifiNetworkByPath(service_path);
if (!wifi) {
LOG(WARNING) << "Attempt to connect to non existing network: "
<< service_path;
return;
}
CallConnectToNetworkForWifi(wifi);
}
// Use this to connect to an unlisted wifi network.
// This needs to request information about the named service.
// The connection attempt will occur in the callback.
virtual void ConnectToWifiNetwork(ConnectionSecurity security,
const std::string& ssid,
const std::string& passphrase,
const std::string& identity,
const std::string& certpath,
bool auto_connect) {
if (!EnsureCrosLoaded())
return;
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(security),
WifiServiceUpdateAndConnect,
this);
// Store the connection data to be used by the callback.
connect_data_.SetData(ssid, passphrase, identity, certpath, auto_connect);
}
// Callback
static void WifiServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
// Blocking DBus call. TODO(stevenjb): make async.
networklib->ConnectToNetworkUsingConnectData(network);
}
}
void ConnectToNetworkUsingConnectData(Network* network) {
ConnectData& data = connect_data_;
if (network->name() != data.name) {
LOG(WARNING) << "Network name does not match ConnectData: "
<< network->name() << " != " << data.name;
return;
}
WifiNetwork *wifi = static_cast<WifiNetwork *>(network);
if (!data.passphrase.empty())
wifi->SetPassphrase(data.passphrase);
if (!data.identity.empty())
wifi->SetIdentity(data.identity);
if (!data.certpath.empty())
wifi->SetCertPath(data.certpath);
wifi->SetAutoConnect(data.auto_connect);
CallConnectToNetworkForWifi(wifi);
}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
RequestNetworkServiceConnect(network->service_path().c_str(),
WirelessConnectCallback, this);
}
// Records information that cellular play payment had happened.
virtual void SignalCellularPlanPayment() {
DCHECK(!HasRecentCellularPlanPayment());
cellular_plan_payment_time_ = base::Time::Now();
}
// Returns true if cellular plan payment had been recorded recently.
virtual bool HasRecentCellularPlanPayment() {
return (base::Time::Now() -
cellular_plan_payment_time_).InHours() < kRecentPlanPaymentHours;
}
virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
if (DisconnectFromNetwork(network->service_path().c_str())) {
// Update local cache and notify listeners.
WirelessNetwork* wireless =
FindWirelessNetworkByPath(network->service_path());
if (wireless) {
wireless->set_connected(false);
if (wireless == active_wifi_)
active_wifi_ = NULL;
else if (wireless == active_cellular_)
active_cellular_ = NULL;
}
NotifyNetworkManagerChanged(false); // Not forced.
}
}
virtual void ForgetWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
// NOTE: service paths for remembered wifi networks do not match the
// service paths in wifi_networks_; calling a libcros funtion that
// operates on the wifi_networks_ list with this service_path will
// trigger a crash because the DBUS path does not exist.
// TODO(stevenjb): modify libcros to warn and fail instead of crash.
// https://crosbug.com/9295
if (DeleteRememberedService(service_path.c_str())) {
DeleteRememberedNetwork(service_path);
NotifyNetworkManagerChanged(false); // Not forced.
}
}
virtual bool ethernet_available() const {
return available_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_available() const {
return available_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_available() const {
return available_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool ethernet_enabled() const {
return enabled_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_enabled() const {
return enabled_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_enabled() const {
return enabled_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool wifi_scanning() const {
return wifi_scanning_;
}
virtual bool offline_mode() const { return offline_mode_; }
// Note: This does not include any virtual networks.
virtual const Network* active_network() const {
// Use flimflam's ordering of the services to determine what the active
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->is_active())
result = ethernet_;
if (active_wifi_ && active_wifi_->is_active() &&
(!result || active_wifi_->priority_ > result->priority_))
result = active_wifi_;
if (active_cellular_ && active_cellular_->is_active() &&
(!result || active_cellular_->priority_ > result->priority_))
result = active_cellular_;
return result;
}
virtual void EnableEthernetNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_ETHERNET, enable);
}
virtual void EnableWifiNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_WIFI, enable);
}
virtual void EnableCellularNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_CELLULAR, enable);
}
virtual void EnableOfflineMode(bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
VLOG(1) << "Trying to enable offline mode when it's already enabled.";
return;
}
if (!enable && !offline_mode_) {
VLOG(1) << "Trying to disable offline mode when it's already disabled.";
return;
}
if (SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address) {
hardware_address->clear();
NetworkIPConfigVector ipconfig_vector;
if (EnsureCrosLoaded() && !device_path.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
*hardware_address = ipconfig_status->hardware_address;
FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
return ipconfig_vector;
}
virtual std::string GetHtmlInfo(int refresh) {
std::string output;
output.append("<html><head><title>About Network</title>");
if (refresh > 0)
output.append("<meta http-equiv=\"refresh\" content=\"" +
base::IntToString(refresh) + "\"/>");
output.append("</head><body>");
if (refresh > 0) {
output.append("(Auto-refreshing page every " +
base::IntToString(refresh) + "s)");
} else {
output.append("(To auto-refresh this page: about:network/<secs>)");
}
if (ethernet_enabled()) {
output.append("<h3>Ethernet:</h3><table border=1>");
if (ethernet_) {
output.append("<tr>" + ToHtmlTableHeader(ethernet_) + "</tr>");
output.append("<tr>" + ToHtmlTableRow(ethernet_) + "</tr>");
}
}
if (wifi_enabled()) {
output.append("</table><h3>Wifi:</h3><table border=1>");
for (size_t i = 0; i < wifi_networks_.size(); ++i) {
if (i == 0)
output.append("<tr>" + ToHtmlTableHeader(wifi_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(wifi_networks_[i]) + "</tr>");
}
}
if (cellular_enabled()) {
output.append("</table><h3>Cellular:</h3><table border=1>");
for (size_t i = 0; i < cellular_networks_.size(); ++i) {
if (i == 0)
output.append("<tr>" + ToHtmlTableHeader(cellular_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(cellular_networks_[i]) + "</tr>");
}
}
output.append("</table><h3>Remembered Wifi:</h3><table border=1>");
for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) {
if (i == 0)
output.append(
"<tr>" + ToHtmlTableHeader(remembered_wifi_networks_[i]) +
"</tr>");
output.append("<tr>" + ToHtmlTableRow(remembered_wifi_networks_[i]) +
"</tr>");
}
output.append("</table></body></html>");
return output;
}
private:
typedef std::map<std::string, Network*> NetworkMap;
typedef std::map<std::string, int> PriorityMap;
typedef std::map<std::string, NetworkDevice*> NetworkDeviceMap;
typedef std::map<std::string, CellularDataPlanVector*> CellularDataPlanMap;
class NetworkObserverList : public ObserverList<NetworkObserver> {
public:
NetworkObserverList(NetworkLibraryImpl* library,
const std::string& service_path) {
network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler,
service_path.c_str(),
library);
}
virtual ~NetworkObserverList() {
if (network_monitor_)
DisconnectPropertyChangeMonitor(network_monitor_);
}
private:
static void NetworkStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkStatus(path, key, value);
}
PropertyChangeMonitor network_monitor_;
};
typedef std::map<std::string, NetworkObserverList*> NetworkObserverMap;
////////////////////////////////////////////////////////////////////////////
// Callbacks.
static void NetworkManagerStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->NetworkManagerStatusChanged(key, value);
}
// This processes all Manager update messages.
void NetworkManagerStatusChanged(const char* key, const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::TimeTicks start = base::TimeTicks::Now();
VLOG(1) << "NetworkManagerStatusChanged: KEY=" << key;
if (!key)
return;
int index = property_index_parser().Get(std::string(key));
switch (index) {
case PROPERTY_INDEX_STATE:
// Currently we ignore the network manager state.
break;
case PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateAvailableTechnologies(vlist);
break;
}
case PROPERTY_INDEX_ENABLED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateEnabledTechnologies(vlist);
break;
}
case PROPERTY_INDEX_CONNECTED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateConnectedTechnologies(vlist);
break;
}
case PROPERTY_INDEX_DEFAULT_TECHNOLOGY:
// Currently we ignore DefaultTechnology.
break;
case PROPERTY_INDEX_OFFLINE_MODE: {
DCHECK_EQ(value->GetType(), Value::TYPE_BOOLEAN);
value->GetAsBoolean(&offline_mode_);
NotifyNetworkManagerChanged(false); // Not forced.
break;
}
case PROPERTY_INDEX_ACTIVE_PROFILE: {
DCHECK_EQ(value->GetType(), Value::TYPE_STRING);
value->GetAsString(&active_profile_path_);
RequestRememberedNetworksUpdate();
break;
}
case PROPERTY_INDEX_PROFILES:
// Currently we ignore Profiles (list of all profiles).
break;
case PROPERTY_INDEX_SERVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_SERVICE_WATCH_LIST: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateWatchedNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_DEVICE:
case PROPERTY_INDEX_DEVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkDeviceList(vlist);
break;
}
default:
LOG(WARNING) << "Unhandled key: " << key;
break;
}
base::TimeDelta delta = base::TimeTicks::Now() - start;
VLOG(1) << " time: " << delta.InMilliseconds() << " ms.";
HISTOGRAM_TIMES("CROS_NETWORK_UPDATE", delta);
}
static void NetworkManagerUpdate(void* object,
const char* manager_path,
const Value* info) {
VLOG(1) << "Received NetworkManagerUpdate.";
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
DCHECK(info);
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkManager(dict);
}
void ParseNetworkManager(const DictionaryValue* dict) {
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = dict->GetWithoutPathExpansion(key, &value);
CHECK(res);
NetworkManagerStatusChanged(key.c_str(), value);
}
}
static void ProfileUpdate(void* object,
const char* profile_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
DCHECK(info);
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
ListValue* entries(NULL);
dict->GetList(kEntriesProperty, &entries);
DCHECK(entries);
networklib->UpdateRememberedServiceList(profile_path, entries);
}
static void NetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Network no longer exists.
networklib->DeleteNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetwork(std::string(service_path), dict);
}
}
}
static void RememberedNetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Remembered network no longer exists.
networklib->DeleteRememberedNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseRememberedNetwork(std::string(service_path), dict);
}
}
}
static void NetworkDeviceUpdate(void* object,
const char* device_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (device_path) {
if (!info) {
// device no longer exists.
networklib->DeleteDevice(std::string(device_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkDevice(std::string(device_path), dict);
}
}
}
static void DataPlanUpdateHandler(void* object,
const char* modem_service_path,
const CellularDataPlanList* dataplan) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (modem_service_path && dataplan) {
networklib->UpdateCellularDataPlan(std::string(modem_service_path),
dataplan);
}
}
////////////////////////////////////////////////////////////////////////////
// Network technology functions.
void UpdateTechnologies(const ListValue* technologies, int* bitfieldp) {
DCHECK(bitfieldp);
if (!technologies)
return;
int bitfield = 0;
for (ListValue::const_iterator iter = technologies->begin();
iter != technologies->end(); ++iter) {
std::string technology;
(*iter)->GetAsString(&technology);
if (!technology.empty()) {
ConnectionType type = ParseType(technology);
bitfield |= 1 << type;
}
}
*bitfieldp = bitfield;
NotifyNetworkManagerChanged(false); // Not forced.
}
void UpdateAvailableTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &available_devices_);
}
void UpdateEnabledTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &enabled_devices_);
if (!ethernet_enabled())
ethernet_ = NULL;
if (!wifi_enabled()) {
active_wifi_ = NULL;
wifi_networks_.clear();
}
if (!cellular_enabled()) {
active_cellular_ = NULL;
cellular_networks_.clear();
}
}
void UpdateConnectedTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &connected_devices_);
}
////////////////////////////////////////////////////////////////////////////
// Network list management functions.
// Note: sometimes flimflam still returns networks when the device type is
// disabled. Always check the appropriate enabled() state before adding
// networks to a list or setting an active network so that we do not show them
// in the UI.
// This relies on services being requested from flimflam in priority order,
// and the updates getting processed and received in order.
void UpdateActiveNetwork(Network* network) {
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (ethernet_enabled()) {
// Set ethernet_ to the first connected ethernet service, or the first
// disconnected ethernet service if none are connected.
if (ethernet_ == NULL || !ethernet_->connected())
ethernet_ = static_cast<EthernetNetwork*>(network);
}
} else if (type == TYPE_WIFI) {
if (wifi_enabled()) {
// Set active_wifi_ to the first connected or connecting wifi service.
if (active_wifi_ == NULL && network->connecting_or_connected())
active_wifi_ = static_cast<WifiNetwork*>(network);
}
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled()) {
// Set active_cellular_ to first connected/connecting celluar service.
if (active_cellular_ == NULL && network->connecting_or_connected())
active_cellular_ = static_cast<CellularNetwork*>(network);
}
} else if (type == TYPE_VPN) {
// Set active_virtual_ to the first connected or connecting vpn service.
if (active_virtual_ == NULL && network->connecting_or_connected())
active_virtual_ = static_cast<VirtualNetwork*>(network);
}
}
void AddNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
network_map_.insert(std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
ConnectionType type(network->type());
if (type == TYPE_WIFI) {
if (wifi_enabled())
wifi_networks_.push_back(static_cast<WifiNetwork*>(network));
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled())
cellular_networks_.push_back(static_cast<CellularNetwork*>(network));
} else if (type == TYPE_VPN) {
virtual_networks_.push_back(static_cast<VirtualNetwork*>(network));
}
// Do not set the active network here. Wait until we parse the network.
}
// This only gets called when NetworkServiceUpdate receives a NULL update
// for an existing network, e.g. an error occurred while fetching a network.
void DeleteNetwork(const std::string& service_path) {
NetworkMap::iterator found = network_map_.find(service_path);
if (found == network_map_.end()) {
// This occurs when we receive an update request followed by a disconnect
// which triggers another update. See UpdateNetworkServiceList.
return;
}
Network* network = found->second;
network_map_.erase(found);
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (network == ethernet_) {
// This should never happen.
LOG(ERROR) << "Deleting active ethernet network: " << service_path;
ethernet_ = NULL;
}
} else if (type == TYPE_WIFI) {
WifiNetworkVector::iterator iter = std::find(
wifi_networks_.begin(), wifi_networks_.end(), network);
if (iter != wifi_networks_.end())
wifi_networks_.erase(iter);
if (network == active_wifi_) {
// This should never happen.
LOG(ERROR) << "Deleting active wifi network: " << service_path;
active_wifi_ = NULL;
}
} else if (type == TYPE_CELLULAR) {
CellularNetworkVector::iterator iter = std::find(
cellular_networks_.begin(), cellular_networks_.end(), network);
if (iter != cellular_networks_.end())
cellular_networks_.erase(iter);
if (network == active_cellular_) {
// This should never happen.
LOG(ERROR) << "Deleting active cellular network: " << service_path;
active_cellular_ = NULL;
}
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
CellularDataPlanVector* data_plans = found->second;
delete data_plans;
data_plan_map_.erase(found);
}
} else if (type == TYPE_VPN) {
VirtualNetworkVector::iterator iter = std::find(
virtual_networks_.begin(), virtual_networks_.end(), network);
if (iter != virtual_networks_.end())
virtual_networks_.erase(iter);
if (network == active_virtual_) {
// This should never happen.
LOG(ERROR) << "Deleting active virtual network: " << service_path;
active_virtual_ = NULL;
}
}
delete network;
}
void AddRememberedNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
remembered_network_map_.insert(
std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
remembered_wifi_networks_.push_back(wifi);
}
}
void DeleteRememberedNetwork(const std::string& service_path) {
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found == remembered_network_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant remembered network: "
<< service_path;
return;
}
Network* remembered_network = found->second;
remembered_network_map_.erase(found);
WifiNetworkVector::iterator iter = std::find(
remembered_wifi_networks_.begin(), remembered_wifi_networks_.end(),
remembered_network);
if (iter != remembered_wifi_networks_.end())
remembered_wifi_networks_.erase(iter);
delete remembered_network;
}
// Update all network lists, and request associated service updates.
void UpdateNetworkServiceList(const ListValue* services) {
// TODO(stevenjb): Wait for wifi_scanning_ to be false.
// Copy the list of existing networks to "old" and clear the map and lists.
NetworkMap old_network_map = network_map_;
ClearNetworks(false /*don't delete*/);
// Clear the list of update requests.
int network_priority = 0;
network_update_requests_.clear();
// wifi_scanning_ will remain false unless we request a network update.
wifi_scanning_ = false;
// |services| represents a complete list of visible networks.
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and lists. Otherwise it will get added when NetworkServiceUpdate
// calls ParseNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddNetwork(found->second);
old_network_map.erase(found);
}
// Always request network updates.
// TODO(stevenjb): Investigate why we are missing updates then
// rely on watched network updates and only request updates here for
// new networks.
// Use update_request map to store network priority.
network_update_requests_[service_path] = network_priority++;
wifi_scanning_ = true;
RequestNetworkServiceInfo(service_path.c_str(),
&NetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
// Request updates for watched networks. Does not affect network lists.
// Existing networks will be updated. There should not be any new networks
// in this list, but if there are they will be added appropriately.
void UpdateWatchedNetworkServiceList(const ListValue* services) {
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
VLOG(1) << "Watched Service: " << service_path;
RequestNetworkServiceInfo(
service_path.c_str(), &NetworkServiceUpdate, this);
}
}
}
// Request the active profile which lists the remembered networks.
void RequestRememberedNetworksUpdate() {
RequestNetworkProfile(
active_profile_path_.c_str(), &ProfileUpdate, this);
}
// Update the list of remembered (profile) networks, and request associated
// service updates.
void UpdateRememberedServiceList(const char* profile_path,
const ListValue* profile_entries) {
// Copy the list of existing networks to "old" and clear the map and list.
NetworkMap old_network_map = remembered_network_map_;
ClearRememberedNetworks(false /*don't delete*/);
// |profile_entries| represents a complete list of remembered networks.
for (ListValue::const_iterator iter = profile_entries->begin();
iter != profile_entries->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and list. Otherwise it will get added when
// RememberedNetworkServiceUpdate calls ParseRememberedNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddRememberedNetwork(found->second);
old_network_map.erase(found);
}
// Always request updates for remembered networks.
RequestNetworkProfileEntry(profile_path,
service_path.c_str(),
&RememberedNetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
Network* CreateNewNetwork(ConnectionType type,
const std::string& service_path) {
switch (type) {
case TYPE_ETHERNET: {
EthernetNetwork* ethernet = new EthernetNetwork(service_path);
return ethernet;
}
case TYPE_WIFI: {
WifiNetwork* wifi = new WifiNetwork(service_path);
return wifi;
}
case TYPE_CELLULAR: {
CellularNetwork* cellular = new CellularNetwork(service_path);
return cellular;
}
case TYPE_VPN: {
VirtualNetwork* vpn = new VirtualNetwork(service_path);
return vpn;
}
default: {
LOG(WARNING) << "Unknown service type: " << type;
return new Network(service_path, type);
}
}
}
Network* ParseNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network = FindNetworkByPath(service_path);
if (!network) {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddNetwork(network);
}
network->ParseInfo(info); // virtual.
UpdateActiveNetwork(network);
// Find and erase entry in update_requests, and set network priority.
PriorityMap::iterator found2 = network_update_requests_.find(service_path);
if (found2 != network_update_requests_.end()) {
network->priority_ = found2->second;
network_update_requests_.erase(found2);
if (network_update_requests_.empty()) {
// Clear wifi_scanning_ when we have no pending requests.
wifi_scanning_ = false;
}
} else {
// TODO(stevenjb): Enable warning once UpdateNetworkServiceList is fixed.
// LOG(WARNING) << "ParseNetwork called with no update request entry: "
// << service_path;
}
VLOG(1) << "ParseNetwork:" << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
Network* ParseRememberedNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network;
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found != remembered_network_map_.end()) {
network = found->second;
} else {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddRememberedNetwork(network);
}
network->ParseInfo(info); // virtual.
VLOG(1) << "ParseRememberedNetwork:" << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
void ClearNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&network_map_);
network_map_.clear();
ethernet_ = NULL;
active_wifi_ = NULL;
active_cellular_ = NULL;
active_virtual_ = NULL;
wifi_networks_.clear();
cellular_networks_.clear();
virtual_networks_.clear();
}
void ClearRememberedNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&remembered_network_map_);
remembered_network_map_.clear();
remembered_wifi_networks_.clear();
}
////////////////////////////////////////////////////////////////////////////
// NetworkDevice list management functions.
// Update device list, and request associated device updates.
// |devices| represents a complete list of devices.
void UpdateNetworkDeviceList(const ListValue* devices) {
NetworkDeviceMap old_device_map = device_map_;
device_map_.clear();
VLOG(2) << "Updating Device List.";
for (ListValue::const_iterator iter = devices->begin();
iter != devices->end(); ++iter) {
std::string device_path;
(*iter)->GetAsString(&device_path);
if (!device_path.empty()) {
NetworkDeviceMap::iterator found = old_device_map.find(device_path);
if (found != old_device_map.end()) {
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = found->second;
old_device_map.erase(found);
}
RequestNetworkDeviceInfo(
device_path.c_str(), &NetworkDeviceUpdate, this);
}
}
// Delete any old devices that no longer exist.
for (NetworkDeviceMap::iterator iter = old_device_map.begin();
iter != old_device_map.end(); ++iter) {
delete iter->second;
}
}
void DeleteDevice(const std::string& device_path) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
if (found == device_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant device: "
<< device_path;
return;
}
VLOG(2) << " Deleting device: " << device_path;
NetworkDevice* device = found->second;
device_map_.erase(found);
delete device;
}
void ParseNetworkDevice(const std::string& device_path,
const DictionaryValue* info) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
NetworkDevice* device;
if (found != device_map_.end()) {
device = found->second;
} else {
device = new NetworkDevice(device_path);
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = device;
}
device->ParseInfo(info);
VLOG(1) << "ParseNetworkDevice:" << device->name();
NotifyNetworkManagerChanged(false); // Not forced.
}
////////////////////////////////////////////////////////////////////////////
void EnableNetworkDeviceType(ConnectionType device, bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to enable a device that's already enabled: "
<< device;
return;
}
if (!enable && !(enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to disable a device that's already disabled: "
<< device;
return;
}
RequestNetworkDeviceEnable(ConnectionTypeToString(device), enable);
}
////////////////////////////////////////////////////////////////////////////
// Notifications.
// We call this any time something in NetworkLibrary changes.
// TODO(stevenjb): We should consider breaking this into multiplie
// notifications, e.g. connection state, devices, services, etc.
void NotifyNetworkManagerChanged(bool force_update) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Cancel any pending signals.
if (notify_task_) {
notify_task_->Cancel();
notify_task_ = NULL;
}
if (force_update) {
// Signal observers now.
SignalNetworkManagerObservers();
} else {
// Schedule a deleayed signal to limit the frequency of notifications.
notify_task_ = NewRunnableMethod(
this, &NetworkLibraryImpl::SignalNetworkManagerObservers);
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, notify_task_,
kNetworkNotifyDelayMs);
}
}
void SignalNetworkManagerObservers() {
notify_task_ = NULL;
FOR_EACH_OBSERVER(NetworkManagerObserver,
network_manager_observers_,
OnNetworkManagerChanged(this));
}
void NotifyNetworkChanged(Network* network) {
DCHECK(network);
NetworkObserverMap::const_iterator iter = network_observers_.find(
network->service_path());
if (iter != network_observers_.end()) {
FOR_EACH_OBSERVER(NetworkObserver,
*(iter->second),
OnNetworkChanged(this, network));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
network->service_path();
}
}
void NotifyCellularDataPlanChanged() {
FOR_EACH_OBSERVER(CellularDataPlanObserver,
data_plan_observers_,
OnCellularDataPlanChanged(this));
}
void NotifyUserConnectionInitiated(const Network* network) {
FOR_EACH_OBSERVER(UserActionObserver,
user_action_observers_,
OnConnectionInitiated(this, network));
}
////////////////////////////////////////////////////////////////////////////
// Service updates.
void UpdateNetworkStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
Network* network = FindNetworkByPath(path);
if (network) {
VLOG(1) << "UpdateNetworkStatus: " << network->name() << "." << key;
// Note: ParseValue is virtual.
int index = property_index_parser().Get(std::string(key));
if (!network->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkStatus: Error parsing: "
<< path << "." << key;
}
NotifyNetworkChanged(network);
// Anything observing the manager needs to know about any service change.
NotifyNetworkManagerChanged(false); // Not forced.
}
}
////////////////////////////////////////////////////////////////////////////
// Data Plans.
const CellularDataPlan* GetSignificantDataPlanFromVector(
const CellularDataPlanVector* plans) const {
const CellularDataPlan* significant = NULL;
for (CellularDataPlanVector::const_iterator iter = plans->begin();
iter != plans->end(); ++iter) {
// Set significant to the first plan or to first non metered base plan.
if (significant == NULL ||
significant->plan_type == CELLULAR_DATA_PLAN_METERED_BASE)
significant = *iter;
}
return significant;
}
CellularNetwork::DataLeft GetDataLeft(
CellularDataPlanVector* data_plans) {
const CellularDataPlan* plan = GetSignificantDataPlanFromVector(data_plans);
if (!plan)
return CellularNetwork::DATA_UNKNOWN;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
base::TimeDelta remaining = plan->remaining_time();
if (remaining <= base::TimeDelta::FromSeconds(0))
return CellularNetwork::DATA_NONE;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs))
return CellularNetwork::DATA_VERY_LOW;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs))
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
} else if (plan->plan_type == CELLULAR_DATA_PLAN_METERED_PAID ||
plan->plan_type == CELLULAR_DATA_PLAN_METERED_BASE) {
int64 remaining = plan->remaining_data();
if (remaining <= 0)
return CellularNetwork::DATA_NONE;
if (remaining <= kCellularDataVeryLowBytes)
return CellularNetwork::DATA_VERY_LOW;
// For base plans, we do not care about low data.
if (remaining <= kCellularDataLowBytes &&
plan->plan_type != CELLULAR_DATA_PLAN_METERED_BASE)
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
}
return CellularNetwork::DATA_UNKNOWN;
}
void UpdateCellularDataPlan(const std::string& service_path,
const CellularDataPlanList* data_plan_list) {
VLOG(1) << "Updating cellular data plans for: " << service_path;
CellularDataPlanVector* data_plans = NULL;
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
data_plans = found->second;
data_plans->reset(); // This will delete existing data plans.
} else {
data_plans = new CellularDataPlanVector;
data_plan_map_[service_path] = data_plans;
}
for (size_t i = 0; i < data_plan_list->plans_size; i++) {
const CellularDataPlanInfo* info(data_plan_list->GetCellularDataPlan(i));
CellularDataPlan* plan = new CellularDataPlan(*info);
data_plans->push_back(plan);
VLOG(2) << " Plan: " << plan->GetPlanDesciption()
<< " : " << plan->GetDataRemainingDesciption();
}
// Now, update any matching cellular network's cached data
CellularNetwork* cellular = FindCellularNetworkByPath(service_path);
if (cellular) {
CellularNetwork::DataLeft data_left;
// If the network needs a new plan, then there's no data.
if (cellular->needs_new_plan())
data_left = CellularNetwork::DATA_NONE;
else
data_left = GetDataLeft(data_plans);
VLOG(2) << " Data left: " << data_left
<< " Need plan: " << cellular->needs_new_plan();
cellular->set_data_left(data_left);
}
NotifyCellularDataPlanChanged();
}
////////////////////////////////////////////////////////////////////////////
void Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
if (EnsureCrosLoaded()) {
VLOG(1) << "Requesting initial network manager info from libcros.";
RequestNetworkManagerInfo(&NetworkManagerUpdate, this);
}
}
void InitTestData() {
is_locked_ = false;
// Devices
int devices =
(1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR);
available_devices_ = devices;
enabled_devices_ = devices;
connected_devices_ = devices;
// Networks
ClearNetworks(true /*delete networks*/);
ethernet_ = new EthernetNetwork("eth1");
ethernet_->set_connected(true);
AddNetwork(ethernet_);
WifiNetwork* wifi1 = new WifiNetwork("fw1");
wifi1->set_name("Fake Wifi Connected");
wifi1->set_strength(90);
wifi1->set_connected(true);
wifi1->set_encryption(SECURITY_NONE);
AddNetwork(wifi1);
WifiNetwork* wifi2 = new WifiNetwork("fw2");
wifi2->set_name("Fake Wifi");
wifi2->set_strength(70);
wifi2->set_connected(false);
wifi2->set_encryption(SECURITY_NONE);
AddNetwork(wifi2);
WifiNetwork* wifi3 = new WifiNetwork("fw3");
wifi3->set_name("Fake Wifi Encrypted");
wifi3->set_strength(60);
wifi3->set_connected(false);
wifi3->set_encryption(SECURITY_WEP);
wifi3->set_passphrase_required(true);
AddNetwork(wifi3);
WifiNetwork* wifi4 = new WifiNetwork("fw4");
wifi4->set_name("Fake Wifi 802.1x");
wifi4->set_strength(50);
wifi4->set_connected(false);
wifi4->set_connectable(false);
wifi4->set_encryption(SECURITY_8021X);
wifi4->set_identity("nobody@google.com");
wifi4->set_cert_path("SETTINGS:key_id=3,cert_id=3,pin=111111");
AddNetwork(wifi4);
active_wifi_ = wifi1;
CellularNetwork* cellular1 = new CellularNetwork("fc1");
cellular1->set_name("Fake Cellular");
cellular1->set_strength(70);
cellular1->set_connected(false);
cellular1->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular1->set_payment_url(std::string("http://www.google.com"));
cellular1->set_usage_url(std::string("http://www.google.com"));
cellular1->set_network_technology(NETWORK_TECHNOLOGY_EVDO);
cellular1->set_roaming_state(ROAMING_STATE_ROAMING);
CellularDataPlan* base_plan = new CellularDataPlan();
base_plan->plan_name = "Base plan";
base_plan->plan_type = CELLULAR_DATA_PLAN_METERED_BASE;
base_plan->plan_data_bytes = 100ll * 1024 * 1024;
base_plan->data_bytes_used = 75ll * 1024 * 1024;
CellularDataPlanVector* data_plans = new CellularDataPlanVector();
data_plan_map_[cellular1->service_path()] = data_plans;
data_plans->push_back(base_plan);
CellularDataPlan* paid_plan = new CellularDataPlan();
paid_plan->plan_name = "Paid plan";
paid_plan->plan_type = CELLULAR_DATA_PLAN_METERED_PAID;
paid_plan->plan_data_bytes = 5ll * 1024 * 1024 * 1024;
paid_plan->data_bytes_used = 3ll * 1024 * 1024 * 1024;
data_plans->push_back(paid_plan);
AddNetwork(cellular1);
active_cellular_ = cellular1;
// Remembered Networks
ClearRememberedNetworks(true /*delete networks*/);
WifiNetwork* remembered_wifi2 = new WifiNetwork("fw2");
remembered_wifi2->set_name("Fake Wifi 2");
remembered_wifi2->set_strength(70);
remembered_wifi2->set_connected(true);
remembered_wifi2->set_encryption(SECURITY_WEP);
AddRememberedNetwork(remembered_wifi2);
wifi_scanning_ = false;
offline_mode_ = false;
}
// Network manager observer list
ObserverList<NetworkManagerObserver> network_manager_observers_;
// Cellular data plan observer list
ObserverList<CellularDataPlanObserver> data_plan_observers_;
// User action observer list
ObserverList<UserActionObserver> user_action_observers_;
// Network observer map
NetworkObserverMap network_observers_;
// For monitoring network manager status changes.
PropertyChangeMonitor network_manager_monitor_;
// For monitoring data plan changes to the connected cellular network.
DataPlanUpdateMonitor data_plan_monitor_;
// Network login observer.
scoped_ptr<NetworkLoginObserver> network_login_observer_;
// A service path based map of all Networks.
NetworkMap network_map_;
// A service path based map of all remembered Networks.
NetworkMap remembered_network_map_;
// A list of services that we are awaiting updates for.
PriorityMap network_update_requests_;
// A device path based map of all NetworkDevices.
NetworkDeviceMap device_map_;
// A network service path based map of all CellularDataPlanVectors.
CellularDataPlanMap data_plan_map_;
// The ethernet network.
EthernetNetwork* ethernet_;
// The list of available wifi networks.
WifiNetworkVector wifi_networks_;
// The current connected (or connecting) wifi network.
WifiNetwork* active_wifi_;
// The remembered wifi networks.
WifiNetworkVector remembered_wifi_networks_;
// The list of available cellular networks.
CellularNetworkVector cellular_networks_;
// The current connected (or connecting) cellular network.
CellularNetwork* active_cellular_;
// The list of available virtual networks.
VirtualNetworkVector virtual_networks_;
// The current connected (or connecting) virtual network.
VirtualNetwork* active_virtual_;
// The path of the active profile (for retrieving remembered services).
std::string active_profile_path_;
// The current available network devices. Bitwise flag of ConnectionTypes.
int available_devices_;
// The current enabled network devices. Bitwise flag of ConnectionTypes.
int enabled_devices_;
// The current connected network devices. Bitwise flag of ConnectionTypes.
int connected_devices_;
// True if we are currently scanning for wifi networks.
bool wifi_scanning_;
// Currently not implemented. TODO: implement or eliminate.
bool offline_mode_;
// True if access network library is locked.
bool is_locked_;
// Delayed task to notify a network change.
CancelableTask* notify_task_;
// Cellular plan payment time.
base::Time cellular_plan_payment_time_;
// Temporary connection data for async connect calls.
struct ConnectData {
ConnectData() : auto_connect(false) {}
void SetData(const std::string& n,
const std::string& p,
const std::string& id,
const std::string& cert,
bool autocon) {
name = n;
passphrase = p;
identity = id;
certpath = cert;
auto_connect = autocon;
}
std::string name;
std::string passphrase;
std::string identity;
std::string certpath;
bool auto_connect;
};
ConnectData connect_data_;
DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl);
};
class NetworkLibraryStubImpl : public NetworkLibrary {
public:
NetworkLibraryStubImpl()
: ip_address_("1.1.1.1"),
ethernet_(new EthernetNetwork("eth0")),
active_wifi_(NULL),
active_cellular_(NULL) {
}
~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; }
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {}
virtual void Lock() {}
virtual void Unlock() {}
virtual bool IsLocked() { return true; }
virtual void AddCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void AddUserActionObserver(UserActionObserver* observer) {}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {}
virtual const EthernetNetwork* ethernet_network() const {
return ethernet_;
}
virtual bool ethernet_connecting() const { return false; }
virtual bool ethernet_connected() const { return true; }
virtual const WifiNetwork* wifi_network() const {
return active_wifi_;
}
virtual bool wifi_connecting() const { return false; }
virtual bool wifi_connected() const { return false; }
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const { return false; }
virtual bool cellular_connected() const { return false; }
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const { return false; }
virtual bool virtual_network_connected() const { return false; }
bool Connected() const { return true; }
bool Connecting() const { return false; }
const std::string& IPAddress() const { return ip_address_; }
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
virtual bool has_cellular_networks() const {
return cellular_networks_.begin() != cellular_networks_.end();
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const { return NULL; }
virtual Network* FindNetworkByPath(
const std::string& path) const { return NULL; }
virtual WifiNetwork* FindWifiNetworkByPath(
const std::string& path) const { return NULL; }
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const { return NULL; }
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const { return NULL; }
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const { return NULL; }
virtual void RequestNetworkScan() {}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
return false;
}
virtual void ConnectToWifiNetwork(WifiNetwork* network) {}
virtual void ConnectToWifiNetwork(const std::string& service_path) {}
virtual void ConnectToWifiNetwork(ConnectionSecurity security,
const std::string& ssid,
const std::string& passphrase,
const std::string& identity,
const std::string& certpath,
bool auto_connect) {}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {}
virtual void SignalCellularPlanPayment() {}
virtual bool HasRecentCellularPlanPayment() { return false; }
virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {}
virtual void ForgetWifiNetwork(const std::string& service_path) {}
virtual bool ethernet_available() const { return true; }
virtual bool wifi_available() const { return false; }
virtual bool cellular_available() const { return false; }
virtual bool ethernet_enabled() const { return true; }
virtual bool wifi_enabled() const { return false; }
virtual bool cellular_enabled() const { return false; }
virtual bool wifi_scanning() const { return false; }
virtual const Network* active_network() const { return NULL; }
virtual bool offline_mode() const { return false; }
virtual void EnableEthernetNetworkDevice(bool enable) {}
virtual void EnableWifiNetworkDevice(bool enable) {}
virtual void EnableCellularNetworkDevice(bool enable) {}
virtual void EnableOfflineMode(bool enable) {}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address) {
hardware_address->clear();
return NetworkIPConfigVector();
}
virtual std::string GetHtmlInfo(int refresh) { return std::string(); }
private:
std::string ip_address_;
EthernetNetwork* ethernet_;
WifiNetwork* active_wifi_;
CellularNetwork* active_cellular_;
VirtualNetwork* active_virtual_;
WifiNetworkVector wifi_networks_;
CellularNetworkVector cellular_networks_;
VirtualNetworkVector virtual_networks_;
};
// static
NetworkLibrary* NetworkLibrary::GetImpl(bool stub) {
if (stub)
return new NetworkLibraryStubImpl();
else
return new NetworkLibraryImpl();
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl);
|
// 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/chromeos/cros/network_library.h"
#include <algorithm>
#include <map>
#include "base/i18n/time_formatting.h"
#include "base/metrics/histogram.h"
#include "base/stl_util-inl.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/network_login_observer.h"
#include "chrome/browser/chromeos/user_cros_settings_provider.h"
#include "chrome/common/time_format.h"
#include "content/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
////////////////////////////////////////////////////////////////////////////////
// Implementation notes.
// NetworkLibraryImpl manages a series of classes that describe network devices
// and services:
//
// NetworkDevice: e.g. ethernet, wifi modem, cellular modem
// device_map_: canonical map<path,NetworkDevice*> for devices
//
// Network: a network service ("network").
// network_map_: canonical map<path,Network*> for all visible networks.
// EthernetNetwork
// ethernet_: EthernetNetwork* to the active ethernet network in network_map_.
// WirelessNetwork: a Wifi or Cellular Network.
// WifiNetwork
// active_wifi_: WifiNetwork* to the active wifi network in network_map_.
// wifi_networks_: ordered vector of WifiNetwork* entries in network_map_,
// in descending order of importance.
// CellularNetwork
// active_cellular_: Cellular version of wifi_.
// cellular_networks_: Cellular version of wifi_.
// network_unique_id_map_: map<unique_id,Network*> for visible networks.
// remembered_network_map_: a canonical map<path,Network*> for all networks
// remembered in the active Profile ("favorites").
// remembered_wifi_networks_: ordered vector of WifiNetwork* entries in
// remembered_network_map_, in descending order of preference.
//
// network_manager_monitor_: a handle to the libcros network Manager handler.
// NetworkManagerStatusChanged: This handles all messages from the Manager.
// Messages are parsed here and the appropriate updates are then requested.
//
// UpdateNetworkServiceList: This is the primary Manager handler. It handles
// the "Services" message which list all visible networks. The handler
// rebuilds the network lists without destroying existing Network structures,
// then requests neccessary updates to be fetched asynchronously from
// libcros (RequestNetworkServiceInfo).
//
// TODO(stevenjb): Document cellular data plan handlers.
//
// AddNetworkObserver: Adds an observer for a specific network.
// NetworkObserverList: A monitor and list of observers of a network.
// network_monitor_: a handle to the libcros network Service handler.
// UpdateNetworkStatus: This handles changes to a monitored service, typically
// changes to transient states like Strength. (Note: also updates State).
//
// AddNetworkDeviceObserver: Adds an observer for a specific device.
// Will be called on any device property change.
// NetworkDeviceObserverList: A monitor and list of observers of a device.
// UpdateNetworkDeviceStatus: Handles changes to a monitored device, like
// SIM lock state and updates device state.
//
// All *Pin(...) methods use internal callback that would update cellular
// device state once async call is completed and notify all device observers.
//
////////////////////////////////////////////////////////////////////////////////
namespace chromeos {
// Local constants.
namespace {
// Only send network change notifications to observers once every 50ms.
const int kNetworkNotifyDelayMs = 50;
// How long we should remember that cellular plan payment was received.
const int kRecentPlanPaymentHours = 6;
// Default value of the SIM unlock retries count. It is updated to the real
// retries count once cellular device with SIM card is initialized.
// If cellular device doesn't have SIM card, then retries are never used.
const int kDefaultSimUnlockRetriesCount = 999;
// Type of a pending SIM operation.
enum SimOperationType {
SIM_OPERATION_NONE = 0,
SIM_OPERATION_CHANGE_PIN = 1,
SIM_OPERATION_CHANGE_REQUIRE_PIN = 2,
SIM_OPERATION_ENTER_PIN = 3,
SIM_OPERATION_UNBLOCK_PIN = 4,
};
// D-Bus interface string constants.
// Flimflam property names.
const char* kSecurityProperty = "Security";
const char* kPassphraseProperty = "Passphrase";
const char* kIdentityProperty = "Identity";
const char* kCertPathProperty = "CertPath";
const char* kPassphraseRequiredProperty = "PassphraseRequired";
const char* kSaveCredentialsProperty = "SaveCredentials";
const char* kProfilesProperty = "Profiles";
const char* kServicesProperty = "Services";
const char* kServiceWatchListProperty = "ServiceWatchList";
const char* kAvailableTechnologiesProperty = "AvailableTechnologies";
const char* kEnabledTechnologiesProperty = "EnabledTechnologies";
const char* kConnectedTechnologiesProperty = "ConnectedTechnologies";
const char* kDefaultTechnologyProperty = "DefaultTechnology";
const char* kOfflineModeProperty = "OfflineMode";
const char* kSignalStrengthProperty = "Strength";
const char* kNameProperty = "Name";
const char* kStateProperty = "State";
const char* kConnectivityStateProperty = "ConnectivityState";
const char* kTypeProperty = "Type";
const char* kDeviceProperty = "Device";
const char* kActivationStateProperty = "Cellular.ActivationState";
const char* kNetworkTechnologyProperty = "Cellular.NetworkTechnology";
const char* kRoamingStateProperty = "Cellular.RoamingState";
const char* kOperatorNameProperty = "Cellular.OperatorName";
const char* kOperatorCodeProperty = "Cellular.OperatorCode";
const char* kPaymentURLProperty = "Cellular.OlpUrl";
const char* kUsageURLProperty = "Cellular.UsageUrl";
const char* kCellularApnProperty = "Cellular.APN";
const char* kCellularLastGoodApnProperty = "Cellular.LastGoodAPN";
const char* kCellularAllowRoamingProperty = "Cellular.AllowRoaming";
const char* kFavoriteProperty = "Favorite";
const char* kConnectableProperty = "Connectable";
const char* kAutoConnectProperty = "AutoConnect";
const char* kIsActiveProperty = "IsActive";
const char* kModeProperty = "Mode";
const char* kErrorProperty = "Error";
const char* kActiveProfileProperty = "ActiveProfile";
const char* kEntriesProperty = "Entries";
const char* kDevicesProperty = "Devices";
const char* kProviderProperty = "Provider";
const char* kHostProperty = "Host";
// Flimflam property names for SIMLock status.
const char* kSIMLockStatusProperty = "Cellular.SIMLockStatus";
const char* kSIMLockTypeProperty = "LockType";
const char* kSIMLockRetriesLeftProperty = "RetriesLeft";
// Flimflam property names for Cellular.FoundNetworks.
const char* kLongNameProperty = "long_name";
const char* kStatusProperty = "status";
const char* kShortNameProperty = "short_name";
const char* kTechnologyProperty = "technology";
// Flimflam SIMLock status types.
const char* kSIMLockPin = "sim-pin";
const char* kSIMLockPuk = "sim-puk";
// APN info property names.
const char* kApnProperty = "apn";
const char* kNetworkIdProperty = "network_id";
const char* kUsernameProperty = "username";
const char* kPasswordProperty = "password";
// Flimflam device info property names.
const char* kScanningProperty = "Scanning";
const char* kCarrierProperty = "Cellular.Carrier";
const char* kHomeProviderProperty = "Cellular.HomeProvider";
const char* kMeidProperty = "Cellular.MEID";
const char* kImeiProperty = "Cellular.IMEI";
const char* kImsiProperty = "Cellular.IMSI";
const char* kEsnProperty = "Cellular.ESN";
const char* kMdnProperty = "Cellular.MDN";
const char* kMinProperty = "Cellular.MIN";
const char* kModelIDProperty = "Cellular.ModelID";
const char* kManufacturerProperty = "Cellular.Manufacturer";
const char* kFirmwareRevisionProperty = "Cellular.FirmwareRevision";
const char* kHardwareRevisionProperty = "Cellular.HardwareRevision";
const char* kLastDeviceUpdateProperty = "Cellular.LastDeviceUpdate";
const char* kPRLVersionProperty = "Cellular.PRLVersion"; // (INT16)
const char* kSelectedNetworkProperty = "Cellular.SelectedNetwork";
const char* kFoundNetworksProperty = "Cellular.FoundNetworks";
// Flimflam type options.
const char* kTypeEthernet = "ethernet";
const char* kTypeWifi = "wifi";
const char* kTypeWimax = "wimax";
const char* kTypeBluetooth = "bluetooth";
const char* kTypeCellular = "cellular";
const char* kTypeVPN = "vpn";
// Flimflam mode options.
const char* kModeManaged = "managed";
const char* kModeAdhoc = "adhoc";
// Flimflam security options.
const char* kSecurityWpa = "wpa";
const char* kSecurityWep = "wep";
const char* kSecurityRsn = "rsn";
const char* kSecurity8021x = "802_1x";
const char* kSecurityPsk = "psk";
const char* kSecurityNone = "none";
// Flimflam L2TPIPsec property names.
const char* kL2TPIPSecCACertProperty = "L2TPIPsec.CACert";
const char* kL2TPIPSecCertProperty = "L2TPIPsec.Cert";
const char* kL2TPIPSecKeyProperty = "L2TPIPsec.Key";
const char* kL2TPIPSecPSKProperty = "L2TPIPsec.PSK";
const char* kL2TPIPSecUserProperty = "L2TPIPsec.User";
const char* kL2TPIPSecPasswordProperty = "L2TPIPsec.Password";
// Flimflam EAP property names.
// See src/third_party/flimflam/doc/service-api.txt.
const char* kEapIdentityProperty = "EAP.Identity";
const char* kEapMethodProperty = "EAP.EAP";
const char* kEapPhase2AuthProperty = "EAP.InnerEAP";
const char* kEapAnonymousIdentityProperty = "EAP.AnonymousIdentity";
const char* kEapClientCertProperty = "EAP.ClientCert"; // path
const char* kEapCertIDProperty = "EAP.CertID"; // PKCS#11 ID
const char* kEapClientCertNssProperty = "EAP.ClientCertNSS"; // NSS nickname
const char* kEapPrivateKeyProperty = "EAP.PrivateKey";
const char* kEapPrivateKeyPasswordProperty = "EAP.PrivateKeyPassword";
const char* kEapKeyIDProperty = "EAP.KeyID";
const char* kEapCaCertProperty = "EAP.CACert"; // server CA cert path
const char* kEapCaCertIDProperty = "EAP.CACertID"; // server CA PKCS#11 ID
const char* kEapCaCertNssProperty = "EAP.CACertNSS"; // server CA NSS nickname
const char* kEapUseSystemCAsProperty = "EAP.UseSystemCAs";
const char* kEapPinProperty = "EAP.PIN";
const char* kEapPasswordProperty = "EAP.Password";
const char* kEapKeyMgmtProperty = "EAP.KeyMgmt";
// Flimflam EAP method options.
const std::string& kEapMethodPEAP = "PEAP";
const std::string& kEapMethodTLS = "TLS";
const std::string& kEapMethodTTLS = "TTLS";
const std::string& kEapMethodLEAP = "LEAP";
// Flimflam EAP phase 2 auth options.
const std::string& kEapPhase2AuthPEAPMD5 = "auth=MD5";
const std::string& kEapPhase2AuthPEAPMSCHAPV2 = "auth=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMD5 = "autheap=MD5";
const std::string& kEapPhase2AuthTTLSMSCHAPV2 = "autheap=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMSCHAP = "autheap=MSCHAP";
const std::string& kEapPhase2AuthTTLSPAP = "autheap=PAP";
const std::string& kEapPhase2AuthTTLSCHAP = "autheap=CHAP";
// Flimflam VPN provider types.
const char* kProviderL2tpIpsec = "l2tpipsec";
const char* kProviderOpenVpn = "openvpn";
// Flimflam state options.
const char* kStateIdle = "idle";
const char* kStateCarrier = "carrier";
const char* kStateAssociation = "association";
const char* kStateConfiguration = "configuration";
const char* kStateReady = "ready";
const char* kStateDisconnect = "disconnect";
const char* kStateFailure = "failure";
const char* kStateActivationFailure = "activation-failure";
// Flimflam connectivity state options.
const char* kConnStateUnrestricted = "unrestricted";
const char* kConnStateRestricted = "restricted";
const char* kConnStateNone = "none";
// Flimflam network technology options.
const char* kNetworkTechnology1Xrtt = "1xRTT";
const char* kNetworkTechnologyEvdo = "EVDO";
const char* kNetworkTechnologyGprs = "GPRS";
const char* kNetworkTechnologyEdge = "EDGE";
const char* kNetworkTechnologyUmts = "UMTS";
const char* kNetworkTechnologyHspa = "HSPA";
const char* kNetworkTechnologyHspaPlus = "HSPA+";
const char* kNetworkTechnologyLte = "LTE";
const char* kNetworkTechnologyLteAdvanced = "LTE Advanced";
// Flimflam roaming state options
const char* kRoamingStateHome = "home";
const char* kRoamingStateRoaming = "roaming";
const char* kRoamingStateUnknown = "unknown";
// Flimflam activation state options
const char* kActivationStateActivated = "activated";
const char* kActivationStateActivating = "activating";
const char* kActivationStateNotActivated = "not-activated";
const char* kActivationStatePartiallyActivated = "partially-activated";
const char* kActivationStateUnknown = "unknown";
// Flimflam error options.
const char* kErrorOutOfRange = "out-of-range";
const char* kErrorPinMissing = "pin-missing";
const char* kErrorDhcpFailed = "dhcp-failed";
const char* kErrorConnectFailed = "connect-failed";
const char* kErrorBadPassphrase = "bad-passphrase";
const char* kErrorBadWEPKey = "bad-wepkey";
const char* kErrorActivationFailed = "activation-failed";
const char* kErrorNeedEvdo = "need-evdo";
const char* kErrorNeedHomeNetwork = "need-home-network";
const char* kErrorOtaspFailed = "otasp-failed";
const char* kErrorAaaFailed = "aaa-failed";
// Flimflam error messages.
const char* kErrorPassphraseRequiredMsg = "Passphrase required";
const char* kErrorIncorrectPinMsg = "org.chromium.flimflam.Device.IncorrectPin";
const char* kErrorPinBlockedMsg = "org.chromium.flimflam.Device.PinBlocked";
const char* kErrorPinRequiredMsg = "org.chromium.flimflam.Device.PinRequired";
const char* kUnknownString = "UNKNOWN";
////////////////////////////////////////////////////////////////////////////
static const char* ConnectionTypeToString(ConnectionType type) {
switch (type) {
case TYPE_UNKNOWN:
break;
case TYPE_ETHERNET:
return kTypeEthernet;
case TYPE_WIFI:
return kTypeWifi;
case TYPE_WIMAX:
return kTypeWimax;
case TYPE_BLUETOOTH:
return kTypeBluetooth;
case TYPE_CELLULAR:
return kTypeCellular;
case TYPE_VPN:
return kTypeVPN;
}
LOG(ERROR) << "ConnectionTypeToString called with unknown type: " << type;
return kUnknownString;
}
// TODO(stevenjb/njw): Deprecate in favor of setting EAP properties.
static const char* SecurityToString(ConnectionSecurity security) {
switch (security) {
case SECURITY_NONE:
return kSecurityNone;
case SECURITY_WEP:
return kSecurityWep;
case SECURITY_WPA:
return kSecurityWpa;
case SECURITY_RSN:
return kSecurityRsn;
case SECURITY_8021X:
return kSecurity8021x;
case SECURITY_PSK:
return kSecurityPsk;
case SECURITY_UNKNOWN:
break;
}
LOG(ERROR) << "SecurityToString called with unknown type: " << security;
return kUnknownString;
}
static const char* ProviderTypeToString(VirtualNetwork::ProviderType type) {
switch (type) {
case VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK:
case VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
return kProviderL2tpIpsec;
case VirtualNetwork::PROVIDER_TYPE_OPEN_VPN:
return kProviderOpenVpn;
case VirtualNetwork::PROVIDER_TYPE_MAX:
break;
}
LOG(ERROR) << "ProviderTypeToString called with unknown type: " << type;
return kUnknownString;
}
////////////////////////////////////////////////////////////////////////////
// Helper class to cache maps of strings to enums.
template <typename Type>
class StringToEnum {
public:
struct Pair {
const char* key;
const Type value;
};
explicit StringToEnum(const Pair* list, size_t num_entries, Type unknown)
: unknown_value_(unknown) {
for (size_t i = 0; i < num_entries; ++i, ++list)
enum_map_[list->key] = list->value;
}
Type Get(const std::string& type) const {
EnumMapConstIter iter = enum_map_.find(type);
if (iter != enum_map_.end())
return iter->second;
return unknown_value_;
}
private:
typedef typename std::map<std::string, Type> EnumMap;
typedef typename std::map<std::string, Type>::const_iterator EnumMapConstIter;
EnumMap enum_map_;
Type unknown_value_;
DISALLOW_COPY_AND_ASSIGN(StringToEnum);
};
////////////////////////////////////////////////////////////////////////////
enum PropertyIndex {
PROPERTY_INDEX_ACTIVATION_STATE,
PROPERTY_INDEX_ACTIVE_PROFILE,
PROPERTY_INDEX_AUTO_CONNECT,
PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES,
PROPERTY_INDEX_CARRIER,
PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING,
PROPERTY_INDEX_CELLULAR_APN,
PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN,
PROPERTY_INDEX_CERT_PATH,
PROPERTY_INDEX_CONNECTABLE,
PROPERTY_INDEX_CONNECTED_TECHNOLOGIES,
PROPERTY_INDEX_CONNECTIVITY_STATE,
PROPERTY_INDEX_DEFAULT_TECHNOLOGY,
PROPERTY_INDEX_DEVICE,
PROPERTY_INDEX_DEVICES,
PROPERTY_INDEX_EAP_IDENTITY,
PROPERTY_INDEX_EAP_METHOD,
PROPERTY_INDEX_EAP_PHASE_2_AUTH,
PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY,
PROPERTY_INDEX_EAP_CLIENT_CERT,
PROPERTY_INDEX_EAP_CERT_ID,
PROPERTY_INDEX_EAP_CLIENT_CERT_NSS,
PROPERTY_INDEX_EAP_PRIVATE_KEY,
PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD,
PROPERTY_INDEX_EAP_KEY_ID,
PROPERTY_INDEX_EAP_CA_CERT,
PROPERTY_INDEX_EAP_CA_CERT_ID,
PROPERTY_INDEX_EAP_CA_CERT_NSS,
PROPERTY_INDEX_EAP_USE_SYSTEM_CAS,
PROPERTY_INDEX_EAP_PIN,
PROPERTY_INDEX_EAP_PASSWORD,
PROPERTY_INDEX_EAP_KEY_MGMT,
PROPERTY_INDEX_ENABLED_TECHNOLOGIES,
PROPERTY_INDEX_ERROR,
PROPERTY_INDEX_ESN,
PROPERTY_INDEX_FAVORITE,
PROPERTY_INDEX_FIRMWARE_REVISION,
PROPERTY_INDEX_FOUND_NETWORKS,
PROPERTY_INDEX_HARDWARE_REVISION,
PROPERTY_INDEX_HOME_PROVIDER,
PROPERTY_INDEX_HOST,
PROPERTY_INDEX_IDENTITY,
PROPERTY_INDEX_IMEI,
PROPERTY_INDEX_IMSI,
PROPERTY_INDEX_IS_ACTIVE,
PROPERTY_INDEX_LAST_DEVICE_UPDATE,
PROPERTY_INDEX_L2TPIPSEC_CA_CERT,
PROPERTY_INDEX_L2TPIPSEC_CERT,
PROPERTY_INDEX_L2TPIPSEC_KEY,
PROPERTY_INDEX_L2TPIPSEC_PASSWORD,
PROPERTY_INDEX_L2TPIPSEC_PSK,
PROPERTY_INDEX_L2TPIPSEC_USER,
PROPERTY_INDEX_MANUFACTURER,
PROPERTY_INDEX_MDN,
PROPERTY_INDEX_MEID,
PROPERTY_INDEX_MIN,
PROPERTY_INDEX_MODE,
PROPERTY_INDEX_MODEL_ID,
PROPERTY_INDEX_NAME,
PROPERTY_INDEX_NETWORK_TECHNOLOGY,
PROPERTY_INDEX_OFFLINE_MODE,
PROPERTY_INDEX_OPERATOR_CODE,
PROPERTY_INDEX_OPERATOR_NAME,
PROPERTY_INDEX_PASSPHRASE,
PROPERTY_INDEX_PASSPHRASE_REQUIRED,
PROPERTY_INDEX_PAYMENT_URL,
PROPERTY_INDEX_PRL_VERSION,
PROPERTY_INDEX_PROFILES,
PROPERTY_INDEX_PROVIDER,
PROPERTY_INDEX_ROAMING_STATE,
PROPERTY_INDEX_SAVE_CREDENTIALS,
PROPERTY_INDEX_SCANNING,
PROPERTY_INDEX_SECURITY,
PROPERTY_INDEX_SELECTED_NETWORK,
PROPERTY_INDEX_SERVICES,
PROPERTY_INDEX_SERVICE_WATCH_LIST,
PROPERTY_INDEX_SIGNAL_STRENGTH,
PROPERTY_INDEX_SIM_LOCK,
PROPERTY_INDEX_STATE,
PROPERTY_INDEX_TYPE,
PROPERTY_INDEX_UNKNOWN,
PROPERTY_INDEX_USAGE_URL,
};
StringToEnum<PropertyIndex>::Pair property_index_table[] = {
{ kActivationStateProperty, PROPERTY_INDEX_ACTIVATION_STATE },
{ kActiveProfileProperty, PROPERTY_INDEX_ACTIVE_PROFILE },
{ kAutoConnectProperty, PROPERTY_INDEX_AUTO_CONNECT },
{ kAvailableTechnologiesProperty, PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES },
{ kCellularAllowRoamingProperty, PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING },
{ kCellularApnProperty, PROPERTY_INDEX_CELLULAR_APN },
{ kCellularLastGoodApnProperty, PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN },
{ kCarrierProperty, PROPERTY_INDEX_CARRIER },
{ kCertPathProperty, PROPERTY_INDEX_CERT_PATH },
{ kConnectableProperty, PROPERTY_INDEX_CONNECTABLE },
{ kConnectedTechnologiesProperty, PROPERTY_INDEX_CONNECTED_TECHNOLOGIES },
{ kConnectivityStateProperty, PROPERTY_INDEX_CONNECTIVITY_STATE },
{ kDefaultTechnologyProperty, PROPERTY_INDEX_DEFAULT_TECHNOLOGY },
{ kDeviceProperty, PROPERTY_INDEX_DEVICE },
{ kDevicesProperty, PROPERTY_INDEX_DEVICES },
{ kEapIdentityProperty, PROPERTY_INDEX_EAP_IDENTITY },
{ kEapMethodProperty, PROPERTY_INDEX_EAP_METHOD },
{ kEapPhase2AuthProperty, PROPERTY_INDEX_EAP_PHASE_2_AUTH },
{ kEapAnonymousIdentityProperty, PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY },
{ kEapClientCertProperty, PROPERTY_INDEX_EAP_CLIENT_CERT },
{ kEapCertIDProperty, PROPERTY_INDEX_EAP_CERT_ID },
{ kEapClientCertNssProperty, PROPERTY_INDEX_EAP_CLIENT_CERT_NSS },
{ kEapPrivateKeyProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY },
{ kEapPrivateKeyPasswordProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD },
{ kEapKeyIDProperty, PROPERTY_INDEX_EAP_KEY_ID },
{ kEapCaCertProperty, PROPERTY_INDEX_EAP_CA_CERT },
{ kEapCaCertIDProperty, PROPERTY_INDEX_EAP_CA_CERT_ID },
{ kEapCaCertNssProperty, PROPERTY_INDEX_EAP_CA_CERT_NSS },
{ kEapUseSystemCAsProperty, PROPERTY_INDEX_EAP_USE_SYSTEM_CAS },
{ kEapPinProperty, PROPERTY_INDEX_EAP_PIN },
{ kEapPasswordProperty, PROPERTY_INDEX_EAP_PASSWORD },
{ kEapKeyMgmtProperty, PROPERTY_INDEX_EAP_KEY_MGMT },
{ kEnabledTechnologiesProperty, PROPERTY_INDEX_ENABLED_TECHNOLOGIES },
{ kErrorProperty, PROPERTY_INDEX_ERROR },
{ kEsnProperty, PROPERTY_INDEX_ESN },
{ kFavoriteProperty, PROPERTY_INDEX_FAVORITE },
{ kFirmwareRevisionProperty, PROPERTY_INDEX_FIRMWARE_REVISION },
{ kFoundNetworksProperty, PROPERTY_INDEX_FOUND_NETWORKS },
{ kHardwareRevisionProperty, PROPERTY_INDEX_HARDWARE_REVISION },
{ kHomeProviderProperty, PROPERTY_INDEX_HOME_PROVIDER },
{ kHostProperty, PROPERTY_INDEX_HOST },
{ kIdentityProperty, PROPERTY_INDEX_IDENTITY },
{ kImeiProperty, PROPERTY_INDEX_IMEI },
{ kImsiProperty, PROPERTY_INDEX_IMSI },
{ kIsActiveProperty, PROPERTY_INDEX_IS_ACTIVE },
{ kL2TPIPSecCACertProperty, PROPERTY_INDEX_L2TPIPSEC_CA_CERT },
{ kL2TPIPSecCertProperty, PROPERTY_INDEX_L2TPIPSEC_CERT },
{ kL2TPIPSecKeyProperty, PROPERTY_INDEX_L2TPIPSEC_KEY },
{ kL2TPIPSecPasswordProperty, PROPERTY_INDEX_L2TPIPSEC_PASSWORD },
{ kL2TPIPSecPSKProperty, PROPERTY_INDEX_L2TPIPSEC_PSK },
{ kL2TPIPSecUserProperty, PROPERTY_INDEX_L2TPIPSEC_USER },
{ kLastDeviceUpdateProperty, PROPERTY_INDEX_LAST_DEVICE_UPDATE },
{ kManufacturerProperty, PROPERTY_INDEX_MANUFACTURER },
{ kMdnProperty, PROPERTY_INDEX_MDN },
{ kMeidProperty, PROPERTY_INDEX_MEID },
{ kMinProperty, PROPERTY_INDEX_MIN },
{ kModeProperty, PROPERTY_INDEX_MODE },
{ kModelIDProperty, PROPERTY_INDEX_MODEL_ID },
{ kNameProperty, PROPERTY_INDEX_NAME },
{ kNetworkTechnologyProperty, PROPERTY_INDEX_NETWORK_TECHNOLOGY },
{ kOfflineModeProperty, PROPERTY_INDEX_OFFLINE_MODE },
{ kOperatorCodeProperty, PROPERTY_INDEX_OPERATOR_CODE },
{ kOperatorNameProperty, PROPERTY_INDEX_OPERATOR_NAME },
{ kPRLVersionProperty, PROPERTY_INDEX_PRL_VERSION },
{ kPassphraseProperty, PROPERTY_INDEX_PASSPHRASE },
{ kPassphraseRequiredProperty, PROPERTY_INDEX_PASSPHRASE_REQUIRED },
{ kPaymentURLProperty, PROPERTY_INDEX_PAYMENT_URL },
{ kProfilesProperty, PROPERTY_INDEX_PROFILES },
{ kProviderProperty, PROPERTY_INDEX_PROVIDER },
{ kRoamingStateProperty, PROPERTY_INDEX_ROAMING_STATE },
{ kSaveCredentialsProperty, PROPERTY_INDEX_SAVE_CREDENTIALS },
{ kScanningProperty, PROPERTY_INDEX_SCANNING },
{ kSecurityProperty, PROPERTY_INDEX_SECURITY },
{ kSelectedNetworkProperty, PROPERTY_INDEX_SELECTED_NETWORK },
{ kServiceWatchListProperty, PROPERTY_INDEX_SERVICE_WATCH_LIST },
{ kServicesProperty, PROPERTY_INDEX_SERVICES },
{ kSignalStrengthProperty, PROPERTY_INDEX_SIGNAL_STRENGTH },
{ kSIMLockStatusProperty, PROPERTY_INDEX_SIM_LOCK },
{ kStateProperty, PROPERTY_INDEX_STATE },
{ kTypeProperty, PROPERTY_INDEX_TYPE },
{ kUsageURLProperty, PROPERTY_INDEX_USAGE_URL },
};
StringToEnum<PropertyIndex>& property_index_parser() {
static StringToEnum<PropertyIndex> parser(property_index_table,
arraysize(property_index_table),
PROPERTY_INDEX_UNKNOWN);
return parser;
}
////////////////////////////////////////////////////////////////////////////
// Parse strings from libcros.
// Network.
static ConnectionType ParseType(const std::string& type) {
static StringToEnum<ConnectionType>::Pair table[] = {
{ kTypeEthernet, TYPE_ETHERNET },
{ kTypeWifi, TYPE_WIFI },
{ kTypeWimax, TYPE_WIMAX },
{ kTypeBluetooth, TYPE_BLUETOOTH },
{ kTypeCellular, TYPE_CELLULAR },
{ kTypeVPN, TYPE_VPN },
};
static StringToEnum<ConnectionType> parser(
table, arraysize(table), TYPE_UNKNOWN);
return parser.Get(type);
}
ConnectionType ParseTypeFromDictionary(const DictionaryValue* info) {
std::string type_string;
info->GetString(kTypeProperty, &type_string);
return ParseType(type_string);
}
static ConnectionMode ParseMode(const std::string& mode) {
static StringToEnum<ConnectionMode>::Pair table[] = {
{ kModeManaged, MODE_MANAGED },
{ kModeAdhoc, MODE_ADHOC },
};
static StringToEnum<ConnectionMode> parser(
table, arraysize(table), MODE_UNKNOWN);
return parser.Get(mode);
}
static ConnectionState ParseState(const std::string& state) {
static StringToEnum<ConnectionState>::Pair table[] = {
{ kStateIdle, STATE_IDLE },
{ kStateCarrier, STATE_CARRIER },
{ kStateAssociation, STATE_ASSOCIATION },
{ kStateConfiguration, STATE_CONFIGURATION },
{ kStateReady, STATE_READY },
{ kStateDisconnect, STATE_DISCONNECT },
{ kStateFailure, STATE_FAILURE },
{ kStateActivationFailure, STATE_ACTIVATION_FAILURE },
};
static StringToEnum<ConnectionState> parser(
table, arraysize(table), STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectionError ParseError(const std::string& error) {
static StringToEnum<ConnectionError>::Pair table[] = {
{ kErrorOutOfRange, ERROR_OUT_OF_RANGE },
{ kErrorPinMissing, ERROR_PIN_MISSING },
{ kErrorDhcpFailed, ERROR_DHCP_FAILED },
{ kErrorConnectFailed, ERROR_CONNECT_FAILED },
{ kErrorBadPassphrase, ERROR_BAD_PASSPHRASE },
{ kErrorBadWEPKey, ERROR_BAD_WEPKEY },
{ kErrorActivationFailed, ERROR_ACTIVATION_FAILED },
{ kErrorNeedEvdo, ERROR_NEED_EVDO },
{ kErrorNeedHomeNetwork, ERROR_NEED_HOME_NETWORK },
{ kErrorOtaspFailed, ERROR_OTASP_FAILED },
{ kErrorAaaFailed, ERROR_AAA_FAILED },
};
static StringToEnum<ConnectionError> parser(
table, arraysize(table), ERROR_UNKNOWN);
return parser.Get(error);
}
// VirtualNetwork
static VirtualNetwork::ProviderType ParseProviderType(const std::string& mode) {
static StringToEnum<VirtualNetwork::ProviderType>::Pair table[] = {
{ kProviderL2tpIpsec, VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK },
{ kProviderOpenVpn, VirtualNetwork::PROVIDER_TYPE_OPEN_VPN },
};
static StringToEnum<VirtualNetwork::ProviderType> parser(
table, arraysize(table), VirtualNetwork::PROVIDER_TYPE_MAX);
return parser.Get(mode);
}
// CellularNetwork.
static ActivationState ParseActivationState(const std::string& state) {
static StringToEnum<ActivationState>::Pair table[] = {
{ kActivationStateActivated, ACTIVATION_STATE_ACTIVATED },
{ kActivationStateActivating, ACTIVATION_STATE_ACTIVATING },
{ kActivationStateNotActivated, ACTIVATION_STATE_NOT_ACTIVATED },
{ kActivationStatePartiallyActivated, ACTIVATION_STATE_PARTIALLY_ACTIVATED},
{ kActivationStateUnknown, ACTIVATION_STATE_UNKNOWN},
};
static StringToEnum<ActivationState> parser(
table, arraysize(table), ACTIVATION_STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectivityState ParseConnectivityState(const std::string& state) {
static StringToEnum<ConnectivityState>::Pair table[] = {
{ kConnStateUnrestricted, CONN_STATE_UNRESTRICTED },
{ kConnStateRestricted, CONN_STATE_RESTRICTED },
{ kConnStateNone, CONN_STATE_NONE },
};
static StringToEnum<ConnectivityState> parser(
table, arraysize(table), CONN_STATE_UNKNOWN);
return parser.Get(state);
}
static NetworkTechnology ParseNetworkTechnology(const std::string& technology) {
static StringToEnum<NetworkTechnology>::Pair table[] = {
{ kNetworkTechnology1Xrtt, NETWORK_TECHNOLOGY_1XRTT },
{ kNetworkTechnologyEvdo, NETWORK_TECHNOLOGY_EVDO },
{ kNetworkTechnologyGprs, NETWORK_TECHNOLOGY_GPRS },
{ kNetworkTechnologyEdge, NETWORK_TECHNOLOGY_EDGE },
{ kNetworkTechnologyUmts, NETWORK_TECHNOLOGY_UMTS },
{ kNetworkTechnologyHspa, NETWORK_TECHNOLOGY_HSPA },
{ kNetworkTechnologyHspaPlus, NETWORK_TECHNOLOGY_HSPA_PLUS },
{ kNetworkTechnologyLte, NETWORK_TECHNOLOGY_LTE },
{ kNetworkTechnologyLteAdvanced, NETWORK_TECHNOLOGY_LTE_ADVANCED },
};
static StringToEnum<NetworkTechnology> parser(
table, arraysize(table), NETWORK_TECHNOLOGY_UNKNOWN);
return parser.Get(technology);
}
static SIMLockState ParseSimLockState(const std::string& state) {
static StringToEnum<SIMLockState>::Pair table[] = {
{ "", SIM_UNLOCKED },
{ kSIMLockPin, SIM_LOCKED_PIN },
{ kSIMLockPuk, SIM_LOCKED_PUK },
};
static StringToEnum<SIMLockState> parser(
table, arraysize(table), SIM_UNKNOWN);
SIMLockState parsed_state = parser.Get(state);
DCHECK(parsed_state != SIM_UNKNOWN) << "Unknown SIMLock state encountered";
return parsed_state;
}
static bool ParseSimLockStateFromDictionary(const DictionaryValue* info,
SIMLockState* out_state,
int* out_retries) {
std::string state_string;
if (!info->GetString(kSIMLockTypeProperty, &state_string) ||
!info->GetInteger(kSIMLockRetriesLeftProperty, out_retries)) {
LOG(ERROR) << "Error parsing SIMLock state";
return false;
}
*out_state = ParseSimLockState(state_string);
return true;
}
static bool ParseFoundNetworksFromList(const ListValue* list,
CellularNetworkList* found_networks_) {
found_networks_->clear();
found_networks_->reserve(list->GetSize());
for (ListValue::const_iterator it = list->begin(); it != list->end(); ++it) {
if ((*it)->IsType(Value::TYPE_DICTIONARY)) {
found_networks_->resize(found_networks_->size() + 1);
DictionaryValue* dict = static_cast<const DictionaryValue*>(*it);
dict->GetStringWithoutPathExpansion(
kStatusProperty, &found_networks_->back().status);
dict->GetStringWithoutPathExpansion(
kNetworkIdProperty, &found_networks_->back().network_id);
dict->GetStringWithoutPathExpansion(
kShortNameProperty, &found_networks_->back().short_name);
dict->GetStringWithoutPathExpansion(
kLongNameProperty, &found_networks_->back().long_name);
dict->GetStringWithoutPathExpansion(
kTechnologyProperty, &found_networks_->back().technology);
} else {
return false;
}
}
return true;
}
static NetworkRoamingState ParseRoamingState(const std::string& roaming_state) {
static StringToEnum<NetworkRoamingState>::Pair table[] = {
{ kRoamingStateHome, ROAMING_STATE_HOME },
{ kRoamingStateRoaming, ROAMING_STATE_ROAMING },
{ kRoamingStateUnknown, ROAMING_STATE_UNKNOWN },
};
static StringToEnum<NetworkRoamingState> parser(
table, arraysize(table), ROAMING_STATE_UNKNOWN);
return parser.Get(roaming_state);
}
// WifiNetwork
static ConnectionSecurity ParseSecurity(const std::string& security) {
static StringToEnum<ConnectionSecurity>::Pair table[] = {
{ kSecurityNone, SECURITY_NONE },
{ kSecurityWep, SECURITY_WEP },
{ kSecurityWpa, SECURITY_WPA },
{ kSecurityRsn, SECURITY_RSN },
{ kSecurityPsk, SECURITY_PSK },
{ kSecurity8021x, SECURITY_8021X },
};
static StringToEnum<ConnectionSecurity> parser(
table, arraysize(table), SECURITY_UNKNOWN);
return parser.Get(security);
}
static EAPMethod ParseEAPMethod(const std::string& method) {
static StringToEnum<EAPMethod>::Pair table[] = {
{ kEapMethodPEAP.c_str(), EAP_METHOD_PEAP },
{ kEapMethodTLS.c_str(), EAP_METHOD_TLS },
{ kEapMethodTTLS.c_str(), EAP_METHOD_TTLS },
{ kEapMethodLEAP.c_str(), EAP_METHOD_LEAP },
};
static StringToEnum<EAPMethod> parser(
table, arraysize(table), EAP_METHOD_UNKNOWN);
return parser.Get(method);
}
static EAPPhase2Auth ParseEAPPhase2Auth(const std::string& auth) {
static StringToEnum<EAPPhase2Auth>::Pair table[] = {
{ kEapPhase2AuthPEAPMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthPEAPMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthTTLSMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMSCHAP.c_str(), EAP_PHASE_2_AUTH_MSCHAP },
{ kEapPhase2AuthTTLSPAP.c_str(), EAP_PHASE_2_AUTH_PAP },
{ kEapPhase2AuthTTLSCHAP.c_str(), EAP_PHASE_2_AUTH_CHAP },
};
static StringToEnum<EAPPhase2Auth> parser(
table, arraysize(table), EAP_PHASE_2_AUTH_AUTO);
return parser.Get(auth);
}
////////////////////////////////////////////////////////////////////////////////
// Misc.
// Safe string constructor since we can't rely on non NULL pointers
// for string values from libcros.
static std::string SafeString(const char* s) {
return s ? std::string(s) : std::string();
}
// Erase the memory used by a string, then clear it.
static void WipeString(std::string* str) {
str->assign(str->size(), '\0');
str->clear();
}
static bool EnsureCrosLoaded() {
if (!CrosLibrary::Get()->EnsureLoaded()) {
return false;
} else {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "chromeos_library calls made from non UI thread!";
NOTREACHED();
}
return true;
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// NetworkDevice
NetworkDevice::NetworkDevice(const std::string& device_path)
: device_path_(device_path),
type_(TYPE_UNKNOWN),
scanning_(false),
sim_lock_state_(SIM_UNKNOWN),
sim_retries_left_(kDefaultSimUnlockRetriesCount),
sim_pin_required_(SIM_PIN_REQUIRE_UNKNOWN),
PRL_version_(0),
data_roaming_allowed_(false) {
}
bool NetworkDevice::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
type_ = ParseType(type_string);
return true;
}
break;
}
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_SCANNING:
return value->GetAsBoolean(&scanning_);
case PROPERTY_INDEX_CARRIER:
return value->GetAsString(&carrier_);
case PROPERTY_INDEX_FOUND_NETWORKS:
if (value->IsType(Value::TYPE_LIST)) {
return ParseFoundNetworksFromList(
static_cast<const ListValue*>(value),
&found_cellular_networks_);
}
break;
case PROPERTY_INDEX_HOME_PROVIDER:
return value->GetAsString(&home_provider_);
case PROPERTY_INDEX_MEID:
return value->GetAsString(&MEID_);
case PROPERTY_INDEX_IMEI:
return value->GetAsString(&IMEI_);
case PROPERTY_INDEX_IMSI:
return value->GetAsString(&IMSI_);
case PROPERTY_INDEX_ESN:
return value->GetAsString(&ESN_);
case PROPERTY_INDEX_MDN:
return value->GetAsString(&MDN_);
case PROPERTY_INDEX_MIN:
return value->GetAsString(&MIN_);
case PROPERTY_INDEX_MODEL_ID:
return value->GetAsString(&model_id_);
case PROPERTY_INDEX_MANUFACTURER:
return value->GetAsString(&manufacturer_);
case PROPERTY_INDEX_SIM_LOCK:
if (value->IsType(Value::TYPE_DICTIONARY)) {
bool result = ParseSimLockStateFromDictionary(
static_cast<const DictionaryValue*>(value),
&sim_lock_state_,
&sim_retries_left_);
// Initialize PinRequired value only once.
// See SIMPinRequire enum comments.
if (sim_pin_required_ == SIM_PIN_REQUIRE_UNKNOWN) {
if (sim_lock_state_ == SIM_UNLOCKED) {
sim_pin_required_ = SIM_PIN_NOT_REQUIRED;
} else if (sim_lock_state_ == SIM_LOCKED_PIN ||
sim_lock_state_ == SIM_LOCKED_PUK) {
sim_pin_required_ = SIM_PIN_REQUIRED;
}
}
return result;
}
break;
case PROPERTY_INDEX_FIRMWARE_REVISION:
return value->GetAsString(&firmware_revision_);
case PROPERTY_INDEX_HARDWARE_REVISION:
return value->GetAsString(&hardware_revision_);
case PROPERTY_INDEX_LAST_DEVICE_UPDATE:
return value->GetAsString(&last_update_);
case PROPERTY_INDEX_PRL_VERSION:
return value->GetAsInteger(&PRL_version_);
case PROPERTY_INDEX_SELECTED_NETWORK:
return value->GetAsString(&selected_cellular_network_);
case PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING:
return value->GetAsBoolean(&data_roaming_allowed_);
default:
break;
}
return false;
}
void NetworkDevice::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseValue(index, value))
VLOG(1) << "NetworkDevice: Unhandled key: " << key;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Network
void Network::SetState(ConnectionState new_state) {
if (new_state == state_)
return;
state_ = new_state;
if (new_state == STATE_FAILURE) {
// The user needs to be notified of this failure.
notify_failure_ = true;
} else {
// State changed, so refresh IP address.
// Note: blocking DBus call. TODO(stevenjb): refactor this.
InitIPAddress();
}
VLOG(1) << " " << name() << ".State = " << GetStateString();
}
bool Network::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
ConnectionType type = ParseType(type_string);
LOG_IF(ERROR, type != type_)
<< "Network with mismatched type: " << service_path_
<< " " << type << " != " << type_;
return true;
}
break;
}
case PROPERTY_INDEX_DEVICE:
return value->GetAsString(&device_path_);
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_STATE: {
std::string state_string;
if (value->GetAsString(&state_string)) {
SetState(ParseState(state_string));
return true;
}
break;
}
case PROPERTY_INDEX_MODE: {
std::string mode_string;
if (value->GetAsString(&mode_string)) {
mode_ = ParseMode(mode_string);
return true;
}
break;
}
case PROPERTY_INDEX_ERROR: {
std::string error_string;
if (value->GetAsString(&error_string)) {
error_ = ParseError(error_string);
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTABLE:
return value->GetAsBoolean(&connectable_);
case PROPERTY_INDEX_IS_ACTIVE:
return value->GetAsBoolean(&is_active_);
case PROPERTY_INDEX_FAVORITE:
return value->GetAsBoolean(&favorite_);
case PROPERTY_INDEX_AUTO_CONNECT:
return value->GetAsBoolean(&auto_connect_);
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
std::string connectivity_state_string;
if (value->GetAsString(&connectivity_state_string)) {
connectivity_state_ = ParseConnectivityState(connectivity_state_string);
return true;
}
break;
}
default:
break;
}
return false;
}
void Network::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseValue(index, value)) // virtual.
VLOG(1) << "Network: " << name()
<< " Type: " << ConnectionTypeToString(type())
<< " Unhandled key: " << key;
}
}
}
void Network::SetValueProperty(const char* prop, Value* val) {
DCHECK(prop);
DCHECK(val);
if (!EnsureCrosLoaded())
return;
SetNetworkServiceProperty(service_path_.c_str(), prop, val);
}
void Network::ClearProperty(const char* prop) {
DCHECK(prop);
if (!EnsureCrosLoaded())
return;
ClearNetworkServiceProperty(service_path_.c_str(), prop);
}
void Network::SetStringProperty(
const char* prop, const std::string& str, std::string* dest) {
if (dest)
*dest = str;
scoped_ptr<Value> value(Value::CreateStringValue(str));
SetValueProperty(prop, value.get());
}
void Network::SetOrClearStringProperty(const char* prop,
const std::string& str,
std::string* dest) {
if (str.empty()) {
ClearProperty(prop);
if (dest)
dest->clear();
} else {
SetStringProperty(prop, str, dest);
}
}
void Network::SetBooleanProperty(const char* prop, bool b, bool* dest) {
if (dest)
*dest = b;
scoped_ptr<Value> value(Value::CreateBooleanValue(b));
SetValueProperty(prop, value.get());
}
void Network::SetIntegerProperty(const char* prop, int i, int* dest) {
if (dest)
*dest = i;
scoped_ptr<Value> value(Value::CreateIntegerValue(i));
SetValueProperty(prop, value.get());
}
void Network::SetAutoConnect(bool auto_connect) {
SetBooleanProperty(kAutoConnectProperty, auto_connect, &auto_connect_);
}
std::string Network::GetStateString() const {
switch (state_) {
case STATE_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN);
case STATE_IDLE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE);
case STATE_CARRIER:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER);
case STATE_ASSOCIATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION);
case STATE_CONFIGURATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION);
case STATE_READY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY);
case STATE_DISCONNECT:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT);
case STATE_FAILURE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE);
case STATE_ACTIVATION_FAILURE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE);
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
std::string Network::GetErrorString() const {
switch (error_) {
case ERROR_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
case ERROR_OUT_OF_RANGE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE);
case ERROR_PIN_MISSING:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING);
case ERROR_DHCP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED);
case ERROR_CONNECT_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED);
case ERROR_BAD_PASSPHRASE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE);
case ERROR_BAD_WEPKEY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY);
case ERROR_ACTIVATION_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED);
case ERROR_NEED_EVDO:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO);
case ERROR_NEED_HOME_NETWORK:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK);
case ERROR_OTASP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED);
case ERROR_AAA_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED);
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
void Network::InitIPAddress() {
ip_address_.clear();
// If connected, get ip config.
if (EnsureCrosLoaded() && connected() && !device_path_.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path_.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0) {
ip_address_ = ipconfig.address;
break;
}
}
FreeIPConfigStatus(ipconfig_status);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// VirtualNetwork
bool VirtualNetwork::ParseProviderValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_HOST:
return value->GetAsString(&server_hostname_);
case PROPERTY_INDEX_NAME:
// Note: shadows Network::name_ property.
return value->GetAsString(&name_);
case PROPERTY_INDEX_TYPE: {
std::string provider_type_string;
if (value->GetAsString(&provider_type_string)) {
provider_type_ = ParseProviderType(provider_type_string);
return true;
}
break;
}
default:
break;
}
return false;
}
bool VirtualNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_PROVIDER: {
DCHECK_EQ(value->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(value);
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* v;
bool res = dict->GetWithoutPathExpansion(key, &v);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseProviderValue(index, v))
VLOG(1) << name() << ": Provider unhandled key: " << key
<< " Type: " << v->GetType();
}
}
return true;
}
case PROPERTY_INDEX_L2TPIPSEC_CA_CERT:
return value->GetAsString(&ca_cert_);
case PROPERTY_INDEX_L2TPIPSEC_PSK:
return value->GetAsString(&psk_passphrase_);
case PROPERTY_INDEX_L2TPIPSEC_CERT:
return value->GetAsString(&user_cert_);
case PROPERTY_INDEX_L2TPIPSEC_KEY:
return value->GetAsString(&user_cert_key_);
case PROPERTY_INDEX_L2TPIPSEC_USER:
return value->GetAsString(&username_);
case PROPERTY_INDEX_L2TPIPSEC_PASSWORD:
return value->GetAsString(&user_passphrase_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
void VirtualNetwork::ParseInfo(const DictionaryValue* info) {
Network::ParseInfo(info);
VLOG(1) << "VPN: " << name()
<< " Type: " << ProviderTypeToString(provider_type());
if (provider_type_ == PROVIDER_TYPE_L2TP_IPSEC_PSK) {
if (!user_cert_.empty())
provider_type_ = PROVIDER_TYPE_L2TP_IPSEC_USER_CERT;
}
}
bool VirtualNetwork::NeedMoreInfoToConnect() const {
if (server_hostname_.empty() || username_.empty() || user_passphrase_.empty())
return true;
switch (provider_type_) {
case PROVIDER_TYPE_L2TP_IPSEC_PSK:
if (psk_passphrase_.empty())
return true;
break;
case PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
case PROVIDER_TYPE_OPEN_VPN:
if (user_cert_.empty())
return true;
break;
case PROVIDER_TYPE_MAX:
break;
}
return false;
}
void VirtualNetwork::SetCACert(const std::string& ca_cert) {
SetStringProperty(kL2TPIPSecCACertProperty, ca_cert, &ca_cert_);
}
void VirtualNetwork::SetPSKPassphrase(const std::string& psk_passphrase) {
SetStringProperty(kL2TPIPSecPSKProperty, psk_passphrase,
&psk_passphrase_);
}
void VirtualNetwork::SetUserCert(const std::string& user_cert) {
SetStringProperty(kL2TPIPSecCertProperty, user_cert, &user_cert_);
}
void VirtualNetwork::SetUserCertKey(const std::string& key) {
SetStringProperty(kL2TPIPSecKeyProperty, key, &user_cert_key_);
}
void VirtualNetwork::SetUsername(const std::string& username) {
SetStringProperty(kL2TPIPSecUserProperty, username, &username_);
}
void VirtualNetwork::SetUserPassphrase(const std::string& user_passphrase) {
SetStringProperty(kL2TPIPSecPasswordProperty, user_passphrase,
&user_passphrase_);
}
std::string VirtualNetwork::GetProviderTypeString() const {
switch (this->provider_type_) {
case PROVIDER_TYPE_L2TP_IPSEC_PSK:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_PSK);
break;
case PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_USER_CERT);
break;
case PROVIDER_TYPE_OPEN_VPN:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_OPEN_VPN);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WirelessNetwork
bool WirelessNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SIGNAL_STRENGTH:
return value->GetAsInteger(&strength_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// CellularDataPlan
string16 CellularDataPlan::GetPlanDesciption() const {
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_UNLIMITED_DATA,
base::TimeFormatFriendlyDate(plan_start_time));
break;
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_RECEIVED_FREE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
default:
break;
}
}
return string16();
}
string16 CellularDataPlan::GetRemainingWarning() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
if (remaining_time().InSeconds() <= chromeos::kCellularDataVeryLowSecs) {
return GetPlanExpiration();
}
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
if (remaining_data() <= chromeos::kCellularDataVeryLowBytes) {
int64 remaining_mbytes = remaining_data() / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
}
return string16();
}
string16 CellularDataPlan::GetDataRemainingDesciption() const {
int64 remaining_bytes = remaining_data();
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_UNLIMITED);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
default:
break;
}
return string16();
}
string16 CellularDataPlan::GetUsageInfo() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
return GetPlanExpiration();
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
int64 remaining_bytes = remaining_data();
if (remaining_bytes == 0) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_NONE_AVAILABLE_MESSAGE);
} else if (remaining_bytes < 1024 * 1024) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_LESS_THAN_ONE_MB_AVAILABLE_MESSAGE);
} else {
int64 remaining_mb = remaining_bytes / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_MB_AVAILABLE_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mb)));
}
}
return string16();
}
std::string CellularDataPlan::GetUniqueIdentifier() const {
// A cellular plan is uniquely described by the union of name, type,
// start time, end time, and max bytes.
// So we just return a union of all these variables.
return plan_name + "|" +
base::Int64ToString(plan_type) + "|" +
base::Int64ToString(plan_start_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_end_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_data_bytes);
}
base::TimeDelta CellularDataPlan::remaining_time() const {
base::TimeDelta time = plan_end_time - base::Time::Now();
return time.InMicroseconds() < 0 ? base::TimeDelta() : time;
}
int64 CellularDataPlan::remaining_minutes() const {
return remaining_time().InMinutes();
}
int64 CellularDataPlan::remaining_data() const {
int64 data = plan_data_bytes - data_bytes_used;
return data < 0 ? 0 : data;
}
string16 CellularDataPlan::GetPlanExpiration() const {
return TimeFormat::TimeRemaining(remaining_time());
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork::Apn
void CellularNetwork::Apn::Set(const DictionaryValue& dict) {
if (!dict.GetStringWithoutPathExpansion(kApnProperty, &apn))
apn.clear();
if (!dict.GetStringWithoutPathExpansion(kNetworkIdProperty, &network_id))
network_id.clear();
if (!dict.GetStringWithoutPathExpansion(kUsernameProperty, &username))
username.clear();
if (!dict.GetStringWithoutPathExpansion(kPasswordProperty, &password))
password.clear();
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork
CellularNetwork::~CellularNetwork() {
}
bool CellularNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_ACTIVATION_STATE: {
std::string activation_state_string;
if (value->GetAsString(&activation_state_string)) {
ActivationState prev_state = activation_state_;
activation_state_ = ParseActivationState(activation_state_string);
if (activation_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CELLULAR_APN: {
if (value->IsType(Value::TYPE_DICTIONARY)) {
apn_.Set(*static_cast<const DictionaryValue*>(value));
return true;
}
break;
}
case PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN: {
if (value->IsType(Value::TYPE_DICTIONARY)) {
last_good_apn_.Set(*static_cast<const DictionaryValue*>(value));
return true;
}
break;
}
case PROPERTY_INDEX_NETWORK_TECHNOLOGY: {
std::string network_technology_string;
if (value->GetAsString(&network_technology_string)) {
network_technology_ = ParseNetworkTechnology(network_technology_string);
return true;
}
break;
}
case PROPERTY_INDEX_ROAMING_STATE: {
std::string roaming_state_string;
if (value->GetAsString(&roaming_state_string)) {
roaming_state_ = ParseRoamingState(roaming_state_string);
return true;
}
break;
}
case PROPERTY_INDEX_OPERATOR_NAME:
return value->GetAsString(&operator_name_);
case PROPERTY_INDEX_OPERATOR_CODE:
return value->GetAsString(&operator_code_);
case PROPERTY_INDEX_PAYMENT_URL:
return value->GetAsString(&payment_url_);
case PROPERTY_INDEX_USAGE_URL:
return value->GetAsString(&usage_url_);
case PROPERTY_INDEX_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectionState prev_state = state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectivityState prev_state = connectivity_state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (connectivity_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
bool CellularNetwork::StartActivation() const {
if (!EnsureCrosLoaded())
return false;
return ActivateCellularModem(service_path().c_str(), NULL);
}
void CellularNetwork::RefreshDataPlansIfNeeded() const {
if (!EnsureCrosLoaded())
return;
if (connected() && activated())
RequestCellularDataPlanUpdate(service_path().c_str());
}
void CellularNetwork::SetApn(const Apn& apn) {
if (!EnsureCrosLoaded())
return;
if (!apn.apn.empty()) {
DictionaryValue value;
value.SetString(kApnProperty, apn.apn);
value.SetString(kNetworkIdProperty, apn.network_id);
value.SetString(kUsernameProperty, apn.username);
value.SetString(kPasswordProperty, apn.password);
SetValueProperty(kCellularApnProperty, &value);
} else {
ClearProperty(kCellularApnProperty);
}
}
std::string CellularNetwork::GetNetworkTechnologyString() const {
// No need to localize these cellular technology abbreviations.
switch (network_technology_) {
case NETWORK_TECHNOLOGY_1XRTT:
return "1xRTT";
break;
case NETWORK_TECHNOLOGY_EVDO:
return "EVDO";
break;
case NETWORK_TECHNOLOGY_GPRS:
return "GPRS";
break;
case NETWORK_TECHNOLOGY_EDGE:
return "EDGE";
break;
case NETWORK_TECHNOLOGY_UMTS:
return "UMTS";
break;
case NETWORK_TECHNOLOGY_HSPA:
return "HSPA";
break;
case NETWORK_TECHNOLOGY_HSPA_PLUS:
return "HSPA Plus";
break;
case NETWORK_TECHNOLOGY_LTE:
return "LTE";
break;
case NETWORK_TECHNOLOGY_LTE_ADVANCED:
return "LTE Advanced";
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_CELLULAR_TECHNOLOGY_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetConnectivityStateString() const {
// These strings do not appear in the UI, so no need to localize them
switch (connectivity_state_) {
case CONN_STATE_UNRESTRICTED:
return "unrestricted";
break;
case CONN_STATE_RESTRICTED:
return "restricted";
break;
case CONN_STATE_NONE:
return "none";
break;
case CONN_STATE_UNKNOWN:
default:
return "unknown";
}
}
std::string CellularNetwork::ActivationStateToString(
ActivationState activation_state) {
switch (activation_state) {
case ACTIVATION_STATE_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED);
break;
case ACTIVATION_STATE_ACTIVATING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING);
break;
case ACTIVATION_STATE_NOT_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED);
break;
case ACTIVATION_STATE_PARTIALLY_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetActivationStateString() const {
return ActivationStateToString(this->activation_state_);
}
std::string CellularNetwork::GetRoamingStateString() const {
switch (this->roaming_state_) {
case ROAMING_STATE_HOME:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME);
break;
case ROAMING_STATE_ROAMING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WifiNetwork
// Called from ParseNetwork after calling ParseInfo.
void WifiNetwork::CalculateUniqueId() {
ConnectionSecurity encryption = encryption_;
// Flimflam treats wpa and rsn as psk internally, so convert those types
// to psk for unique naming.
if (encryption == SECURITY_WPA || encryption == SECURITY_RSN)
encryption = SECURITY_PSK;
std::string security = std::string(SecurityToString(encryption));
unique_id_ = security + "|" + name_;
}
bool WifiNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SECURITY: {
std::string security_string;
if (value->GetAsString(&security_string)) {
encryption_ = ParseSecurity(security_string);
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE: {
std::string passphrase;
if (value->GetAsString(&passphrase)) {
// Only store the passphrase if we are the owner.
// TODO(stevenjb): Remove this when chromium-os:12948 is resolved.
if (chromeos::UserManager::Get()->current_user_is_owner())
passphrase_ = passphrase;
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE_REQUIRED:
return value->GetAsBoolean(&passphrase_required_);
case PROPERTY_INDEX_SAVE_CREDENTIALS:
return value->GetAsBoolean(&save_credentials_);
case PROPERTY_INDEX_IDENTITY:
return value->GetAsString(&identity_);
case PROPERTY_INDEX_CERT_PATH:
return value->GetAsString(&cert_path_);
case PROPERTY_INDEX_EAP_IDENTITY:
return value->GetAsString(&eap_identity_);
case PROPERTY_INDEX_EAP_METHOD: {
std::string method;
if (value->GetAsString(&method)) {
eap_method_ = ParseEAPMethod(method);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_PHASE_2_AUTH: {
std::string auth;
if (value->GetAsString(&auth)) {
eap_phase_2_auth_ = ParseEAPPhase2Auth(auth);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY:
return value->GetAsString(&eap_anonymous_identity_);
case PROPERTY_INDEX_EAP_CERT_ID:
return value->GetAsString(&eap_client_cert_pkcs11_id_);
case PROPERTY_INDEX_EAP_CA_CERT_NSS:
return value->GetAsString(&eap_server_ca_cert_nss_nickname_);
case PROPERTY_INDEX_EAP_USE_SYSTEM_CAS:
return value->GetAsBoolean(&eap_use_system_cas_);
case PROPERTY_INDEX_EAP_PASSWORD:
return value->GetAsString(&eap_passphrase_);
case PROPERTY_INDEX_EAP_CLIENT_CERT:
case PROPERTY_INDEX_EAP_CLIENT_CERT_NSS:
case PROPERTY_INDEX_EAP_PRIVATE_KEY:
case PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD:
case PROPERTY_INDEX_EAP_KEY_ID:
case PROPERTY_INDEX_EAP_CA_CERT:
case PROPERTY_INDEX_EAP_CA_CERT_ID:
case PROPERTY_INDEX_EAP_PIN:
case PROPERTY_INDEX_EAP_KEY_MGMT:
// These properties are currently not used in the UI.
return true;
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
void WifiNetwork::ParseInfo(const DictionaryValue* info) {
Network::ParseInfo(info);
CalculateUniqueId();
}
const std::string& WifiNetwork::GetPassphrase() const {
if (!user_passphrase_.empty())
return user_passphrase_;
return passphrase_;
}
void WifiNetwork::SetPassphrase(const std::string& passphrase) {
// Set the user_passphrase_ only; passphrase_ stores the flimflam value.
// If the user sets an empty passphrase, restore it to the passphrase
// remembered by flimflam.
if (!passphrase.empty()) {
user_passphrase_ = passphrase;
passphrase_ = passphrase;
} else {
user_passphrase_ = passphrase_;
}
// Send the change to flimflam. If the format is valid, it will propagate to
// passphrase_ with a service update.
SetOrClearStringProperty(kPassphraseProperty, passphrase, NULL);
}
void WifiNetwork::SetSaveCredentials(bool save_credentials) {
SetBooleanProperty(kSaveCredentialsProperty, save_credentials,
&save_credentials_);
}
// See src/third_party/flimflam/doc/service-api.txt for properties that
// flimflam will forget when SaveCredentials is false.
void WifiNetwork::EraseCredentials() {
WipeString(&passphrase_);
WipeString(&user_passphrase_);
WipeString(&eap_client_cert_pkcs11_id_);
WipeString(&eap_identity_);
WipeString(&eap_anonymous_identity_);
WipeString(&eap_passphrase_);
}
void WifiNetwork::SetIdentity(const std::string& identity) {
SetStringProperty(kIdentityProperty, identity, &identity_);
}
void WifiNetwork::SetCertPath(const std::string& cert_path) {
SetStringProperty(kCertPathProperty, cert_path, &cert_path_);
}
void WifiNetwork::SetEAPMethod(EAPMethod method) {
eap_method_ = method;
switch (method) {
case EAP_METHOD_PEAP:
SetStringProperty(kEapMethodProperty, kEapMethodPEAP, NULL);
break;
case EAP_METHOD_TLS:
SetStringProperty(kEapMethodProperty, kEapMethodTLS, NULL);
break;
case EAP_METHOD_TTLS:
SetStringProperty(kEapMethodProperty, kEapMethodTTLS, NULL);
break;
case EAP_METHOD_LEAP:
SetStringProperty(kEapMethodProperty, kEapMethodLEAP, NULL);
break;
default:
ClearProperty(kEapMethodProperty);
break;
}
}
void WifiNetwork::SetEAPPhase2Auth(EAPPhase2Auth auth) {
eap_phase_2_auth_ = auth;
bool is_peap = (eap_method_ == EAP_METHOD_PEAP);
switch (auth) {
case EAP_PHASE_2_AUTH_AUTO:
ClearProperty(kEapPhase2AuthProperty);
break;
case EAP_PHASE_2_AUTH_MD5:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMD5
: kEapPhase2AuthTTLSMD5,
NULL);
break;
case EAP_PHASE_2_AUTH_MSCHAPV2:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMSCHAPV2
: kEapPhase2AuthTTLSMSCHAPV2,
NULL);
break;
case EAP_PHASE_2_AUTH_MSCHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSMSCHAP, NULL);
break;
case EAP_PHASE_2_AUTH_PAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSPAP, NULL);
break;
case EAP_PHASE_2_AUTH_CHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSCHAP, NULL);
break;
}
}
void WifiNetwork::SetEAPServerCaCertNssNickname(
const std::string& nss_nickname) {
VLOG(1) << "SetEAPServerCaCertNssNickname " << nss_nickname;
SetOrClearStringProperty(kEapCaCertNssProperty, nss_nickname,
&eap_server_ca_cert_nss_nickname_);
}
void WifiNetwork::SetEAPClientCertPkcs11Id(const std::string& pkcs11_id) {
VLOG(1) << "SetEAPClientCertPkcs11Id " << pkcs11_id;
SetOrClearStringProperty(kEapCertIDProperty, pkcs11_id,
&eap_client_cert_pkcs11_id_);
}
void WifiNetwork::SetEAPUseSystemCAs(bool use_system_cas) {
SetBooleanProperty(kEapUseSystemCAsProperty, use_system_cas,
&eap_use_system_cas_);
}
void WifiNetwork::SetEAPIdentity(const std::string& identity) {
SetOrClearStringProperty(kEapIdentityProperty, identity, &eap_identity_);
}
void WifiNetwork::SetEAPAnonymousIdentity(const std::string& identity) {
SetOrClearStringProperty(kEapAnonymousIdentityProperty, identity,
&eap_anonymous_identity_);
}
void WifiNetwork::SetEAPPassphrase(const std::string& passphrase) {
SetOrClearStringProperty(kEapPasswordProperty, passphrase, &eap_passphrase_);
}
std::string WifiNetwork::GetEncryptionString() const {
switch (encryption_) {
case SECURITY_UNKNOWN:
break;
case SECURITY_NONE:
return "";
case SECURITY_WEP:
return "WEP";
case SECURITY_WPA:
return "WPA";
case SECURITY_RSN:
return "RSN";
case SECURITY_8021X:
return "8021X";
case SECURITY_PSK:
return "PSK";
}
return "Unknown";
}
bool WifiNetwork::IsPassphraseRequired() const {
// TODO(stevenjb): Remove error_ tests when fixed in flimflam
// (http://crosbug.com/10135).
if (error_ == ERROR_BAD_PASSPHRASE || error_ == ERROR_BAD_WEPKEY)
return true;
// For 802.1x networks, configuration is required if connectable is false.
if (encryption_ == SECURITY_8021X)
return !connectable_;
return passphrase_required_;
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
bool WifiNetwork::IsCertificateLoaded() const {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (cert_path_.find(settings_string) == 0) {
std::string::size_type idx = cert_path_.find(pkcs11_key);
if (idx != std::string::npos)
idx = cert_path_.find_first_not_of(kWhitespaceASCII,
idx + pkcs11_key.length());
if (idx != std::string::npos && cert_path_[idx] == '=')
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
class NetworkLibraryImpl : public NetworkLibrary {
public:
NetworkLibraryImpl()
: network_manager_monitor_(NULL),
data_plan_monitor_(NULL),
ethernet_(NULL),
active_wifi_(NULL),
active_cellular_(NULL),
active_virtual_(NULL),
available_devices_(0),
enabled_devices_(0),
connected_devices_(0),
wifi_scanning_(false),
offline_mode_(false),
is_locked_(false),
sim_operation_(SIM_OPERATION_NONE),
notify_task_(NULL) {
if (EnsureCrosLoaded()) {
Init();
network_manager_monitor_ =
MonitorNetworkManager(&NetworkManagerStatusChangedHandler,
this);
data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler,
this);
network_login_observer_.reset(new NetworkLoginObserver(this));
} else {
InitTestData();
}
}
virtual ~NetworkLibraryImpl() {
network_manager_observers_.Clear();
if (network_manager_monitor_)
DisconnectPropertyChangeMonitor(network_manager_monitor_);
data_plan_observers_.Clear();
pin_operation_observers_.Clear();
user_action_observers_.Clear();
if (data_plan_monitor_)
DisconnectDataPlanUpdateMonitor(data_plan_monitor_);
STLDeleteValues(&network_observers_);
STLDeleteValues(&network_device_observers_);
ClearNetworks(true /*delete networks*/);
ClearRememberedNetworks(true /*delete networks*/);
STLDeleteValues(&data_plan_map_);
}
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {
if (!network_manager_observers_.HasObserver(observer))
network_manager_observers_.AddObserver(observer);
}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {
network_manager_observers_.RemoveObserver(observer);
}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkObserverMap::iterator iter = network_observers_.find(service_path);
NetworkObserverList* oblist;
if (iter != network_observers_.end()) {
oblist = iter->second;
} else {
oblist = new NetworkObserverList(this, service_path);
network_observers_[service_path] = oblist;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
DCHECK(service_path.size());
NetworkObserverMap::iterator map_iter =
network_observers_.find(service_path);
if (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter);
}
}
}
virtual void AddNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkDeviceObserverMap::iterator iter =
network_device_observers_.find(device_path);
NetworkDeviceObserverList* oblist;
if (iter != network_device_observers_.end()) {
oblist = iter->second;
} else {
oblist = new NetworkDeviceObserverList(this, device_path);
network_device_observers_[device_path] = oblist;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {
DCHECK(observer);
DCHECK(device_path.size());
NetworkDeviceObserverMap::iterator map_iter =
network_device_observers_.find(device_path);
if (map_iter != network_device_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_device_observers_.erase(map_iter);
}
}
}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {
DCHECK(observer);
NetworkObserverMap::iterator map_iter = network_observers_.begin();
while (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
} else {
++map_iter;
}
}
}
virtual void Lock() {
if (is_locked_)
return;
is_locked_ = true;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual void Unlock() {
DCHECK(is_locked_);
if (!is_locked_)
return;
is_locked_ = false;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool IsLocked() {
return is_locked_;
}
virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) {
if (!data_plan_observers_.HasObserver(observer))
data_plan_observers_.AddObserver(observer);
}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {
data_plan_observers_.RemoveObserver(observer);
}
virtual void AddPinOperationObserver(PinOperationObserver* observer) {
if (!pin_operation_observers_.HasObserver(observer))
pin_operation_observers_.AddObserver(observer);
}
virtual void RemovePinOperationObserver(PinOperationObserver* observer) {
pin_operation_observers_.RemoveObserver(observer);
}
virtual void AddUserActionObserver(UserActionObserver* observer) {
if (!user_action_observers_.HasObserver(observer))
user_action_observers_.AddObserver(observer);
}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {
user_action_observers_.RemoveObserver(observer);
}
virtual const EthernetNetwork* ethernet_network() const { return ethernet_; }
virtual bool ethernet_connecting() const {
return ethernet_ ? ethernet_->connecting() : false;
}
virtual bool ethernet_connected() const {
return ethernet_ ? ethernet_->connected() : false;
}
virtual const WifiNetwork* wifi_network() const { return active_wifi_; }
virtual bool wifi_connecting() const {
return active_wifi_ ? active_wifi_->connecting() : false;
}
virtual bool wifi_connected() const {
return active_wifi_ ? active_wifi_->connected() : false;
}
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const {
return active_cellular_ ? active_cellular_->connecting() : false;
}
virtual bool cellular_connected() const {
return active_cellular_ ? active_cellular_->connected() : false;
}
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const {
return active_virtual_ ? active_virtual_->connecting() : false;
}
virtual bool virtual_network_connected() const {
return active_virtual_ ? active_virtual_->connected() : false;
}
bool Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& IPAddress() const {
// Returns IP address for the active network.
// TODO(stevenjb): Fix this for VPNs. See chromium-os:13972.
const Network* result = active_network();
if (!result)
result = connected_network(); // happens if we are connected to a VPN.
if (!result)
result = ethernet_; // Use non active ethernet addr if no active network.
if (result)
return result->ip_address();
static std::string null_address("0.0.0.0");
return null_address;
}
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return remembered_wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const {
NetworkDeviceMap::const_iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
virtual const NetworkDevice* FindCellularDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_CELLULAR)
return iter->second;
}
return NULL;
}
virtual const NetworkDevice* FindEthernetDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_ETHERNET)
return iter->second;
}
return NULL;
}
virtual const NetworkDevice* FindWifiDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_WIFI)
return iter->second;
}
return NULL;
}
virtual Network* FindNetworkByPath(const std::string& path) const {
NetworkMap::const_iterator iter = network_map_.find(path);
if (iter != network_map_.end())
return iter->second;
return NULL;
}
WirelessNetwork* FindWirelessNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network &&
(network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR))
return static_cast<WirelessNetwork*>(network);
return NULL;
}
virtual WifiNetwork* FindWifiNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_WIFI)
return static_cast<WifiNetwork*>(network);
return NULL;
}
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_CELLULAR)
return static_cast<CellularNetwork*>(network);
return NULL;
}
virtual VirtualNetwork* FindVirtualNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_VPN)
return static_cast<VirtualNetwork*>(network);
return NULL;
}
virtual Network* FindNetworkFromRemembered(
const Network* remembered) const {
NetworkMap::const_iterator found =
network_unique_id_map_.find(remembered->unique_id());
if (found != network_unique_id_map_.end())
return found->second;
return NULL;
}
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const {
CellularDataPlanMap::const_iterator iter = data_plan_map_.find(path);
if (iter != data_plan_map_.end())
return iter->second;
return NULL;
}
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const {
const CellularDataPlanVector* plans = GetDataPlans(path);
if (plans)
return GetSignificantDataPlanFromVector(plans);
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
virtual void ChangePin(const std::string& old_pin,
const std::string& new_pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling ChangePin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_CHANGE_PIN;
chromeos::RequestChangePin(cellular->device_path().c_str(),
old_pin.c_str(), new_pin.c_str(),
PinOperationCallback, this);
}
virtual void ChangeRequirePin(bool require_pin,
const std::string& pin) {
VLOG(1) << "ChangeRequirePin require_pin: " << require_pin
<< " pin: " << pin;
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling ChangeRequirePin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_CHANGE_REQUIRE_PIN;
chromeos::RequestRequirePin(cellular->device_path().c_str(),
pin.c_str(), require_pin,
PinOperationCallback, this);
}
virtual void EnterPin(const std::string& pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling EnterPin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_ENTER_PIN;
chromeos::RequestEnterPin(cellular->device_path().c_str(),
pin.c_str(),
PinOperationCallback, this);
}
virtual void UnblockPin(const std::string& puk,
const std::string& new_pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling UnblockPin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_UNBLOCK_PIN;
chromeos::RequestUnblockPin(cellular->device_path().c_str(),
puk.c_str(), new_pin.c_str(),
PinOperationCallback, this);
}
static void PinOperationCallback(void* object,
const char* path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
PinOperationError pin_error;
VLOG(1) << "PinOperationCallback, error: " << error
<< " error_msg: " << error_message;
if (error == chromeos::NETWORK_METHOD_ERROR_NONE) {
pin_error = PIN_ERROR_NONE;
VLOG(1) << "Pin operation completed successfuly";
// TODO(nkostylev): Might be cleaned up and exposed in flimflam API.
// http://crosbug.com/14253
// Since this option state is not exposed we have to update it manually.
networklib->FlipSimPinRequiredStateIfNeeded();
} else {
if (error_message &&
(strcmp(error_message, kErrorIncorrectPinMsg) == 0 ||
strcmp(error_message, kErrorPinRequiredMsg) == 0)) {
pin_error = PIN_ERROR_INCORRECT_CODE;
} else if (error_message &&
strcmp(error_message, kErrorPinBlockedMsg) == 0) {
pin_error = PIN_ERROR_BLOCKED;
} else {
pin_error = PIN_ERROR_UNKNOWN;
NOTREACHED() << "Unknown PIN error: " << error_message;
}
}
networklib->NotifyPinOperationCompleted(pin_error);
}
virtual void RequestCellularScan() {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling RequestCellularScan method w/o cellular device.";
return;
}
chromeos::ProposeScan(cellular->device_path().c_str());
}
virtual void RequestCellularRegister(const std::string& network_id) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling CellularRegister method w/o cellular device.";
return;
}
chromeos::RequestCellularRegister(cellular->device_path().c_str(),
network_id.c_str(),
CellularRegisterCallback,
this);
}
static void CellularRegisterCallback(void* object,
const char* path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
// TODO(dpolukhin): Notify observers about network registration status
// but not UI doesn't assume such notification so just ignore result.
}
virtual void SetCellularDataRoamingAllowed(bool new_value) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling SetCellularDataRoamingAllowed method "
"w/o cellular device.";
return;
}
scoped_ptr<Value> value(Value::CreateBooleanValue(new_value));
chromeos::SetNetworkDeviceProperty(cellular->device_path().c_str(),
kCellularAllowRoamingProperty,
value.get());
}
/////////////////////////////////////////////////////////////////////////////
virtual void RequestNetworkScan() {
if (EnsureCrosLoaded()) {
if (wifi_enabled()) {
wifi_scanning_ = true; // Cleared when updates are received.
chromeos::RequestNetworkScan(kTypeWifi);
RequestRememberedNetworksUpdate();
}
if (cellular_network())
cellular_network()->RefreshDataPlansIfNeeded();
}
}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
if (!EnsureCrosLoaded())
return false;
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeviceNetworkList* network_list = GetDeviceNetworkList();
if (network_list == NULL)
return false;
result->clear();
result->reserve(network_list->network_size);
const base::Time now = base::Time::Now();
for (size_t i = 0; i < network_list->network_size; ++i) {
DCHECK(network_list->networks[i].address);
DCHECK(network_list->networks[i].name);
WifiAccessPoint ap;
ap.mac_address = SafeString(network_list->networks[i].address);
ap.name = SafeString(network_list->networks[i].name);
ap.timestamp = now -
base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds);
ap.signal_strength = network_list->networks[i].strength;
ap.channel = network_list->networks[i].channel;
result->push_back(ap);
}
FreeDeviceNetworkList(network_list);
return true;
}
static void NetworkConnectCallback(void *object,
const char *path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
Network* network = networklib->FindNetworkByPath(path);
if (!network) {
LOG(ERROR) << "No network for path: " << path;
return;
}
if (error != NETWORK_METHOD_ERROR_NONE) {
LOG(WARNING) << "Error from ServiceConnect callback for: "
<< network->name()
<< " Error: " << error << " Message: " << error_message;
if (error_message &&
strcmp(error_message, kErrorPassphraseRequiredMsg) == 0) {
// This will trigger the connection failed notification.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
network->SetState(STATE_FAILURE);
network->set_error(ERROR_BAD_PASSPHRASE);
networklib->NotifyNetworkManagerChanged(true); // Forced update.
}
return;
}
VLOG(1) << "Connected to service: " << network->name();
// Update local cache and notify listeners.
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork *>(network);
// If the user asked not to save credentials, flimflam will have
// forgotten them. Wipe our cache as well.
if (!wifi->save_credentials()) {
wifi->EraseCredentials();
}
networklib->active_wifi_ = wifi;
} else if (network->type() == TYPE_CELLULAR) {
networklib->active_cellular_ = static_cast<CellularNetwork *>(network);
} else if (network->type() == TYPE_VPN) {
networklib->active_virtual_ = static_cast<VirtualNetwork *>(network);
} else {
LOG(ERROR) << "Network of unexpected type: " << network->type();
}
// If we succeed, this network will be remembered; request an update.
// TODO(stevenjb): flimflam should do this automatically.
networklib->RequestRememberedNetworksUpdate();
// Notify observers.
networklib->NotifyNetworkManagerChanged(true); // Forced update.
networklib->NotifyUserConnectionInitiated(network);
}
void CallConnectToNetwork(Network* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
// In order to be certain to trigger any notifications, set the connecting
// state locally and notify observers. Otherwise there might be a state
// change without a forced notify.
network->set_connecting(true);
NotifyNetworkManagerChanged(true); // Forced update.
RequestNetworkServiceConnect(network->service_path().c_str(),
NetworkConnectCallback, this);
}
virtual void ConnectToWifiNetwork(WifiNetwork* wifi) {
// This will happen if a network resets or gets out of range.
if (wifi->user_passphrase_ != wifi->passphrase_ ||
wifi->passphrase_required())
wifi->SetPassphrase(wifi->user_passphrase_);
CallConnectToNetwork(wifi);
}
// Use this to connect to a wifi network by service path.
virtual void ConnectToWifiNetwork(const std::string& service_path) {
WifiNetwork* wifi = FindWifiNetworkByPath(service_path);
if (!wifi) {
LOG(WARNING) << "Attempt to connect to non existing network: "
<< service_path;
return;
}
ConnectToWifiNetwork(wifi);
}
// Use this to connect to an unlisted wifi network.
// This needs to request information about the named service.
// The connection attempt will occur in the callback.
virtual void ConnectToWifiNetwork(const std::string& ssid,
ConnectionSecurity security,
const std::string& passphrase) {
DCHECK(security != SECURITY_8021X);
if (!EnsureCrosLoaded())
return;
// Store the connection data to be used by the callback.
connect_data_.security = security;
connect_data_.service_name = ssid;
connect_data_.passphrase = passphrase;
// Asynchronously request service properties and call
// WifiServiceUpdateAndConnect.
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(security),
WifiServiceUpdateAndConnect,
this);
}
// As above, but for 802.1X EAP networks.
virtual void ConnectToWifiNetwork8021x(
const std::string& ssid,
EAPMethod eap_method,
EAPPhase2Auth eap_auth,
const std::string& eap_server_ca_cert_nss_nickname,
bool eap_use_system_cas,
const std::string& eap_client_cert_pkcs11_id,
const std::string& eap_identity,
const std::string& eap_anonymous_identity,
const std::string& passphrase,
bool save_credentials) {
if (!EnsureCrosLoaded())
return;
connect_data_.security = SECURITY_8021X;
connect_data_.service_name = ssid;
connect_data_.eap_method = eap_method;
connect_data_.eap_auth = eap_auth;
connect_data_.eap_server_ca_cert_nss_nickname =
eap_server_ca_cert_nss_nickname;
connect_data_.eap_use_system_cas = eap_use_system_cas;
connect_data_.eap_client_cert_pkcs11_id = eap_client_cert_pkcs11_id;
connect_data_.eap_identity = eap_identity;
connect_data_.eap_anonymous_identity = eap_anonymous_identity;
connect_data_.passphrase = passphrase;
connect_data_.save_credentials = save_credentials;
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(SECURITY_8021X),
WifiServiceUpdateAndConnect,
this);
}
// Callback
static void WifiServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
DCHECK(network->type() == TYPE_WIFI);
networklib->ConnectToWifiNetworkUsingConnectData(
static_cast<WifiNetwork*>(network));
}
}
void ConnectToWifiNetworkUsingConnectData(WifiNetwork* wifi) {
ConnectData& data = connect_data_;
if (wifi->name() != data.service_name) {
LOG(WARNING) << "Wifi network name does not match ConnectData: "
<< wifi->name() << " != " << data.service_name;
return;
}
wifi->set_added(true);
if (data.security == SECURITY_8021X) {
// Enterprise 802.1X EAP network.
wifi->SetEAPMethod(data.eap_method);
wifi->SetEAPPhase2Auth(data.eap_auth);
wifi->SetEAPServerCaCertNssNickname(data.eap_server_ca_cert_nss_nickname);
wifi->SetEAPUseSystemCAs(data.eap_use_system_cas);
wifi->SetEAPClientCertPkcs11Id(data.eap_client_cert_pkcs11_id);
wifi->SetEAPIdentity(data.eap_identity);
wifi->SetEAPAnonymousIdentity(data.eap_anonymous_identity);
wifi->SetEAPPassphrase(data.passphrase);
wifi->SetSaveCredentials(data.save_credentials);
} else {
// Ordinary, non-802.1X network.
wifi->SetPassphrase(data.passphrase);
}
ConnectToWifiNetwork(wifi);
}
virtual void ConnectToCellularNetwork(CellularNetwork* cellular) {
CallConnectToNetwork(cellular);
}
// Records information that cellular play payment had happened.
virtual void SignalCellularPlanPayment() {
DCHECK(!HasRecentCellularPlanPayment());
cellular_plan_payment_time_ = base::Time::Now();
}
// Returns true if cellular plan payment had been recorded recently.
virtual bool HasRecentCellularPlanPayment() {
return (base::Time::Now() -
cellular_plan_payment_time_).InHours() < kRecentPlanPaymentHours;
}
virtual void ConnectToVirtualNetwork(VirtualNetwork* vpn) {
CallConnectToNetwork(vpn);
}
virtual void ConnectToVirtualNetworkPSK(
const std::string& service_name,
const std::string& server,
const std::string& psk,
const std::string& username,
const std::string& user_passphrase) {
if (!EnsureCrosLoaded())
return;
// Store the connection data to be used by the callback.
connect_data_.service_name = service_name;
connect_data_.psk_key = psk;
connect_data_.server_hostname = server;
connect_data_.psk_username = username;
connect_data_.passphrase = user_passphrase;
RequestVirtualNetwork(service_name.c_str(),
server.c_str(),
kProviderL2tpIpsec,
VPNServiceUpdateAndConnect,
this);
}
// Callback
static void VPNServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
VLOG(1) << "Connecting to new VPN Service: " << service_path;
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
DCHECK(network->type() == TYPE_VPN);
networklib->ConnectToVirtualNetworkUsingConnectData(
static_cast<VirtualNetwork*>(network));
} else {
LOG(WARNING) << "Unable to create VPN Service: " << service_path;
}
}
void ConnectToVirtualNetworkUsingConnectData(VirtualNetwork* vpn) {
ConnectData& data = connect_data_;
if (vpn->name() != data.service_name) {
LOG(WARNING) << "Virtual network name does not match ConnectData: "
<< vpn->name() << " != " << data.service_name;
return;
}
vpn->set_added(true);
vpn->set_server_hostname(data.server_hostname);
vpn->SetCACert("");
vpn->SetUserCert("");
vpn->SetUserCertKey("");
vpn->SetPSKPassphrase(data.psk_key);
vpn->SetUsername(data.psk_username);
vpn->SetUserPassphrase(data.passphrase);
CallConnectToNetwork(vpn);
}
virtual void DisconnectFromNetwork(const Network* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
VLOG(1) << "Disconnect from network: " << network->service_path();
if (chromeos::DisconnectFromNetwork(network->service_path().c_str())) {
// Update local cache and notify listeners.
Network* found_network = FindNetworkByPath(network->service_path());
if (found_network) {
found_network->set_connected(false);
if (found_network == active_wifi_)
active_wifi_ = NULL;
else if (found_network == active_cellular_)
active_cellular_ = NULL;
else if (found_network == active_virtual_)
active_virtual_ = NULL;
}
NotifyNetworkManagerChanged(true); // Forced update.
}
}
virtual void ForgetWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
DeleteRememberedService(service_path.c_str());
DeleteRememberedWifiNetwork(service_path);
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool ethernet_available() const {
return available_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_available() const {
return available_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_available() const {
return available_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool ethernet_enabled() const {
return enabled_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_enabled() const {
return enabled_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_enabled() const {
return enabled_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool wifi_scanning() const {
return wifi_scanning_;
}
virtual bool offline_mode() const { return offline_mode_; }
// Note: This does not include any virtual networks.
virtual const Network* active_network() const {
// Use flimflam's ordering of the services to determine what the active
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->is_active())
result = ethernet_;
if ((active_wifi_ && active_wifi_->is_active()) &&
(!result ||
active_wifi_->priority_order_ < result->priority_order_))
result = active_wifi_;
if ((active_cellular_ && active_cellular_->is_active()) &&
(!result ||
active_cellular_->priority_order_ < result->priority_order_))
result = active_cellular_;
return result;
}
virtual const Network* connected_network() const {
// Use flimflam's ordering of the services to determine what the connected
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->connected())
result = ethernet_;
if ((active_wifi_ && active_wifi_->connected()) &&
(!result ||
active_wifi_->priority_order_ < result->priority_order_))
result = active_wifi_;
if ((active_cellular_ && active_cellular_->connected()) &&
(!result ||
active_cellular_->priority_order_ < result->priority_order_))
result = active_cellular_;
return result;
}
virtual void EnableEthernetNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_ETHERNET, enable);
}
virtual void EnableWifiNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_WIFI, enable);
}
virtual void EnableCellularNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_CELLULAR, enable);
}
virtual void EnableOfflineMode(bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
VLOG(1) << "Trying to enable offline mode when it's already enabled.";
return;
}
if (!enable && !offline_mode_) {
VLOG(1) << "Trying to disable offline mode when it's already disabled.";
return;
}
if (SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address,
HardwareAddressFormat format) {
DCHECK(hardware_address);
hardware_address->clear();
NetworkIPConfigVector ipconfig_vector;
if (EnsureCrosLoaded() && !device_path.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
*hardware_address = ipconfig_status->hardware_address;
FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
for (size_t i = 0; i < hardware_address->size(); ++i)
(*hardware_address)[i] = toupper((*hardware_address)[i]);
if (format == FORMAT_COLON_SEPARATED_HEX) {
if (hardware_address->size() % 2 == 0) {
std::string output;
for (size_t i = 0; i < hardware_address->size(); ++i) {
if ((i != 0) && (i % 2 == 0))
output.push_back(':');
output.push_back((*hardware_address)[i]);
}
*hardware_address = output;
}
} else {
DCHECK(format == FORMAT_RAW_HEX);
}
return ipconfig_vector;
}
private:
typedef std::map<std::string, Network*> NetworkMap;
typedef std::map<std::string, int> PriorityMap;
typedef std::map<std::string, NetworkDevice*> NetworkDeviceMap;
typedef std::map<std::string, CellularDataPlanVector*> CellularDataPlanMap;
class NetworkObserverList : public ObserverList<NetworkObserver> {
public:
NetworkObserverList(NetworkLibraryImpl* library,
const std::string& service_path) {
network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler,
service_path.c_str(),
library);
}
virtual ~NetworkObserverList() {
if (network_monitor_)
DisconnectPropertyChangeMonitor(network_monitor_);
}
private:
static void NetworkStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkStatus(path, key, value);
}
PropertyChangeMonitor network_monitor_;
DISALLOW_COPY_AND_ASSIGN(NetworkObserverList);
};
typedef std::map<std::string, NetworkObserverList*> NetworkObserverMap;
class NetworkDeviceObserverList : public ObserverList<NetworkDeviceObserver> {
public:
NetworkDeviceObserverList(NetworkLibraryImpl* library,
const std::string& device_path) {
device_monitor_ = MonitorNetworkDevice(
&NetworkDevicePropertyChangedHandler,
device_path.c_str(),
library);
}
virtual ~NetworkDeviceObserverList() {
if (device_monitor_)
DisconnectPropertyChangeMonitor(device_monitor_);
}
private:
static void NetworkDevicePropertyChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkDeviceStatus(path, key, value);
}
PropertyChangeMonitor device_monitor_;
DISALLOW_COPY_AND_ASSIGN(NetworkDeviceObserverList);
};
typedef std::map<std::string, NetworkDeviceObserverList*>
NetworkDeviceObserverMap;
////////////////////////////////////////////////////////////////////////////
// Callbacks.
static void NetworkManagerStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->NetworkManagerStatusChanged(key, value);
}
// This processes all Manager update messages.
void NetworkManagerStatusChanged(const char* key, const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::TimeTicks start = base::TimeTicks::Now();
VLOG(1) << "NetworkManagerStatusChanged: KEY=" << key;
if (!key)
return;
int index = property_index_parser().Get(std::string(key));
switch (index) {
case PROPERTY_INDEX_STATE:
// Currently we ignore the network manager state.
break;
case PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateAvailableTechnologies(vlist);
break;
}
case PROPERTY_INDEX_ENABLED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateEnabledTechnologies(vlist);
break;
}
case PROPERTY_INDEX_CONNECTED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateConnectedTechnologies(vlist);
break;
}
case PROPERTY_INDEX_DEFAULT_TECHNOLOGY:
// Currently we ignore DefaultTechnology.
break;
case PROPERTY_INDEX_OFFLINE_MODE: {
DCHECK_EQ(value->GetType(), Value::TYPE_BOOLEAN);
value->GetAsBoolean(&offline_mode_);
NotifyNetworkManagerChanged(false); // Not forced.
break;
}
case PROPERTY_INDEX_ACTIVE_PROFILE: {
DCHECK_EQ(value->GetType(), Value::TYPE_STRING);
value->GetAsString(&active_profile_path_);
RequestRememberedNetworksUpdate();
break;
}
case PROPERTY_INDEX_PROFILES:
// Currently we ignore Profiles (list of all profiles).
break;
case PROPERTY_INDEX_SERVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_SERVICE_WATCH_LIST: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateWatchedNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_DEVICE:
case PROPERTY_INDEX_DEVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkDeviceList(vlist);
break;
}
default:
LOG(WARNING) << "Unhandled key: " << key;
break;
}
base::TimeDelta delta = base::TimeTicks::Now() - start;
VLOG(1) << " time: " << delta.InMilliseconds() << " ms.";
HISTOGRAM_TIMES("CROS_NETWORK_UPDATE", delta);
}
static void NetworkManagerUpdate(void* object,
const char* manager_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (!info) {
LOG(ERROR) << "Error retrieving manager properties: " << manager_path;
return;
}
VLOG(1) << "Received NetworkManagerUpdate.";
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkManager(dict);
}
void ParseNetworkManager(const DictionaryValue* dict) {
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = dict->GetWithoutPathExpansion(key, &value);
CHECK(res);
NetworkManagerStatusChanged(key.c_str(), value);
}
}
static void ProfileUpdate(void* object,
const char* profile_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (!info) {
LOG(ERROR) << "Error retrieving profile: " << profile_path;
return;
}
VLOG(1) << "Received ProfileUpdate for: " << profile_path;
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
ListValue* entries(NULL);
dict->GetList(kEntriesProperty, &entries);
DCHECK(entries);
networklib->UpdateRememberedServiceList(profile_path, entries);
}
static void NetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info)
return; // Network no longer in visible list, ignore.
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetwork(std::string(service_path), dict);
}
}
static void RememberedNetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Remembered network no longer exists.
networklib->DeleteRememberedWifiNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseRememberedNetwork(std::string(service_path), dict);
}
}
}
static void NetworkDeviceUpdate(void* object,
const char* device_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (device_path) {
if (!info) {
// device no longer exists.
networklib->DeleteDevice(std::string(device_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkDevice(std::string(device_path), dict);
}
}
}
static void DataPlanUpdateHandler(void* object,
const char* modem_service_path,
const CellularDataPlanList* dataplan) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (modem_service_path && dataplan) {
networklib->UpdateCellularDataPlan(std::string(modem_service_path),
dataplan);
}
}
////////////////////////////////////////////////////////////////////////////
// Network technology functions.
void UpdateTechnologies(const ListValue* technologies, int* bitfieldp) {
DCHECK(bitfieldp);
if (!technologies)
return;
int bitfield = 0;
for (ListValue::const_iterator iter = technologies->begin();
iter != technologies->end(); ++iter) {
std::string technology;
(*iter)->GetAsString(&technology);
if (!technology.empty()) {
ConnectionType type = ParseType(technology);
bitfield |= 1 << type;
}
}
*bitfieldp = bitfield;
NotifyNetworkManagerChanged(false); // Not forced.
}
void UpdateAvailableTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &available_devices_);
}
void UpdateEnabledTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &enabled_devices_);
if (!ethernet_enabled())
ethernet_ = NULL;
if (!wifi_enabled()) {
active_wifi_ = NULL;
wifi_networks_.clear();
}
if (!cellular_enabled()) {
active_cellular_ = NULL;
cellular_networks_.clear();
}
}
void UpdateConnectedTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &connected_devices_);
}
////////////////////////////////////////////////////////////////////////////
// Network list management functions.
// Note: sometimes flimflam still returns networks when the device type is
// disabled. Always check the appropriate enabled() state before adding
// networks to a list or setting an active network so that we do not show them
// in the UI.
// This relies on services being requested from flimflam in priority order,
// and the updates getting processed and received in order.
void UpdateActiveNetwork(Network* network) {
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (ethernet_enabled()) {
// Set ethernet_ to the first connected ethernet service, or the first
// disconnected ethernet service if none are connected.
if (ethernet_ == NULL || !ethernet_->connected())
ethernet_ = static_cast<EthernetNetwork*>(network);
}
} else if (type == TYPE_WIFI) {
if (wifi_enabled()) {
// Set active_wifi_ to the first connected or connecting wifi service.
if (active_wifi_ == NULL && network->connecting_or_connected())
active_wifi_ = static_cast<WifiNetwork*>(network);
}
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled()) {
// Set active_cellular_ to first connected/connecting celluar service.
if (active_cellular_ == NULL && network->connecting_or_connected())
active_cellular_ = static_cast<CellularNetwork*>(network);
}
} else if (type == TYPE_VPN) {
// Set active_virtual_ to the first connected or connecting vpn service.
if (active_virtual_ == NULL && network->connecting_or_connected())
active_virtual_ = static_cast<VirtualNetwork*>(network);
}
}
void AddNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
network_map_.insert(std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
VLOG(2) << "Adding Network: " << network->name();
ConnectionType type(network->type());
if (type == TYPE_WIFI) {
if (wifi_enabled())
wifi_networks_.push_back(static_cast<WifiNetwork*>(network));
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled())
cellular_networks_.push_back(static_cast<CellularNetwork*>(network));
} else if (type == TYPE_VPN) {
virtual_networks_.push_back(static_cast<VirtualNetwork*>(network));
}
// Do not set the active network here. Wait until we parse the network.
}
// Deletes a network. It must already be removed from any lists.
void DeleteNetwork(Network* network) {
CHECK(network_map_.find(network->service_path()) == network_map_.end());
ConnectionType type(network->type());
if (type == TYPE_CELLULAR) {
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found =
data_plan_map_.find(network->service_path());
if (found != data_plan_map_.end()) {
CellularDataPlanVector* data_plans = found->second;
delete data_plans;
data_plan_map_.erase(found);
}
}
delete network;
}
void AddRememberedWifiNetwork(WifiNetwork* wifi) {
std::pair<NetworkMap::iterator,bool> result =
remembered_network_map_.insert(
std::make_pair(wifi->service_path(), wifi));
DCHECK(result.second); // Should only get called with new network.
remembered_wifi_networks_.push_back(wifi);
}
void DeleteRememberedWifiNetwork(const std::string& service_path) {
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found == remembered_network_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant remembered network: "
<< service_path;
return;
}
Network* remembered_network = found->second;
remembered_network_map_.erase(found);
WifiNetworkVector::iterator iter = std::find(
remembered_wifi_networks_.begin(), remembered_wifi_networks_.end(),
remembered_network);
if (iter != remembered_wifi_networks_.end())
remembered_wifi_networks_.erase(iter);
Network* network = FindNetworkFromRemembered(remembered_network);
if (network && network->type() == TYPE_WIFI) {
// Clear the stored credentials for any visible forgotten networks.
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
wifi->EraseCredentials();
} else {
// Network is not in visible list.
VLOG(2) << "Remembered Network not found: "
<< remembered_network->unique_id();
}
delete remembered_network;
}
// Update all network lists, and request associated service updates.
void UpdateNetworkServiceList(const ListValue* services) {
// TODO(stevenjb): Wait for wifi_scanning_ to be false.
// Copy the list of existing networks to "old" and clear the map and lists.
NetworkMap old_network_map = network_map_;
ClearNetworks(false /*don't delete*/);
// Clear the list of update requests.
int network_priority_order = 0;
network_update_requests_.clear();
// wifi_scanning_ will remain false unless we request a network update.
wifi_scanning_ = false;
// |services| represents a complete list of visible networks.
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and lists. Otherwise it will get added when NetworkServiceUpdate
// calls ParseNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddNetwork(found->second);
old_network_map.erase(found);
}
// Always request network updates.
// TODO(stevenjb): Investigate why we are missing updates then
// rely on watched network updates and only request updates here for
// new networks.
// Use update_request map to store network priority.
network_update_requests_[service_path] = network_priority_order++;
wifi_scanning_ = true;
RequestNetworkServiceInfo(service_path.c_str(),
&NetworkServiceUpdate,
this);
}
}
// Iterate through list of remaining networks that are no longer in the
// list and delete them or update their status and re-add them to the list.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
Network* network = iter->second;
if (network->failed() && network->notify_failure()) {
// We have not notified observers of a connection failure yet.
AddNetwork(network);
} else if (network->connecting()) {
// Network was in connecting state; set state to failed.
network->SetState(STATE_FAILURE);
AddNetwork(network);
} else {
VLOG(2) << "Deleting non-existant Network: " << network->name()
<< " State = " << network->GetStateString();
DeleteNetwork(network);
}
}
}
// Request updates for watched networks. Does not affect network lists.
// Existing networks will be updated. There should not be any new networks
// in this list, but if there are they will be added appropriately.
void UpdateWatchedNetworkServiceList(const ListValue* services) {
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
VLOG(1) << "Watched Service: " << service_path;
RequestNetworkServiceInfo(
service_path.c_str(), &NetworkServiceUpdate, this);
}
}
}
// Request the active profile which lists the remembered networks.
void RequestRememberedNetworksUpdate() {
RequestNetworkProfile(
active_profile_path_.c_str(), &ProfileUpdate, this);
}
// Update the list of remembered (profile) networks, and request associated
// service updates.
void UpdateRememberedServiceList(const char* profile_path,
const ListValue* profile_entries) {
// Copy the list of existing networks to "old" and clear the map and list.
NetworkMap old_network_map = remembered_network_map_;
ClearRememberedNetworks(false /*don't delete*/);
// |profile_entries| represents a complete list of remembered networks.
for (ListValue::const_iterator iter = profile_entries->begin();
iter != profile_entries->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and list. Otherwise it will get added when
// RememberedNetworkServiceUpdate calls ParseRememberedNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
Network* network = found->second;
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
AddRememberedWifiNetwork(wifi);
old_network_map.erase(found);
}
}
// Always request updates for remembered networks.
RequestNetworkProfileEntry(profile_path,
service_path.c_str(),
&RememberedNetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
Network* CreateNewNetwork(ConnectionType type,
const std::string& service_path) {
switch (type) {
case TYPE_ETHERNET: {
EthernetNetwork* ethernet = new EthernetNetwork(service_path);
return ethernet;
}
case TYPE_WIFI: {
WifiNetwork* wifi = new WifiNetwork(service_path);
return wifi;
}
case TYPE_CELLULAR: {
CellularNetwork* cellular = new CellularNetwork(service_path);
return cellular;
}
case TYPE_VPN: {
VirtualNetwork* vpn = new VirtualNetwork(service_path);
return vpn;
}
default: {
LOG(WARNING) << "Unknown service type: " << type;
return new Network(service_path, type);
}
}
}
Network* ParseNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network = FindNetworkByPath(service_path);
if (!network) {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddNetwork(network);
}
// Erase entry from network_unique_id_map_ in case unique id changes.
if (!network->unique_id().empty())
network_unique_id_map_.erase(network->unique_id());
network->ParseInfo(info); // virtual.
if (!network->unique_id().empty())
network_unique_id_map_[network->unique_id()] = network;
UpdateActiveNetwork(network);
// Find and erase entry in update_requests, and set network priority.
PriorityMap::iterator found2 = network_update_requests_.find(service_path);
if (found2 != network_update_requests_.end()) {
network->priority_order_ = found2->second;
network_update_requests_.erase(found2);
if (network_update_requests_.empty()) {
// Clear wifi_scanning_ when we have no pending requests.
wifi_scanning_ = false;
}
} else {
// TODO(stevenjb): Enable warning once UpdateNetworkServiceList is fixed.
// LOG(WARNING) << "ParseNetwork called with no update request entry: "
// << service_path;
}
VLOG(1) << "ParseNetwork: " << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
// Returns NULL if |service_path| refers to a network that is not a
// remembered type.
Network* ParseRememberedNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network;
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found != remembered_network_map_.end()) {
network = found->second;
} else {
ConnectionType type = ParseTypeFromDictionary(info);
if (type == TYPE_WIFI) {
network = CreateNewNetwork(type, service_path);
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
AddRememberedWifiNetwork(wifi);
} else {
VLOG(1) << "Ignoring remembered network: " << service_path
<< " Type: " << ConnectionTypeToString(type);
return NULL;
}
}
network->ParseInfo(info); // virtual.
VLOG(1) << "ParseRememberedNetwork: " << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
void ClearNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&network_map_);
network_map_.clear();
network_unique_id_map_.clear();
ethernet_ = NULL;
active_wifi_ = NULL;
active_cellular_ = NULL;
active_virtual_ = NULL;
wifi_networks_.clear();
cellular_networks_.clear();
virtual_networks_.clear();
}
void ClearRememberedNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&remembered_network_map_);
remembered_network_map_.clear();
remembered_wifi_networks_.clear();
}
////////////////////////////////////////////////////////////////////////////
// NetworkDevice list management functions.
// Returns pointer to device or NULL if device is not found by path.
// Use FindNetworkDeviceByPath when you're not intending to change device.
NetworkDevice* GetNetworkDeviceByPath(const std::string& path) {
NetworkDeviceMap::iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
// Update device list, and request associated device updates.
// |devices| represents a complete list of devices.
void UpdateNetworkDeviceList(const ListValue* devices) {
NetworkDeviceMap old_device_map = device_map_;
device_map_.clear();
VLOG(2) << "Updating Device List.";
for (ListValue::const_iterator iter = devices->begin();
iter != devices->end(); ++iter) {
std::string device_path;
(*iter)->GetAsString(&device_path);
if (!device_path.empty()) {
NetworkDeviceMap::iterator found = old_device_map.find(device_path);
if (found != old_device_map.end()) {
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = found->second;
old_device_map.erase(found);
}
RequestNetworkDeviceInfo(
device_path.c_str(), &NetworkDeviceUpdate, this);
}
}
// Delete any old devices that no longer exist.
for (NetworkDeviceMap::iterator iter = old_device_map.begin();
iter != old_device_map.end(); ++iter) {
DeleteDeviceFromDeviceObserversMap(iter->first);
// Delete device.
delete iter->second;
}
}
void DeleteDeviceFromDeviceObserversMap(const std::string& device_path) {
// Delete all device observers associated with this device.
NetworkDeviceObserverMap::iterator map_iter =
network_device_observers_.find(device_path);
if (map_iter != network_device_observers_.end()) {
delete map_iter->second;
network_device_observers_.erase(map_iter);
}
}
void DeleteDevice(const std::string& device_path) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
if (found == device_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant device: "
<< device_path;
return;
}
VLOG(2) << " Deleting device: " << device_path;
NetworkDevice* device = found->second;
device_map_.erase(found);
DeleteDeviceFromDeviceObserversMap(device_path);
delete device;
}
void ParseNetworkDevice(const std::string& device_path,
const DictionaryValue* info) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
NetworkDevice* device;
if (found != device_map_.end()) {
device = found->second;
} else {
device = new NetworkDevice(device_path);
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = device;
}
device->ParseInfo(info);
VLOG(1) << "ParseNetworkDevice:" << device->name();
NotifyNetworkManagerChanged(false); // Not forced.
}
////////////////////////////////////////////////////////////////////////////
void EnableNetworkDeviceType(ConnectionType device, bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to enable a device that's already enabled: "
<< device;
return;
}
if (!enable && !(enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to disable a device that's already disabled: "
<< device;
return;
}
RequestNetworkDeviceEnable(ConnectionTypeToString(device), enable);
}
////////////////////////////////////////////////////////////////////////////
// Notifications.
// We call this any time something in NetworkLibrary changes.
// TODO(stevenjb): We should consider breaking this into multiplie
// notifications, e.g. connection state, devices, services, etc.
void NotifyNetworkManagerChanged(bool force_update) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Cancel any pending signals.
if (notify_task_) {
notify_task_->Cancel();
notify_task_ = NULL;
}
if (force_update) {
// Signal observers now.
SignalNetworkManagerObservers();
} else {
// Schedule a deleayed signal to limit the frequency of notifications.
notify_task_ = NewRunnableMethod(
this, &NetworkLibraryImpl::SignalNetworkManagerObservers);
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, notify_task_,
kNetworkNotifyDelayMs);
}
}
void SignalNetworkManagerObservers() {
notify_task_ = NULL;
FOR_EACH_OBSERVER(NetworkManagerObserver,
network_manager_observers_,
OnNetworkManagerChanged(this));
// Clear notification flags.
for (NetworkMap::iterator iter = network_map_.begin();
iter != network_map_.end(); ++iter) {
iter->second->set_notify_failure(false);
}
}
void NotifyNetworkChanged(Network* network) {
VLOG(2) << "Network changed: " << network->name();
DCHECK(network);
NetworkObserverMap::const_iterator iter = network_observers_.find(
network->service_path());
if (iter != network_observers_.end()) {
FOR_EACH_OBSERVER(NetworkObserver,
*(iter->second),
OnNetworkChanged(this, network));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
network->service_path();
}
}
void NotifyNetworkDeviceChanged(NetworkDevice* device) {
DCHECK(device);
NetworkDeviceObserverMap::const_iterator iter =
network_device_observers_.find(device->device_path());
if (iter != network_device_observers_.end()) {
NetworkDeviceObserverList* device_observer_list = iter->second;
FOR_EACH_OBSERVER(NetworkDeviceObserver,
*device_observer_list,
OnNetworkDeviceChanged(this, device));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
device->device_path();
}
}
void NotifyCellularDataPlanChanged() {
FOR_EACH_OBSERVER(CellularDataPlanObserver,
data_plan_observers_,
OnCellularDataPlanChanged(this));
}
void NotifyPinOperationCompleted(PinOperationError error) {
FOR_EACH_OBSERVER(PinOperationObserver,
pin_operation_observers_,
OnPinOperationCompleted(this, error));
sim_operation_ = SIM_OPERATION_NONE;
}
void NotifyUserConnectionInitiated(const Network* network) {
FOR_EACH_OBSERVER(UserActionObserver,
user_action_observers_,
OnConnectionInitiated(this, network));
}
////////////////////////////////////////////////////////////////////////////
// Device updates.
void FlipSimPinRequiredStateIfNeeded() {
if (sim_operation_ != SIM_OPERATION_CHANGE_REQUIRE_PIN)
return;
const NetworkDevice* cellular = FindCellularDevice();
if (cellular) {
NetworkDevice* device = GetNetworkDeviceByPath(cellular->device_path());
if (device->sim_pin_required() == SIM_PIN_NOT_REQUIRED)
device->sim_pin_required_ = SIM_PIN_REQUIRED;
else if (device->sim_pin_required() == SIM_PIN_REQUIRED)
device->sim_pin_required_ = SIM_PIN_NOT_REQUIRED;
}
}
void UpdateNetworkDeviceStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
NetworkDevice* device = GetNetworkDeviceByPath(path);
if (device) {
VLOG(1) << "UpdateNetworkDeviceStatus: " << device->name() << "." << key;
int index = property_index_parser().Get(std::string(key));
if (!device->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkDeviceStatus: Error parsing: "
<< path << "." << key;
} else if (path == kCellularAllowRoamingProperty) {
bool settings_value =
UserCrosSettingsProvider::cached_data_roaming_enabled();
if (device->data_roaming_allowed() != settings_value) {
// Switch back to signed settings value.
SetCellularDataRoamingAllowed(settings_value);
return;
}
}
// Notify only observers on device property change.
NotifyNetworkDeviceChanged(device);
}
}
////////////////////////////////////////////////////////////////////////////
// Service updates.
void UpdateNetworkStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
Network* network = FindNetworkByPath(path);
if (network) {
VLOG(2) << "UpdateNetworkStatus: " << network->name() << "." << key;
// Note: ParseValue is virtual.
int index = property_index_parser().Get(std::string(key));
if (!network->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkStatus: Error parsing: "
<< path << "." << key;
}
NotifyNetworkChanged(network);
// Anything observing the manager needs to know about any service change.
NotifyNetworkManagerChanged(false); // Not forced.
}
}
////////////////////////////////////////////////////////////////////////////
// Data Plans.
const CellularDataPlan* GetSignificantDataPlanFromVector(
const CellularDataPlanVector* plans) const {
const CellularDataPlan* significant = NULL;
for (CellularDataPlanVector::const_iterator iter = plans->begin();
iter != plans->end(); ++iter) {
// Set significant to the first plan or to first non metered base plan.
if (significant == NULL ||
significant->plan_type == CELLULAR_DATA_PLAN_METERED_BASE)
significant = *iter;
}
return significant;
}
CellularNetwork::DataLeft GetDataLeft(
CellularDataPlanVector* data_plans) {
const CellularDataPlan* plan = GetSignificantDataPlanFromVector(data_plans);
if (!plan)
return CellularNetwork::DATA_UNKNOWN;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
base::TimeDelta remaining = plan->remaining_time();
if (remaining <= base::TimeDelta::FromSeconds(0))
return CellularNetwork::DATA_NONE;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs))
return CellularNetwork::DATA_VERY_LOW;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs))
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
} else if (plan->plan_type == CELLULAR_DATA_PLAN_METERED_PAID ||
plan->plan_type == CELLULAR_DATA_PLAN_METERED_BASE) {
int64 remaining = plan->remaining_data();
if (remaining <= 0)
return CellularNetwork::DATA_NONE;
if (remaining <= kCellularDataVeryLowBytes)
return CellularNetwork::DATA_VERY_LOW;
// For base plans, we do not care about low data.
if (remaining <= kCellularDataLowBytes &&
plan->plan_type != CELLULAR_DATA_PLAN_METERED_BASE)
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
}
return CellularNetwork::DATA_UNKNOWN;
}
void UpdateCellularDataPlan(const std::string& service_path,
const CellularDataPlanList* data_plan_list) {
VLOG(1) << "Updating cellular data plans for: " << service_path;
CellularDataPlanVector* data_plans = NULL;
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
data_plans = found->second;
data_plans->reset(); // This will delete existing data plans.
} else {
data_plans = new CellularDataPlanVector;
data_plan_map_[service_path] = data_plans;
}
for (size_t i = 0; i < data_plan_list->plans_size; i++) {
const CellularDataPlanInfo* info(data_plan_list->GetCellularDataPlan(i));
CellularDataPlan* plan = new CellularDataPlan(*info);
data_plans->push_back(plan);
VLOG(2) << " Plan: " << plan->GetPlanDesciption()
<< " : " << plan->GetDataRemainingDesciption();
}
// Now, update any matching cellular network's cached data
CellularNetwork* cellular = FindCellularNetworkByPath(service_path);
if (cellular) {
CellularNetwork::DataLeft data_left;
// If the network needs a new plan, then there's no data.
if (cellular->needs_new_plan())
data_left = CellularNetwork::DATA_NONE;
else
data_left = GetDataLeft(data_plans);
VLOG(2) << " Data left: " << data_left
<< " Need plan: " << cellular->needs_new_plan();
cellular->set_data_left(data_left);
}
NotifyCellularDataPlanChanged();
}
////////////////////////////////////////////////////////////////////////////
void Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
if (EnsureCrosLoaded()) {
VLOG(1) << "Requesting initial network manager info from libcros.";
RequestNetworkManagerInfo(&NetworkManagerUpdate, this);
}
}
void InitTestData() {
is_locked_ = false;
// Devices
int devices =
(1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR);
available_devices_ = devices;
enabled_devices_ = devices;
connected_devices_ = devices;
NetworkDevice* cellular = new NetworkDevice("cellular");
scoped_ptr<Value> cellular_type(Value::CreateStringValue(kTypeCellular));
cellular->ParseValue(PROPERTY_INDEX_TYPE, cellular_type.get());
cellular->IMSI_ = "123456789012345";
device_map_["cellular"] = cellular;
// Networks
ClearNetworks(true /*delete networks*/);
ethernet_ = new EthernetNetwork("eth1");
ethernet_->set_connected(true);
AddNetwork(ethernet_);
WifiNetwork* wifi1 = new WifiNetwork("fw1");
wifi1->set_name("Fake Wifi Connected");
wifi1->set_strength(90);
wifi1->set_connected(true);
wifi1->set_active(true);
wifi1->set_encryption(SECURITY_NONE);
AddNetwork(wifi1);
WifiNetwork* wifi2 = new WifiNetwork("fw2");
wifi2->set_name("Fake Wifi");
wifi2->set_strength(70);
wifi2->set_connected(false);
wifi2->set_encryption(SECURITY_NONE);
AddNetwork(wifi2);
WifiNetwork* wifi3 = new WifiNetwork("fw3");
wifi3->set_name("Fake Wifi Encrypted");
wifi3->set_strength(60);
wifi3->set_connected(false);
wifi3->set_encryption(SECURITY_WEP);
wifi3->set_passphrase_required(true);
AddNetwork(wifi3);
WifiNetwork* wifi4 = new WifiNetwork("fw4");
wifi4->set_name("Fake Wifi 802.1x");
wifi4->set_strength(50);
wifi4->set_connected(false);
wifi4->set_connectable(false);
wifi4->set_encryption(SECURITY_8021X);
wifi4->set_identity("nobody@google.com");
wifi4->set_cert_path("SETTINGS:key_id=3,cert_id=3,pin=111111");
AddNetwork(wifi4);
active_wifi_ = wifi1;
CellularNetwork* cellular1 = new CellularNetwork("fc1");
cellular1->set_name("Fake Cellular");
cellular1->set_strength(70);
cellular1->set_connected(true);
cellular1->set_active(true);
cellular1->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular1->set_payment_url(std::string("http://www.google.com"));
cellular1->set_usage_url(std::string("http://www.google.com"));
cellular1->set_network_technology(NETWORK_TECHNOLOGY_EVDO);
cellular1->set_roaming_state(ROAMING_STATE_ROAMING);
CellularDataPlan* base_plan = new CellularDataPlan();
base_plan->plan_name = "Base plan";
base_plan->plan_type = CELLULAR_DATA_PLAN_METERED_BASE;
base_plan->plan_data_bytes = 100ll * 1024 * 1024;
base_plan->data_bytes_used = 75ll * 1024 * 1024;
CellularDataPlanVector* data_plans = new CellularDataPlanVector();
data_plan_map_[cellular1->service_path()] = data_plans;
data_plans->push_back(base_plan);
CellularDataPlan* paid_plan = new CellularDataPlan();
paid_plan->plan_name = "Paid plan";
paid_plan->plan_type = CELLULAR_DATA_PLAN_METERED_PAID;
paid_plan->plan_data_bytes = 5ll * 1024 * 1024 * 1024;
paid_plan->data_bytes_used = 3ll * 1024 * 1024 * 1024;
data_plans->push_back(paid_plan);
AddNetwork(cellular1);
active_cellular_ = cellular1;
CellularNetwork* cellular2 = new CellularNetwork("fc2");
cellular2->set_name("Fake Cellular 2");
cellular2->set_strength(70);
cellular2->set_connected(true);
cellular2->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular2->set_network_technology(NETWORK_TECHNOLOGY_UMTS);
AddNetwork(cellular2);
// Remembered Networks
ClearRememberedNetworks(true /*delete networks*/);
WifiNetwork* remembered_wifi2 = new WifiNetwork("fw2");
remembered_wifi2->set_name("Fake Wifi 2");
remembered_wifi2->set_strength(70);
remembered_wifi2->set_connected(true);
remembered_wifi2->set_encryption(SECURITY_WEP);
AddRememberedWifiNetwork(remembered_wifi2);
// VPNs.
VirtualNetwork* vpn1 = new VirtualNetwork("fv1");
vpn1->set_name("Fake VPN Provider 1");
vpn1->set_server_hostname("vpn1server.fake.com");
vpn1->set_provider_type(VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK);
vpn1->set_username("VPN User 1");
vpn1->set_connected(false);
AddNetwork(vpn1);
VirtualNetwork* vpn2 = new VirtualNetwork("fv2");
vpn2->set_name("Fake VPN Provider 2");
vpn2->set_server_hostname("vpn2server.fake.com");
vpn2->set_provider_type(VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_USER_CERT);
vpn2->set_username("VPN User 2");
vpn2->set_connected(true);
AddNetwork(vpn2);
VirtualNetwork* vpn3 = new VirtualNetwork("fv3");
vpn3->set_name("Fake VPN Provider 3");
vpn3->set_server_hostname("vpn3server.fake.com");
vpn3->set_provider_type(VirtualNetwork::PROVIDER_TYPE_OPEN_VPN);
vpn3->set_connected(false);
AddNetwork(vpn3);
active_virtual_ = vpn2;
wifi_scanning_ = false;
offline_mode_ = false;
}
// Network manager observer list
ObserverList<NetworkManagerObserver> network_manager_observers_;
// Cellular data plan observer list
ObserverList<CellularDataPlanObserver> data_plan_observers_;
// PIN operation observer list.
ObserverList<PinOperationObserver> pin_operation_observers_;
// User action observer list
ObserverList<UserActionObserver> user_action_observers_;
// Network observer map
NetworkObserverMap network_observers_;
// Network device observer map.
NetworkDeviceObserverMap network_device_observers_;
// For monitoring network manager status changes.
PropertyChangeMonitor network_manager_monitor_;
// For monitoring data plan changes to the connected cellular network.
DataPlanUpdateMonitor data_plan_monitor_;
// Network login observer.
scoped_ptr<NetworkLoginObserver> network_login_observer_;
// A service path based map of all Networks.
NetworkMap network_map_;
// A unique_id_ based map of Networks.
NetworkMap network_unique_id_map_;
// A service path based map of all remembered Networks.
NetworkMap remembered_network_map_;
// A list of services that we are awaiting updates for.
PriorityMap network_update_requests_;
// A device path based map of all NetworkDevices.
NetworkDeviceMap device_map_;
// A network service path based map of all CellularDataPlanVectors.
CellularDataPlanMap data_plan_map_;
// The ethernet network.
EthernetNetwork* ethernet_;
// The list of available wifi networks.
WifiNetworkVector wifi_networks_;
// The current connected (or connecting) wifi network.
WifiNetwork* active_wifi_;
// The remembered wifi networks.
WifiNetworkVector remembered_wifi_networks_;
// The list of available cellular networks.
CellularNetworkVector cellular_networks_;
// The current connected (or connecting) cellular network.
CellularNetwork* active_cellular_;
// The list of available virtual networks.
VirtualNetworkVector virtual_networks_;
// The current connected (or connecting) virtual network.
VirtualNetwork* active_virtual_;
// The path of the active profile (for retrieving remembered services).
std::string active_profile_path_;
// The current available network devices. Bitwise flag of ConnectionTypes.
int available_devices_;
// The current enabled network devices. Bitwise flag of ConnectionTypes.
int enabled_devices_;
// The current connected network devices. Bitwise flag of ConnectionTypes.
int connected_devices_;
// True if we are currently scanning for wifi networks.
bool wifi_scanning_;
// Currently not implemented. TODO: implement or eliminate.
bool offline_mode_;
// True if access network library is locked.
bool is_locked_;
// Type of pending SIM operation, SIM_OPERATION_NONE otherwise.
SimOperationType sim_operation_;
// Delayed task to notify a network change.
CancelableTask* notify_task_;
// Cellular plan payment time.
base::Time cellular_plan_payment_time_;
// Temporary connection data for async connect calls.
struct ConnectData {
ConnectionSecurity security;
std::string service_name; // For example, SSID.
std::string passphrase;
EAPMethod eap_method;
EAPPhase2Auth eap_auth;
std::string eap_server_ca_cert_nss_nickname;
bool eap_use_system_cas;
std::string eap_client_cert_pkcs11_id;
std::string eap_identity;
std::string eap_anonymous_identity;
bool save_credentials;
std::string psk_key;
std::string psk_username;
std::string server_hostname;
};
ConnectData connect_data_;
DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl);
};
class NetworkLibraryStubImpl : public NetworkLibrary {
public:
NetworkLibraryStubImpl()
: ip_address_("1.1.1.1"),
ethernet_(new EthernetNetwork("eth0")),
active_wifi_(NULL),
active_cellular_(NULL) {
}
~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; }
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {}
virtual void AddNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {}
virtual void RemoveNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {}
virtual void Lock() {}
virtual void Unlock() {}
virtual bool IsLocked() { return false; }
virtual void AddCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void AddPinOperationObserver(PinOperationObserver* observer) {}
virtual void RemovePinOperationObserver(PinOperationObserver* observer) {}
virtual void AddUserActionObserver(UserActionObserver* observer) {}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {}
virtual const EthernetNetwork* ethernet_network() const {
return ethernet_;
}
virtual bool ethernet_connecting() const { return false; }
virtual bool ethernet_connected() const { return true; }
virtual const WifiNetwork* wifi_network() const {
return active_wifi_;
}
virtual bool wifi_connecting() const { return false; }
virtual bool wifi_connected() const { return false; }
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const { return false; }
virtual bool cellular_connected() const { return false; }
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const { return false; }
virtual bool virtual_network_connected() const { return false; }
bool Connected() const { return true; }
bool Connecting() const { return false; }
const std::string& IPAddress() const { return ip_address_; }
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
virtual bool has_cellular_networks() const {
return cellular_networks_.begin() != cellular_networks_.end();
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const { return NULL; }
virtual const NetworkDevice* FindCellularDevice() const {
return NULL;
}
virtual const NetworkDevice* FindEthernetDevice() const {
return NULL;
}
virtual const NetworkDevice* FindWifiDevice() const {
return NULL;
}
virtual Network* FindNetworkByPath(
const std::string& path) const { return NULL; }
virtual WifiNetwork* FindWifiNetworkByPath(
const std::string& path) const { return NULL; }
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const { return NULL; }
virtual VirtualNetwork* FindVirtualNetworkByPath(
const std::string& path) const { return NULL; }
virtual Network* FindNetworkFromRemembered(
const Network* remembered) const { return NULL; }
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const { return NULL; }
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const { return NULL; }
virtual void ChangePin(const std::string& old_pin,
const std::string& new_pin) {}
virtual void ChangeRequirePin(bool require_pin, const std::string& pin) {}
virtual void EnterPin(const std::string& pin) {}
virtual void UnblockPin(const std::string& puk, const std::string& new_pin) {}
virtual void RequestCellularScan() {}
virtual void RequestCellularRegister(const std::string& network_id) {}
virtual void SetCellularDataRoamingAllowed(bool new_value) {}
virtual void RequestNetworkScan() {}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
return false;
}
virtual void ConnectToWifiNetwork(WifiNetwork* network) {}
virtual void ConnectToWifiNetwork(const std::string& service_path) {}
virtual void ConnectToWifiNetwork(const std::string& ssid,
ConnectionSecurity security,
const std::string& passphrase) {}
virtual void ConnectToWifiNetwork8021x(
const std::string& ssid,
EAPMethod method,
EAPPhase2Auth auth,
const std::string& server_ca_cert_nss_nickname,
bool use_system_cas,
const std::string& client_cert_pkcs11_id,
const std::string& identity,
const std::string& anonymous_identity,
const std::string& passphrase,
bool save_credentials) {}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {}
virtual void ConnectToVirtualNetwork(VirtualNetwork* network) {}
virtual void ConnectToVirtualNetworkPSK(
const std::string& service_name,
const std::string& server,
const std::string& psk,
const std::string& username,
const std::string& user_passphrase) {}
virtual void SignalCellularPlanPayment() {}
virtual bool HasRecentCellularPlanPayment() { return false; }
virtual void DisconnectFromNetwork(const Network* network) {}
virtual void ForgetWifiNetwork(const std::string& service_path) {}
virtual bool ethernet_available() const { return true; }
virtual bool wifi_available() const { return false; }
virtual bool cellular_available() const { return false; }
virtual bool ethernet_enabled() const { return true; }
virtual bool wifi_enabled() const { return false; }
virtual bool cellular_enabled() const { return false; }
virtual bool wifi_scanning() const { return false; }
virtual const Network* active_network() const { return NULL; }
virtual const Network* connected_network() const { return NULL; }
virtual bool offline_mode() const { return false; }
virtual void EnableEthernetNetworkDevice(bool enable) {}
virtual void EnableWifiNetworkDevice(bool enable) {}
virtual void EnableCellularNetworkDevice(bool enable) {}
virtual void EnableOfflineMode(bool enable) {}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address,
HardwareAddressFormat) {
hardware_address->clear();
return NetworkIPConfigVector();
}
private:
std::string ip_address_;
EthernetNetwork* ethernet_;
WifiNetwork* active_wifi_;
CellularNetwork* active_cellular_;
VirtualNetwork* active_virtual_;
WifiNetworkVector wifi_networks_;
CellularNetworkVector cellular_networks_;
VirtualNetworkVector virtual_networks_;
};
// static
NetworkLibrary* NetworkLibrary::GetImpl(bool stub) {
if (stub)
return new NetworkLibraryStubImpl();
else
return new NetworkLibraryImpl();
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl);
Fix wrong string comparison introduced in #84056
BUG=chromium-os:12008
TEST=build
Review URL: http://codereview.chromium.org/6934001
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@84058 0039d316-1c4b-4281-b951-d872f2087c98
// 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/chromeos/cros/network_library.h"
#include <algorithm>
#include <map>
#include "base/i18n/time_formatting.h"
#include "base/metrics/histogram.h"
#include "base/stl_util-inl.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/network_login_observer.h"
#include "chrome/browser/chromeos/user_cros_settings_provider.h"
#include "chrome/common/time_format.h"
#include "content/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
////////////////////////////////////////////////////////////////////////////////
// Implementation notes.
// NetworkLibraryImpl manages a series of classes that describe network devices
// and services:
//
// NetworkDevice: e.g. ethernet, wifi modem, cellular modem
// device_map_: canonical map<path,NetworkDevice*> for devices
//
// Network: a network service ("network").
// network_map_: canonical map<path,Network*> for all visible networks.
// EthernetNetwork
// ethernet_: EthernetNetwork* to the active ethernet network in network_map_.
// WirelessNetwork: a Wifi or Cellular Network.
// WifiNetwork
// active_wifi_: WifiNetwork* to the active wifi network in network_map_.
// wifi_networks_: ordered vector of WifiNetwork* entries in network_map_,
// in descending order of importance.
// CellularNetwork
// active_cellular_: Cellular version of wifi_.
// cellular_networks_: Cellular version of wifi_.
// network_unique_id_map_: map<unique_id,Network*> for visible networks.
// remembered_network_map_: a canonical map<path,Network*> for all networks
// remembered in the active Profile ("favorites").
// remembered_wifi_networks_: ordered vector of WifiNetwork* entries in
// remembered_network_map_, in descending order of preference.
//
// network_manager_monitor_: a handle to the libcros network Manager handler.
// NetworkManagerStatusChanged: This handles all messages from the Manager.
// Messages are parsed here and the appropriate updates are then requested.
//
// UpdateNetworkServiceList: This is the primary Manager handler. It handles
// the "Services" message which list all visible networks. The handler
// rebuilds the network lists without destroying existing Network structures,
// then requests neccessary updates to be fetched asynchronously from
// libcros (RequestNetworkServiceInfo).
//
// TODO(stevenjb): Document cellular data plan handlers.
//
// AddNetworkObserver: Adds an observer for a specific network.
// NetworkObserverList: A monitor and list of observers of a network.
// network_monitor_: a handle to the libcros network Service handler.
// UpdateNetworkStatus: This handles changes to a monitored service, typically
// changes to transient states like Strength. (Note: also updates State).
//
// AddNetworkDeviceObserver: Adds an observer for a specific device.
// Will be called on any device property change.
// NetworkDeviceObserverList: A monitor and list of observers of a device.
// UpdateNetworkDeviceStatus: Handles changes to a monitored device, like
// SIM lock state and updates device state.
//
// All *Pin(...) methods use internal callback that would update cellular
// device state once async call is completed and notify all device observers.
//
////////////////////////////////////////////////////////////////////////////////
namespace chromeos {
// Local constants.
namespace {
// Only send network change notifications to observers once every 50ms.
const int kNetworkNotifyDelayMs = 50;
// How long we should remember that cellular plan payment was received.
const int kRecentPlanPaymentHours = 6;
// Default value of the SIM unlock retries count. It is updated to the real
// retries count once cellular device with SIM card is initialized.
// If cellular device doesn't have SIM card, then retries are never used.
const int kDefaultSimUnlockRetriesCount = 999;
// Type of a pending SIM operation.
enum SimOperationType {
SIM_OPERATION_NONE = 0,
SIM_OPERATION_CHANGE_PIN = 1,
SIM_OPERATION_CHANGE_REQUIRE_PIN = 2,
SIM_OPERATION_ENTER_PIN = 3,
SIM_OPERATION_UNBLOCK_PIN = 4,
};
// D-Bus interface string constants.
// Flimflam property names.
const char* kSecurityProperty = "Security";
const char* kPassphraseProperty = "Passphrase";
const char* kIdentityProperty = "Identity";
const char* kCertPathProperty = "CertPath";
const char* kPassphraseRequiredProperty = "PassphraseRequired";
const char* kSaveCredentialsProperty = "SaveCredentials";
const char* kProfilesProperty = "Profiles";
const char* kServicesProperty = "Services";
const char* kServiceWatchListProperty = "ServiceWatchList";
const char* kAvailableTechnologiesProperty = "AvailableTechnologies";
const char* kEnabledTechnologiesProperty = "EnabledTechnologies";
const char* kConnectedTechnologiesProperty = "ConnectedTechnologies";
const char* kDefaultTechnologyProperty = "DefaultTechnology";
const char* kOfflineModeProperty = "OfflineMode";
const char* kSignalStrengthProperty = "Strength";
const char* kNameProperty = "Name";
const char* kStateProperty = "State";
const char* kConnectivityStateProperty = "ConnectivityState";
const char* kTypeProperty = "Type";
const char* kDeviceProperty = "Device";
const char* kActivationStateProperty = "Cellular.ActivationState";
const char* kNetworkTechnologyProperty = "Cellular.NetworkTechnology";
const char* kRoamingStateProperty = "Cellular.RoamingState";
const char* kOperatorNameProperty = "Cellular.OperatorName";
const char* kOperatorCodeProperty = "Cellular.OperatorCode";
const char* kPaymentURLProperty = "Cellular.OlpUrl";
const char* kUsageURLProperty = "Cellular.UsageUrl";
const char* kCellularApnProperty = "Cellular.APN";
const char* kCellularLastGoodApnProperty = "Cellular.LastGoodAPN";
const char* kCellularAllowRoamingProperty = "Cellular.AllowRoaming";
const char* kFavoriteProperty = "Favorite";
const char* kConnectableProperty = "Connectable";
const char* kAutoConnectProperty = "AutoConnect";
const char* kIsActiveProperty = "IsActive";
const char* kModeProperty = "Mode";
const char* kErrorProperty = "Error";
const char* kActiveProfileProperty = "ActiveProfile";
const char* kEntriesProperty = "Entries";
const char* kDevicesProperty = "Devices";
const char* kProviderProperty = "Provider";
const char* kHostProperty = "Host";
// Flimflam property names for SIMLock status.
const char* kSIMLockStatusProperty = "Cellular.SIMLockStatus";
const char* kSIMLockTypeProperty = "LockType";
const char* kSIMLockRetriesLeftProperty = "RetriesLeft";
// Flimflam property names for Cellular.FoundNetworks.
const char* kLongNameProperty = "long_name";
const char* kStatusProperty = "status";
const char* kShortNameProperty = "short_name";
const char* kTechnologyProperty = "technology";
// Flimflam SIMLock status types.
const char* kSIMLockPin = "sim-pin";
const char* kSIMLockPuk = "sim-puk";
// APN info property names.
const char* kApnProperty = "apn";
const char* kNetworkIdProperty = "network_id";
const char* kUsernameProperty = "username";
const char* kPasswordProperty = "password";
// Flimflam device info property names.
const char* kScanningProperty = "Scanning";
const char* kCarrierProperty = "Cellular.Carrier";
const char* kHomeProviderProperty = "Cellular.HomeProvider";
const char* kMeidProperty = "Cellular.MEID";
const char* kImeiProperty = "Cellular.IMEI";
const char* kImsiProperty = "Cellular.IMSI";
const char* kEsnProperty = "Cellular.ESN";
const char* kMdnProperty = "Cellular.MDN";
const char* kMinProperty = "Cellular.MIN";
const char* kModelIDProperty = "Cellular.ModelID";
const char* kManufacturerProperty = "Cellular.Manufacturer";
const char* kFirmwareRevisionProperty = "Cellular.FirmwareRevision";
const char* kHardwareRevisionProperty = "Cellular.HardwareRevision";
const char* kLastDeviceUpdateProperty = "Cellular.LastDeviceUpdate";
const char* kPRLVersionProperty = "Cellular.PRLVersion"; // (INT16)
const char* kSelectedNetworkProperty = "Cellular.SelectedNetwork";
const char* kFoundNetworksProperty = "Cellular.FoundNetworks";
// Flimflam type options.
const char* kTypeEthernet = "ethernet";
const char* kTypeWifi = "wifi";
const char* kTypeWimax = "wimax";
const char* kTypeBluetooth = "bluetooth";
const char* kTypeCellular = "cellular";
const char* kTypeVPN = "vpn";
// Flimflam mode options.
const char* kModeManaged = "managed";
const char* kModeAdhoc = "adhoc";
// Flimflam security options.
const char* kSecurityWpa = "wpa";
const char* kSecurityWep = "wep";
const char* kSecurityRsn = "rsn";
const char* kSecurity8021x = "802_1x";
const char* kSecurityPsk = "psk";
const char* kSecurityNone = "none";
// Flimflam L2TPIPsec property names.
const char* kL2TPIPSecCACertProperty = "L2TPIPsec.CACert";
const char* kL2TPIPSecCertProperty = "L2TPIPsec.Cert";
const char* kL2TPIPSecKeyProperty = "L2TPIPsec.Key";
const char* kL2TPIPSecPSKProperty = "L2TPIPsec.PSK";
const char* kL2TPIPSecUserProperty = "L2TPIPsec.User";
const char* kL2TPIPSecPasswordProperty = "L2TPIPsec.Password";
// Flimflam EAP property names.
// See src/third_party/flimflam/doc/service-api.txt.
const char* kEapIdentityProperty = "EAP.Identity";
const char* kEapMethodProperty = "EAP.EAP";
const char* kEapPhase2AuthProperty = "EAP.InnerEAP";
const char* kEapAnonymousIdentityProperty = "EAP.AnonymousIdentity";
const char* kEapClientCertProperty = "EAP.ClientCert"; // path
const char* kEapCertIDProperty = "EAP.CertID"; // PKCS#11 ID
const char* kEapClientCertNssProperty = "EAP.ClientCertNSS"; // NSS nickname
const char* kEapPrivateKeyProperty = "EAP.PrivateKey";
const char* kEapPrivateKeyPasswordProperty = "EAP.PrivateKeyPassword";
const char* kEapKeyIDProperty = "EAP.KeyID";
const char* kEapCaCertProperty = "EAP.CACert"; // server CA cert path
const char* kEapCaCertIDProperty = "EAP.CACertID"; // server CA PKCS#11 ID
const char* kEapCaCertNssProperty = "EAP.CACertNSS"; // server CA NSS nickname
const char* kEapUseSystemCAsProperty = "EAP.UseSystemCAs";
const char* kEapPinProperty = "EAP.PIN";
const char* kEapPasswordProperty = "EAP.Password";
const char* kEapKeyMgmtProperty = "EAP.KeyMgmt";
// Flimflam EAP method options.
const std::string& kEapMethodPEAP = "PEAP";
const std::string& kEapMethodTLS = "TLS";
const std::string& kEapMethodTTLS = "TTLS";
const std::string& kEapMethodLEAP = "LEAP";
// Flimflam EAP phase 2 auth options.
const std::string& kEapPhase2AuthPEAPMD5 = "auth=MD5";
const std::string& kEapPhase2AuthPEAPMSCHAPV2 = "auth=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMD5 = "autheap=MD5";
const std::string& kEapPhase2AuthTTLSMSCHAPV2 = "autheap=MSCHAPV2";
const std::string& kEapPhase2AuthTTLSMSCHAP = "autheap=MSCHAP";
const std::string& kEapPhase2AuthTTLSPAP = "autheap=PAP";
const std::string& kEapPhase2AuthTTLSCHAP = "autheap=CHAP";
// Flimflam VPN provider types.
const char* kProviderL2tpIpsec = "l2tpipsec";
const char* kProviderOpenVpn = "openvpn";
// Flimflam state options.
const char* kStateIdle = "idle";
const char* kStateCarrier = "carrier";
const char* kStateAssociation = "association";
const char* kStateConfiguration = "configuration";
const char* kStateReady = "ready";
const char* kStateDisconnect = "disconnect";
const char* kStateFailure = "failure";
const char* kStateActivationFailure = "activation-failure";
// Flimflam connectivity state options.
const char* kConnStateUnrestricted = "unrestricted";
const char* kConnStateRestricted = "restricted";
const char* kConnStateNone = "none";
// Flimflam network technology options.
const char* kNetworkTechnology1Xrtt = "1xRTT";
const char* kNetworkTechnologyEvdo = "EVDO";
const char* kNetworkTechnologyGprs = "GPRS";
const char* kNetworkTechnologyEdge = "EDGE";
const char* kNetworkTechnologyUmts = "UMTS";
const char* kNetworkTechnologyHspa = "HSPA";
const char* kNetworkTechnologyHspaPlus = "HSPA+";
const char* kNetworkTechnologyLte = "LTE";
const char* kNetworkTechnologyLteAdvanced = "LTE Advanced";
// Flimflam roaming state options
const char* kRoamingStateHome = "home";
const char* kRoamingStateRoaming = "roaming";
const char* kRoamingStateUnknown = "unknown";
// Flimflam activation state options
const char* kActivationStateActivated = "activated";
const char* kActivationStateActivating = "activating";
const char* kActivationStateNotActivated = "not-activated";
const char* kActivationStatePartiallyActivated = "partially-activated";
const char* kActivationStateUnknown = "unknown";
// Flimflam error options.
const char* kErrorOutOfRange = "out-of-range";
const char* kErrorPinMissing = "pin-missing";
const char* kErrorDhcpFailed = "dhcp-failed";
const char* kErrorConnectFailed = "connect-failed";
const char* kErrorBadPassphrase = "bad-passphrase";
const char* kErrorBadWEPKey = "bad-wepkey";
const char* kErrorActivationFailed = "activation-failed";
const char* kErrorNeedEvdo = "need-evdo";
const char* kErrorNeedHomeNetwork = "need-home-network";
const char* kErrorOtaspFailed = "otasp-failed";
const char* kErrorAaaFailed = "aaa-failed";
// Flimflam error messages.
const char* kErrorPassphraseRequiredMsg = "Passphrase required";
const char* kErrorIncorrectPinMsg = "org.chromium.flimflam.Device.IncorrectPin";
const char* kErrorPinBlockedMsg = "org.chromium.flimflam.Device.PinBlocked";
const char* kErrorPinRequiredMsg = "org.chromium.flimflam.Device.PinRequired";
const char* kUnknownString = "UNKNOWN";
////////////////////////////////////////////////////////////////////////////
static const char* ConnectionTypeToString(ConnectionType type) {
switch (type) {
case TYPE_UNKNOWN:
break;
case TYPE_ETHERNET:
return kTypeEthernet;
case TYPE_WIFI:
return kTypeWifi;
case TYPE_WIMAX:
return kTypeWimax;
case TYPE_BLUETOOTH:
return kTypeBluetooth;
case TYPE_CELLULAR:
return kTypeCellular;
case TYPE_VPN:
return kTypeVPN;
}
LOG(ERROR) << "ConnectionTypeToString called with unknown type: " << type;
return kUnknownString;
}
// TODO(stevenjb/njw): Deprecate in favor of setting EAP properties.
static const char* SecurityToString(ConnectionSecurity security) {
switch (security) {
case SECURITY_NONE:
return kSecurityNone;
case SECURITY_WEP:
return kSecurityWep;
case SECURITY_WPA:
return kSecurityWpa;
case SECURITY_RSN:
return kSecurityRsn;
case SECURITY_8021X:
return kSecurity8021x;
case SECURITY_PSK:
return kSecurityPsk;
case SECURITY_UNKNOWN:
break;
}
LOG(ERROR) << "SecurityToString called with unknown type: " << security;
return kUnknownString;
}
static const char* ProviderTypeToString(VirtualNetwork::ProviderType type) {
switch (type) {
case VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK:
case VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
return kProviderL2tpIpsec;
case VirtualNetwork::PROVIDER_TYPE_OPEN_VPN:
return kProviderOpenVpn;
case VirtualNetwork::PROVIDER_TYPE_MAX:
break;
}
LOG(ERROR) << "ProviderTypeToString called with unknown type: " << type;
return kUnknownString;
}
////////////////////////////////////////////////////////////////////////////
// Helper class to cache maps of strings to enums.
template <typename Type>
class StringToEnum {
public:
struct Pair {
const char* key;
const Type value;
};
explicit StringToEnum(const Pair* list, size_t num_entries, Type unknown)
: unknown_value_(unknown) {
for (size_t i = 0; i < num_entries; ++i, ++list)
enum_map_[list->key] = list->value;
}
Type Get(const std::string& type) const {
EnumMapConstIter iter = enum_map_.find(type);
if (iter != enum_map_.end())
return iter->second;
return unknown_value_;
}
private:
typedef typename std::map<std::string, Type> EnumMap;
typedef typename std::map<std::string, Type>::const_iterator EnumMapConstIter;
EnumMap enum_map_;
Type unknown_value_;
DISALLOW_COPY_AND_ASSIGN(StringToEnum);
};
////////////////////////////////////////////////////////////////////////////
enum PropertyIndex {
PROPERTY_INDEX_ACTIVATION_STATE,
PROPERTY_INDEX_ACTIVE_PROFILE,
PROPERTY_INDEX_AUTO_CONNECT,
PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES,
PROPERTY_INDEX_CARRIER,
PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING,
PROPERTY_INDEX_CELLULAR_APN,
PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN,
PROPERTY_INDEX_CERT_PATH,
PROPERTY_INDEX_CONNECTABLE,
PROPERTY_INDEX_CONNECTED_TECHNOLOGIES,
PROPERTY_INDEX_CONNECTIVITY_STATE,
PROPERTY_INDEX_DEFAULT_TECHNOLOGY,
PROPERTY_INDEX_DEVICE,
PROPERTY_INDEX_DEVICES,
PROPERTY_INDEX_EAP_IDENTITY,
PROPERTY_INDEX_EAP_METHOD,
PROPERTY_INDEX_EAP_PHASE_2_AUTH,
PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY,
PROPERTY_INDEX_EAP_CLIENT_CERT,
PROPERTY_INDEX_EAP_CERT_ID,
PROPERTY_INDEX_EAP_CLIENT_CERT_NSS,
PROPERTY_INDEX_EAP_PRIVATE_KEY,
PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD,
PROPERTY_INDEX_EAP_KEY_ID,
PROPERTY_INDEX_EAP_CA_CERT,
PROPERTY_INDEX_EAP_CA_CERT_ID,
PROPERTY_INDEX_EAP_CA_CERT_NSS,
PROPERTY_INDEX_EAP_USE_SYSTEM_CAS,
PROPERTY_INDEX_EAP_PIN,
PROPERTY_INDEX_EAP_PASSWORD,
PROPERTY_INDEX_EAP_KEY_MGMT,
PROPERTY_INDEX_ENABLED_TECHNOLOGIES,
PROPERTY_INDEX_ERROR,
PROPERTY_INDEX_ESN,
PROPERTY_INDEX_FAVORITE,
PROPERTY_INDEX_FIRMWARE_REVISION,
PROPERTY_INDEX_FOUND_NETWORKS,
PROPERTY_INDEX_HARDWARE_REVISION,
PROPERTY_INDEX_HOME_PROVIDER,
PROPERTY_INDEX_HOST,
PROPERTY_INDEX_IDENTITY,
PROPERTY_INDEX_IMEI,
PROPERTY_INDEX_IMSI,
PROPERTY_INDEX_IS_ACTIVE,
PROPERTY_INDEX_LAST_DEVICE_UPDATE,
PROPERTY_INDEX_L2TPIPSEC_CA_CERT,
PROPERTY_INDEX_L2TPIPSEC_CERT,
PROPERTY_INDEX_L2TPIPSEC_KEY,
PROPERTY_INDEX_L2TPIPSEC_PASSWORD,
PROPERTY_INDEX_L2TPIPSEC_PSK,
PROPERTY_INDEX_L2TPIPSEC_USER,
PROPERTY_INDEX_MANUFACTURER,
PROPERTY_INDEX_MDN,
PROPERTY_INDEX_MEID,
PROPERTY_INDEX_MIN,
PROPERTY_INDEX_MODE,
PROPERTY_INDEX_MODEL_ID,
PROPERTY_INDEX_NAME,
PROPERTY_INDEX_NETWORK_TECHNOLOGY,
PROPERTY_INDEX_OFFLINE_MODE,
PROPERTY_INDEX_OPERATOR_CODE,
PROPERTY_INDEX_OPERATOR_NAME,
PROPERTY_INDEX_PASSPHRASE,
PROPERTY_INDEX_PASSPHRASE_REQUIRED,
PROPERTY_INDEX_PAYMENT_URL,
PROPERTY_INDEX_PRL_VERSION,
PROPERTY_INDEX_PROFILES,
PROPERTY_INDEX_PROVIDER,
PROPERTY_INDEX_ROAMING_STATE,
PROPERTY_INDEX_SAVE_CREDENTIALS,
PROPERTY_INDEX_SCANNING,
PROPERTY_INDEX_SECURITY,
PROPERTY_INDEX_SELECTED_NETWORK,
PROPERTY_INDEX_SERVICES,
PROPERTY_INDEX_SERVICE_WATCH_LIST,
PROPERTY_INDEX_SIGNAL_STRENGTH,
PROPERTY_INDEX_SIM_LOCK,
PROPERTY_INDEX_STATE,
PROPERTY_INDEX_TYPE,
PROPERTY_INDEX_UNKNOWN,
PROPERTY_INDEX_USAGE_URL,
};
StringToEnum<PropertyIndex>::Pair property_index_table[] = {
{ kActivationStateProperty, PROPERTY_INDEX_ACTIVATION_STATE },
{ kActiveProfileProperty, PROPERTY_INDEX_ACTIVE_PROFILE },
{ kAutoConnectProperty, PROPERTY_INDEX_AUTO_CONNECT },
{ kAvailableTechnologiesProperty, PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES },
{ kCellularAllowRoamingProperty, PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING },
{ kCellularApnProperty, PROPERTY_INDEX_CELLULAR_APN },
{ kCellularLastGoodApnProperty, PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN },
{ kCarrierProperty, PROPERTY_INDEX_CARRIER },
{ kCertPathProperty, PROPERTY_INDEX_CERT_PATH },
{ kConnectableProperty, PROPERTY_INDEX_CONNECTABLE },
{ kConnectedTechnologiesProperty, PROPERTY_INDEX_CONNECTED_TECHNOLOGIES },
{ kConnectivityStateProperty, PROPERTY_INDEX_CONNECTIVITY_STATE },
{ kDefaultTechnologyProperty, PROPERTY_INDEX_DEFAULT_TECHNOLOGY },
{ kDeviceProperty, PROPERTY_INDEX_DEVICE },
{ kDevicesProperty, PROPERTY_INDEX_DEVICES },
{ kEapIdentityProperty, PROPERTY_INDEX_EAP_IDENTITY },
{ kEapMethodProperty, PROPERTY_INDEX_EAP_METHOD },
{ kEapPhase2AuthProperty, PROPERTY_INDEX_EAP_PHASE_2_AUTH },
{ kEapAnonymousIdentityProperty, PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY },
{ kEapClientCertProperty, PROPERTY_INDEX_EAP_CLIENT_CERT },
{ kEapCertIDProperty, PROPERTY_INDEX_EAP_CERT_ID },
{ kEapClientCertNssProperty, PROPERTY_INDEX_EAP_CLIENT_CERT_NSS },
{ kEapPrivateKeyProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY },
{ kEapPrivateKeyPasswordProperty, PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD },
{ kEapKeyIDProperty, PROPERTY_INDEX_EAP_KEY_ID },
{ kEapCaCertProperty, PROPERTY_INDEX_EAP_CA_CERT },
{ kEapCaCertIDProperty, PROPERTY_INDEX_EAP_CA_CERT_ID },
{ kEapCaCertNssProperty, PROPERTY_INDEX_EAP_CA_CERT_NSS },
{ kEapUseSystemCAsProperty, PROPERTY_INDEX_EAP_USE_SYSTEM_CAS },
{ kEapPinProperty, PROPERTY_INDEX_EAP_PIN },
{ kEapPasswordProperty, PROPERTY_INDEX_EAP_PASSWORD },
{ kEapKeyMgmtProperty, PROPERTY_INDEX_EAP_KEY_MGMT },
{ kEnabledTechnologiesProperty, PROPERTY_INDEX_ENABLED_TECHNOLOGIES },
{ kErrorProperty, PROPERTY_INDEX_ERROR },
{ kEsnProperty, PROPERTY_INDEX_ESN },
{ kFavoriteProperty, PROPERTY_INDEX_FAVORITE },
{ kFirmwareRevisionProperty, PROPERTY_INDEX_FIRMWARE_REVISION },
{ kFoundNetworksProperty, PROPERTY_INDEX_FOUND_NETWORKS },
{ kHardwareRevisionProperty, PROPERTY_INDEX_HARDWARE_REVISION },
{ kHomeProviderProperty, PROPERTY_INDEX_HOME_PROVIDER },
{ kHostProperty, PROPERTY_INDEX_HOST },
{ kIdentityProperty, PROPERTY_INDEX_IDENTITY },
{ kImeiProperty, PROPERTY_INDEX_IMEI },
{ kImsiProperty, PROPERTY_INDEX_IMSI },
{ kIsActiveProperty, PROPERTY_INDEX_IS_ACTIVE },
{ kL2TPIPSecCACertProperty, PROPERTY_INDEX_L2TPIPSEC_CA_CERT },
{ kL2TPIPSecCertProperty, PROPERTY_INDEX_L2TPIPSEC_CERT },
{ kL2TPIPSecKeyProperty, PROPERTY_INDEX_L2TPIPSEC_KEY },
{ kL2TPIPSecPasswordProperty, PROPERTY_INDEX_L2TPIPSEC_PASSWORD },
{ kL2TPIPSecPSKProperty, PROPERTY_INDEX_L2TPIPSEC_PSK },
{ kL2TPIPSecUserProperty, PROPERTY_INDEX_L2TPIPSEC_USER },
{ kLastDeviceUpdateProperty, PROPERTY_INDEX_LAST_DEVICE_UPDATE },
{ kManufacturerProperty, PROPERTY_INDEX_MANUFACTURER },
{ kMdnProperty, PROPERTY_INDEX_MDN },
{ kMeidProperty, PROPERTY_INDEX_MEID },
{ kMinProperty, PROPERTY_INDEX_MIN },
{ kModeProperty, PROPERTY_INDEX_MODE },
{ kModelIDProperty, PROPERTY_INDEX_MODEL_ID },
{ kNameProperty, PROPERTY_INDEX_NAME },
{ kNetworkTechnologyProperty, PROPERTY_INDEX_NETWORK_TECHNOLOGY },
{ kOfflineModeProperty, PROPERTY_INDEX_OFFLINE_MODE },
{ kOperatorCodeProperty, PROPERTY_INDEX_OPERATOR_CODE },
{ kOperatorNameProperty, PROPERTY_INDEX_OPERATOR_NAME },
{ kPRLVersionProperty, PROPERTY_INDEX_PRL_VERSION },
{ kPassphraseProperty, PROPERTY_INDEX_PASSPHRASE },
{ kPassphraseRequiredProperty, PROPERTY_INDEX_PASSPHRASE_REQUIRED },
{ kPaymentURLProperty, PROPERTY_INDEX_PAYMENT_URL },
{ kProfilesProperty, PROPERTY_INDEX_PROFILES },
{ kProviderProperty, PROPERTY_INDEX_PROVIDER },
{ kRoamingStateProperty, PROPERTY_INDEX_ROAMING_STATE },
{ kSaveCredentialsProperty, PROPERTY_INDEX_SAVE_CREDENTIALS },
{ kScanningProperty, PROPERTY_INDEX_SCANNING },
{ kSecurityProperty, PROPERTY_INDEX_SECURITY },
{ kSelectedNetworkProperty, PROPERTY_INDEX_SELECTED_NETWORK },
{ kServiceWatchListProperty, PROPERTY_INDEX_SERVICE_WATCH_LIST },
{ kServicesProperty, PROPERTY_INDEX_SERVICES },
{ kSignalStrengthProperty, PROPERTY_INDEX_SIGNAL_STRENGTH },
{ kSIMLockStatusProperty, PROPERTY_INDEX_SIM_LOCK },
{ kStateProperty, PROPERTY_INDEX_STATE },
{ kTypeProperty, PROPERTY_INDEX_TYPE },
{ kUsageURLProperty, PROPERTY_INDEX_USAGE_URL },
};
StringToEnum<PropertyIndex>& property_index_parser() {
static StringToEnum<PropertyIndex> parser(property_index_table,
arraysize(property_index_table),
PROPERTY_INDEX_UNKNOWN);
return parser;
}
////////////////////////////////////////////////////////////////////////////
// Parse strings from libcros.
// Network.
static ConnectionType ParseType(const std::string& type) {
static StringToEnum<ConnectionType>::Pair table[] = {
{ kTypeEthernet, TYPE_ETHERNET },
{ kTypeWifi, TYPE_WIFI },
{ kTypeWimax, TYPE_WIMAX },
{ kTypeBluetooth, TYPE_BLUETOOTH },
{ kTypeCellular, TYPE_CELLULAR },
{ kTypeVPN, TYPE_VPN },
};
static StringToEnum<ConnectionType> parser(
table, arraysize(table), TYPE_UNKNOWN);
return parser.Get(type);
}
ConnectionType ParseTypeFromDictionary(const DictionaryValue* info) {
std::string type_string;
info->GetString(kTypeProperty, &type_string);
return ParseType(type_string);
}
static ConnectionMode ParseMode(const std::string& mode) {
static StringToEnum<ConnectionMode>::Pair table[] = {
{ kModeManaged, MODE_MANAGED },
{ kModeAdhoc, MODE_ADHOC },
};
static StringToEnum<ConnectionMode> parser(
table, arraysize(table), MODE_UNKNOWN);
return parser.Get(mode);
}
static ConnectionState ParseState(const std::string& state) {
static StringToEnum<ConnectionState>::Pair table[] = {
{ kStateIdle, STATE_IDLE },
{ kStateCarrier, STATE_CARRIER },
{ kStateAssociation, STATE_ASSOCIATION },
{ kStateConfiguration, STATE_CONFIGURATION },
{ kStateReady, STATE_READY },
{ kStateDisconnect, STATE_DISCONNECT },
{ kStateFailure, STATE_FAILURE },
{ kStateActivationFailure, STATE_ACTIVATION_FAILURE },
};
static StringToEnum<ConnectionState> parser(
table, arraysize(table), STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectionError ParseError(const std::string& error) {
static StringToEnum<ConnectionError>::Pair table[] = {
{ kErrorOutOfRange, ERROR_OUT_OF_RANGE },
{ kErrorPinMissing, ERROR_PIN_MISSING },
{ kErrorDhcpFailed, ERROR_DHCP_FAILED },
{ kErrorConnectFailed, ERROR_CONNECT_FAILED },
{ kErrorBadPassphrase, ERROR_BAD_PASSPHRASE },
{ kErrorBadWEPKey, ERROR_BAD_WEPKEY },
{ kErrorActivationFailed, ERROR_ACTIVATION_FAILED },
{ kErrorNeedEvdo, ERROR_NEED_EVDO },
{ kErrorNeedHomeNetwork, ERROR_NEED_HOME_NETWORK },
{ kErrorOtaspFailed, ERROR_OTASP_FAILED },
{ kErrorAaaFailed, ERROR_AAA_FAILED },
};
static StringToEnum<ConnectionError> parser(
table, arraysize(table), ERROR_UNKNOWN);
return parser.Get(error);
}
// VirtualNetwork
static VirtualNetwork::ProviderType ParseProviderType(const std::string& mode) {
static StringToEnum<VirtualNetwork::ProviderType>::Pair table[] = {
{ kProviderL2tpIpsec, VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK },
{ kProviderOpenVpn, VirtualNetwork::PROVIDER_TYPE_OPEN_VPN },
};
static StringToEnum<VirtualNetwork::ProviderType> parser(
table, arraysize(table), VirtualNetwork::PROVIDER_TYPE_MAX);
return parser.Get(mode);
}
// CellularNetwork.
static ActivationState ParseActivationState(const std::string& state) {
static StringToEnum<ActivationState>::Pair table[] = {
{ kActivationStateActivated, ACTIVATION_STATE_ACTIVATED },
{ kActivationStateActivating, ACTIVATION_STATE_ACTIVATING },
{ kActivationStateNotActivated, ACTIVATION_STATE_NOT_ACTIVATED },
{ kActivationStatePartiallyActivated, ACTIVATION_STATE_PARTIALLY_ACTIVATED},
{ kActivationStateUnknown, ACTIVATION_STATE_UNKNOWN},
};
static StringToEnum<ActivationState> parser(
table, arraysize(table), ACTIVATION_STATE_UNKNOWN);
return parser.Get(state);
}
static ConnectivityState ParseConnectivityState(const std::string& state) {
static StringToEnum<ConnectivityState>::Pair table[] = {
{ kConnStateUnrestricted, CONN_STATE_UNRESTRICTED },
{ kConnStateRestricted, CONN_STATE_RESTRICTED },
{ kConnStateNone, CONN_STATE_NONE },
};
static StringToEnum<ConnectivityState> parser(
table, arraysize(table), CONN_STATE_UNKNOWN);
return parser.Get(state);
}
static NetworkTechnology ParseNetworkTechnology(const std::string& technology) {
static StringToEnum<NetworkTechnology>::Pair table[] = {
{ kNetworkTechnology1Xrtt, NETWORK_TECHNOLOGY_1XRTT },
{ kNetworkTechnologyEvdo, NETWORK_TECHNOLOGY_EVDO },
{ kNetworkTechnologyGprs, NETWORK_TECHNOLOGY_GPRS },
{ kNetworkTechnologyEdge, NETWORK_TECHNOLOGY_EDGE },
{ kNetworkTechnologyUmts, NETWORK_TECHNOLOGY_UMTS },
{ kNetworkTechnologyHspa, NETWORK_TECHNOLOGY_HSPA },
{ kNetworkTechnologyHspaPlus, NETWORK_TECHNOLOGY_HSPA_PLUS },
{ kNetworkTechnologyLte, NETWORK_TECHNOLOGY_LTE },
{ kNetworkTechnologyLteAdvanced, NETWORK_TECHNOLOGY_LTE_ADVANCED },
};
static StringToEnum<NetworkTechnology> parser(
table, arraysize(table), NETWORK_TECHNOLOGY_UNKNOWN);
return parser.Get(technology);
}
static SIMLockState ParseSimLockState(const std::string& state) {
static StringToEnum<SIMLockState>::Pair table[] = {
{ "", SIM_UNLOCKED },
{ kSIMLockPin, SIM_LOCKED_PIN },
{ kSIMLockPuk, SIM_LOCKED_PUK },
};
static StringToEnum<SIMLockState> parser(
table, arraysize(table), SIM_UNKNOWN);
SIMLockState parsed_state = parser.Get(state);
DCHECK(parsed_state != SIM_UNKNOWN) << "Unknown SIMLock state encountered";
return parsed_state;
}
static bool ParseSimLockStateFromDictionary(const DictionaryValue* info,
SIMLockState* out_state,
int* out_retries) {
std::string state_string;
if (!info->GetString(kSIMLockTypeProperty, &state_string) ||
!info->GetInteger(kSIMLockRetriesLeftProperty, out_retries)) {
LOG(ERROR) << "Error parsing SIMLock state";
return false;
}
*out_state = ParseSimLockState(state_string);
return true;
}
static bool ParseFoundNetworksFromList(const ListValue* list,
CellularNetworkList* found_networks_) {
found_networks_->clear();
found_networks_->reserve(list->GetSize());
for (ListValue::const_iterator it = list->begin(); it != list->end(); ++it) {
if ((*it)->IsType(Value::TYPE_DICTIONARY)) {
found_networks_->resize(found_networks_->size() + 1);
DictionaryValue* dict = static_cast<const DictionaryValue*>(*it);
dict->GetStringWithoutPathExpansion(
kStatusProperty, &found_networks_->back().status);
dict->GetStringWithoutPathExpansion(
kNetworkIdProperty, &found_networks_->back().network_id);
dict->GetStringWithoutPathExpansion(
kShortNameProperty, &found_networks_->back().short_name);
dict->GetStringWithoutPathExpansion(
kLongNameProperty, &found_networks_->back().long_name);
dict->GetStringWithoutPathExpansion(
kTechnologyProperty, &found_networks_->back().technology);
} else {
return false;
}
}
return true;
}
static NetworkRoamingState ParseRoamingState(const std::string& roaming_state) {
static StringToEnum<NetworkRoamingState>::Pair table[] = {
{ kRoamingStateHome, ROAMING_STATE_HOME },
{ kRoamingStateRoaming, ROAMING_STATE_ROAMING },
{ kRoamingStateUnknown, ROAMING_STATE_UNKNOWN },
};
static StringToEnum<NetworkRoamingState> parser(
table, arraysize(table), ROAMING_STATE_UNKNOWN);
return parser.Get(roaming_state);
}
// WifiNetwork
static ConnectionSecurity ParseSecurity(const std::string& security) {
static StringToEnum<ConnectionSecurity>::Pair table[] = {
{ kSecurityNone, SECURITY_NONE },
{ kSecurityWep, SECURITY_WEP },
{ kSecurityWpa, SECURITY_WPA },
{ kSecurityRsn, SECURITY_RSN },
{ kSecurityPsk, SECURITY_PSK },
{ kSecurity8021x, SECURITY_8021X },
};
static StringToEnum<ConnectionSecurity> parser(
table, arraysize(table), SECURITY_UNKNOWN);
return parser.Get(security);
}
static EAPMethod ParseEAPMethod(const std::string& method) {
static StringToEnum<EAPMethod>::Pair table[] = {
{ kEapMethodPEAP.c_str(), EAP_METHOD_PEAP },
{ kEapMethodTLS.c_str(), EAP_METHOD_TLS },
{ kEapMethodTTLS.c_str(), EAP_METHOD_TTLS },
{ kEapMethodLEAP.c_str(), EAP_METHOD_LEAP },
};
static StringToEnum<EAPMethod> parser(
table, arraysize(table), EAP_METHOD_UNKNOWN);
return parser.Get(method);
}
static EAPPhase2Auth ParseEAPPhase2Auth(const std::string& auth) {
static StringToEnum<EAPPhase2Auth>::Pair table[] = {
{ kEapPhase2AuthPEAPMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthPEAPMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMD5.c_str(), EAP_PHASE_2_AUTH_MD5 },
{ kEapPhase2AuthTTLSMSCHAPV2.c_str(), EAP_PHASE_2_AUTH_MSCHAPV2 },
{ kEapPhase2AuthTTLSMSCHAP.c_str(), EAP_PHASE_2_AUTH_MSCHAP },
{ kEapPhase2AuthTTLSPAP.c_str(), EAP_PHASE_2_AUTH_PAP },
{ kEapPhase2AuthTTLSCHAP.c_str(), EAP_PHASE_2_AUTH_CHAP },
};
static StringToEnum<EAPPhase2Auth> parser(
table, arraysize(table), EAP_PHASE_2_AUTH_AUTO);
return parser.Get(auth);
}
////////////////////////////////////////////////////////////////////////////////
// Misc.
// Safe string constructor since we can't rely on non NULL pointers
// for string values from libcros.
static std::string SafeString(const char* s) {
return s ? std::string(s) : std::string();
}
// Erase the memory used by a string, then clear it.
static void WipeString(std::string* str) {
str->assign(str->size(), '\0');
str->clear();
}
static bool EnsureCrosLoaded() {
if (!CrosLibrary::Get()->EnsureLoaded()) {
return false;
} else {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "chromeos_library calls made from non UI thread!";
NOTREACHED();
}
return true;
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// NetworkDevice
NetworkDevice::NetworkDevice(const std::string& device_path)
: device_path_(device_path),
type_(TYPE_UNKNOWN),
scanning_(false),
sim_lock_state_(SIM_UNKNOWN),
sim_retries_left_(kDefaultSimUnlockRetriesCount),
sim_pin_required_(SIM_PIN_REQUIRE_UNKNOWN),
PRL_version_(0),
data_roaming_allowed_(false) {
}
bool NetworkDevice::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
type_ = ParseType(type_string);
return true;
}
break;
}
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_SCANNING:
return value->GetAsBoolean(&scanning_);
case PROPERTY_INDEX_CARRIER:
return value->GetAsString(&carrier_);
case PROPERTY_INDEX_FOUND_NETWORKS:
if (value->IsType(Value::TYPE_LIST)) {
return ParseFoundNetworksFromList(
static_cast<const ListValue*>(value),
&found_cellular_networks_);
}
break;
case PROPERTY_INDEX_HOME_PROVIDER:
return value->GetAsString(&home_provider_);
case PROPERTY_INDEX_MEID:
return value->GetAsString(&MEID_);
case PROPERTY_INDEX_IMEI:
return value->GetAsString(&IMEI_);
case PROPERTY_INDEX_IMSI:
return value->GetAsString(&IMSI_);
case PROPERTY_INDEX_ESN:
return value->GetAsString(&ESN_);
case PROPERTY_INDEX_MDN:
return value->GetAsString(&MDN_);
case PROPERTY_INDEX_MIN:
return value->GetAsString(&MIN_);
case PROPERTY_INDEX_MODEL_ID:
return value->GetAsString(&model_id_);
case PROPERTY_INDEX_MANUFACTURER:
return value->GetAsString(&manufacturer_);
case PROPERTY_INDEX_SIM_LOCK:
if (value->IsType(Value::TYPE_DICTIONARY)) {
bool result = ParseSimLockStateFromDictionary(
static_cast<const DictionaryValue*>(value),
&sim_lock_state_,
&sim_retries_left_);
// Initialize PinRequired value only once.
// See SIMPinRequire enum comments.
if (sim_pin_required_ == SIM_PIN_REQUIRE_UNKNOWN) {
if (sim_lock_state_ == SIM_UNLOCKED) {
sim_pin_required_ = SIM_PIN_NOT_REQUIRED;
} else if (sim_lock_state_ == SIM_LOCKED_PIN ||
sim_lock_state_ == SIM_LOCKED_PUK) {
sim_pin_required_ = SIM_PIN_REQUIRED;
}
}
return result;
}
break;
case PROPERTY_INDEX_FIRMWARE_REVISION:
return value->GetAsString(&firmware_revision_);
case PROPERTY_INDEX_HARDWARE_REVISION:
return value->GetAsString(&hardware_revision_);
case PROPERTY_INDEX_LAST_DEVICE_UPDATE:
return value->GetAsString(&last_update_);
case PROPERTY_INDEX_PRL_VERSION:
return value->GetAsInteger(&PRL_version_);
case PROPERTY_INDEX_SELECTED_NETWORK:
return value->GetAsString(&selected_cellular_network_);
case PROPERTY_INDEX_CELLULAR_ALLOW_ROAMING:
return value->GetAsBoolean(&data_roaming_allowed_);
default:
break;
}
return false;
}
void NetworkDevice::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseValue(index, value))
VLOG(1) << "NetworkDevice: Unhandled key: " << key;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Network
void Network::SetState(ConnectionState new_state) {
if (new_state == state_)
return;
state_ = new_state;
if (new_state == STATE_FAILURE) {
// The user needs to be notified of this failure.
notify_failure_ = true;
} else {
// State changed, so refresh IP address.
// Note: blocking DBus call. TODO(stevenjb): refactor this.
InitIPAddress();
}
VLOG(1) << " " << name() << ".State = " << GetStateString();
}
bool Network::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_TYPE: {
std::string type_string;
if (value->GetAsString(&type_string)) {
ConnectionType type = ParseType(type_string);
LOG_IF(ERROR, type != type_)
<< "Network with mismatched type: " << service_path_
<< " " << type << " != " << type_;
return true;
}
break;
}
case PROPERTY_INDEX_DEVICE:
return value->GetAsString(&device_path_);
case PROPERTY_INDEX_NAME:
return value->GetAsString(&name_);
case PROPERTY_INDEX_STATE: {
std::string state_string;
if (value->GetAsString(&state_string)) {
SetState(ParseState(state_string));
return true;
}
break;
}
case PROPERTY_INDEX_MODE: {
std::string mode_string;
if (value->GetAsString(&mode_string)) {
mode_ = ParseMode(mode_string);
return true;
}
break;
}
case PROPERTY_INDEX_ERROR: {
std::string error_string;
if (value->GetAsString(&error_string)) {
error_ = ParseError(error_string);
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTABLE:
return value->GetAsBoolean(&connectable_);
case PROPERTY_INDEX_IS_ACTIVE:
return value->GetAsBoolean(&is_active_);
case PROPERTY_INDEX_FAVORITE:
return value->GetAsBoolean(&favorite_);
case PROPERTY_INDEX_AUTO_CONNECT:
return value->GetAsBoolean(&auto_connect_);
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
std::string connectivity_state_string;
if (value->GetAsString(&connectivity_state_string)) {
connectivity_state_ = ParseConnectivityState(connectivity_state_string);
return true;
}
break;
}
default:
break;
}
return false;
}
void Network::ParseInfo(const DictionaryValue* info) {
for (DictionaryValue::key_iterator iter = info->begin_keys();
iter != info->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = info->GetWithoutPathExpansion(key, &value);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseValue(index, value)) // virtual.
VLOG(1) << "Network: " << name()
<< " Type: " << ConnectionTypeToString(type())
<< " Unhandled key: " << key;
}
}
}
void Network::SetValueProperty(const char* prop, Value* val) {
DCHECK(prop);
DCHECK(val);
if (!EnsureCrosLoaded())
return;
SetNetworkServiceProperty(service_path_.c_str(), prop, val);
}
void Network::ClearProperty(const char* prop) {
DCHECK(prop);
if (!EnsureCrosLoaded())
return;
ClearNetworkServiceProperty(service_path_.c_str(), prop);
}
void Network::SetStringProperty(
const char* prop, const std::string& str, std::string* dest) {
if (dest)
*dest = str;
scoped_ptr<Value> value(Value::CreateStringValue(str));
SetValueProperty(prop, value.get());
}
void Network::SetOrClearStringProperty(const char* prop,
const std::string& str,
std::string* dest) {
if (str.empty()) {
ClearProperty(prop);
if (dest)
dest->clear();
} else {
SetStringProperty(prop, str, dest);
}
}
void Network::SetBooleanProperty(const char* prop, bool b, bool* dest) {
if (dest)
*dest = b;
scoped_ptr<Value> value(Value::CreateBooleanValue(b));
SetValueProperty(prop, value.get());
}
void Network::SetIntegerProperty(const char* prop, int i, int* dest) {
if (dest)
*dest = i;
scoped_ptr<Value> value(Value::CreateIntegerValue(i));
SetValueProperty(prop, value.get());
}
void Network::SetAutoConnect(bool auto_connect) {
SetBooleanProperty(kAutoConnectProperty, auto_connect, &auto_connect_);
}
std::string Network::GetStateString() const {
switch (state_) {
case STATE_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN);
case STATE_IDLE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE);
case STATE_CARRIER:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER);
case STATE_ASSOCIATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION);
case STATE_CONFIGURATION:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION);
case STATE_READY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY);
case STATE_DISCONNECT:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT);
case STATE_FAILURE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE);
case STATE_ACTIVATION_FAILURE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE);
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
std::string Network::GetErrorString() const {
switch (error_) {
case ERROR_UNKNOWN:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
case ERROR_OUT_OF_RANGE:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE);
case ERROR_PIN_MISSING:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING);
case ERROR_DHCP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED);
case ERROR_CONNECT_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED);
case ERROR_BAD_PASSPHRASE:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE);
case ERROR_BAD_WEPKEY:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY);
case ERROR_ACTIVATION_FAILED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED);
case ERROR_NEED_EVDO:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO);
case ERROR_NEED_HOME_NETWORK:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK);
case ERROR_OTASP_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED);
case ERROR_AAA_FAILED:
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED);
}
return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
void Network::InitIPAddress() {
ip_address_.clear();
// If connected, get ip config.
if (EnsureCrosLoaded() && connected() && !device_path_.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path_.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0) {
ip_address_ = ipconfig.address;
break;
}
}
FreeIPConfigStatus(ipconfig_status);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// VirtualNetwork
bool VirtualNetwork::ParseProviderValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_HOST:
return value->GetAsString(&server_hostname_);
case PROPERTY_INDEX_NAME:
// Note: shadows Network::name_ property.
return value->GetAsString(&name_);
case PROPERTY_INDEX_TYPE: {
std::string provider_type_string;
if (value->GetAsString(&provider_type_string)) {
provider_type_ = ParseProviderType(provider_type_string);
return true;
}
break;
}
default:
break;
}
return false;
}
bool VirtualNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_PROVIDER: {
DCHECK_EQ(value->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(value);
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* v;
bool res = dict->GetWithoutPathExpansion(key, &v);
DCHECK(res);
if (res) {
int index = property_index_parser().Get(key);
if (!ParseProviderValue(index, v))
VLOG(1) << name() << ": Provider unhandled key: " << key
<< " Type: " << v->GetType();
}
}
return true;
}
case PROPERTY_INDEX_L2TPIPSEC_CA_CERT:
return value->GetAsString(&ca_cert_);
case PROPERTY_INDEX_L2TPIPSEC_PSK:
return value->GetAsString(&psk_passphrase_);
case PROPERTY_INDEX_L2TPIPSEC_CERT:
return value->GetAsString(&user_cert_);
case PROPERTY_INDEX_L2TPIPSEC_KEY:
return value->GetAsString(&user_cert_key_);
case PROPERTY_INDEX_L2TPIPSEC_USER:
return value->GetAsString(&username_);
case PROPERTY_INDEX_L2TPIPSEC_PASSWORD:
return value->GetAsString(&user_passphrase_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
void VirtualNetwork::ParseInfo(const DictionaryValue* info) {
Network::ParseInfo(info);
VLOG(1) << "VPN: " << name()
<< " Type: " << ProviderTypeToString(provider_type());
if (provider_type_ == PROVIDER_TYPE_L2TP_IPSEC_PSK) {
if (!user_cert_.empty())
provider_type_ = PROVIDER_TYPE_L2TP_IPSEC_USER_CERT;
}
}
bool VirtualNetwork::NeedMoreInfoToConnect() const {
if (server_hostname_.empty() || username_.empty() || user_passphrase_.empty())
return true;
switch (provider_type_) {
case PROVIDER_TYPE_L2TP_IPSEC_PSK:
if (psk_passphrase_.empty())
return true;
break;
case PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
case PROVIDER_TYPE_OPEN_VPN:
if (user_cert_.empty())
return true;
break;
case PROVIDER_TYPE_MAX:
break;
}
return false;
}
void VirtualNetwork::SetCACert(const std::string& ca_cert) {
SetStringProperty(kL2TPIPSecCACertProperty, ca_cert, &ca_cert_);
}
void VirtualNetwork::SetPSKPassphrase(const std::string& psk_passphrase) {
SetStringProperty(kL2TPIPSecPSKProperty, psk_passphrase,
&psk_passphrase_);
}
void VirtualNetwork::SetUserCert(const std::string& user_cert) {
SetStringProperty(kL2TPIPSecCertProperty, user_cert, &user_cert_);
}
void VirtualNetwork::SetUserCertKey(const std::string& key) {
SetStringProperty(kL2TPIPSecKeyProperty, key, &user_cert_key_);
}
void VirtualNetwork::SetUsername(const std::string& username) {
SetStringProperty(kL2TPIPSecUserProperty, username, &username_);
}
void VirtualNetwork::SetUserPassphrase(const std::string& user_passphrase) {
SetStringProperty(kL2TPIPSecPasswordProperty, user_passphrase,
&user_passphrase_);
}
std::string VirtualNetwork::GetProviderTypeString() const {
switch (this->provider_type_) {
case PROVIDER_TYPE_L2TP_IPSEC_PSK:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_PSK);
break;
case PROVIDER_TYPE_L2TP_IPSEC_USER_CERT:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_L2TP_IPSEC_USER_CERT);
break;
case PROVIDER_TYPE_OPEN_VPN:
return l10n_util::GetStringUTF8(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_OPEN_VPN);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WirelessNetwork
bool WirelessNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SIGNAL_STRENGTH:
return value->GetAsInteger(&strength_);
default:
return Network::ParseValue(index, value);
break;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// CellularDataPlan
string16 CellularDataPlan::GetPlanDesciption() const {
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_UNLIMITED_DATA,
base::TimeFormatFriendlyDate(plan_start_time));
break;
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PURCHASE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return l10n_util::GetStringFUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_RECEIVED_FREE_DATA,
FormatBytes(plan_data_bytes,
GetByteDisplayUnits(plan_data_bytes),
true),
base::TimeFormatFriendlyDate(plan_start_time));
default:
break;
}
}
return string16();
}
string16 CellularDataPlan::GetRemainingWarning() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
if (remaining_time().InSeconds() <= chromeos::kCellularDataVeryLowSecs) {
return GetPlanExpiration();
}
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
if (remaining_data() <= chromeos::kCellularDataVeryLowBytes) {
int64 remaining_mbytes = remaining_data() / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
}
return string16();
}
string16 CellularDataPlan::GetDataRemainingDesciption() const {
int64 remaining_bytes = remaining_data();
switch (plan_type) {
case chromeos::CELLULAR_DATA_PLAN_UNLIMITED: {
return l10n_util::GetStringUTF16(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_UNLIMITED);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_PAID: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
case chromeos::CELLULAR_DATA_PLAN_METERED_BASE: {
return FormatBytes(remaining_bytes,
GetByteDisplayUnits(remaining_bytes),
true);
}
default:
break;
}
return string16();
}
string16 CellularDataPlan::GetUsageInfo() const {
if (plan_type == chromeos::CELLULAR_DATA_PLAN_UNLIMITED) {
// Time based plan. Show nearing expiration and data expiration.
return GetPlanExpiration();
} else if (plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_PAID ||
plan_type == chromeos::CELLULAR_DATA_PLAN_METERED_BASE) {
// Metered plan. Show low data and out of data.
int64 remaining_bytes = remaining_data();
if (remaining_bytes == 0) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_NONE_AVAILABLE_MESSAGE);
} else if (remaining_bytes < 1024 * 1024) {
return l10n_util::GetStringUTF16(
IDS_NETWORK_DATA_LESS_THAN_ONE_MB_AVAILABLE_MESSAGE);
} else {
int64 remaining_mb = remaining_bytes / (1024 * 1024);
return l10n_util::GetStringFUTF16(
IDS_NETWORK_DATA_MB_AVAILABLE_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mb)));
}
}
return string16();
}
std::string CellularDataPlan::GetUniqueIdentifier() const {
// A cellular plan is uniquely described by the union of name, type,
// start time, end time, and max bytes.
// So we just return a union of all these variables.
return plan_name + "|" +
base::Int64ToString(plan_type) + "|" +
base::Int64ToString(plan_start_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_end_time.ToInternalValue()) + "|" +
base::Int64ToString(plan_data_bytes);
}
base::TimeDelta CellularDataPlan::remaining_time() const {
base::TimeDelta time = plan_end_time - base::Time::Now();
return time.InMicroseconds() < 0 ? base::TimeDelta() : time;
}
int64 CellularDataPlan::remaining_minutes() const {
return remaining_time().InMinutes();
}
int64 CellularDataPlan::remaining_data() const {
int64 data = plan_data_bytes - data_bytes_used;
return data < 0 ? 0 : data;
}
string16 CellularDataPlan::GetPlanExpiration() const {
return TimeFormat::TimeRemaining(remaining_time());
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork::Apn
void CellularNetwork::Apn::Set(const DictionaryValue& dict) {
if (!dict.GetStringWithoutPathExpansion(kApnProperty, &apn))
apn.clear();
if (!dict.GetStringWithoutPathExpansion(kNetworkIdProperty, &network_id))
network_id.clear();
if (!dict.GetStringWithoutPathExpansion(kUsernameProperty, &username))
username.clear();
if (!dict.GetStringWithoutPathExpansion(kPasswordProperty, &password))
password.clear();
}
////////////////////////////////////////////////////////////////////////////////
// CellularNetwork
CellularNetwork::~CellularNetwork() {
}
bool CellularNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_ACTIVATION_STATE: {
std::string activation_state_string;
if (value->GetAsString(&activation_state_string)) {
ActivationState prev_state = activation_state_;
activation_state_ = ParseActivationState(activation_state_string);
if (activation_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CELLULAR_APN: {
if (value->IsType(Value::TYPE_DICTIONARY)) {
apn_.Set(*static_cast<const DictionaryValue*>(value));
return true;
}
break;
}
case PROPERTY_INDEX_CELLULAR_LAST_GOOD_APN: {
if (value->IsType(Value::TYPE_DICTIONARY)) {
last_good_apn_.Set(*static_cast<const DictionaryValue*>(value));
return true;
}
break;
}
case PROPERTY_INDEX_NETWORK_TECHNOLOGY: {
std::string network_technology_string;
if (value->GetAsString(&network_technology_string)) {
network_technology_ = ParseNetworkTechnology(network_technology_string);
return true;
}
break;
}
case PROPERTY_INDEX_ROAMING_STATE: {
std::string roaming_state_string;
if (value->GetAsString(&roaming_state_string)) {
roaming_state_ = ParseRoamingState(roaming_state_string);
return true;
}
break;
}
case PROPERTY_INDEX_OPERATOR_NAME:
return value->GetAsString(&operator_name_);
case PROPERTY_INDEX_OPERATOR_CODE:
return value->GetAsString(&operator_code_);
case PROPERTY_INDEX_PAYMENT_URL:
return value->GetAsString(&payment_url_);
case PROPERTY_INDEX_USAGE_URL:
return value->GetAsString(&usage_url_);
case PROPERTY_INDEX_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectionState prev_state = state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
case PROPERTY_INDEX_CONNECTIVITY_STATE: {
// Save previous state before calling WirelessNetwork::ParseValue.
ConnectivityState prev_state = connectivity_state_;
if (WirelessNetwork::ParseValue(index, value)) {
if (connectivity_state_ != prev_state)
RefreshDataPlansIfNeeded();
return true;
}
break;
}
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
bool CellularNetwork::StartActivation() const {
if (!EnsureCrosLoaded())
return false;
return ActivateCellularModem(service_path().c_str(), NULL);
}
void CellularNetwork::RefreshDataPlansIfNeeded() const {
if (!EnsureCrosLoaded())
return;
if (connected() && activated())
RequestCellularDataPlanUpdate(service_path().c_str());
}
void CellularNetwork::SetApn(const Apn& apn) {
if (!EnsureCrosLoaded())
return;
if (!apn.apn.empty()) {
DictionaryValue value;
value.SetString(kApnProperty, apn.apn);
value.SetString(kNetworkIdProperty, apn.network_id);
value.SetString(kUsernameProperty, apn.username);
value.SetString(kPasswordProperty, apn.password);
SetValueProperty(kCellularApnProperty, &value);
} else {
ClearProperty(kCellularApnProperty);
}
}
std::string CellularNetwork::GetNetworkTechnologyString() const {
// No need to localize these cellular technology abbreviations.
switch (network_technology_) {
case NETWORK_TECHNOLOGY_1XRTT:
return "1xRTT";
break;
case NETWORK_TECHNOLOGY_EVDO:
return "EVDO";
break;
case NETWORK_TECHNOLOGY_GPRS:
return "GPRS";
break;
case NETWORK_TECHNOLOGY_EDGE:
return "EDGE";
break;
case NETWORK_TECHNOLOGY_UMTS:
return "UMTS";
break;
case NETWORK_TECHNOLOGY_HSPA:
return "HSPA";
break;
case NETWORK_TECHNOLOGY_HSPA_PLUS:
return "HSPA Plus";
break;
case NETWORK_TECHNOLOGY_LTE:
return "LTE";
break;
case NETWORK_TECHNOLOGY_LTE_ADVANCED:
return "LTE Advanced";
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_CELLULAR_TECHNOLOGY_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetConnectivityStateString() const {
// These strings do not appear in the UI, so no need to localize them
switch (connectivity_state_) {
case CONN_STATE_UNRESTRICTED:
return "unrestricted";
break;
case CONN_STATE_RESTRICTED:
return "restricted";
break;
case CONN_STATE_NONE:
return "none";
break;
case CONN_STATE_UNKNOWN:
default:
return "unknown";
}
}
std::string CellularNetwork::ActivationStateToString(
ActivationState activation_state) {
switch (activation_state) {
case ACTIVATION_STATE_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED);
break;
case ACTIVATION_STATE_ACTIVATING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING);
break;
case ACTIVATION_STATE_NOT_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED);
break;
case ACTIVATION_STATE_PARTIALLY_ACTIVATED:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN);
break;
}
}
std::string CellularNetwork::GetActivationStateString() const {
return ActivationStateToString(this->activation_state_);
}
std::string CellularNetwork::GetRoamingStateString() const {
switch (this->roaming_state_) {
case ROAMING_STATE_HOME:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME);
break;
case ROAMING_STATE_ROAMING:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING);
break;
default:
return l10n_util::GetStringUTF8(
IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN);
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// WifiNetwork
// Called from ParseNetwork after calling ParseInfo.
void WifiNetwork::CalculateUniqueId() {
ConnectionSecurity encryption = encryption_;
// Flimflam treats wpa and rsn as psk internally, so convert those types
// to psk for unique naming.
if (encryption == SECURITY_WPA || encryption == SECURITY_RSN)
encryption = SECURITY_PSK;
std::string security = std::string(SecurityToString(encryption));
unique_id_ = security + "|" + name_;
}
bool WifiNetwork::ParseValue(int index, const Value* value) {
switch (index) {
case PROPERTY_INDEX_SECURITY: {
std::string security_string;
if (value->GetAsString(&security_string)) {
encryption_ = ParseSecurity(security_string);
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE: {
std::string passphrase;
if (value->GetAsString(&passphrase)) {
// Only store the passphrase if we are the owner.
// TODO(stevenjb): Remove this when chromium-os:12948 is resolved.
if (chromeos::UserManager::Get()->current_user_is_owner())
passphrase_ = passphrase;
return true;
}
break;
}
case PROPERTY_INDEX_PASSPHRASE_REQUIRED:
return value->GetAsBoolean(&passphrase_required_);
case PROPERTY_INDEX_SAVE_CREDENTIALS:
return value->GetAsBoolean(&save_credentials_);
case PROPERTY_INDEX_IDENTITY:
return value->GetAsString(&identity_);
case PROPERTY_INDEX_CERT_PATH:
return value->GetAsString(&cert_path_);
case PROPERTY_INDEX_EAP_IDENTITY:
return value->GetAsString(&eap_identity_);
case PROPERTY_INDEX_EAP_METHOD: {
std::string method;
if (value->GetAsString(&method)) {
eap_method_ = ParseEAPMethod(method);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_PHASE_2_AUTH: {
std::string auth;
if (value->GetAsString(&auth)) {
eap_phase_2_auth_ = ParseEAPPhase2Auth(auth);
return true;
}
break;
}
case PROPERTY_INDEX_EAP_ANONYMOUS_IDENTITY:
return value->GetAsString(&eap_anonymous_identity_);
case PROPERTY_INDEX_EAP_CERT_ID:
return value->GetAsString(&eap_client_cert_pkcs11_id_);
case PROPERTY_INDEX_EAP_CA_CERT_NSS:
return value->GetAsString(&eap_server_ca_cert_nss_nickname_);
case PROPERTY_INDEX_EAP_USE_SYSTEM_CAS:
return value->GetAsBoolean(&eap_use_system_cas_);
case PROPERTY_INDEX_EAP_PASSWORD:
return value->GetAsString(&eap_passphrase_);
case PROPERTY_INDEX_EAP_CLIENT_CERT:
case PROPERTY_INDEX_EAP_CLIENT_CERT_NSS:
case PROPERTY_INDEX_EAP_PRIVATE_KEY:
case PROPERTY_INDEX_EAP_PRIVATE_KEY_PASSWORD:
case PROPERTY_INDEX_EAP_KEY_ID:
case PROPERTY_INDEX_EAP_CA_CERT:
case PROPERTY_INDEX_EAP_CA_CERT_ID:
case PROPERTY_INDEX_EAP_PIN:
case PROPERTY_INDEX_EAP_KEY_MGMT:
// These properties are currently not used in the UI.
return true;
default:
return WirelessNetwork::ParseValue(index, value);
}
return false;
}
void WifiNetwork::ParseInfo(const DictionaryValue* info) {
Network::ParseInfo(info);
CalculateUniqueId();
}
const std::string& WifiNetwork::GetPassphrase() const {
if (!user_passphrase_.empty())
return user_passphrase_;
return passphrase_;
}
void WifiNetwork::SetPassphrase(const std::string& passphrase) {
// Set the user_passphrase_ only; passphrase_ stores the flimflam value.
// If the user sets an empty passphrase, restore it to the passphrase
// remembered by flimflam.
if (!passphrase.empty()) {
user_passphrase_ = passphrase;
passphrase_ = passphrase;
} else {
user_passphrase_ = passphrase_;
}
// Send the change to flimflam. If the format is valid, it will propagate to
// passphrase_ with a service update.
SetOrClearStringProperty(kPassphraseProperty, passphrase, NULL);
}
void WifiNetwork::SetSaveCredentials(bool save_credentials) {
SetBooleanProperty(kSaveCredentialsProperty, save_credentials,
&save_credentials_);
}
// See src/third_party/flimflam/doc/service-api.txt for properties that
// flimflam will forget when SaveCredentials is false.
void WifiNetwork::EraseCredentials() {
WipeString(&passphrase_);
WipeString(&user_passphrase_);
WipeString(&eap_client_cert_pkcs11_id_);
WipeString(&eap_identity_);
WipeString(&eap_anonymous_identity_);
WipeString(&eap_passphrase_);
}
void WifiNetwork::SetIdentity(const std::string& identity) {
SetStringProperty(kIdentityProperty, identity, &identity_);
}
void WifiNetwork::SetCertPath(const std::string& cert_path) {
SetStringProperty(kCertPathProperty, cert_path, &cert_path_);
}
void WifiNetwork::SetEAPMethod(EAPMethod method) {
eap_method_ = method;
switch (method) {
case EAP_METHOD_PEAP:
SetStringProperty(kEapMethodProperty, kEapMethodPEAP, NULL);
break;
case EAP_METHOD_TLS:
SetStringProperty(kEapMethodProperty, kEapMethodTLS, NULL);
break;
case EAP_METHOD_TTLS:
SetStringProperty(kEapMethodProperty, kEapMethodTTLS, NULL);
break;
case EAP_METHOD_LEAP:
SetStringProperty(kEapMethodProperty, kEapMethodLEAP, NULL);
break;
default:
ClearProperty(kEapMethodProperty);
break;
}
}
void WifiNetwork::SetEAPPhase2Auth(EAPPhase2Auth auth) {
eap_phase_2_auth_ = auth;
bool is_peap = (eap_method_ == EAP_METHOD_PEAP);
switch (auth) {
case EAP_PHASE_2_AUTH_AUTO:
ClearProperty(kEapPhase2AuthProperty);
break;
case EAP_PHASE_2_AUTH_MD5:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMD5
: kEapPhase2AuthTTLSMD5,
NULL);
break;
case EAP_PHASE_2_AUTH_MSCHAPV2:
SetStringProperty(kEapPhase2AuthProperty,
is_peap ? kEapPhase2AuthPEAPMSCHAPV2
: kEapPhase2AuthTTLSMSCHAPV2,
NULL);
break;
case EAP_PHASE_2_AUTH_MSCHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSMSCHAP, NULL);
break;
case EAP_PHASE_2_AUTH_PAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSPAP, NULL);
break;
case EAP_PHASE_2_AUTH_CHAP:
SetStringProperty(kEapPhase2AuthProperty, kEapPhase2AuthTTLSCHAP, NULL);
break;
}
}
void WifiNetwork::SetEAPServerCaCertNssNickname(
const std::string& nss_nickname) {
VLOG(1) << "SetEAPServerCaCertNssNickname " << nss_nickname;
SetOrClearStringProperty(kEapCaCertNssProperty, nss_nickname,
&eap_server_ca_cert_nss_nickname_);
}
void WifiNetwork::SetEAPClientCertPkcs11Id(const std::string& pkcs11_id) {
VLOG(1) << "SetEAPClientCertPkcs11Id " << pkcs11_id;
SetOrClearStringProperty(kEapCertIDProperty, pkcs11_id,
&eap_client_cert_pkcs11_id_);
}
void WifiNetwork::SetEAPUseSystemCAs(bool use_system_cas) {
SetBooleanProperty(kEapUseSystemCAsProperty, use_system_cas,
&eap_use_system_cas_);
}
void WifiNetwork::SetEAPIdentity(const std::string& identity) {
SetOrClearStringProperty(kEapIdentityProperty, identity, &eap_identity_);
}
void WifiNetwork::SetEAPAnonymousIdentity(const std::string& identity) {
SetOrClearStringProperty(kEapAnonymousIdentityProperty, identity,
&eap_anonymous_identity_);
}
void WifiNetwork::SetEAPPassphrase(const std::string& passphrase) {
SetOrClearStringProperty(kEapPasswordProperty, passphrase, &eap_passphrase_);
}
std::string WifiNetwork::GetEncryptionString() const {
switch (encryption_) {
case SECURITY_UNKNOWN:
break;
case SECURITY_NONE:
return "";
case SECURITY_WEP:
return "WEP";
case SECURITY_WPA:
return "WPA";
case SECURITY_RSN:
return "RSN";
case SECURITY_8021X:
return "8021X";
case SECURITY_PSK:
return "PSK";
}
return "Unknown";
}
bool WifiNetwork::IsPassphraseRequired() const {
// TODO(stevenjb): Remove error_ tests when fixed in flimflam
// (http://crosbug.com/10135).
if (error_ == ERROR_BAD_PASSPHRASE || error_ == ERROR_BAD_WEPKEY)
return true;
// For 802.1x networks, configuration is required if connectable is false.
if (encryption_ == SECURITY_8021X)
return !connectable_;
return passphrase_required_;
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
bool WifiNetwork::IsCertificateLoaded() const {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (cert_path_.find(settings_string) == 0) {
std::string::size_type idx = cert_path_.find(pkcs11_key);
if (idx != std::string::npos)
idx = cert_path_.find_first_not_of(kWhitespaceASCII,
idx + pkcs11_key.length());
if (idx != std::string::npos && cert_path_[idx] == '=')
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
class NetworkLibraryImpl : public NetworkLibrary {
public:
NetworkLibraryImpl()
: network_manager_monitor_(NULL),
data_plan_monitor_(NULL),
ethernet_(NULL),
active_wifi_(NULL),
active_cellular_(NULL),
active_virtual_(NULL),
available_devices_(0),
enabled_devices_(0),
connected_devices_(0),
wifi_scanning_(false),
offline_mode_(false),
is_locked_(false),
sim_operation_(SIM_OPERATION_NONE),
notify_task_(NULL) {
if (EnsureCrosLoaded()) {
Init();
network_manager_monitor_ =
MonitorNetworkManager(&NetworkManagerStatusChangedHandler,
this);
data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler,
this);
network_login_observer_.reset(new NetworkLoginObserver(this));
} else {
InitTestData();
}
}
virtual ~NetworkLibraryImpl() {
network_manager_observers_.Clear();
if (network_manager_monitor_)
DisconnectPropertyChangeMonitor(network_manager_monitor_);
data_plan_observers_.Clear();
pin_operation_observers_.Clear();
user_action_observers_.Clear();
if (data_plan_monitor_)
DisconnectDataPlanUpdateMonitor(data_plan_monitor_);
STLDeleteValues(&network_observers_);
STLDeleteValues(&network_device_observers_);
ClearNetworks(true /*delete networks*/);
ClearRememberedNetworks(true /*delete networks*/);
STLDeleteValues(&data_plan_map_);
}
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {
if (!network_manager_observers_.HasObserver(observer))
network_manager_observers_.AddObserver(observer);
}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {
network_manager_observers_.RemoveObserver(observer);
}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkObserverMap::iterator iter = network_observers_.find(service_path);
NetworkObserverList* oblist;
if (iter != network_observers_.end()) {
oblist = iter->second;
} else {
oblist = new NetworkObserverList(this, service_path);
network_observers_[service_path] = oblist;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {
DCHECK(observer);
DCHECK(service_path.size());
NetworkObserverMap::iterator map_iter =
network_observers_.find(service_path);
if (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter);
}
}
}
virtual void AddNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {
DCHECK(observer);
if (!EnsureCrosLoaded())
return;
// First, add the observer to the callback map.
NetworkDeviceObserverMap::iterator iter =
network_device_observers_.find(device_path);
NetworkDeviceObserverList* oblist;
if (iter != network_device_observers_.end()) {
oblist = iter->second;
} else {
oblist = new NetworkDeviceObserverList(this, device_path);
network_device_observers_[device_path] = oblist;
}
if (!oblist->HasObserver(observer))
oblist->AddObserver(observer);
}
virtual void RemoveNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {
DCHECK(observer);
DCHECK(device_path.size());
NetworkDeviceObserverMap::iterator map_iter =
network_device_observers_.find(device_path);
if (map_iter != network_device_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_device_observers_.erase(map_iter);
}
}
}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {
DCHECK(observer);
NetworkObserverMap::iterator map_iter = network_observers_.begin();
while (map_iter != network_observers_.end()) {
map_iter->second->RemoveObserver(observer);
if (!map_iter->second->size()) {
delete map_iter->second;
network_observers_.erase(map_iter++);
} else {
++map_iter;
}
}
}
virtual void Lock() {
if (is_locked_)
return;
is_locked_ = true;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual void Unlock() {
DCHECK(is_locked_);
if (!is_locked_)
return;
is_locked_ = false;
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool IsLocked() {
return is_locked_;
}
virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) {
if (!data_plan_observers_.HasObserver(observer))
data_plan_observers_.AddObserver(observer);
}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {
data_plan_observers_.RemoveObserver(observer);
}
virtual void AddPinOperationObserver(PinOperationObserver* observer) {
if (!pin_operation_observers_.HasObserver(observer))
pin_operation_observers_.AddObserver(observer);
}
virtual void RemovePinOperationObserver(PinOperationObserver* observer) {
pin_operation_observers_.RemoveObserver(observer);
}
virtual void AddUserActionObserver(UserActionObserver* observer) {
if (!user_action_observers_.HasObserver(observer))
user_action_observers_.AddObserver(observer);
}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {
user_action_observers_.RemoveObserver(observer);
}
virtual const EthernetNetwork* ethernet_network() const { return ethernet_; }
virtual bool ethernet_connecting() const {
return ethernet_ ? ethernet_->connecting() : false;
}
virtual bool ethernet_connected() const {
return ethernet_ ? ethernet_->connected() : false;
}
virtual const WifiNetwork* wifi_network() const { return active_wifi_; }
virtual bool wifi_connecting() const {
return active_wifi_ ? active_wifi_->connecting() : false;
}
virtual bool wifi_connected() const {
return active_wifi_ ? active_wifi_->connected() : false;
}
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const {
return active_cellular_ ? active_cellular_->connecting() : false;
}
virtual bool cellular_connected() const {
return active_cellular_ ? active_cellular_->connected() : false;
}
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const {
return active_virtual_ ? active_virtual_->connecting() : false;
}
virtual bool virtual_network_connected() const {
return active_virtual_ ? active_virtual_->connected() : false;
}
bool Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& IPAddress() const {
// Returns IP address for the active network.
// TODO(stevenjb): Fix this for VPNs. See chromium-os:13972.
const Network* result = active_network();
if (!result)
result = connected_network(); // happens if we are connected to a VPN.
if (!result)
result = ethernet_; // Use non active ethernet addr if no active network.
if (result)
return result->ip_address();
static std::string null_address("0.0.0.0");
return null_address;
}
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return remembered_wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const {
NetworkDeviceMap::const_iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
virtual const NetworkDevice* FindCellularDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_CELLULAR)
return iter->second;
}
return NULL;
}
virtual const NetworkDevice* FindEthernetDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_ETHERNET)
return iter->second;
}
return NULL;
}
virtual const NetworkDevice* FindWifiDevice() const {
for (NetworkDeviceMap::const_iterator iter = device_map_.begin();
iter != device_map_.end(); ++iter) {
if (iter->second->type() == TYPE_WIFI)
return iter->second;
}
return NULL;
}
virtual Network* FindNetworkByPath(const std::string& path) const {
NetworkMap::const_iterator iter = network_map_.find(path);
if (iter != network_map_.end())
return iter->second;
return NULL;
}
WirelessNetwork* FindWirelessNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network &&
(network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR))
return static_cast<WirelessNetwork*>(network);
return NULL;
}
virtual WifiNetwork* FindWifiNetworkByPath(const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_WIFI)
return static_cast<WifiNetwork*>(network);
return NULL;
}
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_CELLULAR)
return static_cast<CellularNetwork*>(network);
return NULL;
}
virtual VirtualNetwork* FindVirtualNetworkByPath(
const std::string& path) const {
Network* network = FindNetworkByPath(path);
if (network && network->type() == TYPE_VPN)
return static_cast<VirtualNetwork*>(network);
return NULL;
}
virtual Network* FindNetworkFromRemembered(
const Network* remembered) const {
NetworkMap::const_iterator found =
network_unique_id_map_.find(remembered->unique_id());
if (found != network_unique_id_map_.end())
return found->second;
return NULL;
}
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const {
CellularDataPlanMap::const_iterator iter = data_plan_map_.find(path);
if (iter != data_plan_map_.end())
return iter->second;
return NULL;
}
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const {
const CellularDataPlanVector* plans = GetDataPlans(path);
if (plans)
return GetSignificantDataPlanFromVector(plans);
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
virtual void ChangePin(const std::string& old_pin,
const std::string& new_pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling ChangePin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_CHANGE_PIN;
chromeos::RequestChangePin(cellular->device_path().c_str(),
old_pin.c_str(), new_pin.c_str(),
PinOperationCallback, this);
}
virtual void ChangeRequirePin(bool require_pin,
const std::string& pin) {
VLOG(1) << "ChangeRequirePin require_pin: " << require_pin
<< " pin: " << pin;
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling ChangeRequirePin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_CHANGE_REQUIRE_PIN;
chromeos::RequestRequirePin(cellular->device_path().c_str(),
pin.c_str(), require_pin,
PinOperationCallback, this);
}
virtual void EnterPin(const std::string& pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling EnterPin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_ENTER_PIN;
chromeos::RequestEnterPin(cellular->device_path().c_str(),
pin.c_str(),
PinOperationCallback, this);
}
virtual void UnblockPin(const std::string& puk,
const std::string& new_pin) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling UnblockPin method w/o cellular device.";
return;
}
sim_operation_ = SIM_OPERATION_UNBLOCK_PIN;
chromeos::RequestUnblockPin(cellular->device_path().c_str(),
puk.c_str(), new_pin.c_str(),
PinOperationCallback, this);
}
static void PinOperationCallback(void* object,
const char* path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
PinOperationError pin_error;
VLOG(1) << "PinOperationCallback, error: " << error
<< " error_msg: " << error_message;
if (error == chromeos::NETWORK_METHOD_ERROR_NONE) {
pin_error = PIN_ERROR_NONE;
VLOG(1) << "Pin operation completed successfuly";
// TODO(nkostylev): Might be cleaned up and exposed in flimflam API.
// http://crosbug.com/14253
// Since this option state is not exposed we have to update it manually.
networklib->FlipSimPinRequiredStateIfNeeded();
} else {
if (error_message &&
(strcmp(error_message, kErrorIncorrectPinMsg) == 0 ||
strcmp(error_message, kErrorPinRequiredMsg) == 0)) {
pin_error = PIN_ERROR_INCORRECT_CODE;
} else if (error_message &&
strcmp(error_message, kErrorPinBlockedMsg) == 0) {
pin_error = PIN_ERROR_BLOCKED;
} else {
pin_error = PIN_ERROR_UNKNOWN;
NOTREACHED() << "Unknown PIN error: " << error_message;
}
}
networklib->NotifyPinOperationCompleted(pin_error);
}
virtual void RequestCellularScan() {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling RequestCellularScan method w/o cellular device.";
return;
}
chromeos::ProposeScan(cellular->device_path().c_str());
}
virtual void RequestCellularRegister(const std::string& network_id) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling CellularRegister method w/o cellular device.";
return;
}
chromeos::RequestCellularRegister(cellular->device_path().c_str(),
network_id.c_str(),
CellularRegisterCallback,
this);
}
static void CellularRegisterCallback(void* object,
const char* path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
// TODO(dpolukhin): Notify observers about network registration status
// but not UI doesn't assume such notification so just ignore result.
}
virtual void SetCellularDataRoamingAllowed(bool new_value) {
const NetworkDevice* cellular = FindCellularDevice();
if (!cellular) {
NOTREACHED() << "Calling SetCellularDataRoamingAllowed method "
"w/o cellular device.";
return;
}
scoped_ptr<Value> value(Value::CreateBooleanValue(new_value));
chromeos::SetNetworkDeviceProperty(cellular->device_path().c_str(),
kCellularAllowRoamingProperty,
value.get());
}
/////////////////////////////////////////////////////////////////////////////
virtual void RequestNetworkScan() {
if (EnsureCrosLoaded()) {
if (wifi_enabled()) {
wifi_scanning_ = true; // Cleared when updates are received.
chromeos::RequestNetworkScan(kTypeWifi);
RequestRememberedNetworksUpdate();
}
if (cellular_network())
cellular_network()->RefreshDataPlansIfNeeded();
}
}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
if (!EnsureCrosLoaded())
return false;
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DeviceNetworkList* network_list = GetDeviceNetworkList();
if (network_list == NULL)
return false;
result->clear();
result->reserve(network_list->network_size);
const base::Time now = base::Time::Now();
for (size_t i = 0; i < network_list->network_size; ++i) {
DCHECK(network_list->networks[i].address);
DCHECK(network_list->networks[i].name);
WifiAccessPoint ap;
ap.mac_address = SafeString(network_list->networks[i].address);
ap.name = SafeString(network_list->networks[i].name);
ap.timestamp = now -
base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds);
ap.signal_strength = network_list->networks[i].strength;
ap.channel = network_list->networks[i].channel;
result->push_back(ap);
}
FreeDeviceNetworkList(network_list);
return true;
}
static void NetworkConnectCallback(void *object,
const char *path,
NetworkMethodErrorType error,
const char* error_message) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
Network* network = networklib->FindNetworkByPath(path);
if (!network) {
LOG(ERROR) << "No network for path: " << path;
return;
}
if (error != NETWORK_METHOD_ERROR_NONE) {
LOG(WARNING) << "Error from ServiceConnect callback for: "
<< network->name()
<< " Error: " << error << " Message: " << error_message;
if (error_message &&
strcmp(error_message, kErrorPassphraseRequiredMsg) == 0) {
// This will trigger the connection failed notification.
// TODO(stevenjb): Remove if chromium-os:13203 gets fixed.
network->SetState(STATE_FAILURE);
network->set_error(ERROR_BAD_PASSPHRASE);
networklib->NotifyNetworkManagerChanged(true); // Forced update.
}
return;
}
VLOG(1) << "Connected to service: " << network->name();
// Update local cache and notify listeners.
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork *>(network);
// If the user asked not to save credentials, flimflam will have
// forgotten them. Wipe our cache as well.
if (!wifi->save_credentials()) {
wifi->EraseCredentials();
}
networklib->active_wifi_ = wifi;
} else if (network->type() == TYPE_CELLULAR) {
networklib->active_cellular_ = static_cast<CellularNetwork *>(network);
} else if (network->type() == TYPE_VPN) {
networklib->active_virtual_ = static_cast<VirtualNetwork *>(network);
} else {
LOG(ERROR) << "Network of unexpected type: " << network->type();
}
// If we succeed, this network will be remembered; request an update.
// TODO(stevenjb): flimflam should do this automatically.
networklib->RequestRememberedNetworksUpdate();
// Notify observers.
networklib->NotifyNetworkManagerChanged(true); // Forced update.
networklib->NotifyUserConnectionInitiated(network);
}
void CallConnectToNetwork(Network* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
// In order to be certain to trigger any notifications, set the connecting
// state locally and notify observers. Otherwise there might be a state
// change without a forced notify.
network->set_connecting(true);
NotifyNetworkManagerChanged(true); // Forced update.
RequestNetworkServiceConnect(network->service_path().c_str(),
NetworkConnectCallback, this);
}
virtual void ConnectToWifiNetwork(WifiNetwork* wifi) {
// This will happen if a network resets or gets out of range.
if (wifi->user_passphrase_ != wifi->passphrase_ ||
wifi->passphrase_required())
wifi->SetPassphrase(wifi->user_passphrase_);
CallConnectToNetwork(wifi);
}
// Use this to connect to a wifi network by service path.
virtual void ConnectToWifiNetwork(const std::string& service_path) {
WifiNetwork* wifi = FindWifiNetworkByPath(service_path);
if (!wifi) {
LOG(WARNING) << "Attempt to connect to non existing network: "
<< service_path;
return;
}
ConnectToWifiNetwork(wifi);
}
// Use this to connect to an unlisted wifi network.
// This needs to request information about the named service.
// The connection attempt will occur in the callback.
virtual void ConnectToWifiNetwork(const std::string& ssid,
ConnectionSecurity security,
const std::string& passphrase) {
DCHECK(security != SECURITY_8021X);
if (!EnsureCrosLoaded())
return;
// Store the connection data to be used by the callback.
connect_data_.security = security;
connect_data_.service_name = ssid;
connect_data_.passphrase = passphrase;
// Asynchronously request service properties and call
// WifiServiceUpdateAndConnect.
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(security),
WifiServiceUpdateAndConnect,
this);
}
// As above, but for 802.1X EAP networks.
virtual void ConnectToWifiNetwork8021x(
const std::string& ssid,
EAPMethod eap_method,
EAPPhase2Auth eap_auth,
const std::string& eap_server_ca_cert_nss_nickname,
bool eap_use_system_cas,
const std::string& eap_client_cert_pkcs11_id,
const std::string& eap_identity,
const std::string& eap_anonymous_identity,
const std::string& passphrase,
bool save_credentials) {
if (!EnsureCrosLoaded())
return;
connect_data_.security = SECURITY_8021X;
connect_data_.service_name = ssid;
connect_data_.eap_method = eap_method;
connect_data_.eap_auth = eap_auth;
connect_data_.eap_server_ca_cert_nss_nickname =
eap_server_ca_cert_nss_nickname;
connect_data_.eap_use_system_cas = eap_use_system_cas;
connect_data_.eap_client_cert_pkcs11_id = eap_client_cert_pkcs11_id;
connect_data_.eap_identity = eap_identity;
connect_data_.eap_anonymous_identity = eap_anonymous_identity;
connect_data_.passphrase = passphrase;
connect_data_.save_credentials = save_credentials;
RequestHiddenWifiNetwork(ssid.c_str(),
SecurityToString(SECURITY_8021X),
WifiServiceUpdateAndConnect,
this);
}
// Callback
static void WifiServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
DCHECK(network->type() == TYPE_WIFI);
networklib->ConnectToWifiNetworkUsingConnectData(
static_cast<WifiNetwork*>(network));
}
}
void ConnectToWifiNetworkUsingConnectData(WifiNetwork* wifi) {
ConnectData& data = connect_data_;
if (wifi->name() != data.service_name) {
LOG(WARNING) << "Wifi network name does not match ConnectData: "
<< wifi->name() << " != " << data.service_name;
return;
}
wifi->set_added(true);
if (data.security == SECURITY_8021X) {
// Enterprise 802.1X EAP network.
wifi->SetEAPMethod(data.eap_method);
wifi->SetEAPPhase2Auth(data.eap_auth);
wifi->SetEAPServerCaCertNssNickname(data.eap_server_ca_cert_nss_nickname);
wifi->SetEAPUseSystemCAs(data.eap_use_system_cas);
wifi->SetEAPClientCertPkcs11Id(data.eap_client_cert_pkcs11_id);
wifi->SetEAPIdentity(data.eap_identity);
wifi->SetEAPAnonymousIdentity(data.eap_anonymous_identity);
wifi->SetEAPPassphrase(data.passphrase);
wifi->SetSaveCredentials(data.save_credentials);
} else {
// Ordinary, non-802.1X network.
wifi->SetPassphrase(data.passphrase);
}
ConnectToWifiNetwork(wifi);
}
virtual void ConnectToCellularNetwork(CellularNetwork* cellular) {
CallConnectToNetwork(cellular);
}
// Records information that cellular play payment had happened.
virtual void SignalCellularPlanPayment() {
DCHECK(!HasRecentCellularPlanPayment());
cellular_plan_payment_time_ = base::Time::Now();
}
// Returns true if cellular plan payment had been recorded recently.
virtual bool HasRecentCellularPlanPayment() {
return (base::Time::Now() -
cellular_plan_payment_time_).InHours() < kRecentPlanPaymentHours;
}
virtual void ConnectToVirtualNetwork(VirtualNetwork* vpn) {
CallConnectToNetwork(vpn);
}
virtual void ConnectToVirtualNetworkPSK(
const std::string& service_name,
const std::string& server,
const std::string& psk,
const std::string& username,
const std::string& user_passphrase) {
if (!EnsureCrosLoaded())
return;
// Store the connection data to be used by the callback.
connect_data_.service_name = service_name;
connect_data_.psk_key = psk;
connect_data_.server_hostname = server;
connect_data_.psk_username = username;
connect_data_.passphrase = user_passphrase;
RequestVirtualNetwork(service_name.c_str(),
server.c_str(),
kProviderL2tpIpsec,
VPNServiceUpdateAndConnect,
this);
}
// Callback
static void VPNServiceUpdateAndConnect(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path && info) {
VLOG(1) << "Connecting to new VPN Service: " << service_path;
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
Network* network =
networklib->ParseNetwork(std::string(service_path), dict);
DCHECK(network->type() == TYPE_VPN);
networklib->ConnectToVirtualNetworkUsingConnectData(
static_cast<VirtualNetwork*>(network));
} else {
LOG(WARNING) << "Unable to create VPN Service: " << service_path;
}
}
void ConnectToVirtualNetworkUsingConnectData(VirtualNetwork* vpn) {
ConnectData& data = connect_data_;
if (vpn->name() != data.service_name) {
LOG(WARNING) << "Virtual network name does not match ConnectData: "
<< vpn->name() << " != " << data.service_name;
return;
}
vpn->set_added(true);
vpn->set_server_hostname(data.server_hostname);
vpn->SetCACert("");
vpn->SetUserCert("");
vpn->SetUserCertKey("");
vpn->SetPSKPassphrase(data.psk_key);
vpn->SetUsername(data.psk_username);
vpn->SetUserPassphrase(data.passphrase);
CallConnectToNetwork(vpn);
}
virtual void DisconnectFromNetwork(const Network* network) {
DCHECK(network);
if (!EnsureCrosLoaded() || !network)
return;
VLOG(1) << "Disconnect from network: " << network->service_path();
if (chromeos::DisconnectFromNetwork(network->service_path().c_str())) {
// Update local cache and notify listeners.
Network* found_network = FindNetworkByPath(network->service_path());
if (found_network) {
found_network->set_connected(false);
if (found_network == active_wifi_)
active_wifi_ = NULL;
else if (found_network == active_cellular_)
active_cellular_ = NULL;
else if (found_network == active_virtual_)
active_virtual_ = NULL;
}
NotifyNetworkManagerChanged(true); // Forced update.
}
}
virtual void ForgetWifiNetwork(const std::string& service_path) {
if (!EnsureCrosLoaded())
return;
DeleteRememberedService(service_path.c_str());
DeleteRememberedWifiNetwork(service_path);
NotifyNetworkManagerChanged(true); // Forced update.
}
virtual bool ethernet_available() const {
return available_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_available() const {
return available_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_available() const {
return available_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool ethernet_enabled() const {
return enabled_devices_ & (1 << TYPE_ETHERNET);
}
virtual bool wifi_enabled() const {
return enabled_devices_ & (1 << TYPE_WIFI);
}
virtual bool cellular_enabled() const {
return enabled_devices_ & (1 << TYPE_CELLULAR);
}
virtual bool wifi_scanning() const {
return wifi_scanning_;
}
virtual bool offline_mode() const { return offline_mode_; }
// Note: This does not include any virtual networks.
virtual const Network* active_network() const {
// Use flimflam's ordering of the services to determine what the active
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->is_active())
result = ethernet_;
if ((active_wifi_ && active_wifi_->is_active()) &&
(!result ||
active_wifi_->priority_order_ < result->priority_order_))
result = active_wifi_;
if ((active_cellular_ && active_cellular_->is_active()) &&
(!result ||
active_cellular_->priority_order_ < result->priority_order_))
result = active_cellular_;
return result;
}
virtual const Network* connected_network() const {
// Use flimflam's ordering of the services to determine what the connected
// network is (i.e. don't assume priority of network types).
Network* result = NULL;
if (ethernet_ && ethernet_->connected())
result = ethernet_;
if ((active_wifi_ && active_wifi_->connected()) &&
(!result ||
active_wifi_->priority_order_ < result->priority_order_))
result = active_wifi_;
if ((active_cellular_ && active_cellular_->connected()) &&
(!result ||
active_cellular_->priority_order_ < result->priority_order_))
result = active_cellular_;
return result;
}
virtual void EnableEthernetNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_ETHERNET, enable);
}
virtual void EnableWifiNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_WIFI, enable);
}
virtual void EnableCellularNetworkDevice(bool enable) {
if (is_locked_)
return;
EnableNetworkDeviceType(TYPE_CELLULAR, enable);
}
virtual void EnableOfflineMode(bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
VLOG(1) << "Trying to enable offline mode when it's already enabled.";
return;
}
if (!enable && !offline_mode_) {
VLOG(1) << "Trying to disable offline mode when it's already disabled.";
return;
}
if (SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address,
HardwareAddressFormat format) {
DCHECK(hardware_address);
hardware_address->clear();
NetworkIPConfigVector ipconfig_vector;
if (EnsureCrosLoaded() && !device_path.empty()) {
IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
*hardware_address = ipconfig_status->hardware_address;
FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
for (size_t i = 0; i < hardware_address->size(); ++i)
(*hardware_address)[i] = toupper((*hardware_address)[i]);
if (format == FORMAT_COLON_SEPARATED_HEX) {
if (hardware_address->size() % 2 == 0) {
std::string output;
for (size_t i = 0; i < hardware_address->size(); ++i) {
if ((i != 0) && (i % 2 == 0))
output.push_back(':');
output.push_back((*hardware_address)[i]);
}
*hardware_address = output;
}
} else {
DCHECK(format == FORMAT_RAW_HEX);
}
return ipconfig_vector;
}
private:
typedef std::map<std::string, Network*> NetworkMap;
typedef std::map<std::string, int> PriorityMap;
typedef std::map<std::string, NetworkDevice*> NetworkDeviceMap;
typedef std::map<std::string, CellularDataPlanVector*> CellularDataPlanMap;
class NetworkObserverList : public ObserverList<NetworkObserver> {
public:
NetworkObserverList(NetworkLibraryImpl* library,
const std::string& service_path) {
network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler,
service_path.c_str(),
library);
}
virtual ~NetworkObserverList() {
if (network_monitor_)
DisconnectPropertyChangeMonitor(network_monitor_);
}
private:
static void NetworkStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkStatus(path, key, value);
}
PropertyChangeMonitor network_monitor_;
DISALLOW_COPY_AND_ASSIGN(NetworkObserverList);
};
typedef std::map<std::string, NetworkObserverList*> NetworkObserverMap;
class NetworkDeviceObserverList : public ObserverList<NetworkDeviceObserver> {
public:
NetworkDeviceObserverList(NetworkLibraryImpl* library,
const std::string& device_path) {
device_monitor_ = MonitorNetworkDevice(
&NetworkDevicePropertyChangedHandler,
device_path.c_str(),
library);
}
virtual ~NetworkDeviceObserverList() {
if (device_monitor_)
DisconnectPropertyChangeMonitor(device_monitor_);
}
private:
static void NetworkDevicePropertyChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->UpdateNetworkDeviceStatus(path, key, value);
}
PropertyChangeMonitor device_monitor_;
DISALLOW_COPY_AND_ASSIGN(NetworkDeviceObserverList);
};
typedef std::map<std::string, NetworkDeviceObserverList*>
NetworkDeviceObserverMap;
////////////////////////////////////////////////////////////////////////////
// Callbacks.
static void NetworkManagerStatusChangedHandler(void* object,
const char* path,
const char* key,
const Value* value) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
networklib->NetworkManagerStatusChanged(key, value);
}
// This processes all Manager update messages.
void NetworkManagerStatusChanged(const char* key, const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
base::TimeTicks start = base::TimeTicks::Now();
VLOG(1) << "NetworkManagerStatusChanged: KEY=" << key;
if (!key)
return;
int index = property_index_parser().Get(std::string(key));
switch (index) {
case PROPERTY_INDEX_STATE:
// Currently we ignore the network manager state.
break;
case PROPERTY_INDEX_AVAILABLE_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateAvailableTechnologies(vlist);
break;
}
case PROPERTY_INDEX_ENABLED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateEnabledTechnologies(vlist);
break;
}
case PROPERTY_INDEX_CONNECTED_TECHNOLOGIES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateConnectedTechnologies(vlist);
break;
}
case PROPERTY_INDEX_DEFAULT_TECHNOLOGY:
// Currently we ignore DefaultTechnology.
break;
case PROPERTY_INDEX_OFFLINE_MODE: {
DCHECK_EQ(value->GetType(), Value::TYPE_BOOLEAN);
value->GetAsBoolean(&offline_mode_);
NotifyNetworkManagerChanged(false); // Not forced.
break;
}
case PROPERTY_INDEX_ACTIVE_PROFILE: {
DCHECK_EQ(value->GetType(), Value::TYPE_STRING);
value->GetAsString(&active_profile_path_);
RequestRememberedNetworksUpdate();
break;
}
case PROPERTY_INDEX_PROFILES:
// Currently we ignore Profiles (list of all profiles).
break;
case PROPERTY_INDEX_SERVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_SERVICE_WATCH_LIST: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateWatchedNetworkServiceList(vlist);
break;
}
case PROPERTY_INDEX_DEVICE:
case PROPERTY_INDEX_DEVICES: {
DCHECK_EQ(value->GetType(), Value::TYPE_LIST);
const ListValue* vlist = static_cast<const ListValue*>(value);
UpdateNetworkDeviceList(vlist);
break;
}
default:
LOG(WARNING) << "Unhandled key: " << key;
break;
}
base::TimeDelta delta = base::TimeTicks::Now() - start;
VLOG(1) << " time: " << delta.InMilliseconds() << " ms.";
HISTOGRAM_TIMES("CROS_NETWORK_UPDATE", delta);
}
static void NetworkManagerUpdate(void* object,
const char* manager_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (!info) {
LOG(ERROR) << "Error retrieving manager properties: " << manager_path;
return;
}
VLOG(1) << "Received NetworkManagerUpdate.";
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkManager(dict);
}
void ParseNetworkManager(const DictionaryValue* dict) {
for (DictionaryValue::key_iterator iter = dict->begin_keys();
iter != dict->end_keys(); ++iter) {
const std::string& key = *iter;
Value* value;
bool res = dict->GetWithoutPathExpansion(key, &value);
CHECK(res);
NetworkManagerStatusChanged(key.c_str(), value);
}
}
static void ProfileUpdate(void* object,
const char* profile_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (!info) {
LOG(ERROR) << "Error retrieving profile: " << profile_path;
return;
}
VLOG(1) << "Received ProfileUpdate for: " << profile_path;
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
ListValue* entries(NULL);
dict->GetList(kEntriesProperty, &entries);
DCHECK(entries);
networklib->UpdateRememberedServiceList(profile_path, entries);
}
static void NetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info)
return; // Network no longer in visible list, ignore.
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetwork(std::string(service_path), dict);
}
}
static void RememberedNetworkServiceUpdate(void* object,
const char* service_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (service_path) {
if (!info) {
// Remembered network no longer exists.
networklib->DeleteRememberedWifiNetwork(std::string(service_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseRememberedNetwork(std::string(service_path), dict);
}
}
}
static void NetworkDeviceUpdate(void* object,
const char* device_path,
const Value* info) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (device_path) {
if (!info) {
// device no longer exists.
networklib->DeleteDevice(std::string(device_path));
} else {
DCHECK_EQ(info->GetType(), Value::TYPE_DICTIONARY);
const DictionaryValue* dict = static_cast<const DictionaryValue*>(info);
networklib->ParseNetworkDevice(std::string(device_path), dict);
}
}
}
static void DataPlanUpdateHandler(void* object,
const char* modem_service_path,
const CellularDataPlanList* dataplan) {
NetworkLibraryImpl* networklib = static_cast<NetworkLibraryImpl*>(object);
DCHECK(networklib);
if (modem_service_path && dataplan) {
networklib->UpdateCellularDataPlan(std::string(modem_service_path),
dataplan);
}
}
////////////////////////////////////////////////////////////////////////////
// Network technology functions.
void UpdateTechnologies(const ListValue* technologies, int* bitfieldp) {
DCHECK(bitfieldp);
if (!technologies)
return;
int bitfield = 0;
for (ListValue::const_iterator iter = technologies->begin();
iter != technologies->end(); ++iter) {
std::string technology;
(*iter)->GetAsString(&technology);
if (!technology.empty()) {
ConnectionType type = ParseType(technology);
bitfield |= 1 << type;
}
}
*bitfieldp = bitfield;
NotifyNetworkManagerChanged(false); // Not forced.
}
void UpdateAvailableTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &available_devices_);
}
void UpdateEnabledTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &enabled_devices_);
if (!ethernet_enabled())
ethernet_ = NULL;
if (!wifi_enabled()) {
active_wifi_ = NULL;
wifi_networks_.clear();
}
if (!cellular_enabled()) {
active_cellular_ = NULL;
cellular_networks_.clear();
}
}
void UpdateConnectedTechnologies(const ListValue* technologies) {
UpdateTechnologies(technologies, &connected_devices_);
}
////////////////////////////////////////////////////////////////////////////
// Network list management functions.
// Note: sometimes flimflam still returns networks when the device type is
// disabled. Always check the appropriate enabled() state before adding
// networks to a list or setting an active network so that we do not show them
// in the UI.
// This relies on services being requested from flimflam in priority order,
// and the updates getting processed and received in order.
void UpdateActiveNetwork(Network* network) {
ConnectionType type(network->type());
if (type == TYPE_ETHERNET) {
if (ethernet_enabled()) {
// Set ethernet_ to the first connected ethernet service, or the first
// disconnected ethernet service if none are connected.
if (ethernet_ == NULL || !ethernet_->connected())
ethernet_ = static_cast<EthernetNetwork*>(network);
}
} else if (type == TYPE_WIFI) {
if (wifi_enabled()) {
// Set active_wifi_ to the first connected or connecting wifi service.
if (active_wifi_ == NULL && network->connecting_or_connected())
active_wifi_ = static_cast<WifiNetwork*>(network);
}
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled()) {
// Set active_cellular_ to first connected/connecting celluar service.
if (active_cellular_ == NULL && network->connecting_or_connected())
active_cellular_ = static_cast<CellularNetwork*>(network);
}
} else if (type == TYPE_VPN) {
// Set active_virtual_ to the first connected or connecting vpn service.
if (active_virtual_ == NULL && network->connecting_or_connected())
active_virtual_ = static_cast<VirtualNetwork*>(network);
}
}
void AddNetwork(Network* network) {
std::pair<NetworkMap::iterator,bool> result =
network_map_.insert(std::make_pair(network->service_path(), network));
DCHECK(result.second); // Should only get called with new network.
VLOG(2) << "Adding Network: " << network->name();
ConnectionType type(network->type());
if (type == TYPE_WIFI) {
if (wifi_enabled())
wifi_networks_.push_back(static_cast<WifiNetwork*>(network));
} else if (type == TYPE_CELLULAR) {
if (cellular_enabled())
cellular_networks_.push_back(static_cast<CellularNetwork*>(network));
} else if (type == TYPE_VPN) {
virtual_networks_.push_back(static_cast<VirtualNetwork*>(network));
}
// Do not set the active network here. Wait until we parse the network.
}
// Deletes a network. It must already be removed from any lists.
void DeleteNetwork(Network* network) {
CHECK(network_map_.find(network->service_path()) == network_map_.end());
ConnectionType type(network->type());
if (type == TYPE_CELLULAR) {
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found =
data_plan_map_.find(network->service_path());
if (found != data_plan_map_.end()) {
CellularDataPlanVector* data_plans = found->second;
delete data_plans;
data_plan_map_.erase(found);
}
}
delete network;
}
void AddRememberedWifiNetwork(WifiNetwork* wifi) {
std::pair<NetworkMap::iterator,bool> result =
remembered_network_map_.insert(
std::make_pair(wifi->service_path(), wifi));
DCHECK(result.second); // Should only get called with new network.
remembered_wifi_networks_.push_back(wifi);
}
void DeleteRememberedWifiNetwork(const std::string& service_path) {
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found == remembered_network_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant remembered network: "
<< service_path;
return;
}
Network* remembered_network = found->second;
remembered_network_map_.erase(found);
WifiNetworkVector::iterator iter = std::find(
remembered_wifi_networks_.begin(), remembered_wifi_networks_.end(),
remembered_network);
if (iter != remembered_wifi_networks_.end())
remembered_wifi_networks_.erase(iter);
Network* network = FindNetworkFromRemembered(remembered_network);
if (network && network->type() == TYPE_WIFI) {
// Clear the stored credentials for any visible forgotten networks.
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
wifi->EraseCredentials();
} else {
// Network is not in visible list.
VLOG(2) << "Remembered Network not found: "
<< remembered_network->unique_id();
}
delete remembered_network;
}
// Update all network lists, and request associated service updates.
void UpdateNetworkServiceList(const ListValue* services) {
// TODO(stevenjb): Wait for wifi_scanning_ to be false.
// Copy the list of existing networks to "old" and clear the map and lists.
NetworkMap old_network_map = network_map_;
ClearNetworks(false /*don't delete*/);
// Clear the list of update requests.
int network_priority_order = 0;
network_update_requests_.clear();
// wifi_scanning_ will remain false unless we request a network update.
wifi_scanning_ = false;
// |services| represents a complete list of visible networks.
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and lists. Otherwise it will get added when NetworkServiceUpdate
// calls ParseNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
AddNetwork(found->second);
old_network_map.erase(found);
}
// Always request network updates.
// TODO(stevenjb): Investigate why we are missing updates then
// rely on watched network updates and only request updates here for
// new networks.
// Use update_request map to store network priority.
network_update_requests_[service_path] = network_priority_order++;
wifi_scanning_ = true;
RequestNetworkServiceInfo(service_path.c_str(),
&NetworkServiceUpdate,
this);
}
}
// Iterate through list of remaining networks that are no longer in the
// list and delete them or update their status and re-add them to the list.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
Network* network = iter->second;
if (network->failed() && network->notify_failure()) {
// We have not notified observers of a connection failure yet.
AddNetwork(network);
} else if (network->connecting()) {
// Network was in connecting state; set state to failed.
network->SetState(STATE_FAILURE);
AddNetwork(network);
} else {
VLOG(2) << "Deleting non-existant Network: " << network->name()
<< " State = " << network->GetStateString();
DeleteNetwork(network);
}
}
}
// Request updates for watched networks. Does not affect network lists.
// Existing networks will be updated. There should not be any new networks
// in this list, but if there are they will be added appropriately.
void UpdateWatchedNetworkServiceList(const ListValue* services) {
for (ListValue::const_iterator iter = services->begin();
iter != services->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
VLOG(1) << "Watched Service: " << service_path;
RequestNetworkServiceInfo(
service_path.c_str(), &NetworkServiceUpdate, this);
}
}
}
// Request the active profile which lists the remembered networks.
void RequestRememberedNetworksUpdate() {
RequestNetworkProfile(
active_profile_path_.c_str(), &ProfileUpdate, this);
}
// Update the list of remembered (profile) networks, and request associated
// service updates.
void UpdateRememberedServiceList(const char* profile_path,
const ListValue* profile_entries) {
// Copy the list of existing networks to "old" and clear the map and list.
NetworkMap old_network_map = remembered_network_map_;
ClearRememberedNetworks(false /*don't delete*/);
// |profile_entries| represents a complete list of remembered networks.
for (ListValue::const_iterator iter = profile_entries->begin();
iter != profile_entries->end(); ++iter) {
std::string service_path;
(*iter)->GetAsString(&service_path);
if (!service_path.empty()) {
// If we find the network in "old", add it immediately to the map
// and list. Otherwise it will get added when
// RememberedNetworkServiceUpdate calls ParseRememberedNetwork.
NetworkMap::iterator found = old_network_map.find(service_path);
if (found != old_network_map.end()) {
Network* network = found->second;
if (network->type() == TYPE_WIFI) {
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
AddRememberedWifiNetwork(wifi);
old_network_map.erase(found);
}
}
// Always request updates for remembered networks.
RequestNetworkProfileEntry(profile_path,
service_path.c_str(),
&RememberedNetworkServiceUpdate,
this);
}
}
// Delete any old networks that no longer exist.
for (NetworkMap::iterator iter = old_network_map.begin();
iter != old_network_map.end(); ++iter) {
delete iter->second;
}
}
Network* CreateNewNetwork(ConnectionType type,
const std::string& service_path) {
switch (type) {
case TYPE_ETHERNET: {
EthernetNetwork* ethernet = new EthernetNetwork(service_path);
return ethernet;
}
case TYPE_WIFI: {
WifiNetwork* wifi = new WifiNetwork(service_path);
return wifi;
}
case TYPE_CELLULAR: {
CellularNetwork* cellular = new CellularNetwork(service_path);
return cellular;
}
case TYPE_VPN: {
VirtualNetwork* vpn = new VirtualNetwork(service_path);
return vpn;
}
default: {
LOG(WARNING) << "Unknown service type: " << type;
return new Network(service_path, type);
}
}
}
Network* ParseNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network = FindNetworkByPath(service_path);
if (!network) {
ConnectionType type = ParseTypeFromDictionary(info);
network = CreateNewNetwork(type, service_path);
AddNetwork(network);
}
// Erase entry from network_unique_id_map_ in case unique id changes.
if (!network->unique_id().empty())
network_unique_id_map_.erase(network->unique_id());
network->ParseInfo(info); // virtual.
if (!network->unique_id().empty())
network_unique_id_map_[network->unique_id()] = network;
UpdateActiveNetwork(network);
// Find and erase entry in update_requests, and set network priority.
PriorityMap::iterator found2 = network_update_requests_.find(service_path);
if (found2 != network_update_requests_.end()) {
network->priority_order_ = found2->second;
network_update_requests_.erase(found2);
if (network_update_requests_.empty()) {
// Clear wifi_scanning_ when we have no pending requests.
wifi_scanning_ = false;
}
} else {
// TODO(stevenjb): Enable warning once UpdateNetworkServiceList is fixed.
// LOG(WARNING) << "ParseNetwork called with no update request entry: "
// << service_path;
}
VLOG(1) << "ParseNetwork: " << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
// Returns NULL if |service_path| refers to a network that is not a
// remembered type.
Network* ParseRememberedNetwork(const std::string& service_path,
const DictionaryValue* info) {
Network* network;
NetworkMap::iterator found = remembered_network_map_.find(service_path);
if (found != remembered_network_map_.end()) {
network = found->second;
} else {
ConnectionType type = ParseTypeFromDictionary(info);
if (type == TYPE_WIFI) {
network = CreateNewNetwork(type, service_path);
WifiNetwork* wifi = static_cast<WifiNetwork*>(network);
AddRememberedWifiNetwork(wifi);
} else {
VLOG(1) << "Ignoring remembered network: " << service_path
<< " Type: " << ConnectionTypeToString(type);
return NULL;
}
}
network->ParseInfo(info); // virtual.
VLOG(1) << "ParseRememberedNetwork: " << network->name();
NotifyNetworkManagerChanged(false); // Not forced.
return network;
}
void ClearNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&network_map_);
network_map_.clear();
network_unique_id_map_.clear();
ethernet_ = NULL;
active_wifi_ = NULL;
active_cellular_ = NULL;
active_virtual_ = NULL;
wifi_networks_.clear();
cellular_networks_.clear();
virtual_networks_.clear();
}
void ClearRememberedNetworks(bool delete_networks) {
if (delete_networks)
STLDeleteValues(&remembered_network_map_);
remembered_network_map_.clear();
remembered_wifi_networks_.clear();
}
////////////////////////////////////////////////////////////////////////////
// NetworkDevice list management functions.
// Returns pointer to device or NULL if device is not found by path.
// Use FindNetworkDeviceByPath when you're not intending to change device.
NetworkDevice* GetNetworkDeviceByPath(const std::string& path) {
NetworkDeviceMap::iterator iter = device_map_.find(path);
if (iter != device_map_.end())
return iter->second;
LOG(WARNING) << "Device path not found: " << path;
return NULL;
}
// Update device list, and request associated device updates.
// |devices| represents a complete list of devices.
void UpdateNetworkDeviceList(const ListValue* devices) {
NetworkDeviceMap old_device_map = device_map_;
device_map_.clear();
VLOG(2) << "Updating Device List.";
for (ListValue::const_iterator iter = devices->begin();
iter != devices->end(); ++iter) {
std::string device_path;
(*iter)->GetAsString(&device_path);
if (!device_path.empty()) {
NetworkDeviceMap::iterator found = old_device_map.find(device_path);
if (found != old_device_map.end()) {
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = found->second;
old_device_map.erase(found);
}
RequestNetworkDeviceInfo(
device_path.c_str(), &NetworkDeviceUpdate, this);
}
}
// Delete any old devices that no longer exist.
for (NetworkDeviceMap::iterator iter = old_device_map.begin();
iter != old_device_map.end(); ++iter) {
DeleteDeviceFromDeviceObserversMap(iter->first);
// Delete device.
delete iter->second;
}
}
void DeleteDeviceFromDeviceObserversMap(const std::string& device_path) {
// Delete all device observers associated with this device.
NetworkDeviceObserverMap::iterator map_iter =
network_device_observers_.find(device_path);
if (map_iter != network_device_observers_.end()) {
delete map_iter->second;
network_device_observers_.erase(map_iter);
}
}
void DeleteDevice(const std::string& device_path) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
if (found == device_map_.end()) {
LOG(WARNING) << "Attempt to delete non-existant device: "
<< device_path;
return;
}
VLOG(2) << " Deleting device: " << device_path;
NetworkDevice* device = found->second;
device_map_.erase(found);
DeleteDeviceFromDeviceObserversMap(device_path);
delete device;
}
void ParseNetworkDevice(const std::string& device_path,
const DictionaryValue* info) {
NetworkDeviceMap::iterator found = device_map_.find(device_path);
NetworkDevice* device;
if (found != device_map_.end()) {
device = found->second;
} else {
device = new NetworkDevice(device_path);
VLOG(2) << " Adding device: " << device_path;
device_map_[device_path] = device;
}
device->ParseInfo(info);
VLOG(1) << "ParseNetworkDevice:" << device->name();
NotifyNetworkManagerChanged(false); // Not forced.
}
////////////////////////////////////////////////////////////////////////////
void EnableNetworkDeviceType(ConnectionType device, bool enable) {
if (!EnsureCrosLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to enable a device that's already enabled: "
<< device;
return;
}
if (!enable && !(enabled_devices_ & (1 << device))) {
LOG(WARNING) << "Trying to disable a device that's already disabled: "
<< device;
return;
}
RequestNetworkDeviceEnable(ConnectionTypeToString(device), enable);
}
////////////////////////////////////////////////////////////////////////////
// Notifications.
// We call this any time something in NetworkLibrary changes.
// TODO(stevenjb): We should consider breaking this into multiplie
// notifications, e.g. connection state, devices, services, etc.
void NotifyNetworkManagerChanged(bool force_update) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Cancel any pending signals.
if (notify_task_) {
notify_task_->Cancel();
notify_task_ = NULL;
}
if (force_update) {
// Signal observers now.
SignalNetworkManagerObservers();
} else {
// Schedule a deleayed signal to limit the frequency of notifications.
notify_task_ = NewRunnableMethod(
this, &NetworkLibraryImpl::SignalNetworkManagerObservers);
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, notify_task_,
kNetworkNotifyDelayMs);
}
}
void SignalNetworkManagerObservers() {
notify_task_ = NULL;
FOR_EACH_OBSERVER(NetworkManagerObserver,
network_manager_observers_,
OnNetworkManagerChanged(this));
// Clear notification flags.
for (NetworkMap::iterator iter = network_map_.begin();
iter != network_map_.end(); ++iter) {
iter->second->set_notify_failure(false);
}
}
void NotifyNetworkChanged(Network* network) {
VLOG(2) << "Network changed: " << network->name();
DCHECK(network);
NetworkObserverMap::const_iterator iter = network_observers_.find(
network->service_path());
if (iter != network_observers_.end()) {
FOR_EACH_OBSERVER(NetworkObserver,
*(iter->second),
OnNetworkChanged(this, network));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
network->service_path();
}
}
void NotifyNetworkDeviceChanged(NetworkDevice* device) {
DCHECK(device);
NetworkDeviceObserverMap::const_iterator iter =
network_device_observers_.find(device->device_path());
if (iter != network_device_observers_.end()) {
NetworkDeviceObserverList* device_observer_list = iter->second;
FOR_EACH_OBSERVER(NetworkDeviceObserver,
*device_observer_list,
OnNetworkDeviceChanged(this, device));
} else {
NOTREACHED() <<
"There weren't supposed to be any property change observers of " <<
device->device_path();
}
}
void NotifyCellularDataPlanChanged() {
FOR_EACH_OBSERVER(CellularDataPlanObserver,
data_plan_observers_,
OnCellularDataPlanChanged(this));
}
void NotifyPinOperationCompleted(PinOperationError error) {
FOR_EACH_OBSERVER(PinOperationObserver,
pin_operation_observers_,
OnPinOperationCompleted(this, error));
sim_operation_ = SIM_OPERATION_NONE;
}
void NotifyUserConnectionInitiated(const Network* network) {
FOR_EACH_OBSERVER(UserActionObserver,
user_action_observers_,
OnConnectionInitiated(this, network));
}
////////////////////////////////////////////////////////////////////////////
// Device updates.
void FlipSimPinRequiredStateIfNeeded() {
if (sim_operation_ != SIM_OPERATION_CHANGE_REQUIRE_PIN)
return;
const NetworkDevice* cellular = FindCellularDevice();
if (cellular) {
NetworkDevice* device = GetNetworkDeviceByPath(cellular->device_path());
if (device->sim_pin_required() == SIM_PIN_NOT_REQUIRED)
device->sim_pin_required_ = SIM_PIN_REQUIRED;
else if (device->sim_pin_required() == SIM_PIN_REQUIRED)
device->sim_pin_required_ = SIM_PIN_NOT_REQUIRED;
}
}
void UpdateNetworkDeviceStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
NetworkDevice* device = GetNetworkDeviceByPath(path);
if (device) {
VLOG(1) << "UpdateNetworkDeviceStatus: " << device->name() << "." << key;
int index = property_index_parser().Get(std::string(key));
if (!device->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkDeviceStatus: Error parsing: "
<< path << "." << key;
} else if (strcmp(key, kCellularAllowRoamingProperty) == 0) {
bool settings_value =
UserCrosSettingsProvider::cached_data_roaming_enabled();
if (device->data_roaming_allowed() != settings_value) {
// Switch back to signed settings value.
SetCellularDataRoamingAllowed(settings_value);
return;
}
}
// Notify only observers on device property change.
NotifyNetworkDeviceChanged(device);
}
}
////////////////////////////////////////////////////////////////////////////
// Service updates.
void UpdateNetworkStatus(const char* path,
const char* key,
const Value* value) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (key == NULL || value == NULL)
return;
Network* network = FindNetworkByPath(path);
if (network) {
VLOG(2) << "UpdateNetworkStatus: " << network->name() << "." << key;
// Note: ParseValue is virtual.
int index = property_index_parser().Get(std::string(key));
if (!network->ParseValue(index, value)) {
LOG(WARNING) << "UpdateNetworkStatus: Error parsing: "
<< path << "." << key;
}
NotifyNetworkChanged(network);
// Anything observing the manager needs to know about any service change.
NotifyNetworkManagerChanged(false); // Not forced.
}
}
////////////////////////////////////////////////////////////////////////////
// Data Plans.
const CellularDataPlan* GetSignificantDataPlanFromVector(
const CellularDataPlanVector* plans) const {
const CellularDataPlan* significant = NULL;
for (CellularDataPlanVector::const_iterator iter = plans->begin();
iter != plans->end(); ++iter) {
// Set significant to the first plan or to first non metered base plan.
if (significant == NULL ||
significant->plan_type == CELLULAR_DATA_PLAN_METERED_BASE)
significant = *iter;
}
return significant;
}
CellularNetwork::DataLeft GetDataLeft(
CellularDataPlanVector* data_plans) {
const CellularDataPlan* plan = GetSignificantDataPlanFromVector(data_plans);
if (!plan)
return CellularNetwork::DATA_UNKNOWN;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
base::TimeDelta remaining = plan->remaining_time();
if (remaining <= base::TimeDelta::FromSeconds(0))
return CellularNetwork::DATA_NONE;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs))
return CellularNetwork::DATA_VERY_LOW;
if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs))
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
} else if (plan->plan_type == CELLULAR_DATA_PLAN_METERED_PAID ||
plan->plan_type == CELLULAR_DATA_PLAN_METERED_BASE) {
int64 remaining = plan->remaining_data();
if (remaining <= 0)
return CellularNetwork::DATA_NONE;
if (remaining <= kCellularDataVeryLowBytes)
return CellularNetwork::DATA_VERY_LOW;
// For base plans, we do not care about low data.
if (remaining <= kCellularDataLowBytes &&
plan->plan_type != CELLULAR_DATA_PLAN_METERED_BASE)
return CellularNetwork::DATA_LOW;
return CellularNetwork::DATA_NORMAL;
}
return CellularNetwork::DATA_UNKNOWN;
}
void UpdateCellularDataPlan(const std::string& service_path,
const CellularDataPlanList* data_plan_list) {
VLOG(1) << "Updating cellular data plans for: " << service_path;
CellularDataPlanVector* data_plans = NULL;
// Find and delete any existing data plans associated with |service_path|.
CellularDataPlanMap::iterator found = data_plan_map_.find(service_path);
if (found != data_plan_map_.end()) {
data_plans = found->second;
data_plans->reset(); // This will delete existing data plans.
} else {
data_plans = new CellularDataPlanVector;
data_plan_map_[service_path] = data_plans;
}
for (size_t i = 0; i < data_plan_list->plans_size; i++) {
const CellularDataPlanInfo* info(data_plan_list->GetCellularDataPlan(i));
CellularDataPlan* plan = new CellularDataPlan(*info);
data_plans->push_back(plan);
VLOG(2) << " Plan: " << plan->GetPlanDesciption()
<< " : " << plan->GetDataRemainingDesciption();
}
// Now, update any matching cellular network's cached data
CellularNetwork* cellular = FindCellularNetworkByPath(service_path);
if (cellular) {
CellularNetwork::DataLeft data_left;
// If the network needs a new plan, then there's no data.
if (cellular->needs_new_plan())
data_left = CellularNetwork::DATA_NONE;
else
data_left = GetDataLeft(data_plans);
VLOG(2) << " Data left: " << data_left
<< " Need plan: " << cellular->needs_new_plan();
cellular->set_data_left(data_left);
}
NotifyCellularDataPlanChanged();
}
////////////////////////////////////////////////////////////////////////////
void Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
if (EnsureCrosLoaded()) {
VLOG(1) << "Requesting initial network manager info from libcros.";
RequestNetworkManagerInfo(&NetworkManagerUpdate, this);
}
}
void InitTestData() {
is_locked_ = false;
// Devices
int devices =
(1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR);
available_devices_ = devices;
enabled_devices_ = devices;
connected_devices_ = devices;
NetworkDevice* cellular = new NetworkDevice("cellular");
scoped_ptr<Value> cellular_type(Value::CreateStringValue(kTypeCellular));
cellular->ParseValue(PROPERTY_INDEX_TYPE, cellular_type.get());
cellular->IMSI_ = "123456789012345";
device_map_["cellular"] = cellular;
// Networks
ClearNetworks(true /*delete networks*/);
ethernet_ = new EthernetNetwork("eth1");
ethernet_->set_connected(true);
AddNetwork(ethernet_);
WifiNetwork* wifi1 = new WifiNetwork("fw1");
wifi1->set_name("Fake Wifi Connected");
wifi1->set_strength(90);
wifi1->set_connected(true);
wifi1->set_active(true);
wifi1->set_encryption(SECURITY_NONE);
AddNetwork(wifi1);
WifiNetwork* wifi2 = new WifiNetwork("fw2");
wifi2->set_name("Fake Wifi");
wifi2->set_strength(70);
wifi2->set_connected(false);
wifi2->set_encryption(SECURITY_NONE);
AddNetwork(wifi2);
WifiNetwork* wifi3 = new WifiNetwork("fw3");
wifi3->set_name("Fake Wifi Encrypted");
wifi3->set_strength(60);
wifi3->set_connected(false);
wifi3->set_encryption(SECURITY_WEP);
wifi3->set_passphrase_required(true);
AddNetwork(wifi3);
WifiNetwork* wifi4 = new WifiNetwork("fw4");
wifi4->set_name("Fake Wifi 802.1x");
wifi4->set_strength(50);
wifi4->set_connected(false);
wifi4->set_connectable(false);
wifi4->set_encryption(SECURITY_8021X);
wifi4->set_identity("nobody@google.com");
wifi4->set_cert_path("SETTINGS:key_id=3,cert_id=3,pin=111111");
AddNetwork(wifi4);
active_wifi_ = wifi1;
CellularNetwork* cellular1 = new CellularNetwork("fc1");
cellular1->set_name("Fake Cellular");
cellular1->set_strength(70);
cellular1->set_connected(true);
cellular1->set_active(true);
cellular1->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular1->set_payment_url(std::string("http://www.google.com"));
cellular1->set_usage_url(std::string("http://www.google.com"));
cellular1->set_network_technology(NETWORK_TECHNOLOGY_EVDO);
cellular1->set_roaming_state(ROAMING_STATE_ROAMING);
CellularDataPlan* base_plan = new CellularDataPlan();
base_plan->plan_name = "Base plan";
base_plan->plan_type = CELLULAR_DATA_PLAN_METERED_BASE;
base_plan->plan_data_bytes = 100ll * 1024 * 1024;
base_plan->data_bytes_used = 75ll * 1024 * 1024;
CellularDataPlanVector* data_plans = new CellularDataPlanVector();
data_plan_map_[cellular1->service_path()] = data_plans;
data_plans->push_back(base_plan);
CellularDataPlan* paid_plan = new CellularDataPlan();
paid_plan->plan_name = "Paid plan";
paid_plan->plan_type = CELLULAR_DATA_PLAN_METERED_PAID;
paid_plan->plan_data_bytes = 5ll * 1024 * 1024 * 1024;
paid_plan->data_bytes_used = 3ll * 1024 * 1024 * 1024;
data_plans->push_back(paid_plan);
AddNetwork(cellular1);
active_cellular_ = cellular1;
CellularNetwork* cellular2 = new CellularNetwork("fc2");
cellular2->set_name("Fake Cellular 2");
cellular2->set_strength(70);
cellular2->set_connected(true);
cellular2->set_activation_state(ACTIVATION_STATE_ACTIVATED);
cellular2->set_network_technology(NETWORK_TECHNOLOGY_UMTS);
AddNetwork(cellular2);
// Remembered Networks
ClearRememberedNetworks(true /*delete networks*/);
WifiNetwork* remembered_wifi2 = new WifiNetwork("fw2");
remembered_wifi2->set_name("Fake Wifi 2");
remembered_wifi2->set_strength(70);
remembered_wifi2->set_connected(true);
remembered_wifi2->set_encryption(SECURITY_WEP);
AddRememberedWifiNetwork(remembered_wifi2);
// VPNs.
VirtualNetwork* vpn1 = new VirtualNetwork("fv1");
vpn1->set_name("Fake VPN Provider 1");
vpn1->set_server_hostname("vpn1server.fake.com");
vpn1->set_provider_type(VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_PSK);
vpn1->set_username("VPN User 1");
vpn1->set_connected(false);
AddNetwork(vpn1);
VirtualNetwork* vpn2 = new VirtualNetwork("fv2");
vpn2->set_name("Fake VPN Provider 2");
vpn2->set_server_hostname("vpn2server.fake.com");
vpn2->set_provider_type(VirtualNetwork::PROVIDER_TYPE_L2TP_IPSEC_USER_CERT);
vpn2->set_username("VPN User 2");
vpn2->set_connected(true);
AddNetwork(vpn2);
VirtualNetwork* vpn3 = new VirtualNetwork("fv3");
vpn3->set_name("Fake VPN Provider 3");
vpn3->set_server_hostname("vpn3server.fake.com");
vpn3->set_provider_type(VirtualNetwork::PROVIDER_TYPE_OPEN_VPN);
vpn3->set_connected(false);
AddNetwork(vpn3);
active_virtual_ = vpn2;
wifi_scanning_ = false;
offline_mode_ = false;
}
// Network manager observer list
ObserverList<NetworkManagerObserver> network_manager_observers_;
// Cellular data plan observer list
ObserverList<CellularDataPlanObserver> data_plan_observers_;
// PIN operation observer list.
ObserverList<PinOperationObserver> pin_operation_observers_;
// User action observer list
ObserverList<UserActionObserver> user_action_observers_;
// Network observer map
NetworkObserverMap network_observers_;
// Network device observer map.
NetworkDeviceObserverMap network_device_observers_;
// For monitoring network manager status changes.
PropertyChangeMonitor network_manager_monitor_;
// For monitoring data plan changes to the connected cellular network.
DataPlanUpdateMonitor data_plan_monitor_;
// Network login observer.
scoped_ptr<NetworkLoginObserver> network_login_observer_;
// A service path based map of all Networks.
NetworkMap network_map_;
// A unique_id_ based map of Networks.
NetworkMap network_unique_id_map_;
// A service path based map of all remembered Networks.
NetworkMap remembered_network_map_;
// A list of services that we are awaiting updates for.
PriorityMap network_update_requests_;
// A device path based map of all NetworkDevices.
NetworkDeviceMap device_map_;
// A network service path based map of all CellularDataPlanVectors.
CellularDataPlanMap data_plan_map_;
// The ethernet network.
EthernetNetwork* ethernet_;
// The list of available wifi networks.
WifiNetworkVector wifi_networks_;
// The current connected (or connecting) wifi network.
WifiNetwork* active_wifi_;
// The remembered wifi networks.
WifiNetworkVector remembered_wifi_networks_;
// The list of available cellular networks.
CellularNetworkVector cellular_networks_;
// The current connected (or connecting) cellular network.
CellularNetwork* active_cellular_;
// The list of available virtual networks.
VirtualNetworkVector virtual_networks_;
// The current connected (or connecting) virtual network.
VirtualNetwork* active_virtual_;
// The path of the active profile (for retrieving remembered services).
std::string active_profile_path_;
// The current available network devices. Bitwise flag of ConnectionTypes.
int available_devices_;
// The current enabled network devices. Bitwise flag of ConnectionTypes.
int enabled_devices_;
// The current connected network devices. Bitwise flag of ConnectionTypes.
int connected_devices_;
// True if we are currently scanning for wifi networks.
bool wifi_scanning_;
// Currently not implemented. TODO: implement or eliminate.
bool offline_mode_;
// True if access network library is locked.
bool is_locked_;
// Type of pending SIM operation, SIM_OPERATION_NONE otherwise.
SimOperationType sim_operation_;
// Delayed task to notify a network change.
CancelableTask* notify_task_;
// Cellular plan payment time.
base::Time cellular_plan_payment_time_;
// Temporary connection data for async connect calls.
struct ConnectData {
ConnectionSecurity security;
std::string service_name; // For example, SSID.
std::string passphrase;
EAPMethod eap_method;
EAPPhase2Auth eap_auth;
std::string eap_server_ca_cert_nss_nickname;
bool eap_use_system_cas;
std::string eap_client_cert_pkcs11_id;
std::string eap_identity;
std::string eap_anonymous_identity;
bool save_credentials;
std::string psk_key;
std::string psk_username;
std::string server_hostname;
};
ConnectData connect_data_;
DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl);
};
class NetworkLibraryStubImpl : public NetworkLibrary {
public:
NetworkLibraryStubImpl()
: ip_address_("1.1.1.1"),
ethernet_(new EthernetNetwork("eth0")),
active_wifi_(NULL),
active_cellular_(NULL) {
}
~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; }
virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {}
virtual void AddNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveNetworkObserver(const std::string& service_path,
NetworkObserver* observer) {}
virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {}
virtual void AddNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {}
virtual void RemoveNetworkDeviceObserver(const std::string& device_path,
NetworkDeviceObserver* observer) {}
virtual void Lock() {}
virtual void Unlock() {}
virtual bool IsLocked() { return false; }
virtual void AddCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void RemoveCellularDataPlanObserver(
CellularDataPlanObserver* observer) {}
virtual void AddPinOperationObserver(PinOperationObserver* observer) {}
virtual void RemovePinOperationObserver(PinOperationObserver* observer) {}
virtual void AddUserActionObserver(UserActionObserver* observer) {}
virtual void RemoveUserActionObserver(UserActionObserver* observer) {}
virtual const EthernetNetwork* ethernet_network() const {
return ethernet_;
}
virtual bool ethernet_connecting() const { return false; }
virtual bool ethernet_connected() const { return true; }
virtual const WifiNetwork* wifi_network() const {
return active_wifi_;
}
virtual bool wifi_connecting() const { return false; }
virtual bool wifi_connected() const { return false; }
virtual const CellularNetwork* cellular_network() const {
return active_cellular_;
}
virtual bool cellular_connecting() const { return false; }
virtual bool cellular_connected() const { return false; }
virtual const VirtualNetwork* virtual_network() const {
return active_virtual_;
}
virtual bool virtual_network_connecting() const { return false; }
virtual bool virtual_network_connected() const { return false; }
bool Connected() const { return true; }
bool Connecting() const { return false; }
const std::string& IPAddress() const { return ip_address_; }
virtual const WifiNetworkVector& wifi_networks() const {
return wifi_networks_;
}
virtual const WifiNetworkVector& remembered_wifi_networks() const {
return wifi_networks_;
}
virtual const CellularNetworkVector& cellular_networks() const {
return cellular_networks_;
}
virtual const VirtualNetworkVector& virtual_networks() const {
return virtual_networks_;
}
virtual bool has_cellular_networks() const {
return cellular_networks_.begin() != cellular_networks_.end();
}
/////////////////////////////////////////////////////////////////////////////
virtual const NetworkDevice* FindNetworkDeviceByPath(
const std::string& path) const { return NULL; }
virtual const NetworkDevice* FindCellularDevice() const {
return NULL;
}
virtual const NetworkDevice* FindEthernetDevice() const {
return NULL;
}
virtual const NetworkDevice* FindWifiDevice() const {
return NULL;
}
virtual Network* FindNetworkByPath(
const std::string& path) const { return NULL; }
virtual WifiNetwork* FindWifiNetworkByPath(
const std::string& path) const { return NULL; }
virtual CellularNetwork* FindCellularNetworkByPath(
const std::string& path) const { return NULL; }
virtual VirtualNetwork* FindVirtualNetworkByPath(
const std::string& path) const { return NULL; }
virtual Network* FindNetworkFromRemembered(
const Network* remembered) const { return NULL; }
virtual const CellularDataPlanVector* GetDataPlans(
const std::string& path) const { return NULL; }
virtual const CellularDataPlan* GetSignificantDataPlan(
const std::string& path) const { return NULL; }
virtual void ChangePin(const std::string& old_pin,
const std::string& new_pin) {}
virtual void ChangeRequirePin(bool require_pin, const std::string& pin) {}
virtual void EnterPin(const std::string& pin) {}
virtual void UnblockPin(const std::string& puk, const std::string& new_pin) {}
virtual void RequestCellularScan() {}
virtual void RequestCellularRegister(const std::string& network_id) {}
virtual void SetCellularDataRoamingAllowed(bool new_value) {}
virtual void RequestNetworkScan() {}
virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
return false;
}
virtual void ConnectToWifiNetwork(WifiNetwork* network) {}
virtual void ConnectToWifiNetwork(const std::string& service_path) {}
virtual void ConnectToWifiNetwork(const std::string& ssid,
ConnectionSecurity security,
const std::string& passphrase) {}
virtual void ConnectToWifiNetwork8021x(
const std::string& ssid,
EAPMethod method,
EAPPhase2Auth auth,
const std::string& server_ca_cert_nss_nickname,
bool use_system_cas,
const std::string& client_cert_pkcs11_id,
const std::string& identity,
const std::string& anonymous_identity,
const std::string& passphrase,
bool save_credentials) {}
virtual void ConnectToCellularNetwork(CellularNetwork* network) {}
virtual void ConnectToVirtualNetwork(VirtualNetwork* network) {}
virtual void ConnectToVirtualNetworkPSK(
const std::string& service_name,
const std::string& server,
const std::string& psk,
const std::string& username,
const std::string& user_passphrase) {}
virtual void SignalCellularPlanPayment() {}
virtual bool HasRecentCellularPlanPayment() { return false; }
virtual void DisconnectFromNetwork(const Network* network) {}
virtual void ForgetWifiNetwork(const std::string& service_path) {}
virtual bool ethernet_available() const { return true; }
virtual bool wifi_available() const { return false; }
virtual bool cellular_available() const { return false; }
virtual bool ethernet_enabled() const { return true; }
virtual bool wifi_enabled() const { return false; }
virtual bool cellular_enabled() const { return false; }
virtual bool wifi_scanning() const { return false; }
virtual const Network* active_network() const { return NULL; }
virtual const Network* connected_network() const { return NULL; }
virtual bool offline_mode() const { return false; }
virtual void EnableEthernetNetworkDevice(bool enable) {}
virtual void EnableWifiNetworkDevice(bool enable) {}
virtual void EnableCellularNetworkDevice(bool enable) {}
virtual void EnableOfflineMode(bool enable) {}
virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
std::string* hardware_address,
HardwareAddressFormat) {
hardware_address->clear();
return NetworkIPConfigVector();
}
private:
std::string ip_address_;
EthernetNetwork* ethernet_;
WifiNetwork* active_wifi_;
CellularNetwork* active_cellular_;
VirtualNetwork* active_virtual_;
WifiNetworkVector wifi_networks_;
CellularNetworkVector cellular_networks_;
VirtualNetworkVector virtual_networks_;
};
// static
NetworkLibrary* NetworkLibrary::GetImpl(bool stub) {
if (stub)
return new NetworkLibraryStubImpl();
else
return new NetworkLibraryImpl();
}
} // namespace chromeos
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl);
|
#include "Environment.hpp"
#include "Entity.hpp"
#include "Ball.hpp"
#include "Field.hpp"
#include "Robot.hpp"
#include <Constants.hpp>
#include <Network.hpp>
#include <Geometry2d/Util.hpp>
#include <protobuf/messages_robocup_ssl_detection.pb.h>
#include <protobuf/messages_robocup_ssl_geometry.pb.h>
#include <protobuf/messages_robocup_ssl_wrapper.pb.h>
#include <QDomDocument>
#include <QDomAttr>
#include <QDebug>
#include <QFile>
#include <stdexcept>
#include <iostream>
#include <sys/time.h>
using namespace std;
using namespace Geometry2d;
static const QHostAddress LocalAddress(QHostAddress::LocalHost);
static const QHostAddress MulticastAddress(SharedVisionAddress);
const int Oversample = 1;
Environment::Environment(const QString& configFile, bool sendShared_,
SimEngine* engine)
: _dropFrame(false),
_configFile(configFile),
_frameNumber(0),
_stepCount(0),
_simEngine(engine),
sendShared(sendShared_),
ballVisibility(100) {
// NOTE: does not start simulation/thread until triggered
_field = new Field(this);
_field->initPhysics();
loadConfigFile(_configFile);
}
Environment::~Environment() { delete _field; }
void Environment::connectSockets() {
// Bind sockets
bool success = (_visionSocket.bind(SimCommandPort) &&
_radioSocketYellow.bind(RadioTxPort) &&
_radioSocketBlue.bind(RadioTxPort + 1));
if (!success) {
throw std::runtime_error(
"Unable to bind sockets. Is there another instance of simulator "
"already running?");
}
gettimeofday(&_lastStepTime, nullptr);
connect(&_timer, SIGNAL(timeout()), SLOT(step()));
_timer.start(16 / Oversample);
}
void Environment::preStep(float deltaTime) {
for (::Robot* robot : _yellow) {
robot->applyEngineForces(deltaTime);
}
for (::Robot* robot : _blue) {
robot->applyEngineForces(deltaTime);
}
}
void Environment::step() {
// Check for SimCommands
while (_visionSocket.hasPendingDatagrams()) {
Packet::SimCommand cmd;
if (!loadPacket<Packet::SimCommand>(_visionSocket, cmd)) continue;
handleSimCommand(cmd);
}
// Check for RadioTx packets from blue team
while (_radioSocketBlue.hasPendingDatagrams()) {
Packet::RadioTx tx;
if (!loadPacket<Packet::RadioTx>(_radioSocketBlue, tx)) continue;
handleRadioTx(true, tx);
}
// Check for RadioTx packets from yellow team
while (_radioSocketYellow.hasPendingDatagrams()) {
Packet::RadioTx tx;
if (!loadPacket<Packet::RadioTx>(_radioSocketYellow, tx)) continue;
handleRadioTx(false, tx);
}
// timing
struct timeval tv;
gettimeofday(&tv, nullptr);
_lastStepTime = tv;
// execute simulation step
// TODO: execute
// Send vision data
++_stepCount;
if (_stepCount == Oversample) {
_stepCount = 0;
if (_dropFrame) {
_dropFrame = false;
} else {
sendVision();
}
}
}
void Environment::handleSimCommand(const Packet::SimCommand& cmd) {
if (!_balls.empty()) {
if (cmd.has_ball_vel()) {
// added because physics engine was maintaining some state
// related to velocity causing the ball to keep going even
// when we send a command to set velocity to 0.
_balls[0]->resetScene();
_balls[0]->velocity(cmd.ball_vel().x(), cmd.ball_vel().y());
}
if (cmd.has_ball_pos()) {
_balls[0]->position(cmd.ball_pos().x(), cmd.ball_pos().y());
}
}
for (const Packet::SimCommand::Robot& rcmd : cmd.robots()) {
const RobotMap& team = rcmd.blue_team() ? _blue : _yellow;
RobotMap::const_iterator i = team.find(rcmd.shell());
if (i == team.end()) {
if (rcmd.has_pos()) {
// add a new robot
addRobot(
rcmd.blue_team(), rcmd.shell(), rcmd.pos(),
Robot::rev2008); // TODO: make this check robot revision
} else {
// if there's no position, we can't add a robot
printf("Trying to override non-existent robot %d:%d\n",
rcmd.blue_team(), rcmd.shell());
continue;
}
}
// remove a robot if it is marked not visible
if (rcmd.has_visible() && !rcmd.visible()) {
removeRobot(rcmd.blue_team(), rcmd.shell());
continue;
}
// change existing robots
Robot* robot = *i;
if (rcmd.has_pos()) {
float x = rcmd.pos().x();
float y = rcmd.pos().y();
robot->position(x, y);
QVector3D pos3(x, y, 0.0);
QVector3D axis(0.0, 0.0, 1.0);
}
float new_w = 0.0;
if (rcmd.has_w()) {
new_w = rcmd.w();
if (!rcmd.has_vel()) {
robot->velocity(0.0, 0.0, new_w);
}
}
if (rcmd.has_vel()) {
robot->velocity(rcmd.vel().x(), rcmd.vel().y(), new_w);
}
}
if (cmd.has_reset() && cmd.reset()) {
resetScene();
}
}
void Environment::sendVision() {
SSL_WrapperPacket wrapper;
SSL_DetectionFrame* det = wrapper.mutable_detection();
det->set_frame_number(_frameNumber++);
det->set_camera_id(0);
struct timeval tv;
gettimeofday(&tv, nullptr);
det->set_t_capture(tv.tv_sec + (double)tv.tv_usec * 1.0e-6);
det->set_t_sent(det->t_capture());
for (Robot* robot : _yellow) {
if ((rand() % 100) < robot->visibility) {
SSL_DetectionRobot* out = det->add_robots_yellow();
convert_robot(robot, out);
}
}
for (Robot* robot : _blue) {
if ((rand() % 100) < robot->visibility) {
SSL_DetectionRobot* out = det->add_robots_blue();
convert_robot(robot, out);
}
}
for (const Ball* b : _balls) {
Geometry2d::Point ballPos = b->getPosition();
// bool occ;
// if (ballPos.x < 0)
// {
// occ = occluded(ballPos, cam0);
// } else {
// occ = occluded(ballPos, cam1);
// }
if ((rand() % 100) < ballVisibility) {
SSL_DetectionBall* out = det->add_balls();
out->set_confidence(1);
out->set_x(ballPos.x() * 1000);
out->set_y(ballPos.y() * 1000);
out->set_pixel_x(ballPos.x() * 1000);
out->set_pixel_y(ballPos.y() * 1000);
}
}
std::string buf;
wrapper.SerializeToString(&buf);
if (sendShared) {
_visionSocket.writeDatagram(&buf[0], buf.size(), MulticastAddress,
SharedVisionPort);
} else {
_visionSocket.writeDatagram(&buf[0], buf.size(), LocalAddress,
SimVisionPort);
_visionSocket.writeDatagram(&buf[0], buf.size(), LocalAddress,
SimVisionPort + 1);
}
}
void Environment::convert_robot(const Robot* robot, SSL_DetectionRobot* out) {
Geometry2d::Point pos = robot->getPosition();
out->set_confidence(1);
out->set_robot_id(robot->shell);
out->set_x(pos.x() * 1000);
out->set_y(pos.y() * 1000);
out->set_orientation(robot->getAngle());
out->set_pixel_x(pos.x() * 1000);
out->set_pixel_y(pos.y() * 1000);
}
void Environment::addBall(Geometry2d::Point pos) {
Ball* b = new Ball(this);
b->initPhysics();
b->position(pos.x(), pos.y());
_balls.append(b);
printf("New Ball: %f %f\n", pos.x(), pos.y());
}
void Environment::addRobot(bool blue, int id, Geometry2d::Point pos,
Robot::RobotRevision rev) {
Robot* r = new Robot(this, id, rev, pos);
r->initPhysics(blue);
if (blue) {
_blue.insert(id, r);
} else {
_yellow.insert(id, r);
}
Geometry2d::Point actPos = r->getPosition();
switch (rev) {
case Robot::rev2008:
printf("New 2008 Robot: %d : %f %f\n", id, actPos.x(), actPos.y());
break;
case Robot::rev2011:
printf("New 2011 Robot: %d : %f %f\n", id, actPos.x(), actPos.y());
}
QVector3D pos3(pos.x(), pos.y(), 0.0);
QVector3D axis(0.0, 0.0, 1.0);
}
void Environment::removeRobot(bool blue, int id) {
if (blue) {
_blue.remove(id);
} else {
_yellow.remove(id);
}
}
Geometry2d::Point gaussianPoint(int n, float scale) {
Geometry2d::Point pt;
for (int i = 0; i < n; ++i) {
pt.x() += drand48() - 0.5;
pt.y() += drand48() - 0.5;
}
pt *= scale / n;
return pt;
}
bool Environment::occluded(Geometry2d::Point ball, Geometry2d::Point camera) {
float camZ = 4;
float ballZ = Ball_Radius;
float intZ = Robot_Height;
// FIXME: use actual physics engine to determine line of sight
// Find where the line from the camera to the ball intersects the
// plane at the top of the robots.
//
// intZ = (ballZ - camZ) * t + camZ
float t = (intZ - camZ) / (ballZ - camZ);
Geometry2d::Point intersection;
intersection.x() = (ball.x() - camera.x()) * t + camera.x();
intersection.y() = (ball.y() - camera.y()) * t + camera.y();
// Return true if the intersection point is inside any robot
for (const Robot* r : _blue) {
if (intersection.nearPoint(r->getPosition(), Robot_Radius)) {
return true;
}
}
for (const Robot* r : _yellow) {
if (intersection.nearPoint(r->getPosition(), Robot_Radius)) {
return true;
}
}
return false;
}
Robot* Environment::robot(bool blue, int board_id) const {
const QMap<unsigned int, Robot*>& robots = blue ? _blue : _yellow;
if (robots.contains(board_id)) {
return robots.value(board_id, nullptr);
} else {
return nullptr;
}
}
void Environment::handleRadioTx(bool blue, const Packet::RadioTx& tx) {
for (int i = 0; i < tx.robots_size(); ++i) {
const Packet::Robot& cmd = tx.robots(i);
Robot* r = robot(blue, cmd.uid());
if (r) {
// run controls update
r->radioTx(&cmd.control());
// trigger signals to update visualization
Geometry2d::Point pos2 = r->getPosition();
QVector3D pos3(pos2.x(), pos2.y(), 0.0);
QVector3D axis(0.0, 0.0, 1.0);
} else {
printf("Commanding nonexistent robot %s:%d\n",
blue ? "Blue" : "Yellow", cmd.uid());
}
Packet::RadioRx rx = r->radioRx();
rx.set_robot_id(r->shell);
// Send the RX packet
std::string out;
rx.SerializeToString(&out);
if (blue)
_radioSocketBlue.writeDatagram(&out[0], out.size(), LocalAddress,
RadioRxPort + 1);
else
_radioSocketYellow.writeDatagram(&out[0], out.size(), LocalAddress,
RadioRxPort);
}
// FIXME: the interface changed for this part
// Robot *rev = robot(blue, tx.robot_id());
// if (rev)
// {
// Packet::RadioRx rx = rev->radioRx();
// rx.set_robot_id(tx.robot_id());
//
// // Send the RX packet
// std::string out;
// rx.SerializeToString(&out);
// _radioSocket[ch].writeDatagram(&out[0], out.size(), LocalAddress,
// RadioRxPort + ch);
// }
}
void Environment::renderScene(GL_ShapeDrawer* shapeDrawer,
const btVector3& worldBoundsMin,
const btVector3& worldBoundsMax) {
_field->renderField();
for (Robot* r : _blue) {
r->renderWheels(shapeDrawer, worldBoundsMin, worldBoundsMax);
}
for (Robot* r : _yellow) {
r->renderWheels(shapeDrawer, worldBoundsMin, worldBoundsMax);
}
}
void Environment::resetScene() {
for (Robot* r : _blue) {
r->resetScene();
}
for (Robot* r : _yellow) {
r->resetScene();
}
for (Ball* b : _balls) {
b->resetScene();
}
}
bool Environment::loadConfigFile() { return loadConfigFile(_configFile); }
bool Environment::loadConfigFile(const QString& filename) {
// load the config file
QFile configFile(filename);
if (!configFile.exists()) {
fprintf(stderr, "Configuration file %s does not exist\n",
(const char*)filename.toLatin1());
return false;
}
QDomDocument _doc;
if (!configFile.open(QIODevice::ReadOnly)) {
throw std::runtime_error("Unable to open config file.");
}
if (!_doc.setContent(&configFile)) {
configFile.close();
throw std::runtime_error("Internal: unable to set document content.");
}
configFile.close();
// load rest of file
qDebug() << "Loading config: " << filename;
QDomElement root = _doc.documentElement();
if (root.isNull() || root.tagName() != QString("simulation")) {
throw std::runtime_error("Document format: expected <motion> tag");
}
QDomElement element = root.firstChildElement();
while (!element.isNull()) {
if (element.tagName() == QString("ball")) {
float x = element.attribute("x").toFloat();
float y = element.attribute("y").toFloat();
addBall(Geometry2d::Point(x, y));
} else if (element.tagName() == QString("blue")) {
procTeam(element, true);
} else if (element.tagName() == QString("yellow")) {
procTeam(element, false);
}
element = element.nextSiblingElement();
}
return true;
}
void Environment::procTeam(QDomElement e, bool blue) {
QDomElement elem = e.firstChildElement();
while (!elem.isNull()) {
if (elem.tagName() == "robot") {
float x = elem.attribute("x").toFloat();
float y = elem.attribute("y").toFloat();
int id = elem.attribute("id").toInt();
if (elem.hasAttribute("rev")) {
QString rev = elem.attribute("rev");
Robot::RobotRevision r = Robot::rev2008;
if (rev.contains("2008")) {
r = Robot::rev2008;
} else if (rev.contains("2011")) {
r = Robot::rev2011;
}
addRobot(blue, id, Geometry2d::Point(x, y), r);
} else {
addRobot(blue, id, Geometry2d::Point(x, y), Robot::rev2008);
}
}
elem = elem.nextSiblingElement();
}
}
void Environment::reshapeFieldBodies() { _field->reshapeBodies(); }
Only reset simulator scene when placing ball
#include "Environment.hpp"
#include "Entity.hpp"
#include "Ball.hpp"
#include "Field.hpp"
#include "Robot.hpp"
#include <Constants.hpp>
#include <Network.hpp>
#include <Geometry2d/Util.hpp>
#include <protobuf/messages_robocup_ssl_detection.pb.h>
#include <protobuf/messages_robocup_ssl_geometry.pb.h>
#include <protobuf/messages_robocup_ssl_wrapper.pb.h>
#include <QDomDocument>
#include <QDomAttr>
#include <QDebug>
#include <QFile>
#include <stdexcept>
#include <iostream>
#include <sys/time.h>
using namespace std;
using namespace Geometry2d;
static const QHostAddress LocalAddress(QHostAddress::LocalHost);
static const QHostAddress MulticastAddress(SharedVisionAddress);
const int Oversample = 1;
Environment::Environment(const QString& configFile, bool sendShared_,
SimEngine* engine)
: _dropFrame(false),
_configFile(configFile),
_frameNumber(0),
_stepCount(0),
_simEngine(engine),
sendShared(sendShared_),
ballVisibility(100) {
// NOTE: does not start simulation/thread until triggered
_field = new Field(this);
_field->initPhysics();
loadConfigFile(_configFile);
}
Environment::~Environment() { delete _field; }
void Environment::connectSockets() {
// Bind sockets
bool success = (_visionSocket.bind(SimCommandPort) &&
_radioSocketYellow.bind(RadioTxPort) &&
_radioSocketBlue.bind(RadioTxPort + 1));
if (!success) {
throw std::runtime_error(
"Unable to bind sockets. Is there another instance of simulator "
"already running?");
}
gettimeofday(&_lastStepTime, nullptr);
connect(&_timer, SIGNAL(timeout()), SLOT(step()));
_timer.start(16 / Oversample);
}
void Environment::preStep(float deltaTime) {
for (::Robot* robot : _yellow) {
robot->applyEngineForces(deltaTime);
}
for (::Robot* robot : _blue) {
robot->applyEngineForces(deltaTime);
}
}
void Environment::step() {
// Check for SimCommands
while (_visionSocket.hasPendingDatagrams()) {
Packet::SimCommand cmd;
if (!loadPacket<Packet::SimCommand>(_visionSocket, cmd)) continue;
handleSimCommand(cmd);
}
// Check for RadioTx packets from blue team
while (_radioSocketBlue.hasPendingDatagrams()) {
Packet::RadioTx tx;
if (!loadPacket<Packet::RadioTx>(_radioSocketBlue, tx)) continue;
handleRadioTx(true, tx);
}
// Check for RadioTx packets from yellow team
while (_radioSocketYellow.hasPendingDatagrams()) {
Packet::RadioTx tx;
if (!loadPacket<Packet::RadioTx>(_radioSocketYellow, tx)) continue;
handleRadioTx(false, tx);
}
// timing
struct timeval tv;
gettimeofday(&tv, nullptr);
_lastStepTime = tv;
// execute simulation step
// TODO: execute
// Send vision data
++_stepCount;
if (_stepCount == Oversample) {
_stepCount = 0;
if (_dropFrame) {
_dropFrame = false;
} else {
sendVision();
}
}
}
void Environment::handleSimCommand(const Packet::SimCommand& cmd) {
if (!_balls.empty()) {
if (cmd.has_ball_vel()) {
// added because physics engine was maintaining some state
// related to velocity causing the ball to keep going even
// when we send a command to set velocity to 0.
if (cmd.ball_vel().x() == 0 && cmd.ball_vel().y() == 0) {
_balls[0]->resetScene();
}
_balls[0]->velocity(cmd.ball_vel().x(), cmd.ball_vel().y());
}
if (cmd.has_ball_pos()) {
_balls[0]->position(cmd.ball_pos().x(), cmd.ball_pos().y());
}
}
for (const Packet::SimCommand::Robot& rcmd : cmd.robots()) {
const RobotMap& team = rcmd.blue_team() ? _blue : _yellow;
RobotMap::const_iterator i = team.find(rcmd.shell());
if (i == team.end()) {
if (rcmd.has_pos()) {
// add a new robot
addRobot(
rcmd.blue_team(), rcmd.shell(), rcmd.pos(),
Robot::rev2008); // TODO: make this check robot revision
} else {
// if there's no position, we can't add a robot
printf("Trying to override non-existent robot %d:%d\n",
rcmd.blue_team(), rcmd.shell());
continue;
}
}
// remove a robot if it is marked not visible
if (rcmd.has_visible() && !rcmd.visible()) {
removeRobot(rcmd.blue_team(), rcmd.shell());
continue;
}
// change existing robots
Robot* robot = *i;
if (rcmd.has_pos()) {
float x = rcmd.pos().x();
float y = rcmd.pos().y();
robot->position(x, y);
QVector3D pos3(x, y, 0.0);
QVector3D axis(0.0, 0.0, 1.0);
}
float new_w = 0.0;
if (rcmd.has_w()) {
new_w = rcmd.w();
if (!rcmd.has_vel()) {
robot->velocity(0.0, 0.0, new_w);
}
}
if (rcmd.has_vel()) {
robot->velocity(rcmd.vel().x(), rcmd.vel().y(), new_w);
}
}
if (cmd.has_reset() && cmd.reset()) {
resetScene();
}
}
void Environment::sendVision() {
SSL_WrapperPacket wrapper;
SSL_DetectionFrame* det = wrapper.mutable_detection();
det->set_frame_number(_frameNumber++);
det->set_camera_id(0);
struct timeval tv;
gettimeofday(&tv, nullptr);
det->set_t_capture(tv.tv_sec + (double)tv.tv_usec * 1.0e-6);
det->set_t_sent(det->t_capture());
for (Robot* robot : _yellow) {
if ((rand() % 100) < robot->visibility) {
SSL_DetectionRobot* out = det->add_robots_yellow();
convert_robot(robot, out);
}
}
for (Robot* robot : _blue) {
if ((rand() % 100) < robot->visibility) {
SSL_DetectionRobot* out = det->add_robots_blue();
convert_robot(robot, out);
}
}
for (const Ball* b : _balls) {
Geometry2d::Point ballPos = b->getPosition();
// bool occ;
// if (ballPos.x < 0)
// {
// occ = occluded(ballPos, cam0);
// } else {
// occ = occluded(ballPos, cam1);
// }
if ((rand() % 100) < ballVisibility) {
SSL_DetectionBall* out = det->add_balls();
out->set_confidence(1);
out->set_x(ballPos.x() * 1000);
out->set_y(ballPos.y() * 1000);
out->set_pixel_x(ballPos.x() * 1000);
out->set_pixel_y(ballPos.y() * 1000);
}
}
std::string buf;
wrapper.SerializeToString(&buf);
if (sendShared) {
_visionSocket.writeDatagram(&buf[0], buf.size(), MulticastAddress,
SharedVisionPort);
} else {
_visionSocket.writeDatagram(&buf[0], buf.size(), LocalAddress,
SimVisionPort);
_visionSocket.writeDatagram(&buf[0], buf.size(), LocalAddress,
SimVisionPort + 1);
}
}
void Environment::convert_robot(const Robot* robot, SSL_DetectionRobot* out) {
Geometry2d::Point pos = robot->getPosition();
out->set_confidence(1);
out->set_robot_id(robot->shell);
out->set_x(pos.x() * 1000);
out->set_y(pos.y() * 1000);
out->set_orientation(robot->getAngle());
out->set_pixel_x(pos.x() * 1000);
out->set_pixel_y(pos.y() * 1000);
}
void Environment::addBall(Geometry2d::Point pos) {
Ball* b = new Ball(this);
b->initPhysics();
b->position(pos.x(), pos.y());
_balls.append(b);
printf("New Ball: %f %f\n", pos.x(), pos.y());
}
void Environment::addRobot(bool blue, int id, Geometry2d::Point pos,
Robot::RobotRevision rev) {
Robot* r = new Robot(this, id, rev, pos);
r->initPhysics(blue);
if (blue) {
_blue.insert(id, r);
} else {
_yellow.insert(id, r);
}
Geometry2d::Point actPos = r->getPosition();
switch (rev) {
case Robot::rev2008:
printf("New 2008 Robot: %d : %f %f\n", id, actPos.x(), actPos.y());
break;
case Robot::rev2011:
printf("New 2011 Robot: %d : %f %f\n", id, actPos.x(), actPos.y());
}
QVector3D pos3(pos.x(), pos.y(), 0.0);
QVector3D axis(0.0, 0.0, 1.0);
}
void Environment::removeRobot(bool blue, int id) {
if (blue) {
_blue.remove(id);
} else {
_yellow.remove(id);
}
}
Geometry2d::Point gaussianPoint(int n, float scale) {
Geometry2d::Point pt;
for (int i = 0; i < n; ++i) {
pt.x() += drand48() - 0.5;
pt.y() += drand48() - 0.5;
}
pt *= scale / n;
return pt;
}
bool Environment::occluded(Geometry2d::Point ball, Geometry2d::Point camera) {
float camZ = 4;
float ballZ = Ball_Radius;
float intZ = Robot_Height;
// FIXME: use actual physics engine to determine line of sight
// Find where the line from the camera to the ball intersects the
// plane at the top of the robots.
//
// intZ = (ballZ - camZ) * t + camZ
float t = (intZ - camZ) / (ballZ - camZ);
Geometry2d::Point intersection;
intersection.x() = (ball.x() - camera.x()) * t + camera.x();
intersection.y() = (ball.y() - camera.y()) * t + camera.y();
// Return true if the intersection point is inside any robot
for (const Robot* r : _blue) {
if (intersection.nearPoint(r->getPosition(), Robot_Radius)) {
return true;
}
}
for (const Robot* r : _yellow) {
if (intersection.nearPoint(r->getPosition(), Robot_Radius)) {
return true;
}
}
return false;
}
Robot* Environment::robot(bool blue, int board_id) const {
const QMap<unsigned int, Robot*>& robots = blue ? _blue : _yellow;
if (robots.contains(board_id)) {
return robots.value(board_id, nullptr);
} else {
return nullptr;
}
}
void Environment::handleRadioTx(bool blue, const Packet::RadioTx& tx) {
for (int i = 0; i < tx.robots_size(); ++i) {
const Packet::Robot& cmd = tx.robots(i);
Robot* r = robot(blue, cmd.uid());
if (r) {
// run controls update
r->radioTx(&cmd.control());
// trigger signals to update visualization
Geometry2d::Point pos2 = r->getPosition();
QVector3D pos3(pos2.x(), pos2.y(), 0.0);
QVector3D axis(0.0, 0.0, 1.0);
} else {
printf("Commanding nonexistent robot %s:%d\n",
blue ? "Blue" : "Yellow", cmd.uid());
}
Packet::RadioRx rx = r->radioRx();
rx.set_robot_id(r->shell);
// Send the RX packet
std::string out;
rx.SerializeToString(&out);
if (blue)
_radioSocketBlue.writeDatagram(&out[0], out.size(), LocalAddress,
RadioRxPort + 1);
else
_radioSocketYellow.writeDatagram(&out[0], out.size(), LocalAddress,
RadioRxPort);
}
// FIXME: the interface changed for this part
// Robot *rev = robot(blue, tx.robot_id());
// if (rev)
// {
// Packet::RadioRx rx = rev->radioRx();
// rx.set_robot_id(tx.robot_id());
//
// // Send the RX packet
// std::string out;
// rx.SerializeToString(&out);
// _radioSocket[ch].writeDatagram(&out[0], out.size(), LocalAddress,
// RadioRxPort + ch);
// }
}
void Environment::renderScene(GL_ShapeDrawer* shapeDrawer,
const btVector3& worldBoundsMin,
const btVector3& worldBoundsMax) {
_field->renderField();
for (Robot* r : _blue) {
r->renderWheels(shapeDrawer, worldBoundsMin, worldBoundsMax);
}
for (Robot* r : _yellow) {
r->renderWheels(shapeDrawer, worldBoundsMin, worldBoundsMax);
}
}
void Environment::resetScene() {
for (Robot* r : _blue) {
r->resetScene();
}
for (Robot* r : _yellow) {
r->resetScene();
}
for (Ball* b : _balls) {
b->resetScene();
}
}
bool Environment::loadConfigFile() { return loadConfigFile(_configFile); }
bool Environment::loadConfigFile(const QString& filename) {
// load the config file
QFile configFile(filename);
if (!configFile.exists()) {
fprintf(stderr, "Configuration file %s does not exist\n",
(const char*)filename.toLatin1());
return false;
}
QDomDocument _doc;
if (!configFile.open(QIODevice::ReadOnly)) {
throw std::runtime_error("Unable to open config file.");
}
if (!_doc.setContent(&configFile)) {
configFile.close();
throw std::runtime_error("Internal: unable to set document content.");
}
configFile.close();
// load rest of file
qDebug() << "Loading config: " << filename;
QDomElement root = _doc.documentElement();
if (root.isNull() || root.tagName() != QString("simulation")) {
throw std::runtime_error("Document format: expected <motion> tag");
}
QDomElement element = root.firstChildElement();
while (!element.isNull()) {
if (element.tagName() == QString("ball")) {
float x = element.attribute("x").toFloat();
float y = element.attribute("y").toFloat();
addBall(Geometry2d::Point(x, y));
} else if (element.tagName() == QString("blue")) {
procTeam(element, true);
} else if (element.tagName() == QString("yellow")) {
procTeam(element, false);
}
element = element.nextSiblingElement();
}
return true;
}
void Environment::procTeam(QDomElement e, bool blue) {
QDomElement elem = e.firstChildElement();
while (!elem.isNull()) {
if (elem.tagName() == "robot") {
float x = elem.attribute("x").toFloat();
float y = elem.attribute("y").toFloat();
int id = elem.attribute("id").toInt();
if (elem.hasAttribute("rev")) {
QString rev = elem.attribute("rev");
Robot::RobotRevision r = Robot::rev2008;
if (rev.contains("2008")) {
r = Robot::rev2008;
} else if (rev.contains("2011")) {
r = Robot::rev2011;
}
addRobot(blue, id, Geometry2d::Point(x, y), r);
} else {
addRobot(blue, id, Geometry2d::Point(x, y), Robot::rev2008);
}
}
elem = elem.nextSiblingElement();
}
}
void Environment::reshapeFieldBodies() { _field->reshapeBodies(); }
|
//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
#include "rtcp/RtcpConfig.h"
#define LOGEM
#undef LOGEM
// SYSTEM INCLUDES
#include <assert.h>
#include <string.h>
#ifdef _VXWORKS /* [ */
#include <selectLib.h>
#include <iosLib.h>
#include <inetlib.h>
#endif /* _VXWORKS ] */
#ifdef WIN32 /* [ */
# ifndef WINCE
# include <io.h>
# endif
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#endif /* WIN32 ] */
#ifdef __pingtel_on_posix__ /* [ */
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/time.h>
#endif /* __pingtel_on_posix__ ] */
// APPLICATION INCLUDES
#include "os/OsDefs.h"
#include "os/OsTask.h"
#include "os/OsServerSocket.h"
#include "os/OsConnectionSocket.h"
#include "os/OsEvent.h"
#include "mp/NetInTask.h"
#include "mp/MpUdpBuf.h"
#include "mp/MprFromNet.h"
#include "mp/MpBufferMsg.h"
#include "mp/dmaTask.h"
#ifdef _VXWORKS /* [ */
#ifdef CPU_XSCALE /* [ */
#include "mp/pxa255.h"
#define OSTIMER_COUNTER_POINTER ((int*) PXA250_OSTIMER_OSCR)
#else /* CPU_XSCALE ] [ */
#include "mp/sa1100.h"
#define OSTIMER_COUNTER_POINTER ((int*) SA1100_OSTIMER_COUNTER)
#endif /* CPU_XSCALE ] */
#else /* _VXWORKS ][ */
#define OSTIMER_COUNTER_POINTER (&dummy0)
static int dummy0 = 0;
#endif /* _VXWORKS ] */
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#else
# define RTL_START(x)
# define RTL_BLOCK(x)
# define RTL_EVENT(x,y)
# define RTL_WRITE(x)
# define RTL_STOP
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#define NET_TASK_MAX_MSG_LEN sizeof(netInTaskMsg)
#define NET_TASK_MAX_FD_PAIRS 100
#define MAX_RTP_BYTES 1500
struct __netInTaskMsg {
OsSocket* pRtpSocket;
OsSocket* pRtcpSocket;
MprFromNet* fwdTo;
OsNotification* notify;
};
typedef struct __netInTaskMsg netInTaskMsg, *netInTaskMsgPtr;
// STATIC VARIABLE INITIALIZATIONS
volatile int* pOsTC = OSTIMER_COUNTER_POINTER;
static netInTaskMsg pairs[NET_TASK_MAX_FD_PAIRS];
static int numPairs;
NetInTask* NetInTask::spInstance = 0;
OsRWMutex NetInTask::sLock(OsBSem::Q_PRIORITY);
const int NetInTask::DEF_NET_IN_TASK_PRIORITY = 0; // default task priority: HIGHEST
const int NetInTask::DEF_NET_IN_TASK_OPTIONS = 0; // default task options
#ifdef USING_NET_EQ /* [ */
const int NetInTask::DEF_NET_IN_TASK_STACKSIZE = 40960;//default task stacksize
#else /* USING_NET_EQ ] [ */
const int NetInTask::DEF_NET_IN_TASK_STACKSIZE = 4096;// default task stacksize
#endif /* USING_NET_EQ ] */
#define SIPX_DEBUG
#undef SIPX_DEBUG
/************************************************************************/
/**
* @brief Help create writer side of connection for NetInTask internal use.
*
* This task is used to create connection to socket we're listening. Main task
* create OsServerConnection and wait call OsServerConnection::accept() to
* get reader side of connection. On the side of this task writer side of
* connection is connected.
*/
class NetInTaskHelper : public OsTask
{
public:
NetInTaskHelper(int port);
~NetInTaskHelper();
/// Do the task.
virtual int run(void* pArg);
/// Wait for helper task to finish and return connected socket.
inline OsConnectionSocket* getSocket();
private:
OsConnectionSocket* mpSocket;
int mPort;
};
NetInTaskHelper::NetInTaskHelper(int port)
: OsTask("NetInTaskHelper-%d", NULL, 25, 0, 2000)
, mpSocket(NULL)
, mPort(port)
{
}
NetInTaskHelper::~NetInTaskHelper()
{
waitUntilShutDown();
}
int NetInTaskHelper::run(void*)
{
int numTry = 0;
while (numTry < 1000)
{
// Delay for some time on consecutive runs.
if (numTry > 0)
{
OsTask::delay(1);
}
// Connect...
mpSocket = new OsConnectionSocket(mPort, "127.0.0.1");
if (mpSocket && mpSocket->isConnected()) break;
numTry++;
}
OsSysLog::add(FAC_MP, PRI_INFO,
"NetInTaskHelper::run()... returning 0, after %d tries\n", numTry);
return 0;
}
OsConnectionSocket* NetInTaskHelper::getSocket()
{
waitUntilShutDown();
return mpSocket;
}
/************************************************************************/
int NetInTask::getWriteFD()
{
int writeSocketDescriptor = -1;
if (NULL != mpWriteSocket)
{
writeSocketDescriptor = mpWriteSocket->getSocketDescriptor();
}
else
{
assert(FALSE);
}
return(writeSocketDescriptor);
}
OsConnectionSocket* NetInTask::getWriteSocket()
{
if (NULL == mpWriteSocket) {
getWriteFD();
}
return mpWriteSocket;
}
/************************************************************************/
static OsStatus get1Msg(OsSocket* pRxpSkt, MprFromNet* fwdTo, bool isRtcp,
int ostc)
{
MpUdpBufPtr ib;
int nRead;
struct in_addr fromIP;
int fromPort;
static int numFlushed = 0;
static int flushedLimit = 125;
if (numFlushed >= flushedLimit) {
Zprintf("get1Msg: flushed %d packets! (after %d DMA frames).\n",
numFlushed, showFrameCount(1), 0,0,0,0);
if (flushedLimit<1000000) {
flushedLimit = flushedLimit << 1;
} else {
numFlushed = 0;
flushedLimit = 125;
}
}
// Get new buffer for incoming packet
ib = MpMisc.UdpPool->getBuffer();
if (ib.isValid()) {
// Read packet data.
// Note: nRead could not be greater then buffer size.
nRead = pRxpSkt->read(ib->getWriteDataPtr(), ib->getMaximumPacketSize()
, &fromIP, &fromPort);
// Set size of received data
ib->setPacketSize(nRead);
// Set IP address and port of this packet
ib->setIP(fromIP);
ib->setUdpPort(fromPort);
// Set time we receive this packet.
ib->setTimecode(ostc);
if (nRead > 0)
{
fwdTo->pushPacket(ib, isRtcp);
}
else
{
if (!pRxpSkt->isOk())
{
Zprintf(" *** get1Msg: read(%d) returned %d, errno=%d=0x%X)\n",
(int) pRxpSkt, nRead, errno, errno, 0,0);
return OS_NO_MORE_DATA;
}
}
} else {
// Flush packet if could not get buffer for it.
char buffer[UDP_MTU];
nRead = pRxpSkt->read(buffer, UDP_MTU, &fromIP, &fromPort);
if (numFlushed++ < 10) {
Zprintf("get1Msg: flushing a packet! (%d, %d, %d)"
" (after %d DMA frames).\n",
nRead, errno, (int) pRxpSkt, showFrameCount(1), 0,0);
}
if ((nRead < 1) && !pRxpSkt->isOk())
{
return OS_NO_MORE_DATA;
}
}
return OS_SUCCESS;
}
static int selectErrors;
int isFdPoison(int fd)
{
fd_set fdset;
fd_set *fds;
int numReady;
struct timeval tv, *ptv;
if (0 > fd) {
return TRUE;
}
tv.tv_sec = tv.tv_usec = 0;
ptv = &tv;
fds = &fdset;
FD_ZERO(fds);
FD_SET((UINT) fd, fds);
numReady = select(fd+1, fds, NULL, NULL, ptv);
return (0 > numReady) ? TRUE : FALSE;
}
int findPoisonFds(int pipeFD)
{
int i;
int n = 0;
netInTaskMsgPtr ppr;
if (isFdPoison(pipeFD)) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: pipeFd socketDescriptor=%d busted!\n", pipeFD);
return -1;
}
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (ppr->pRtpSocket && // not NULL socket and
isFdPoison(ppr->pRtpSocket->getSocketDescriptor())) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Removing fdRtp[%d], socket=0x%08x, socketDescriptor=%d\n", ppr-pairs,(int)ppr->pRtpSocket, (int)ppr->pRtpSocket->getSocketDescriptor());
n++;
ppr->pRtpSocket = NULL;
if (NULL == ppr->pRtcpSocket) ppr->fwdTo = NULL;
}
if (ppr->pRtcpSocket && // not NULL socket and
isFdPoison(ppr->pRtcpSocket->getSocketDescriptor())) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Removing fdRtcp[%d], socket=0x%08x, socketDescriptor=%d\n", ppr-pairs,(int)ppr->pRtcpSocket, (int)ppr->pRtcpSocket->getSocketDescriptor());
n++;
ppr->pRtcpSocket = NULL;
if (NULL == ppr->pRtpSocket) ppr->fwdTo = NULL;
}
ppr++;
}
return n;
}
static volatile int selectCounter = 0;
int whereSelectCounter()
{
int save;
save = selectCounter;
selectCounter = 0;
return save;
}
int showNetInTable() {
int last = 1234567;
int pipeFd;
int i;
netInTaskMsgPtr ppr;
NetInTask* pInst = NetInTask::getNetInTask();
pipeFd = pInst->getWriteFD();
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
last=max(last, ppr->pRtpSocket->getSocketDescriptor());
if (NULL != ppr->pRtcpSocket)
last=max(last, ppr->pRtcpSocket->getSocketDescriptor());
}
ppr++;
}
Zprintf("pipeFd = %d (last = %d)\n", pipeFd, last, 0,0,0,0);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
Zprintf(" %2d: MprFromNet=0x%X, pRtpSocket: 0x%x, pRtcpSocket: 0x%x\n",
i, (int) (ppr->fwdTo), (int) (ppr->pRtpSocket),
(int) (ppr->pRtcpSocket), 0,0);
}
ppr++;
}
return last;
}
int NetInTask::run(void *pNotUsed)
{
fd_set fdset;
fd_set *fds;
int last;
int i;
OsStatus stat;
int numReady;
netInTaskMsg msg;
netInTaskMsgPtr ppr;
int ostc;
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
ppr->pRtpSocket = NULL;
ppr->pRtcpSocket = NULL;
ppr->fwdTo = NULL;
ppr++;
}
numPairs = 0;
selectErrors = 0;
fds = &fdset;
last = OS_INVALID_SOCKET_DESCRIPTOR;
Zprintf(" *** NetInTask: pipeFd is %d\n",
mpReadSocket->getSocketDescriptor(), 0,0,0,0,0);
while (mpReadSocket && mpReadSocket->isOk()) {
if (OS_INVALID_SOCKET_DESCRIPTOR == last) {
last = mpReadSocket->getSocketDescriptor();
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
last=max(last, ppr->pRtpSocket->getSocketDescriptor());
if (NULL != ppr->pRtcpSocket)
last=max(last, ppr->pRtcpSocket->getSocketDescriptor());
}
ppr++;
}
}
FD_ZERO(fds);
FD_SET((UINT) mpReadSocket->getSocketDescriptor(), fds);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
{
int fd = ppr->pRtpSocket->getSocketDescriptor();
if (fd > 0)
FD_SET(fd, fds);
}
if (NULL != ppr->pRtcpSocket)
{
int fd = ppr->pRtcpSocket->getSocketDescriptor();
if (fd > 0)
FD_SET(fd, fds);
}
}
ppr++;
}
errno = 0;
numReady = select(last+1, fds, NULL, NULL, NULL);
ostc = *pOsTC;
selectCounter++;
if (0 > numReady) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: select returned %d, errno=%d=0x%X\n",
numReady, errno, errno);
i = findPoisonFds(mpReadSocket->getSocketDescriptor());
if (i < 0) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: My comm socket failed! Quitting!\n");
mpReadSocket->close();
} else if (0 < i) {
last = OS_INVALID_SOCKET_DESCRIPTOR;
}
/*
if (selectErrors++ > 10) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Quitting!\n");
mpReadSocket->close();
}
*/
continue;
}
#ifdef DEBUG_BY_SUSPEND /* [ */
if (0 == numReady) {
Zprintf(" !!! select() returned 0!!! errno=%d\n",
errno, 0,0,0,0,0);
taskSuspend(0);
continue;
}
#endif /* DEBUG_BY_SUSPEND ] */
/* is it a request to modify the set of file descriptors? */
if (FD_ISSET(mpReadSocket->getSocketDescriptor(), fds)) {
numReady--;
if (NET_TASK_MAX_MSG_LEN !=
mpReadSocket->read((char *) &msg, NET_TASK_MAX_MSG_LEN)) {
osPrintf("NetInTask::run: Invalid request!\n");
} else if (-2 == (int) msg.pRtpSocket) {
/* request to exit... */
Nprintf(" *** NetInTask: closing pipeFd (%d)\n",
mpReadSocket->getSocketDescriptor(), 0,0,0,0,0);
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: closing pipeFd (%d)\n",
mpReadSocket->getSocketDescriptor());
getLockObj().acquireWrite();
if (mpReadSocket)
{
mpReadSocket->close();
delete mpReadSocket;
mpReadSocket = NULL;
}
getLockObj().releaseWrite();
} else if (NULL != msg.fwdTo) {
if ((NULL != msg.pRtpSocket) || (NULL != msg.pRtcpSocket)) {
/* add a new pair of file descriptors */
last = max(last,msg.pRtpSocket->getSocketDescriptor());
last = max(last,msg.pRtcpSocket->getSocketDescriptor());
#define CHECK_FOR_DUP_DESCRIPTORS
#ifdef CHECK_FOR_DUP_DESCRIPTORS
int newRtpFd = (msg.pRtpSocket) ? msg.pRtpSocket->getSocketDescriptor() : -1;
int newRtcpFd = (msg.pRtcpSocket) ? msg.pRtcpSocket->getSocketDescriptor() : -1;
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Adding new RTP/RTCP sockets (RTP:%p,%d, RTCP:%p,%d)\n",
msg.pRtpSocket, newRtpFd, msg.pRtcpSocket, newRtcpFd);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
int existingRtpFd = (ppr->pRtpSocket) ? ppr->pRtpSocket->getSocketDescriptor() : -1;
int existingRtcpFd = (ppr->pRtcpSocket) ? ppr->pRtcpSocket->getSocketDescriptor() : -1;
UtlBoolean foundDupRtpFd = FALSE;
UtlBoolean foundDupRtcpFd = FALSE;
if (existingRtpFd >= 0 &&
(existingRtpFd == newRtpFd || existingRtpFd == newRtcpFd))
{
foundDupRtpFd = TRUE;
}
if (existingRtcpFd >= 0 &&
(existingRtcpFd == newRtpFd || existingRtcpFd == newRtcpFd))
{
foundDupRtcpFd = TRUE;
}
if (foundDupRtpFd || foundDupRtcpFd)
{
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Using a dup descriptor (New RTP:%p,%d, New RTCP:%p,%d, Old RTP:%p,%d, Old RTCP:%p,%d)\n",
msg.pRtpSocket, newRtpFd, msg.pRtcpSocket, newRtcpFd, ppr->pRtpSocket, existingRtpFd, ppr->pRtcpSocket, existingRtcpFd);
if (foundDupRtpFd)
ppr->pRtpSocket = NULL;
if (foundDupRtcpFd)
ppr->pRtcpSocket = NULL;
if (ppr->pRtpSocket == NULL && ppr->pRtcpSocket == NULL)
ppr->fwdTo = NULL;
}
}
ppr++;
}
#endif
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL == ppr->fwdTo) {
ppr->pRtpSocket = msg.pRtpSocket;
ppr->pRtcpSocket = msg.pRtcpSocket;
ppr->fwdTo = msg.fwdTo;
i = NET_TASK_MAX_FD_PAIRS;
numPairs++;
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Add socket Fds: RTP=%p, RTCP=%p, Q=%p\n",
msg.pRtpSocket, msg.pRtcpSocket, msg.fwdTo);
}
ppr++;
}
if (NULL != msg.notify) {
msg.notify->signal(0);
}
} else {
/* remove a pair of file descriptors */
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (msg.fwdTo == ppr->fwdTo) {
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Remove socket Fds: RTP=%p, RTCP=%p, Q=%p\n",
ppr->pRtpSocket, ppr->pRtcpSocket, ppr->fwdTo);
ppr->pRtpSocket = NULL;
ppr->pRtcpSocket = NULL;
ppr->fwdTo = NULL;
numPairs--;
last = -1;
}
ppr++;
}
if (NULL != msg.notify) {
msg.notify->signal(0);
}
}
}
else // NULL FromNet, not good
{
osPrintf("NetInTask::run msg with NULL FromNet\n");
}
}
ppr=pairs;
for (i=0; ((i<NET_TASK_MAX_FD_PAIRS)&&(numReady>0)); i++) {
if ((NULL != ppr->pRtpSocket) &&
(FD_ISSET(ppr->pRtpSocket->getSocketDescriptor(), fds))) {
stat = get1Msg(ppr->pRtpSocket, ppr->fwdTo,
false, ostc);
if (OS_SUCCESS != stat) {
Zprintf(" *** NetInTask: removing RTP#%d pSkt=0x%x due"
" to read error.\n", ppr-pairs,
(int) ppr->pRtpSocket, 0,0,0,0);
if (last == ppr->pRtpSocket->getSocketDescriptor())
last = OS_INVALID_SOCKET_DESCRIPTOR;
ppr->pRtpSocket = NULL;
if (NULL == ppr->pRtcpSocket) ppr->fwdTo = NULL;
}
numReady--;
}
if ((NULL != ppr->pRtcpSocket) &&
(FD_ISSET(ppr->pRtcpSocket->getSocketDescriptor(), fds))) {
stat = get1Msg(ppr->pRtcpSocket, ppr->fwdTo,
true, ostc);
if (OS_SUCCESS != stat) {
Zprintf(" *** NetInTask: removing RTCP#%d pSkt=0x%x due"
" to read error.\n", ppr-pairs,
(int) ppr->pRtcpSocket, 0,0,0,0);
if (last == ppr->pRtcpSocket->getSocketDescriptor())
last = OS_INVALID_SOCKET_DESCRIPTOR;
ppr->pRtcpSocket = NULL;
if (NULL == ppr->pRtpSocket) ppr->fwdTo = NULL;
}
numReady--;
}
ppr++;
}
}
return 0;
}
/* possible args are: buffer pool to take from, max message size */
OsStatus startNetInTask()
{
NetInTask *pTask;
pTask = NetInTask::getNetInTask();
return (NULL != pTask) ? OS_SUCCESS : OS_TASK_NOT_STARTED;
}
NetInTask* NetInTask::getNetInTask()
{
UtlBoolean isStarted;
// OsStatus stat;
// If the task object already exists, and the corresponding low-level task
// has been started, then use it
if (spInstance != NULL && spInstance->isStarted())
return spInstance;
// If the task does not yet exist or hasn't been started, then acquire
// the lock to ensure that only one instance of the task is started
getLockObj().acquireRead();
if (spInstance == NULL) {
spInstance = new NetInTask();
}
isStarted = spInstance->isStarted();
if (!isStarted)
{
isStarted = spInstance->start();
assert(isStarted);
}
getLockObj().releaseRead();
// Synchronize with NetInTask startup
int numDelays = 0;
while (spInstance->mCmdPort == -1)
{
OsTask::delay(20) ;
numDelays++;
if((numDelays % 50) == 0) osPrintf("NetInTask::getNetInTask %d delays\n", numDelays);
}
return spInstance;
}
void NetInTask::shutdownSockets()
{
getLockObj().acquireWrite();
if (mpWriteSocket)
{
mpWriteSocket->close();
delete mpWriteSocket;
mpWriteSocket = NULL;
}
/*if (mpReadSocket)
{
mpReadSocket->close();
delete mpReadSocket;
mpReadSocket = NULL;
}*/
getLockObj().releaseWrite();
}
// Default constructor (called only indirectly via getNetInTask())
NetInTask::NetInTask(int prio, int options, int stack)
: OsTask("NetInTask", NULL, prio, options, stack),
mpWriteSocket(NULL),
mpReadSocket(NULL)
{
// Create temporary listening socket.
OsServerSocket *pBindSocket = new OsServerSocket(1, PORT_DEFAULT, "127.0.0.1");
RTL_EVENT("NetInTask::NetInTask", 1);
mCmdPort = pBindSocket->getLocalHostPort();
assert(-1 != mCmdPort);
// Start our helper thread to go open the socket
RTL_EVENT("NetInTask::NetInTask", 2);
NetInTaskHelper* pHelper = new NetInTaskHelper(mCmdPort);
if (!pHelper->isStarted()) {
RTL_EVENT("NetInTask::NetInTask", 3);
pHelper->start();
}
RTL_EVENT("NetInTask::NetInTask", 4);
mpReadSocket = pBindSocket->accept();
RTL_EVENT("NetInTask::NetInTask", 5);
pBindSocket->close();
RTL_EVENT("NetInTask::NetInTask", 6);
delete pBindSocket;
// Create socket for write side of connection.
mpWriteSocket = pHelper->getSocket();
assert(mpWriteSocket != NULL && mpWriteSocket->isConnected());
RTL_EVENT("NetInTask::NetInTask", 7);
delete pHelper;
}
// Destructor
NetInTask::~NetInTask()
{
waitUntilShutDown();
spInstance = NULL;
}
// $$$ These messages need to contain OsSocket* instead of fds.
OsStatus shutdownNetInTask()
{
int wrote;
// Lock access to write socket.
NetInTask::getLockObj().acquireWrite();
NetInTask* pInst = NetInTask::getNetInTask();
// Request shutdown here, so next msg will unblock select() and request
// will be processed.
pInst->requestShutdown();
// Write message to socket to release sockets.
{
OsConnectionSocket* writeSocket = pInst->getWriteSocket();
netInTaskMsg msg;
msg.pRtpSocket = (OsSocket*) -2;
msg.pRtcpSocket = (OsSocket*) -1;
msg.fwdTo = NULL;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
}
NetInTask::getLockObj().releaseWrite();
pInst->shutdownSockets();
delete pInst;
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
// $$$ This is quite Unix-centric; on Win/NT these are handles...
/* neither fd can be < -1, at least one must be > -1, and fwdTo non-NULL */
OsStatus addNetInputSources(OsSocket* pRtpSocket, OsSocket* pRtcpSocket,
MprFromNet* fwdTo, OsNotification* notify)
{
netInTaskMsg msg;
int wrote = 0;
NetInTask* pInst = NetInTask::getNetInTask();
OsConnectionSocket* writeSocket;
// pInst->getWriteFD();
writeSocket = pInst->getWriteSocket();
if (NULL != fwdTo) {
msg.pRtpSocket = pRtpSocket;
msg.pRtcpSocket = pRtcpSocket;
msg.fwdTo = fwdTo;
msg.notify = notify;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
if (wrote != NET_TASK_MAX_MSG_LEN)
{
OsSysLog::add(FAC_MP, PRI_ERR,
"addNetInputSources - writeSocket error: 0x%08x,%d wrote %d",
(int)writeSocket, writeSocket->getSocketDescriptor(), wrote);
}
}
else
{
osPrintf("fwdTo NULL\n");
}
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
OsStatus removeNetInputSources(MprFromNet* fwdTo, OsNotification* notify)
{
netInTaskMsg msg;
int wrote = NET_TASK_MAX_MSG_LEN;
NetInTask* pInst = NetInTask::getNetInTask();
OsConnectionSocket* writeSocket;
// pInst->getWriteFD();
writeSocket = pInst->getWriteSocket();
if (NULL != fwdTo) {
msg.pRtpSocket = NULL;
msg.pRtcpSocket = NULL;
msg.fwdTo = fwdTo;
msg.notify = notify;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
if (wrote != NET_TASK_MAX_MSG_LEN)
{
OsSysLog::add(FAC_MP, PRI_ERR,
"removeNetInputSources - writeSocket error: 0x%08x,%d wrote %d",
(int)writeSocket, writeSocket->getSocketDescriptor(), wrote);
}
}
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
#define LOGEM
#undef LOGEM
/************************************************************************/
// return something random (32 bits)
UINT rand_timer32()
{
#ifdef _VXWORKS /* [ */
// On VxWorks, this is based on reading the 3.686400 MHz counter
UINT x;
static UINT last_timer = 0x12345678;
x = *pOsTC;
if (x == last_timer) {
SEM_ID s;
s = semBCreate(SEM_Q_FIFO, SEM_EMPTY);
semTake(s, 0);
semDelete(s);
x = *pOsTC;
}
last_timer = x;
/* Rotate left 8 */
return (((x&0xFF)<<8) | ((x&0xFFFF00)<<16) | ((x&0xFF000000)>>24));
#endif /* _VXWORKS ] */
#if defined(_WIN32) || defined(__pingtel_on_posix__) /* [ */
// Otherwise, call rand() 3 times, using 12 or 8 bits from each call (15 max)
static int firstTime = 1;
unsigned int x, y, z;
if (firstTime) {
assert(RAND_MAX > 0xfff);
srand((unsigned)time(NULL));
firstTime = 0;
}
x = rand();
y = rand();
z = rand();
return ((x&0xFFF) | ((y<<12)&0xFFF000) | ((z<<24)&0xFF000000));
#endif /* _WIN32 || __pingtel_on_posix__ ] */
}
#define RTP_DIR_NEW 4
rtpHandle StartRtpSession(OsSocket* socket, int direction, char type)
{
struct rtpSession *ret;
USHORT rseq;
rseq = 0xFFFF & rand_timer32();
ret = (struct rtpSession *) malloc(sizeof(struct rtpSession));
if (ret) {
ret->vpxcc = ((2<<6) | (0<<5) | (0<<4) | 0);
ret->mpt = ((0<<7) | (type & 0x7f));
ret->seq = rseq;
/* ret->timestamp = rand_timer32(); */
#ifdef INCLUDE_RTCP /* [ */
ret->ssrc = 0; // Changed by DMG. SSRC now generated in MpFlowGraph
#else /* INCLUDE_RTCP ] [ */
ret->ssrc = rand_timer32();
#endif /* INCLUDE_RTCP ] */
ret->dir = direction | RTP_DIR_NEW;
ret->socket = socket;
ret->packets = 0;
ret->octets = 0;
ret->cycles = 0;
}
return ret;
}
void FinishRtpSession(rtpHandle h)
{
if (NULL != h) {
h->socket = NULL;
free(h);
}
}
/* ============================ FUNCTIONS ================================= */
Old comments removed from NetInTask.
git-svn-id: 5274dacc98e2a95d0b0452670772bfdffe61ca90@9652 a612230a-c5fa-0310-af8b-88eea846685b
//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
#include "rtcp/RtcpConfig.h"
#define LOGEM
#undef LOGEM
// SYSTEM INCLUDES
#include <assert.h>
#include <string.h>
#ifdef _VXWORKS /* [ */
#include <selectLib.h>
#include <iosLib.h>
#include <inetlib.h>
#endif /* _VXWORKS ] */
#ifdef WIN32 /* [ */
# ifndef WINCE
# include <io.h>
# endif
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#endif /* WIN32 ] */
#ifdef __pingtel_on_posix__ /* [ */
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/time.h>
#endif /* __pingtel_on_posix__ ] */
// APPLICATION INCLUDES
#include "os/OsDefs.h"
#include "os/OsTask.h"
#include "os/OsServerSocket.h"
#include "os/OsConnectionSocket.h"
#include "os/OsEvent.h"
#include "mp/NetInTask.h"
#include "mp/MpUdpBuf.h"
#include "mp/MprFromNet.h"
#include "mp/MpBufferMsg.h"
#include "mp/dmaTask.h"
#ifdef _VXWORKS /* [ */
#ifdef CPU_XSCALE /* [ */
#include "mp/pxa255.h"
#define OSTIMER_COUNTER_POINTER ((int*) PXA250_OSTIMER_OSCR)
#else /* CPU_XSCALE ] [ */
#include "mp/sa1100.h"
#define OSTIMER_COUNTER_POINTER ((int*) SA1100_OSTIMER_COUNTER)
#endif /* CPU_XSCALE ] */
#else /* _VXWORKS ][ */
#define OSTIMER_COUNTER_POINTER (&dummy0)
static int dummy0 = 0;
#endif /* _VXWORKS ] */
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#else
# define RTL_START(x)
# define RTL_BLOCK(x)
# define RTL_EVENT(x,y)
# define RTL_WRITE(x)
# define RTL_STOP
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#define NET_TASK_MAX_MSG_LEN sizeof(netInTaskMsg)
#define NET_TASK_MAX_FD_PAIRS 100
#define MAX_RTP_BYTES 1500
struct __netInTaskMsg {
OsSocket* pRtpSocket;
OsSocket* pRtcpSocket;
MprFromNet* fwdTo;
OsNotification* notify;
};
typedef struct __netInTaskMsg netInTaskMsg, *netInTaskMsgPtr;
// STATIC VARIABLE INITIALIZATIONS
volatile int* pOsTC = OSTIMER_COUNTER_POINTER;
static netInTaskMsg pairs[NET_TASK_MAX_FD_PAIRS];
static int numPairs;
NetInTask* NetInTask::spInstance = 0;
OsRWMutex NetInTask::sLock(OsBSem::Q_PRIORITY);
const int NetInTask::DEF_NET_IN_TASK_PRIORITY = 0; // default task priority: HIGHEST
const int NetInTask::DEF_NET_IN_TASK_OPTIONS = 0; // default task options
#ifdef USING_NET_EQ /* [ */
const int NetInTask::DEF_NET_IN_TASK_STACKSIZE = 40960;//default task stacksize
#else /* USING_NET_EQ ] [ */
const int NetInTask::DEF_NET_IN_TASK_STACKSIZE = 4096;// default task stacksize
#endif /* USING_NET_EQ ] */
#define SIPX_DEBUG
#undef SIPX_DEBUG
/************************************************************************/
/**
* @brief Help create writer side of connection for NetInTask internal use.
*
* This task is used to create connection to socket we're listening. Main task
* create OsServerConnection and wait call OsServerConnection::accept() to
* get reader side of connection. On the side of this task writer side of
* connection is connected.
*/
class NetInTaskHelper : public OsTask
{
public:
NetInTaskHelper(int port);
~NetInTaskHelper();
/// Do the task.
virtual int run(void* pArg);
/// Wait for helper task to finish and return connected socket.
inline OsConnectionSocket* getSocket();
private:
OsConnectionSocket* mpSocket;
int mPort;
};
NetInTaskHelper::NetInTaskHelper(int port)
: OsTask("NetInTaskHelper-%d", NULL, 25, 0, 2000)
, mpSocket(NULL)
, mPort(port)
{
}
NetInTaskHelper::~NetInTaskHelper()
{
waitUntilShutDown();
}
int NetInTaskHelper::run(void*)
{
int numTry = 0;
while (numTry < 1000)
{
// Delay for some time on consecutive runs.
if (numTry > 0)
{
OsTask::delay(1);
}
// Connect...
mpSocket = new OsConnectionSocket(mPort, "127.0.0.1");
if (mpSocket && mpSocket->isConnected()) break;
numTry++;
}
OsSysLog::add(FAC_MP, PRI_INFO,
"NetInTaskHelper::run()... returning 0, after %d tries\n", numTry);
return 0;
}
OsConnectionSocket* NetInTaskHelper::getSocket()
{
waitUntilShutDown();
return mpSocket;
}
/************************************************************************/
int NetInTask::getWriteFD()
{
int writeSocketDescriptor = -1;
if (NULL != mpWriteSocket)
{
writeSocketDescriptor = mpWriteSocket->getSocketDescriptor();
}
else
{
assert(FALSE);
}
return(writeSocketDescriptor);
}
OsConnectionSocket* NetInTask::getWriteSocket()
{
if (NULL == mpWriteSocket) {
getWriteFD();
}
return mpWriteSocket;
}
/************************************************************************/
static OsStatus get1Msg(OsSocket* pRxpSkt, MprFromNet* fwdTo, bool isRtcp,
int ostc)
{
MpUdpBufPtr ib;
int nRead;
struct in_addr fromIP;
int fromPort;
static int numFlushed = 0;
static int flushedLimit = 125;
if (numFlushed >= flushedLimit) {
Zprintf("get1Msg: flushed %d packets! (after %d DMA frames).\n",
numFlushed, showFrameCount(1), 0,0,0,0);
if (flushedLimit<1000000) {
flushedLimit = flushedLimit << 1;
} else {
numFlushed = 0;
flushedLimit = 125;
}
}
// Get new buffer for incoming packet
ib = MpMisc.UdpPool->getBuffer();
if (ib.isValid()) {
// Read packet data.
// Note: nRead could not be greater then buffer size.
nRead = pRxpSkt->read(ib->getWriteDataPtr(), ib->getMaximumPacketSize()
, &fromIP, &fromPort);
// Set size of received data
ib->setPacketSize(nRead);
// Set IP address and port of this packet
ib->setIP(fromIP);
ib->setUdpPort(fromPort);
// Set time we receive this packet.
ib->setTimecode(ostc);
if (nRead > 0)
{
fwdTo->pushPacket(ib, isRtcp);
}
else
{
if (!pRxpSkt->isOk())
{
Zprintf(" *** get1Msg: read(%d) returned %d, errno=%d=0x%X)\n",
(int) pRxpSkt, nRead, errno, errno, 0,0);
return OS_NO_MORE_DATA;
}
}
} else {
// Flush packet if could not get buffer for it.
char buffer[UDP_MTU];
nRead = pRxpSkt->read(buffer, UDP_MTU, &fromIP, &fromPort);
if (numFlushed++ < 10) {
Zprintf("get1Msg: flushing a packet! (%d, %d, %d)"
" (after %d DMA frames).\n",
nRead, errno, (int) pRxpSkt, showFrameCount(1), 0,0);
}
if ((nRead < 1) && !pRxpSkt->isOk())
{
return OS_NO_MORE_DATA;
}
}
return OS_SUCCESS;
}
static int selectErrors;
int isFdPoison(int fd)
{
fd_set fdset;
fd_set *fds;
int numReady;
struct timeval tv, *ptv;
if (0 > fd) {
return TRUE;
}
tv.tv_sec = tv.tv_usec = 0;
ptv = &tv;
fds = &fdset;
FD_ZERO(fds);
FD_SET((UINT) fd, fds);
numReady = select(fd+1, fds, NULL, NULL, ptv);
return (0 > numReady) ? TRUE : FALSE;
}
int findPoisonFds(int pipeFD)
{
int i;
int n = 0;
netInTaskMsgPtr ppr;
if (isFdPoison(pipeFD)) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: pipeFd socketDescriptor=%d busted!\n", pipeFD);
return -1;
}
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (ppr->pRtpSocket && // not NULL socket and
isFdPoison(ppr->pRtpSocket->getSocketDescriptor())) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Removing fdRtp[%d], socket=0x%08x, socketDescriptor=%d\n", ppr-pairs,(int)ppr->pRtpSocket, (int)ppr->pRtpSocket->getSocketDescriptor());
n++;
ppr->pRtpSocket = NULL;
if (NULL == ppr->pRtcpSocket) ppr->fwdTo = NULL;
}
if (ppr->pRtcpSocket && // not NULL socket and
isFdPoison(ppr->pRtcpSocket->getSocketDescriptor())) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Removing fdRtcp[%d], socket=0x%08x, socketDescriptor=%d\n", ppr-pairs,(int)ppr->pRtcpSocket, (int)ppr->pRtcpSocket->getSocketDescriptor());
n++;
ppr->pRtcpSocket = NULL;
if (NULL == ppr->pRtpSocket) ppr->fwdTo = NULL;
}
ppr++;
}
return n;
}
static volatile int selectCounter = 0;
int whereSelectCounter()
{
int save;
save = selectCounter;
selectCounter = 0;
return save;
}
int showNetInTable() {
int last = 1234567;
int pipeFd;
int i;
netInTaskMsgPtr ppr;
NetInTask* pInst = NetInTask::getNetInTask();
pipeFd = pInst->getWriteFD();
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
last=max(last, ppr->pRtpSocket->getSocketDescriptor());
if (NULL != ppr->pRtcpSocket)
last=max(last, ppr->pRtcpSocket->getSocketDescriptor());
}
ppr++;
}
Zprintf("pipeFd = %d (last = %d)\n", pipeFd, last, 0,0,0,0);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
Zprintf(" %2d: MprFromNet=0x%X, pRtpSocket: 0x%x, pRtcpSocket: 0x%x\n",
i, (int) (ppr->fwdTo), (int) (ppr->pRtpSocket),
(int) (ppr->pRtcpSocket), 0,0);
}
ppr++;
}
return last;
}
int NetInTask::run(void *pNotUsed)
{
fd_set fdset;
fd_set *fds;
int last;
int i;
OsStatus stat;
int numReady;
netInTaskMsg msg;
netInTaskMsgPtr ppr;
int ostc;
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
ppr->pRtpSocket = NULL;
ppr->pRtcpSocket = NULL;
ppr->fwdTo = NULL;
ppr++;
}
numPairs = 0;
selectErrors = 0;
fds = &fdset;
last = OS_INVALID_SOCKET_DESCRIPTOR;
Zprintf(" *** NetInTask: pipeFd is %d\n",
mpReadSocket->getSocketDescriptor(), 0,0,0,0,0);
while (mpReadSocket && mpReadSocket->isOk()) {
if (OS_INVALID_SOCKET_DESCRIPTOR == last) {
last = mpReadSocket->getSocketDescriptor();
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
last=max(last, ppr->pRtpSocket->getSocketDescriptor());
if (NULL != ppr->pRtcpSocket)
last=max(last, ppr->pRtcpSocket->getSocketDescriptor());
}
ppr++;
}
}
FD_ZERO(fds);
FD_SET((UINT) mpReadSocket->getSocketDescriptor(), fds);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
if (NULL != ppr->pRtpSocket)
{
int fd = ppr->pRtpSocket->getSocketDescriptor();
if (fd > 0)
FD_SET(fd, fds);
}
if (NULL != ppr->pRtcpSocket)
{
int fd = ppr->pRtcpSocket->getSocketDescriptor();
if (fd > 0)
FD_SET(fd, fds);
}
}
ppr++;
}
errno = 0;
numReady = select(last+1, fds, NULL, NULL, NULL);
ostc = *pOsTC;
selectCounter++;
if (0 > numReady) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: select returned %d, errno=%d=0x%X\n",
numReady, errno, errno);
i = findPoisonFds(mpReadSocket->getSocketDescriptor());
if (i < 0) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: My comm socket failed! Quitting!\n");
mpReadSocket->close();
} else if (0 < i) {
last = OS_INVALID_SOCKET_DESCRIPTOR;
}
/*
if (selectErrors++ > 10) {
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Quitting!\n");
mpReadSocket->close();
}
*/
continue;
}
#ifdef DEBUG_BY_SUSPEND /* [ */
if (0 == numReady) {
Zprintf(" !!! select() returned 0!!! errno=%d\n",
errno, 0,0,0,0,0);
taskSuspend(0);
continue;
}
#endif /* DEBUG_BY_SUSPEND ] */
/* is it a request to modify the set of file descriptors? */
if (FD_ISSET(mpReadSocket->getSocketDescriptor(), fds)) {
numReady--;
if (NET_TASK_MAX_MSG_LEN !=
mpReadSocket->read((char *) &msg, NET_TASK_MAX_MSG_LEN)) {
osPrintf("NetInTask::run: Invalid request!\n");
} else if (-2 == (int) msg.pRtpSocket) {
/* request to exit... */
Nprintf(" *** NetInTask: closing pipeFd (%d)\n",
mpReadSocket->getSocketDescriptor(), 0,0,0,0,0);
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: closing pipeFd (%d)\n",
mpReadSocket->getSocketDescriptor());
getLockObj().acquireWrite();
if (mpReadSocket)
{
mpReadSocket->close();
delete mpReadSocket;
mpReadSocket = NULL;
}
getLockObj().releaseWrite();
} else if (NULL != msg.fwdTo) {
if ((NULL != msg.pRtpSocket) || (NULL != msg.pRtcpSocket)) {
/* add a new pair of file descriptors */
last = max(last,msg.pRtpSocket->getSocketDescriptor());
last = max(last,msg.pRtcpSocket->getSocketDescriptor());
#define CHECK_FOR_DUP_DESCRIPTORS
#ifdef CHECK_FOR_DUP_DESCRIPTORS
int newRtpFd = (msg.pRtpSocket) ? msg.pRtpSocket->getSocketDescriptor() : -1;
int newRtcpFd = (msg.pRtcpSocket) ? msg.pRtcpSocket->getSocketDescriptor() : -1;
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Adding new RTP/RTCP sockets (RTP:%p,%d, RTCP:%p,%d)\n",
msg.pRtpSocket, newRtpFd, msg.pRtcpSocket, newRtcpFd);
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL != ppr->fwdTo) {
int existingRtpFd = (ppr->pRtpSocket) ? ppr->pRtpSocket->getSocketDescriptor() : -1;
int existingRtcpFd = (ppr->pRtcpSocket) ? ppr->pRtcpSocket->getSocketDescriptor() : -1;
UtlBoolean foundDupRtpFd = FALSE;
UtlBoolean foundDupRtcpFd = FALSE;
if (existingRtpFd >= 0 &&
(existingRtpFd == newRtpFd || existingRtpFd == newRtcpFd))
{
foundDupRtpFd = TRUE;
}
if (existingRtcpFd >= 0 &&
(existingRtcpFd == newRtpFd || existingRtcpFd == newRtcpFd))
{
foundDupRtcpFd = TRUE;
}
if (foundDupRtpFd || foundDupRtcpFd)
{
OsSysLog::add(FAC_MP, PRI_ERR, " *** NetInTask: Using a dup descriptor (New RTP:%p,%d, New RTCP:%p,%d, Old RTP:%p,%d, Old RTCP:%p,%d)\n",
msg.pRtpSocket, newRtpFd, msg.pRtcpSocket, newRtcpFd, ppr->pRtpSocket, existingRtpFd, ppr->pRtcpSocket, existingRtcpFd);
if (foundDupRtpFd)
ppr->pRtpSocket = NULL;
if (foundDupRtcpFd)
ppr->pRtcpSocket = NULL;
if (ppr->pRtpSocket == NULL && ppr->pRtcpSocket == NULL)
ppr->fwdTo = NULL;
}
}
ppr++;
}
#endif
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (NULL == ppr->fwdTo) {
ppr->pRtpSocket = msg.pRtpSocket;
ppr->pRtcpSocket = msg.pRtcpSocket;
ppr->fwdTo = msg.fwdTo;
i = NET_TASK_MAX_FD_PAIRS;
numPairs++;
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Add socket Fds: RTP=%p, RTCP=%p, Q=%p\n",
msg.pRtpSocket, msg.pRtcpSocket, msg.fwdTo);
}
ppr++;
}
if (NULL != msg.notify) {
msg.notify->signal(0);
}
} else {
/* remove a pair of file descriptors */
for (i=0, ppr=pairs; i<NET_TASK_MAX_FD_PAIRS; i++) {
if (msg.fwdTo == ppr->fwdTo) {
OsSysLog::add(FAC_MP, PRI_DEBUG, " *** NetInTask: Remove socket Fds: RTP=%p, RTCP=%p, Q=%p\n",
ppr->pRtpSocket, ppr->pRtcpSocket, ppr->fwdTo);
ppr->pRtpSocket = NULL;
ppr->pRtcpSocket = NULL;
ppr->fwdTo = NULL;
numPairs--;
last = -1;
}
ppr++;
}
if (NULL != msg.notify) {
msg.notify->signal(0);
}
}
}
else // NULL FromNet, not good
{
osPrintf("NetInTask::run msg with NULL FromNet\n");
}
}
ppr=pairs;
for (i=0; ((i<NET_TASK_MAX_FD_PAIRS)&&(numReady>0)); i++) {
if ((NULL != ppr->pRtpSocket) &&
(FD_ISSET(ppr->pRtpSocket->getSocketDescriptor(), fds))) {
stat = get1Msg(ppr->pRtpSocket, ppr->fwdTo,
false, ostc);
if (OS_SUCCESS != stat) {
Zprintf(" *** NetInTask: removing RTP#%d pSkt=0x%x due"
" to read error.\n", ppr-pairs,
(int) ppr->pRtpSocket, 0,0,0,0);
if (last == ppr->pRtpSocket->getSocketDescriptor())
last = OS_INVALID_SOCKET_DESCRIPTOR;
ppr->pRtpSocket = NULL;
if (NULL == ppr->pRtcpSocket) ppr->fwdTo = NULL;
}
numReady--;
}
if ((NULL != ppr->pRtcpSocket) &&
(FD_ISSET(ppr->pRtcpSocket->getSocketDescriptor(), fds))) {
stat = get1Msg(ppr->pRtcpSocket, ppr->fwdTo,
true, ostc);
if (OS_SUCCESS != stat) {
Zprintf(" *** NetInTask: removing RTCP#%d pSkt=0x%x due"
" to read error.\n", ppr-pairs,
(int) ppr->pRtcpSocket, 0,0,0,0);
if (last == ppr->pRtcpSocket->getSocketDescriptor())
last = OS_INVALID_SOCKET_DESCRIPTOR;
ppr->pRtcpSocket = NULL;
if (NULL == ppr->pRtpSocket) ppr->fwdTo = NULL;
}
numReady--;
}
ppr++;
}
}
return 0;
}
/* possible args are: buffer pool to take from, max message size */
OsStatus startNetInTask()
{
NetInTask *pTask;
pTask = NetInTask::getNetInTask();
return (NULL != pTask) ? OS_SUCCESS : OS_TASK_NOT_STARTED;
}
NetInTask* NetInTask::getNetInTask()
{
UtlBoolean isStarted;
// If the task object already exists, and the corresponding low-level task
// has been started, then use it
if (spInstance != NULL && spInstance->isStarted())
return spInstance;
// If the task does not yet exist or hasn't been started, then acquire
// the lock to ensure that only one instance of the task is started
getLockObj().acquireRead();
if (spInstance == NULL) {
spInstance = new NetInTask();
}
isStarted = spInstance->isStarted();
if (!isStarted)
{
isStarted = spInstance->start();
assert(isStarted);
}
getLockObj().releaseRead();
// Synchronize with NetInTask startup
int numDelays = 0;
while (spInstance->mCmdPort == -1)
{
OsTask::delay(20) ;
numDelays++;
if((numDelays % 50) == 0) osPrintf("NetInTask::getNetInTask %d delays\n", numDelays);
}
return spInstance;
}
void NetInTask::shutdownSockets()
{
getLockObj().acquireWrite();
if (mpWriteSocket)
{
mpWriteSocket->close();
delete mpWriteSocket;
mpWriteSocket = NULL;
}
getLockObj().releaseWrite();
}
// Default constructor (called only indirectly via getNetInTask())
NetInTask::NetInTask(int prio, int options, int stack)
: OsTask("NetInTask", NULL, prio, options, stack),
mpWriteSocket(NULL),
mpReadSocket(NULL)
{
// Create temporary listening socket.
OsServerSocket *pBindSocket = new OsServerSocket(1, PORT_DEFAULT, "127.0.0.1");
RTL_EVENT("NetInTask::NetInTask", 1);
mCmdPort = pBindSocket->getLocalHostPort();
assert(-1 != mCmdPort);
// Start our helper thread to go open the socket
RTL_EVENT("NetInTask::NetInTask", 2);
NetInTaskHelper* pHelper = new NetInTaskHelper(mCmdPort);
if (!pHelper->isStarted()) {
RTL_EVENT("NetInTask::NetInTask", 3);
pHelper->start();
}
RTL_EVENT("NetInTask::NetInTask", 4);
mpReadSocket = pBindSocket->accept();
RTL_EVENT("NetInTask::NetInTask", 5);
pBindSocket->close();
RTL_EVENT("NetInTask::NetInTask", 6);
delete pBindSocket;
// Create socket for write side of connection.
mpWriteSocket = pHelper->getSocket();
assert(mpWriteSocket != NULL && mpWriteSocket->isConnected());
RTL_EVENT("NetInTask::NetInTask", 7);
delete pHelper;
}
// Destructor
NetInTask::~NetInTask()
{
waitUntilShutDown();
spInstance = NULL;
}
// $$$ These messages need to contain OsSocket* instead of fds.
OsStatus shutdownNetInTask()
{
int wrote;
// Lock access to write socket.
NetInTask::getLockObj().acquireWrite();
NetInTask* pInst = NetInTask::getNetInTask();
// Request shutdown here, so next msg will unblock select() and request
// will be processed.
pInst->requestShutdown();
// Write message to socket to release sockets.
{
OsConnectionSocket* writeSocket = pInst->getWriteSocket();
netInTaskMsg msg;
msg.pRtpSocket = (OsSocket*) -2;
msg.pRtcpSocket = (OsSocket*) -1;
msg.fwdTo = NULL;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
}
NetInTask::getLockObj().releaseWrite();
pInst->shutdownSockets();
delete pInst;
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
// $$$ This is quite Unix-centric; on Win/NT these are handles...
/* neither fd can be < -1, at least one must be > -1, and fwdTo non-NULL */
OsStatus addNetInputSources(OsSocket* pRtpSocket, OsSocket* pRtcpSocket,
MprFromNet* fwdTo, OsNotification* notify)
{
netInTaskMsg msg;
int wrote = 0;
NetInTask* pInst = NetInTask::getNetInTask();
OsConnectionSocket* writeSocket;
// pInst->getWriteFD();
writeSocket = pInst->getWriteSocket();
if (NULL != fwdTo) {
msg.pRtpSocket = pRtpSocket;
msg.pRtcpSocket = pRtcpSocket;
msg.fwdTo = fwdTo;
msg.notify = notify;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
if (wrote != NET_TASK_MAX_MSG_LEN)
{
OsSysLog::add(FAC_MP, PRI_ERR,
"addNetInputSources - writeSocket error: 0x%08x,%d wrote %d",
(int)writeSocket, writeSocket->getSocketDescriptor(), wrote);
}
}
else
{
osPrintf("fwdTo NULL\n");
}
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
OsStatus removeNetInputSources(MprFromNet* fwdTo, OsNotification* notify)
{
netInTaskMsg msg;
int wrote = NET_TASK_MAX_MSG_LEN;
NetInTask* pInst = NetInTask::getNetInTask();
OsConnectionSocket* writeSocket;
// pInst->getWriteFD();
writeSocket = pInst->getWriteSocket();
if (NULL != fwdTo) {
msg.pRtpSocket = NULL;
msg.pRtcpSocket = NULL;
msg.fwdTo = fwdTo;
msg.notify = notify;
wrote = writeSocket->write((char *) &msg, NET_TASK_MAX_MSG_LEN);
if (wrote != NET_TASK_MAX_MSG_LEN)
{
OsSysLog::add(FAC_MP, PRI_ERR,
"removeNetInputSources - writeSocket error: 0x%08x,%d wrote %d",
(int)writeSocket, writeSocket->getSocketDescriptor(), wrote);
}
}
return ((NET_TASK_MAX_MSG_LEN == wrote) ? OS_SUCCESS : OS_BUSY);
}
#define LOGEM
#undef LOGEM
/************************************************************************/
// return something random (32 bits)
UINT rand_timer32()
{
#ifdef _VXWORKS /* [ */
// On VxWorks, this is based on reading the 3.686400 MHz counter
UINT x;
static UINT last_timer = 0x12345678;
x = *pOsTC;
if (x == last_timer) {
SEM_ID s;
s = semBCreate(SEM_Q_FIFO, SEM_EMPTY);
semTake(s, 0);
semDelete(s);
x = *pOsTC;
}
last_timer = x;
/* Rotate left 8 */
return (((x&0xFF)<<8) | ((x&0xFFFF00)<<16) | ((x&0xFF000000)>>24));
#endif /* _VXWORKS ] */
#if defined(_WIN32) || defined(__pingtel_on_posix__) /* [ */
// Otherwise, call rand() 3 times, using 12 or 8 bits from each call (15 max)
static int firstTime = 1;
unsigned int x, y, z;
if (firstTime) {
assert(RAND_MAX > 0xfff);
srand((unsigned)time(NULL));
firstTime = 0;
}
x = rand();
y = rand();
z = rand();
return ((x&0xFFF) | ((y<<12)&0xFFF000) | ((z<<24)&0xFF000000));
#endif /* _WIN32 || __pingtel_on_posix__ ] */
}
#define RTP_DIR_NEW 4
rtpHandle StartRtpSession(OsSocket* socket, int direction, char type)
{
struct rtpSession *ret;
USHORT rseq;
rseq = 0xFFFF & rand_timer32();
ret = (struct rtpSession *) malloc(sizeof(struct rtpSession));
if (ret) {
ret->vpxcc = ((2<<6) | (0<<5) | (0<<4) | 0);
ret->mpt = ((0<<7) | (type & 0x7f));
ret->seq = rseq;
/* ret->timestamp = rand_timer32(); */
#ifdef INCLUDE_RTCP /* [ */
ret->ssrc = 0; // Changed by DMG. SSRC now generated in MpFlowGraph
#else /* INCLUDE_RTCP ] [ */
ret->ssrc = rand_timer32();
#endif /* INCLUDE_RTCP ] */
ret->dir = direction | RTP_DIR_NEW;
ret->socket = socket;
ret->packets = 0;
ret->octets = 0;
ret->cycles = 0;
}
return ret;
}
void FinishRtpSession(rtpHandle h)
{
if (NULL != h) {
h->socket = NULL;
free(h);
}
}
/* ============================ FUNCTIONS ================================= */
|
/**
* @file sparse_autoencoder_test.cpp
* @author Siddharth Agrawal
*
* Test the SparseAutoencoder class.
*/
#include <mlpack/methods/sparse_autoencoder/sparse_autoencoder_function.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/layer/base_layer.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace arma;
using FSigmoidLayer = ann::SigmoidLayer<ann::LogisticFunction>;
//sparse autoencoder function
using SAEF = nn::SparseAutoencoderFunction<FSigmoidLayer, FSigmoidLayer>;
//sparse autoencoder function greedy
using SAEFG = nn::SparseAutoencoderFunction<FSigmoidLayer, FSigmoidLayer, std::true_type>;
BOOST_AUTO_TEST_SUITE(SparseAutoencoderTest2);
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionEvaluate)
{
const size_t vSize = 5;
const size_t hSize = 3;
const size_t r = 2 * hSize + 1;
const size_t c = vSize + 1;
// Simple fake dataset.
arma::mat data1("0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5");
// Transpose of the above dataset.
arma::mat data2 = data1.t();
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf1(data1, vSize, hSize, 0, 0);
// Test using first dataset. Values were calculated using Octave.
BOOST_REQUIRE_CLOSE(saf1.Evaluate(arma::ones(r, c)), 1.190472606540, 1e-5);
BOOST_REQUIRE_CLOSE(saf1.Evaluate(arma::zeros(r, c)), 0.150000000000, 1e-5);
BOOST_REQUIRE_CLOSE(saf1.Evaluate(-arma::ones(r, c)), 0.048800332266, 1e-5);
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf2(data2, vSize, hSize, 0, 0);
// Test using second dataset. Values were calculated using Octave.
BOOST_REQUIRE_CLOSE(saf2.Evaluate(arma::ones(r, c)), 1.197585812647, 1e-5);
BOOST_REQUIRE_CLOSE(saf2.Evaluate(arma::zeros(r, c)), 0.150000000000, 1e-5);
BOOST_REQUIRE_CLOSE(saf2.Evaluate(-arma::ones(r, c)), 0.063466617408, 1e-5);
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionRandomEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l1 = hSize;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf(data, vSize, hSize, 0, 0);
// Run a number of trials.
for (size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
double reconstructionError = 0;
// Compute error for each training example.
for (size_t j = 0; j < points; j++)
{
arma::mat hiddenLayer, outputLayer, diff;
hiddenLayer = 1.0 /
(1 + arma::exp(-(parameters.submat(0, 0, l1 - 1, l2 - 1) *
data.col(j) + parameters.submat(0, l2, l1 - 1, l2))));
outputLayer = 1.0 /
(1 + arma::exp(-(parameters.submat(l1, 0, l3 - 1,l2 - 1).t()
* hiddenLayer + parameters.submat(l3, 0, l3, l2 - 1).t())));
diff = outputLayer - data.col(j);
reconstructionError += 0.5 * arma::sum(arma::sum(diff % diff));
}
reconstructionError /= points;
// Compare with the value returned by the function.
BOOST_REQUIRE_CLOSE(saf.Evaluate(parameters), reconstructionError, 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionRegularizationEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for comparing regularization costs.
SAEF safNoReg(data, vSize, hSize, 0, 0);
SAEF safSmallReg(data, vSize, hSize, 0.5, 0);
SAEF safBigReg(data, vSize, hSize, 20, 0);
// Run a number of trials.
for (size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
double wL2SquaredNorm;
wL2SquaredNorm = arma::accu(parameters.submat(0, 0, l3 - 1, l2 - 1) %
parameters.submat(0, 0, l3 - 1, l2 - 1));
// Calculate regularization terms.
const double smallRegTerm = 0.25 * wL2SquaredNorm;
const double bigRegTerm = 10 * wL2SquaredNorm;
BOOST_REQUIRE_CLOSE(safNoReg.Evaluate(parameters) + smallRegTerm,
safSmallReg.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(safNoReg.Evaluate(parameters) + bigRegTerm,
safBigReg.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionKLDivergenceEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l1 = hSize;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
const double rho = 0.01;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for comparing divergence costs.
SAEF safNoDiv(data, vSize, hSize, 0, 0, rho);
SAEF safSmallDiv(data, vSize, hSize, 0, 5, rho);
SAEF safBigDiv(data, vSize, hSize, 0, 20, rho);
// Run a number of trials.
for(size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
arma::mat rhoCap;
rhoCap.zeros(hSize, 1);
// Compute hidden layer activations for each example.
for (size_t j = 0; j < points; j++)
{
arma::mat hiddenLayer;
hiddenLayer = 1.0 / (1 +
arma::exp(-(parameters.submat(0, 0, l1 - 1, l2 - 1) *
data.col(j) + parameters.submat(0, l2, l1 - 1, l2))));
rhoCap += hiddenLayer;
}
rhoCap /= points;
// Calculate divergence terms.
const double smallDivTerm = 5 * arma::accu(rho * arma::log(rho / rhoCap) +
(1 - rho) * arma::log((1 - rho) / (1 - rhoCap)));
const double bigDivTerm = 20 * arma::accu(rho * arma::log(rho / rhoCap) +
(1 - rho) * arma::log((1 - rho) / (1 - rhoCap)));
BOOST_REQUIRE_CLOSE(safNoDiv.Evaluate(parameters) + smallDivTerm,
safSmallDiv.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(safNoDiv.Evaluate(parameters) + bigDivTerm,
safBigDiv.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionGradient)
{
const size_t points = 1000;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for 3 terms in the cost function. Each term contributes towards
// the gradient and thus need to be checked independently.
SAEFG saf1(data, vSize, hSize, 0, 0);
SAEFG saf2(data, vSize, hSize, 20, 0);
SAEFG saf3(data, vSize, hSize, 20, 20);
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
// Get gradients for the current parameters.
arma::mat gradient1, gradient2, gradient3;
saf1.Gradient(parameters, gradient1);
saf2.Gradient(parameters, gradient2);
saf3.Gradient(parameters, gradient3);
// Perturbation constant.
const double epsilon = 0.0001;
double costPlus1, costMinus1, numGradient1;
double costPlus2, costMinus2, numGradient2;
double costPlus3, costMinus3, numGradient3;
// For each parameter.
for (size_t i = 0; i <= l3; i++)
{
for (size_t j = 0; j <= l2; j++)
{
// Perturb parameter with a positive constant and get costs.
parameters(i, j) += epsilon;
costPlus1 = saf1.Evaluate(parameters);
costPlus2 = saf2.Evaluate(parameters);
costPlus3 = saf3.Evaluate(parameters);
// Perturb parameter with a negative constant and get costs.
parameters(i, j) -= 2 * epsilon;
costMinus1 = saf1.Evaluate(parameters);
costMinus2 = saf2.Evaluate(parameters);
costMinus3 = saf3.Evaluate(parameters);
// Compute numerical gradients using the costs calculated above.
numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);
numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);
numGradient3 = (costPlus3 - costMinus3) / (2 * epsilon);
// Restore the parameter value.
parameters(i, j) += epsilon;
// Compare numerical and backpropagation gradient values.
BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient3, gradient3(i, j), 1e-2);
}
}
}
BOOST_AUTO_TEST_SUITE_END();
1 : adjust format
2 : use the layer and activation function from mlpack::nn
/**
* @file sparse_autoencoder_test.cpp
* @author Siddharth Agrawal
*
* Test the SparseAutoencoder class.
*/
#include <mlpack/methods/sparse_autoencoder/sparse_autoencoder_function.hpp>
#include <mlpack/methods/sparse_autoencoder/activation_functions/logistic_function.hpp>
#include <mlpack/core.hpp>
#include <mlpack/methods/sparse_autoencoder/layer/base_layer.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
using namespace mlpack;
using namespace arma;
using SigmoidLayer = nn::SigmoidLayer<nn::LogisticFunction>;
//sparse autoencoder function
using SAEF = nn::SparseAutoencoderFunction<SigmoidLayer, SigmoidLayer>;
//sparse autoencoder function greedy
using SAEFG = nn::SparseAutoencoderFunction<SigmoidLayer, SigmoidLayer, std::true_type>;
BOOST_AUTO_TEST_SUITE(SparseAutoencoderTest2);
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionEvaluate)
{
const size_t vSize = 5;
const size_t hSize = 3;
const size_t r = 2 * hSize + 1;
const size_t c = vSize + 1;
// Simple fake dataset.
arma::mat data1("0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5;"
"0.1 0.2 0.3 0.4 0.5");
// Transpose of the above dataset.
arma::mat data2 = data1.t();
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf1(data1, vSize, hSize, 0, 0);
// Test using first dataset. Values were calculated using Octave.
BOOST_REQUIRE_CLOSE(saf1.Evaluate(arma::ones(r, c)), 1.190472606540, 1e-5);
BOOST_REQUIRE_CLOSE(saf1.Evaluate(arma::zeros(r, c)), 0.150000000000, 1e-5);
BOOST_REQUIRE_CLOSE(saf1.Evaluate(-arma::ones(r, c)), 0.048800332266, 1e-5);
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf2(data2, vSize, hSize, 0, 0);
// Test using second dataset. Values were calculated using Octave.
BOOST_REQUIRE_CLOSE(saf2.Evaluate(arma::ones(r, c)), 1.197585812647, 1e-5);
BOOST_REQUIRE_CLOSE(saf2.Evaluate(arma::zeros(r, c)), 0.150000000000, 1e-5);
BOOST_REQUIRE_CLOSE(saf2.Evaluate(-arma::ones(r, c)), 0.063466617408, 1e-5);
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionRandomEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l1 = hSize;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// Create a SparseAutoencoderFunction. Regularization and KL divergence terms
// ignored.
SAEF saf(data, vSize, hSize, 0, 0);
// Run a number of trials.
for (size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
double reconstructionError = 0;
// Compute error for each training example.
for (size_t j = 0; j < points; j++)
{
arma::mat hiddenLayer, outputLayer, diff;
hiddenLayer = 1.0 /
(1 + arma::exp(-(parameters.submat(0, 0, l1 - 1, l2 - 1) *
data.col(j) + parameters.submat(0, l2, l1 - 1, l2))));
outputLayer = 1.0 /
(1 + arma::exp(-(parameters.submat(l1, 0, l3 - 1,l2 - 1).t()
* hiddenLayer + parameters.submat(l3, 0, l3, l2 - 1).t())));
diff = outputLayer - data.col(j);
reconstructionError += 0.5 * arma::sum(arma::sum(diff % diff));
}
reconstructionError /= points;
// Compare with the value returned by the function.
BOOST_REQUIRE_CLOSE(saf.Evaluate(parameters), reconstructionError, 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionRegularizationEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for comparing regularization costs.
SAEF safNoReg(data, vSize, hSize, 0, 0);
SAEF safSmallReg(data, vSize, hSize, 0.5, 0);
SAEF safBigReg(data, vSize, hSize, 20, 0);
// Run a number of trials.
for (size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
double wL2SquaredNorm;
wL2SquaredNorm = arma::accu(parameters.submat(0, 0, l3 - 1, l2 - 1) %
parameters.submat(0, 0, l3 - 1, l2 - 1));
// Calculate regularization terms.
const double smallRegTerm = 0.25 * wL2SquaredNorm;
const double bigRegTerm = 10 * wL2SquaredNorm;
BOOST_REQUIRE_CLOSE(safNoReg.Evaluate(parameters) + smallRegTerm,
safSmallReg.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(safNoReg.Evaluate(parameters) + bigRegTerm,
safBigReg.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionKLDivergenceEvaluate)
{
const size_t points = 1000;
const size_t trials = 50;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l1 = hSize;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
const double rho = 0.01;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for comparing divergence costs.
SAEF safNoDiv(data, vSize, hSize, 0, 0, rho);
SAEF safSmallDiv(data, vSize, hSize, 0, 5, rho);
SAEF safBigDiv(data, vSize, hSize, 0, 20, rho);
// Run a number of trials.
for(size_t i = 0; i < trials; i++)
{
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
arma::mat rhoCap;
rhoCap.zeros(hSize, 1);
// Compute hidden layer activations for each example.
for (size_t j = 0; j < points; j++)
{
arma::mat hiddenLayer;
hiddenLayer = 1.0 / (1 +
arma::exp(-(parameters.submat(0, 0, l1 - 1, l2 - 1) *
data.col(j) + parameters.submat(0, l2, l1 - 1, l2))));
rhoCap += hiddenLayer;
}
rhoCap /= points;
// Calculate divergence terms.
const double smallDivTerm = 5 * arma::accu(rho * arma::log(rho / rhoCap) +
(1 - rho) * arma::log((1 - rho) / (1 - rhoCap)));
const double bigDivTerm = 20 * arma::accu(rho * arma::log(rho / rhoCap) +
(1 - rho) * arma::log((1 - rho) / (1 - rhoCap)));
BOOST_REQUIRE_CLOSE(safNoDiv.Evaluate(parameters) + smallDivTerm,
safSmallDiv.Evaluate(parameters), 1e-5);
BOOST_REQUIRE_CLOSE(safNoDiv.Evaluate(parameters) + bigDivTerm,
safBigDiv.Evaluate(parameters), 1e-5);
}
}
BOOST_AUTO_TEST_CASE(SparseAutoencoderFunctionGradient)
{
const size_t points = 1000;
const size_t vSize = 20;
const size_t hSize = 10;
const size_t l2 = vSize;
const size_t l3 = 2 * hSize;
// Initialize a random dataset.
arma::mat data;
data.randu(vSize, points);
// 3 objects for 3 terms in the cost function. Each term contributes towards
// the gradient and thus need to be checked independently.
SAEFG saf1(data, vSize, hSize, 0, 0);
SAEFG saf2(data, vSize, hSize, 20, 0);
SAEFG saf3(data, vSize, hSize, 20, 20);
// Create a random set of parameters.
arma::mat parameters;
parameters.randu(l3 + 1, l2 + 1);
// Get gradients for the current parameters.
arma::mat gradient1, gradient2, gradient3;
saf1.Gradient(parameters, gradient1);
saf2.Gradient(parameters, gradient2);
saf3.Gradient(parameters, gradient3);
// Perturbation constant.
const double epsilon = 0.0001;
double costPlus1, costMinus1, numGradient1;
double costPlus2, costMinus2, numGradient2;
double costPlus3, costMinus3, numGradient3;
// For each parameter.
for (size_t i = 0; i <= l3; i++)
{
for (size_t j = 0; j <= l2; j++)
{
// Perturb parameter with a positive constant and get costs.
parameters(i, j) += epsilon;
costPlus1 = saf1.Evaluate(parameters);
costPlus2 = saf2.Evaluate(parameters);
costPlus3 = saf3.Evaluate(parameters);
// Perturb parameter with a negative constant and get costs.
parameters(i, j) -= 2 * epsilon;
costMinus1 = saf1.Evaluate(parameters);
costMinus2 = saf2.Evaluate(parameters);
costMinus3 = saf3.Evaluate(parameters);
// Compute numerical gradients using the costs calculated above.
numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);
numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);
numGradient3 = (costPlus3 - costMinus3) / (2 * epsilon);
// Restore the parameter value.
parameters(i, j) += epsilon;
// Compare numerical and backpropagation gradient values.
BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 1e-2);
BOOST_REQUIRE_CLOSE(numGradient3, gradient3(i, j), 1e-2);
}
}
}
BOOST_AUTO_TEST_SUITE_END();
|
/****************************************************************************
*
* Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file airspeed_calibration.cpp
* Airspeed sensor calibration routine
*/
#include "airspeed_calibration.h"
#include "calibration_messages.h"
#include "commander_helper.h"
#include <stdio.h>
#include <fcntl.h>
#include <poll.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <drivers/drv_airspeed.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/differential_pressure.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
/* oddly, ERROR is not defined for c++ */
#ifdef ERROR
# undef ERROR
#endif
static const int ERROR = -1;
static const char *sensor_name = "dpress";
int do_airspeed_calibration(int mavlink_fd)
{
/* give directions */
mavlink_log_info(mavlink_fd, CAL_STARTED_MSG, sensor_name);
mavlink_log_info(mavlink_fd, "ensure airspeed sensor is not registering wind");
const int calibration_count = 2000;
int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));
struct differential_pressure_s diff_pres;
int calibration_counter = 0;
float diff_pres_offset = 0.0f;
/* Reset sensor parameters */
struct airspeed_scale airscale = {
diff_pres_offset,
1.0f,
};
bool paramreset_successful = false;
int fd = open(AIRSPEED_DEVICE_PATH, 0);
if (fd > 0) {
if (OK == ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
paramreset_successful = true;
} else {
mavlink_log_critical(mavlink_fd, "airspeed offset zero failed");
}
close(fd);
}
if (!paramreset_successful) {
warn("FAILED to reset - assuming analog");
mavlink_log_critical(mavlink_fd, "assuming analog sensor");
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
}
while (calibration_counter < calibration_count) {
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
diff_pres_offset += diff_pres.differential_pressure_raw_pa;
calibration_counter++;
if (calibration_counter % (calibration_count / 20) == 0) {
mavlink_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, (calibration_counter * 100) / calibration_count);
}
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name);
close(diff_pres_sub);
return ERROR;
}
}
diff_pres_offset = diff_pres_offset / calibration_count;
if (isfinite(diff_pres_offset)) {
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warn("WARNING: auto-save of params to storage failed");
mavlink_log_critical(mavlink_fd, CAL_FAILED_SAVE_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
mavlink_log_info(mavlink_fd, CAL_DONE_MSG, sensor_name);
tune_neutral(true);
close(diff_pres_sub);
return OK;
} else {
mavlink_log_info(mavlink_fd, CAL_FAILED_MSG, sensor_name);
close(diff_pres_sub);
return ERROR;
}
}
airspeed cal: Improve user feedback
/****************************************************************************
*
* Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file airspeed_calibration.cpp
* Airspeed sensor calibration routine
*/
#include "airspeed_calibration.h"
#include "calibration_messages.h"
#include "commander_helper.h"
#include <stdio.h>
#include <fcntl.h>
#include <poll.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <drivers/drv_airspeed.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/differential_pressure.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
/* oddly, ERROR is not defined for c++ */
#ifdef ERROR
# undef ERROR
#endif
static const int ERROR = -1;
static const char *sensor_name = "dpress";
int do_airspeed_calibration(int mavlink_fd)
{
/* give directions */
mavlink_log_info(mavlink_fd, CAL_STARTED_MSG, sensor_name);
mavlink_log_info(mavlink_fd, "ensure airspeed sensor is not registering wind");
const int calibration_count = 2000;
int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));
struct differential_pressure_s diff_pres;
int calibration_counter = 0;
float diff_pres_offset = 0.0f;
/* Reset sensor parameters */
struct airspeed_scale airscale = {
diff_pres_offset,
1.0f,
};
bool paramreset_successful = false;
int fd = open(AIRSPEED_DEVICE_PATH, 0);
if (fd > 0) {
if (OK == ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
paramreset_successful = true;
} else {
mavlink_log_critical(mavlink_fd, "airspeed offset zero failed");
}
close(fd);
}
if (!paramreset_successful) {
warn("FAILED to reset - assuming analog");
mavlink_log_critical(mavlink_fd, "If analog sens, retry with [SENS_DPRES_ANSC=1000]");
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
}
while (calibration_counter < calibration_count) {
/* wait blocking for new data */
struct pollfd fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
diff_pres_offset += diff_pres.differential_pressure_raw_pa;
calibration_counter++;
if (calibration_counter % (calibration_count / 20) == 0) {
mavlink_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, (calibration_counter * 100) / calibration_count);
}
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
mavlink_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name);
close(diff_pres_sub);
return ERROR;
}
}
diff_pres_offset = diff_pres_offset / calibration_count;
if (isfinite(diff_pres_offset)) {
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
mavlink_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
/* auto-save to EEPROM */
int save_ret = param_save_default();
if (save_ret != 0) {
warn("WARNING: auto-save of params to storage failed");
mavlink_log_critical(mavlink_fd, CAL_FAILED_SAVE_PARAMS_MSG);
close(diff_pres_sub);
return ERROR;
}
mavlink_log_info(mavlink_fd, CAL_DONE_MSG, sensor_name);
tune_neutral(true);
close(diff_pres_sub);
return OK;
} else {
mavlink_log_info(mavlink_fd, CAL_FAILED_MSG, sensor_name);
close(diff_pres_sub);
return ERROR;
}
}
|
//
// kern_model.cpp
// WhateverGreen
//
// Copyright © 2017 vit9696. All rights reserved.
//
#include <Headers/kern_iokit.hpp>
#include "kern_weg.hpp"
/**
* General rules for AMD GPU names (first table):
*
* 1. Only use device identifiers present in Apple kexts starting with 5xxx series
* 2. Follow Apple naming style (e.g., ATI for 5xxx series, AMD for 6xxx series, Radeon Pro for 5xx GPUs)
* 3. Write earliest available hardware with slashes (e.g. Radeon Pro 455/555)
* 4. Avoid using generic names like "AMD Radeon RX"
* 5. Provide revision identifiers whenever possible
* 6. Detection order should be vendor-id, device-id, subsystem-vendor-id, subsystem-id, revision-id
*
* General rules for Intel GPU names (second table):
*
* 1. All identifiers from Sandy and newer are allowed to be present
* 2. For idenitifiers not present in Apple kexts provide a fake id (AMD GPUs are just too many)
* 3. Use nullptr if the exact GPU name is not known
*
* Some identifiers are taken from https://github.com/pciutils/pciids/blob/master/pci.ids?raw=true
* Last synced version 2017.07.24 (https://github.com/pciutils/pciids/blob/699e70f3de/pci.ids?raw=true)
*/
struct Model {
enum Detect : uint16_t {
DetectDef = 0x0,
DetectSub = 0x1,
DetectRev = 0x2,
DetectAll = DetectSub | DetectRev
};
uint16_t mode {DetectDef};
uint16_t subven {0};
uint16_t sub {0};
uint16_t rev {0};
const char *name {nullptr};
};
struct BuiltinModel {
uint32_t device;
uint32_t fake;
const char *name;
};
struct DevicePair {
uint16_t dev;
const Model *models;
size_t modelNum;
};
static constexpr Model dev6640[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro M6100"}
};
static constexpr Model dev6641[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8930M"}
};
static constexpr Model dev6646[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M280X"}
};
static constexpr Model dev6647[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M270X"}
};
static constexpr Model dev665c[] {
{Model::DetectSub, 0x1462, 0x2932, 0x0000, "AMD Radeon HD 8770"},
{Model::DetectSub, 0x1462, 0x2934, 0x0000, "AMD Radeon R9 260"},
{Model::DetectSub, 0x1462, 0x2938, 0x0000, "AMD Radeon R9 360"},
{Model::DetectSub, 0x148c, 0x0907, 0x0000, "AMD Radeon R7 360"},
{Model::DetectSub, 0x148c, 0x9260, 0x0000, "AMD Radeon R9 260"},
{Model::DetectSub, 0x148c, 0x9360, 0x0000, "AMD Radeon R9 360"},
{Model::DetectSub, 0x1682, 0x0907, 0x0000, "AMD Radeon R7 360"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7790"}
};
static constexpr Model dev665d[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 260"}
};
static constexpr Model dev66af[] {
{Model::DetectDef, 0x0000, 0x0000, 0x00c1, "AMD Radeon VII"}
};
static constexpr Model dev6704[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro V7900"}
};
static constexpr Model dev6718[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6970"}
};
static constexpr Model dev6719[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6950"}
};
static constexpr Model dev6720[] {
{Model::DetectSub, 0x1028, 0x0490, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x1028, 0x04a4, 0x0000, "AMD FirePro M8900"},
{Model::DetectSub, 0x1028, 0x053f, 0x0000, "AMD FirePro M8900"},
{Model::DetectSub, 0x106b, 0x0b00, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x1558, 0x5102, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x174b, 0xe188, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6990M"}
};
static constexpr Model dev6722[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6900M"}
};
static constexpr Model dev6738[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6870"}
};
static constexpr Model dev6739[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6850"}
};
static constexpr Model dev6740[] {
{Model::DetectSub, 0x1019, 0x2392, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x1028, 0x04a3, 0x0000, "Precision M4600"},
{Model::DetectSub, 0x1028, 0x053e, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x1630, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x1631, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x164e, 0x0000, "AMD Radeon HD 6730M5"},
{Model::DetectSub, 0x103c, 0x1657, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1658, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x165a, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x165b, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1688, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1689, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x168a, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x185e, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectSub, 0x103c, 0x3388, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x3389, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x3582, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6730M"}
};
static constexpr Model dev6741[] {
{Model::DetectSub, 0x1028, 0x04c1, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04c5, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04cd, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04d7, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04d9, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x052d, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x103c, 0x1646, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1688, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1689, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x168a, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1860, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectSub, 0x103c, 0x3385, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x103c, 0x3560, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x358d, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x3590, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x3593, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x1043, 0x2125, 0x0000, "AMD Radeon HD 7670M"},
{Model::DetectSub, 0x1043, 0x2127, 0x0000, "AMD Radeon HD 7670M"},
{Model::DetectSub, 0x104d, 0x907b, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x104d, 0x9080, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x104d, 0x9081, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1179, 0xfd63, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1179, 0xfd65, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x144d, 0xc0b3, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x144d, 0xc539, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x144d, 0xc609, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x17aa, 0x21e1, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6650M"}
};
static constexpr Model dev6745[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6600M"}
};
static constexpr Model dev6750[] {
{Model::DetectSub, 0x1462, 0x2670, 0x0000, "AMD Radeon HD 6670A"},
{Model::DetectSub, 0x17aa, 0x3079, 0x0000, "AMD Radeon HD 7650A"},
{Model::DetectSub, 0x17aa, 0x3087, 0x0000, "AMD Radeon HD 7650A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6650A"}
};
static constexpr Model dev6758[] {
{Model::DetectSub, 0x1028, 0x0b0e, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x103c, 0x6882, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe181, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe198, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1787, 0x2309, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1043, 0x0443, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2205, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1043, 0x03ea, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2545, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe194, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2557, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7670"}
};
static constexpr Model dev6759[] {
{Model::DetectSub, 0x1462, 0x2509, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x148c, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1682, 0x3280, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1682, 0x3530, 0x0000, "AMD Radeon HD 8850"},
{Model::DetectSub, 0x174b, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1b0a, 0x90b5, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1b0a, 0x90b6, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6570"}
};
static constexpr Model dev6760[] {
{Model::DetectSub, 0x1028, 0x04cc, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x1028, 0x051c, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1028, 0x051d, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1622, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1623, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1656, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1658, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1659, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x165b, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x167d, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x167f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x169c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1855, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x1859, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x185c, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x185d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x103c, 0x185f, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x103c, 0x1863, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x355c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x355f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3581, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x358c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x358f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3592, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3596, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3671, 0x0000, "AMD FirePro M3900"},
{Model::DetectSub, 0x1043, 0x100a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x102a, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x1043, 0x104b, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x105d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x106b, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x106d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x107d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2002, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2107, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2108, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2109, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x8515, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x8517, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x855a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0x0001, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0x0003, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0x0004, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0xfb22, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb23, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb2c, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb31, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb32, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb33, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb38, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb39, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb3a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb40, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb41, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb42, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb47, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb48, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb51, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb52, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb53, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb81, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb82, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb83, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfc52, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfc56, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcd3, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcd4, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcee, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfdee, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc0b3, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x144d, 0xc609, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc625, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc636, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3900, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3902, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3970, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5101, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x17aa, 0x5102, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5103, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5106, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6470M"}
};
static constexpr Model dev6761[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6430M"}
};
static constexpr Model dev6768[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6400M"}
};
static constexpr Model dev6770[] {
{Model::DetectSub, 0x17aa, 0x308d, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x17aa, 0x3658, 0x0000, "AMD Radeon HD 7470A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6450A"}
};
static constexpr Model dev6779[] {
{Model::DetectSub, 0x103c, 0x2aee, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x1462, 0x2346, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1462, 0x2496, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x148c, 0x7450, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x148c, 0x8450, 0x0000, "AMD Radeon HD 8450"},
{Model::DetectSub, 0x1545, 0x7470, 0x0000, "AMD Radeon HD 7470"},
{Model::DetectSub, 0x1642, 0x3a66, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1642, 0x3a76, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1682, 0x3200, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x174b, 0x7450, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1b0a, 0x90a8, 0x0000, "AMD Radeon HD 6450A"},
{Model::DetectSub, 0x1b0a, 0x90b3, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x1b0a, 0x90bb, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6450"}
};
static constexpr Model dev6780[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W9000"}
};
static constexpr Model dev6790[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970"}
};
static constexpr Model dev6798[] {
{Model::DetectSub, 0x1002, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1002, 0x4000, 0x0000, "AMD Radeon HD 8970"},
{Model::DetectSub, 0x1043, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x3006, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x3005, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1462, 0x2775, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1682, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x9999, 0x0000, "ASUS ARES II"},
{Model::DetectSub, 0x148C, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1458, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1787, 0x2317, 0x0000, "AMD Radeon HD 7990"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970"}
};
static constexpr Model dev679a[] {
{Model::DetectSub, 0x1002, 0x3000, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x174b, 0x3000, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1043, 0x047e, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1043, 0x0424, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1462, 0x277c, 0x0000, "AMD Radeon R9 280"},
{Model::DetectSub, 0x174b, 0xa003, 0x0000, "AMD Radeon R9 280"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8950"}
};
static constexpr Model dev679e[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870"}
};
static constexpr Model dev67b0[] {
{Model::DetectSub, 0x1028, 0x0b00, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x103c, 0x6566, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x0476, 0x0000, "ASUS ARES III"},
{Model::DetectSub, 0x1043, 0x04d7, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04db, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04df, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04e9, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1458, 0x22bc, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1458, 0x22c1, 0x0000, "AMD Radeon R9 390"},
{Model::DetectSub, 0x1462, 0x2015, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x148c, 0x2347, 0x0000, "Devil 13 Dual Core R9 290X"},
{Model::DetectSub, 0x148c, 0x2357, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1682, 0x9395, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x174b, 0x0e34, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x174b, 0xe324, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1787, 0x2357, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 290X"}
};
static constexpr Model dev67c0[] {
{Model::DetectRev, 0x0000, 0x0000, 0x0080, "AMD Radeon E9550"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 7100"}
};
static constexpr Model dev67c4[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 7100"}
};
static constexpr Model dev67c7[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 5100"}
};
static constexpr Model dev67df[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00e1, "Radeon RX 590"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c2, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c3, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c4, "Radeon RX 480"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c5, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c6, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c7, "Radeon RX 480"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00d7, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e0, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e7, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 470"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon RX 480"}
};
static constexpr Model dev67e0[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon Pro WX 7100"}
};
static constexpr Model dev67e3[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 4100"}
};
static constexpr Model dev67ef[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon Pro 460/560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c5, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c7, "Radeon Pro 455/555"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e0, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e5, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e7, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon Pro 450/550"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 460"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro 460"}
};
static constexpr Model dev67ff[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon Pro 465"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon Pro 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 550"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro 560"}
};
static constexpr Model dev6800[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970M"}
};
static constexpr Model dev6801[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8970M"}
};
static constexpr Model dev6806[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W7000"}
};
static constexpr Model dev6808[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W7000"}
};
static constexpr Model dev6810[] {
{Model::DetectSub, 0x1458, 0x2272, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x1462, 0x3033, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x174b, 0xe271, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x1787, 0x201c, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x148c, 0x0908, 0x0000, "AMD Radeon R9 370"},
{Model::DetectSub, 0x1682, 0x7370, 0x0000, "AMD Radeon R7 370"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 370X"}
};
static constexpr Model dev6818[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870"}
};
static constexpr Model dev6819[] {
{Model::DetectSub, 0x174b, 0xe218, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x174b, 0xe221, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x1458, 0x255a, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x1462, 0x3058, 0x0000, "AMD Radeon R7 265"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 270"}
};
static constexpr Model dev6820[] {
{Model::DetectSub, 0x103c, 0x1851, 0x0000, "AMD Radeon HD 7750M"},
{Model::DetectSub, 0x17aa, 0x3643, 0x0000, "AMD Radeon R9 A375"},
{Model::DetectSub, 0x17aa, 0x3801, 0x0000, "AMD Radeon R9 M275"},
{Model::DetectSub, 0x1028, 0x06da, 0x0000, "AMD FirePro W5170M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M375"}
};
static constexpr Model dev6821[] {
{Model::DetectSub, 0x1002, 0x031e, 0x0000, "AMD FirePro SX4000"},
{Model::DetectSub, 0x1028, 0x05cc, 0x0000, "AMD FirePro M5100"},
{Model::DetectSub, 0x1028, 0x15cc, 0x0000, "AMD FirePro M5100"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M370X"}
};
static constexpr Model dev6823[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8850M/R9 M265X"}
};
static constexpr Model dev6825[] {
{Model::DetectSub, 0x1028, 0x053f, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x1028, 0x05cd, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x1028, 0x15cd, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x103c, 0x176c, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x8086, 0x2111, 0x0000, "AMD Radeon HD 7730M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870M"}
};
static constexpr Model dev6827[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7850M/8850M"}
};
static constexpr Model dev682b[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8830M"}
};
static constexpr Model dev682d[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro M4000"}
};
static constexpr Model dev682f[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7730M"}
};
static constexpr Model dev6835[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 255"}
};
static constexpr Model dev6839[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7700"}
};
static constexpr Model dev683b[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7700"}
};
static constexpr Model dev683d[] {
{Model::DetectSub, 0x1002, 0x0030, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1019, 0x0030, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x103c, 0x6890, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1043, 0x8760, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1462, 0x2710, 0x0000, "AMD Radeon HD 7770"},
{Model::DetectSub, 0x174b, 0x8304, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7770"}
};
static constexpr Model dev683f[] {
{Model::DetectSub, 0x1462, 0x2790, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectSub, 0x1462, 0x2791, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectSub, 0x1642, 0x3b97, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7750"}
};
static constexpr Model dev6840[] {
{Model::DetectSub, 0x1025, 0x0696, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0697, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0698, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0699, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x103c, 0x1789, 0x0000, "AMD FirePro M2000"},
{Model::DetectSub, 0x103c, 0x17f1, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x17f4, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x103c, 0x1813, 0x0000, "AMD Radeon HD 7590M"},
{Model::DetectSub, 0x144d, 0xc0c5, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7670M"}
};
static constexpr Model dev6841[] {
{Model::DetectSub, 0x1028, 0x057f, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x17f1, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x1813, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0x0001, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0x0002, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0xfb43, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb91, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb92, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb93, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfba2, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfba3, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x144d, 0xc0c7, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7650M"}
};
static constexpr Model dev6861[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 9100"}
};
static constexpr Model dev6863[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Vega Frontier Edition"}
};
static constexpr Model dev687f[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon RX Vega 64"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX Vega 64"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c3, "Radeon RX Vega 56"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon RX Vega 64"}
};
static constexpr Model dev6898[] {
{Model::DetectSub, 0x174b, 0x6870, 0x0000, "AMD Radeon HD 6870"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5870"}
};
static constexpr Model dev6899[] {
{Model::DetectSub, 0x174b, 0x237b, 0x0000, "ATI Radeon HD 5850 (x2)"},
{Model::DetectSub, 0x174b, 0x6850, 0x0000, "AMD Radeon HD 6850"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5850"}
};
static constexpr Model dev68a0[] {
{Model::DetectSub, 0x1028, 0x12ef, 0x0000, "ATI FirePro M7820"},
{Model::DetectSub, 0x103c, 0x1520, 0x0000, "ATI FirePro M7820"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5870"}
};
static constexpr Model dev68a1[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5850"}
};
static constexpr Model dev68b0[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68b1[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68b8[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68c0[] {
{Model::DetectSub, 0x103c, 0x1521, 0x0000, "ATI FirePro M5800"},
{Model::DetectSub, 0x17aa, 0x3978, 0x0000, "AMD Radeon HD 6570M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5730"}
};
static constexpr Model dev68c1[] {
{Model::DetectSub, 0x1025, 0x0347, 0x0000, "ATI Mobility Radeon HD 5470"},
{Model::DetectSub, 0x1025, 0x0517, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051a, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051b, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051d, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0525, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0526, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x052b, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x052c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053d, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053e, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053f, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0607, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x103c, 0x1521, 0x0000, "ATI FirePro M5800"},
{Model::DetectSub, 0x103c, 0xfd52, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfd63, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfd65, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfdd2, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x17aa, 0x3977, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5650"}
};
static constexpr Model dev68d8[] {
{Model::DetectSub, 0x1028, 0x68e0, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x174b, 0x5690, 0x0000, "ATI Radeon HD 5690"},
{Model::DetectSub, 0x174b, 0xe151, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x174b, 0xe166, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x1043, 0x0356, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x1787, 0x200d, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x17af, 0x3011, 0x0000, "ATI Radeon HD 5690"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5730"}
};
static constexpr Model dev68d9[] {
{Model::DetectSub, 0x148c, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x148c, 0x3001, 0x0000, "AMD Radeon HD 6610"},
{Model::DetectSub, 0x1545, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x174b, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x174b, 0x6510, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x174b, 0x6610, 0x0000, "AMD Radeon HD 6610"},
{Model::DetectSub, 0x1787, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x17af, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x17af, 0x3010, 0x0000, "ATI Radeon HD 5630"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5570"}
};
static constexpr Model dev68e0[] {
{Model::DetectSub, 0x1682, 0x9e52, 0x0000, "ATI FirePro M3800"},
{Model::DetectSub, 0x1682, 0x9e53, 0x0000, "ATI FirePro M3800"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5450"}
};
static constexpr Model dev68e1[] {
{Model::DetectSub, 0x148c, 0x3001, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x148c, 0x3002, 0x0000, "AMD Radeon HD 6250"},
{Model::DetectSub, 0x148c, 0x3003, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x148c, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x148c, 0x8350, 0x0000, "AMD Radeon HD 8350"},
{Model::DetectSub, 0x1545, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x1682, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x174b, 0x5470, 0x0000, "ATI Radeon HD 5470"},
{Model::DetectSub, 0x174b, 0x6230, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x174b, 0x6350, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x174b, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x17af, 0x3001, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x17af, 0x3014, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x17af, 0x3015, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x17af, 0x8350, 0x0000, "AMD Radeon HD 8350"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5450"}
};
static constexpr Model dev6920[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M395"}
};
static constexpr Model dev6921[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M295X"}
};
static constexpr Model dev6938[] {
{Model::DetectSub, 0x106b, 0x013a, 0x0000, "AMD Radeon R9 M295X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 380X"}
};
static constexpr Model dev6939[] {
{Model::DetectSub, 0x148c, 0x9380, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x174b, 0xe308, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x1043, 0x0498, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x1462, 0x2015, 0x0000, "AMD Radeon R9 380"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 285"}
};
static constexpr Model dev7300[] {
{Model::DetectSub, 0x1002, 0x1b36, 0x0000, "AMD Radeon Pro Duo"},
{Model::DetectSub, 0x1043, 0x04a0, 0x0000, "AMD Radeon FURY X"},
{Model::DetectSub, 0x1002, 0x0b36, 0x0000, "AMD Radeon FURY X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon FURY"}
};
static constexpr DevicePair devices[] {
{0x6640, dev6640, arrsize(dev6640)},
{0x6641, dev6641, arrsize(dev6641)},
{0x6646, dev6646, arrsize(dev6646)},
{0x6647, dev6647, arrsize(dev6647)},
{0x665c, dev665c, arrsize(dev665c)},
{0x665d, dev665d, arrsize(dev665d)},
{0x66af, dev66af, arrsize(dev66af)},
{0x6704, dev6704, arrsize(dev6704)},
{0x6718, dev6718, arrsize(dev6718)},
{0x6719, dev6719, arrsize(dev6719)},
{0x6720, dev6720, arrsize(dev6720)},
{0x6722, dev6722, arrsize(dev6722)},
{0x6738, dev6738, arrsize(dev6738)},
{0x6739, dev6739, arrsize(dev6739)},
{0x6740, dev6740, arrsize(dev6740)},
{0x6741, dev6741, arrsize(dev6741)},
{0x6745, dev6745, arrsize(dev6745)},
{0x6750, dev6750, arrsize(dev6750)},
{0x6758, dev6758, arrsize(dev6758)},
{0x6759, dev6759, arrsize(dev6759)},
{0x6760, dev6760, arrsize(dev6760)},
{0x6761, dev6761, arrsize(dev6761)},
{0x6768, dev6768, arrsize(dev6768)},
{0x6770, dev6770, arrsize(dev6770)},
{0x6779, dev6779, arrsize(dev6779)},
{0x6780, dev6780, arrsize(dev6780)},
{0x6790, dev6790, arrsize(dev6790)},
{0x6798, dev6798, arrsize(dev6798)},
{0x679a, dev679a, arrsize(dev679a)},
{0x679e, dev679e, arrsize(dev679e)},
{0x67b0, dev67b0, arrsize(dev67b0)},
{0x67c0, dev67c0, arrsize(dev67c0)},
{0x67c4, dev67c4, arrsize(dev67c4)},
{0x67c7, dev67c7, arrsize(dev67c7)},
{0x67df, dev67df, arrsize(dev67df)},
{0x67e0, dev67e0, arrsize(dev67e0)},
{0x67e3, dev67e3, arrsize(dev67e3)},
{0x67ef, dev67ef, arrsize(dev67ef)},
{0x67ff, dev67ff, arrsize(dev67ff)},
{0x6800, dev6800, arrsize(dev6800)},
{0x6801, dev6801, arrsize(dev6801)},
{0x6806, dev6806, arrsize(dev6806)},
{0x6808, dev6808, arrsize(dev6808)},
{0x6810, dev6810, arrsize(dev6810)},
{0x6818, dev6818, arrsize(dev6818)},
{0x6819, dev6819, arrsize(dev6819)},
{0x6820, dev6820, arrsize(dev6820)},
{0x6821, dev6821, arrsize(dev6821)},
{0x6823, dev6823, arrsize(dev6823)},
{0x6825, dev6825, arrsize(dev6825)},
{0x6827, dev6827, arrsize(dev6827)},
{0x682b, dev682b, arrsize(dev682b)},
{0x682d, dev682d, arrsize(dev682d)},
{0x682f, dev682f, arrsize(dev682f)},
{0x6835, dev6835, arrsize(dev6835)},
{0x6839, dev6839, arrsize(dev6839)},
{0x683b, dev683b, arrsize(dev683b)},
{0x683d, dev683d, arrsize(dev683d)},
{0x683f, dev683f, arrsize(dev683f)},
{0x6840, dev6840, arrsize(dev6840)},
{0x6841, dev6841, arrsize(dev6841)},
{0x6861, dev6861, arrsize(dev6861)},
{0x6863, dev6863, arrsize(dev6863)},
{0x687f, dev687f, arrsize(dev687f)},
{0x6898, dev6898, arrsize(dev6898)},
{0x6899, dev6899, arrsize(dev6899)},
{0x68a0, dev68a0, arrsize(dev68a0)},
{0x68a1, dev68a1, arrsize(dev68a1)},
{0x68b0, dev68b0, arrsize(dev68b0)},
{0x68b1, dev68b1, arrsize(dev68b1)},
{0x68b8, dev68b8, arrsize(dev68b8)},
{0x68c0, dev68c0, arrsize(dev68c0)},
{0x68c1, dev68c1, arrsize(dev68c1)},
{0x68d8, dev68d8, arrsize(dev68d8)},
{0x68d9, dev68d9, arrsize(dev68d9)},
{0x68e0, dev68e0, arrsize(dev68e0)},
{0x68e1, dev68e1, arrsize(dev68e1)},
{0x6920, dev6920, arrsize(dev6920)},
{0x6921, dev6921, arrsize(dev6921)},
{0x6938, dev6938, arrsize(dev6938)},
{0x6939, dev6939, arrsize(dev6939)},
{0x7300, dev7300, arrsize(dev7300)}
};
static BuiltinModel devIntel[] {
// For Sandy only 0x0116 and 0x0126 controllers are properly supported by AppleIntelSNBGraphicsFB.
// 0x0102 and 0x0106 are implemented as AppleIntelSNBGraphicsController/AppleIntelSNBGraphicsController2.
// AppleIntelHD3000Graphics actually supports more (0x0106, 0x0601, 0x0102, 0x0116, 0x0126).
// To make sure we have at least acceleration we fake unsupported ones as 0x0102.
// 0x0106 is likely a typo from 0x0106 or a fulty device (AppleIntelHD3000Graphics)
{ 0x0106, 0x0000, "Intel HD Graphics 2000" },
{ 0x0601, 0x0106, "Intel HD Graphics 2000" },
{ 0x0102, 0x0000, "Intel HD Graphics 2000" },
{ 0x0112, 0x0116, "Intel HD Graphics 2000" },
{ 0x0116, 0x0000, "Intel HD Graphics 3000" },
{ 0x0122, 0x0126, "Intel HD Graphics 2000" },
{ 0x0126, 0x0000, "Intel HD Graphics 3000" },
{ 0x0152, 0x0000, "Intel HD Graphics 2500" },
{ 0x015A, 0x0152, "Intel HD Graphics P2500" },
{ 0x0156, 0x0000, "Intel HD Graphics 2500" },
{ 0x0162, 0x0000, "Intel HD Graphics 4000" },
{ 0x016A, 0x0162, "Intel HD Graphics P4000" },
{ 0x0166, 0x0000, "Intel HD Graphics 4000" },
{ 0x0D26, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D22, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2A, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2B, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2E, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0A26, 0x0000, "Intel HD Graphics 5000" },
{ 0x0A2A, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0A2B, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0A2E, 0x0000, "Intel Iris Graphics 5100" },
{ 0x0412, 0x0000, "Intel HD Graphics 4600" },
{ 0x0416, 0x0412, "Intel HD Graphics 4600" },
{ 0x041A, 0x0412, "Intel HD Graphics P4600" },
{ 0x041B, 0x0412, nullptr },
{ 0x041E, 0x0412, "Intel HD Graphics 4400" },
{ 0x0A12, 0x0412, nullptr },
{ 0x0A16, 0x0412, "Intel HD Graphics 4400" },
{ 0x0A1A, 0x0412, nullptr },
{ 0x0A1E, 0x0412, "Intel HD Graphics 4200" },
{ 0x0A22, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0D12, 0x0412, "Intel HD Graphics 4600" },
{ 0x0D16, 0x0412, "Intel HD Graphics 4600" },
{ 0x1612, 0x0000, "Intel HD Graphics 5600" },
{ 0x1616, 0x0000, "Intel HD Graphics 5500" },
{ 0x161E, 0x0000, "Intel HD Graphics 5300" },
{ 0x1622, 0x0000, "Intel Iris Pro Graphics 6200" },
{ 0x1626, 0x0000, "Intel HD Graphics 6000" },
{ 0x162B, 0x0000, "Intel Iris Graphics 6100" },
{ 0x162A, 0x0000, "Intel Iris Pro Graphics P6300" },
{ 0x162D, 0x0000, "Intel Iris Pro Graphics P6300" },
// Reserved/unused/generic Broadwell },
// { 0x0BD1, 0x0000, nullptr },
// { 0x0BD2, 0x0000, nullptr },
// { 0x0BD3, 0x0000, nullptr },
// { 0x1602, 0x0000, nullptr },
// { 0x1606, 0x0000, nullptr },
// { 0x160B, 0x0000, nullptr },
// { 0x160A, 0x0000, nullptr },
// { 0x160D, 0x0000, nullptr },
// { 0x160E, 0x0000, nullptr },
// { 0x161B, 0x0000, nullptr },
// { 0x161A, 0x0000, nullptr },
// { 0x161D, 0x0000, nullptr },
// { 0x162E, 0x0000, nullptr },
// { 0x1632, 0x0000, nullptr },
// { 0x1636, 0x0000, nullptr },
// { 0x163B, 0x0000, nullptr },
// { 0x163A, 0x0000, nullptr },
// { 0x163D, 0x0000, nullptr },
// { 0x163E, 0x0000, nullptr },
{ 0x1902, 0x0000, "Intel HD Graphics 510" },
{ 0x1906, 0x0000, "Intel HD Graphics 510" },
{ 0x190B, 0x0000, "Intel HD Graphics 510" },
{ 0x191E, 0x0000, "Intel HD Graphics 515" },
{ 0x1916, 0x0000, "Intel HD Graphics 520" },
{ 0x1921, 0x0000, "Intel HD Graphics 520" },
{ 0x1912, 0x0000, "Intel HD Graphics 530" },
{ 0x191B, 0x0000, "Intel HD Graphics 530" },
{ 0x191D, 0x191B, "Intel HD Graphics P530" },
{ 0x1923, 0x191B, "Intel HD Graphics 535" },
{ 0x1926, 0x0000, "Intel Iris Graphics 540" },
{ 0x1927, 0x0000, "Intel Iris Graphics 550" },
{ 0x192B, 0x0000, "Intel Iris Graphics 555" },
{ 0x192D, 0x1927, "Intel Iris Graphics P555" },
{ 0x1932, 0x0000, "Intel Iris Pro Graphics 580" },
{ 0x193A, 0x193B, "Intel Iris Pro Graphics P580" },
{ 0x193B, 0x0000, "Intel Iris Pro Graphics 580" },
{ 0x193D, 0x193B, "Intel Iris Pro Graphics P580" },
// Reserved/unused/generic Skylake },
// { 0x0901, 0x0000, nullptr },
// { 0x0902, 0x0000, nullptr },
// { 0x0903, 0x0000, nullptr },
// { 0x0904, 0x0000, nullptr },
// { 0x190E, 0x0000, nullptr },
// { 0x1913, 0x0000, nullptr },
// { 0x1915, 0x0000, nullptr },
// { 0x1917, 0x0000, nullptr },
{ 0x5902, 0x591E, "Intel HD Graphics 610" },
{ 0x591E, 0x0000, "Intel HD Graphics 615" },
{ 0x5916, 0x0000, "Intel HD Graphics 620" },
{ 0x5917, 0x5916, "Intel UHD Graphics 620" },
{ 0x5912, 0x0000, "Intel HD Graphics 630" },
{ 0x591B, 0x0000, "Intel HD Graphics 630" },
{ 0x591C, 0x0000, "Intel UHD Graphics 615" },
{ 0x591D, 0x591B, "Intel HD Graphics P630" },
{ 0x5923, 0x0000, "Intel HD Graphics 635" },
{ 0x5926, 0x0000, "Intel Iris Plus Graphics 640" },
{ 0x5927, 0x0000, "Intel Iris Plus Graphics 650" },
{ 0x3E90, 0x3E92, "Intel UHD Graphics 610" },
{ 0x3E91, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E92, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E93, 0x3E92, "Intel UHD Graphics 610" },
{ 0x3E98, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E9B, 0x0000, "Intel UHD Graphics 630" },
{ 0x3EA5, 0x0000, "Intel Iris Plus Graphics 655" },
{ 0x3EA0, 0x5916, "Intel UHD Graphics 620" },
{ 0x87C0, 0x0000, "Intel UHD Graphics 617" },
// Reserved/unused/generic Kaby Lake / Coffee Lake },
};
const char *WEG::getIntelModel(uint32_t dev, uint32_t &fakeId) {
fakeId = 0;
for (size_t i = 0; i < arrsize(devIntel); i++) {
if (devIntel[i].device == dev) {
fakeId = devIntel[i].fake;
return devIntel[i].name;
}
}
return nullptr;
}
const char *WEG::getRadeonModel(uint16_t dev, uint16_t rev, uint16_t subven, uint16_t sub) {
for (auto &device : devices) {
if (device.dev == dev) {
for (size_t j = 0; j < device.modelNum; j++) {
auto &model = device.models[j];
if (model.mode & Model::DetectSub && (model.subven != subven || model.sub != sub))
continue;
if (model.mode & Model::DetectRev && (model.rev != rev))
continue;
return model.name;
}
break;
}
}
return nullptr;
}
Fixed UHD620 Whiskey Lake
//
// kern_model.cpp
// WhateverGreen
//
// Copyright © 2017 vit9696. All rights reserved.
//
#include <Headers/kern_iokit.hpp>
#include "kern_weg.hpp"
/**
* General rules for AMD GPU names (first table):
*
* 1. Only use device identifiers present in Apple kexts starting with 5xxx series
* 2. Follow Apple naming style (e.g., ATI for 5xxx series, AMD for 6xxx series, Radeon Pro for 5xx GPUs)
* 3. Write earliest available hardware with slashes (e.g. Radeon Pro 455/555)
* 4. Avoid using generic names like "AMD Radeon RX"
* 5. Provide revision identifiers whenever possible
* 6. Detection order should be vendor-id, device-id, subsystem-vendor-id, subsystem-id, revision-id
*
* General rules for Intel GPU names (second table):
*
* 1. All identifiers from Sandy and newer are allowed to be present
* 2. For idenitifiers not present in Apple kexts provide a fake id (AMD GPUs are just too many)
* 3. Use nullptr if the exact GPU name is not known
*
* Some identifiers are taken from https://github.com/pciutils/pciids/blob/master/pci.ids?raw=true
* Last synced version 2017.07.24 (https://github.com/pciutils/pciids/blob/699e70f3de/pci.ids?raw=true)
*/
struct Model {
enum Detect : uint16_t {
DetectDef = 0x0,
DetectSub = 0x1,
DetectRev = 0x2,
DetectAll = DetectSub | DetectRev
};
uint16_t mode {DetectDef};
uint16_t subven {0};
uint16_t sub {0};
uint16_t rev {0};
const char *name {nullptr};
};
struct BuiltinModel {
uint32_t device;
uint32_t fake;
const char *name;
};
struct DevicePair {
uint16_t dev;
const Model *models;
size_t modelNum;
};
static constexpr Model dev6640[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro M6100"}
};
static constexpr Model dev6641[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8930M"}
};
static constexpr Model dev6646[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M280X"}
};
static constexpr Model dev6647[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M270X"}
};
static constexpr Model dev665c[] {
{Model::DetectSub, 0x1462, 0x2932, 0x0000, "AMD Radeon HD 8770"},
{Model::DetectSub, 0x1462, 0x2934, 0x0000, "AMD Radeon R9 260"},
{Model::DetectSub, 0x1462, 0x2938, 0x0000, "AMD Radeon R9 360"},
{Model::DetectSub, 0x148c, 0x0907, 0x0000, "AMD Radeon R7 360"},
{Model::DetectSub, 0x148c, 0x9260, 0x0000, "AMD Radeon R9 260"},
{Model::DetectSub, 0x148c, 0x9360, 0x0000, "AMD Radeon R9 360"},
{Model::DetectSub, 0x1682, 0x0907, 0x0000, "AMD Radeon R7 360"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7790"}
};
static constexpr Model dev665d[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 260"}
};
static constexpr Model dev66af[] {
{Model::DetectDef, 0x0000, 0x0000, 0x00c1, "AMD Radeon VII"}
};
static constexpr Model dev6704[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro V7900"}
};
static constexpr Model dev6718[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6970"}
};
static constexpr Model dev6719[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6950"}
};
static constexpr Model dev6720[] {
{Model::DetectSub, 0x1028, 0x0490, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x1028, 0x04a4, 0x0000, "AMD FirePro M8900"},
{Model::DetectSub, 0x1028, 0x053f, 0x0000, "AMD FirePro M8900"},
{Model::DetectSub, 0x106b, 0x0b00, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x1558, 0x5102, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectSub, 0x174b, 0xe188, 0x0000, "AMD Radeon HD 6970M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6990M"}
};
static constexpr Model dev6722[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6900M"}
};
static constexpr Model dev6738[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6870"}
};
static constexpr Model dev6739[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6850"}
};
static constexpr Model dev6740[] {
{Model::DetectSub, 0x1019, 0x2392, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x1028, 0x04a3, 0x0000, "Precision M4600"},
{Model::DetectSub, 0x1028, 0x053e, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x1630, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x1631, 0x0000, "AMD FirePro M5950"},
{Model::DetectSub, 0x103c, 0x164e, 0x0000, "AMD Radeon HD 6730M5"},
{Model::DetectSub, 0x103c, 0x1657, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1658, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x165a, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x165b, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1688, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x1689, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x168a, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x185e, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectSub, 0x103c, 0x3388, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x3389, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectSub, 0x103c, 0x3582, 0x0000, "AMD Radeon HD 6770M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6730M"}
};
static constexpr Model dev6741[] {
{Model::DetectSub, 0x1028, 0x04c1, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04c5, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04cd, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04d7, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x04d9, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1028, 0x052d, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x103c, 0x1646, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1688, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1689, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x168a, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x1860, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectSub, 0x103c, 0x3385, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x103c, 0x3560, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x358d, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x3590, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x103c, 0x3593, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x1043, 0x2125, 0x0000, "AMD Radeon HD 7670M"},
{Model::DetectSub, 0x1043, 0x2127, 0x0000, "AMD Radeon HD 7670M"},
{Model::DetectSub, 0x104d, 0x907b, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x104d, 0x9080, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x104d, 0x9081, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1179, 0xfd63, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x1179, 0xfd65, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x144d, 0xc0b3, 0x0000, "AMD Radeon HD 6750M"},
{Model::DetectSub, 0x144d, 0xc539, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x144d, 0xc609, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectSub, 0x17aa, 0x21e1, 0x0000, "AMD Radeon HD 6630M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6650M"}
};
static constexpr Model dev6745[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6600M"}
};
static constexpr Model dev6750[] {
{Model::DetectSub, 0x1462, 0x2670, 0x0000, "AMD Radeon HD 6670A"},
{Model::DetectSub, 0x17aa, 0x3079, 0x0000, "AMD Radeon HD 7650A"},
{Model::DetectSub, 0x17aa, 0x3087, 0x0000, "AMD Radeon HD 7650A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6650A"}
};
static constexpr Model dev6758[] {
{Model::DetectSub, 0x1028, 0x0b0e, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x103c, 0x6882, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe181, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe198, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1787, 0x2309, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1043, 0x0443, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2205, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1043, 0x03ea, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2545, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x174b, 0xe194, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectSub, 0x1458, 0x2557, 0x0000, "AMD Radeon HD 6670"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7670"}
};
static constexpr Model dev6759[] {
{Model::DetectSub, 0x1462, 0x2509, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x148c, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1682, 0x3280, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1682, 0x3530, 0x0000, "AMD Radeon HD 8850"},
{Model::DetectSub, 0x174b, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1b0a, 0x90b5, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x1b0a, 0x90b6, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6570"}
};
static constexpr Model dev6760[] {
{Model::DetectSub, 0x1028, 0x04cc, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x1028, 0x051c, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1028, 0x051d, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1622, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1623, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x103c, 0x1656, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1658, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1659, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x165b, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x167d, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x167f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x169c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x1855, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x1859, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x185c, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x185d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x103c, 0x185f, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x103c, 0x1863, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x103c, 0x355c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x355f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3581, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x358c, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x358f, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3592, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3596, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x103c, 0x3671, 0x0000, "AMD FirePro M3900"},
{Model::DetectSub, 0x1043, 0x100a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x102a, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x1043, 0x104b, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x105d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x106b, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x106d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x107d, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2002, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2107, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2108, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x2109, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x8515, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x8517, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1043, 0x855a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0x0001, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0x0003, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0x0004, 0x0000, "AMD Radeon HD 6450M"},
{Model::DetectSub, 0x1179, 0xfb22, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb23, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb2c, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb31, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb32, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb33, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb38, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb39, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb3a, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb40, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb41, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb42, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb47, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb48, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb51, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb52, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb53, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb81, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb82, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfb83, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfc52, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfc56, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcd3, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcd4, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfcee, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x1179, 0xfdee, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc0b3, 0x0000, "AMD Radeon HD 6490M"},
{Model::DetectSub, 0x144d, 0xc609, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc625, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x144d, 0xc636, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3900, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3902, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x3970, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5101, 0x0000, "AMD Radeon HD 7470M"},
{Model::DetectSub, 0x17aa, 0x5102, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5103, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectSub, 0x17aa, 0x5106, 0x0000, "AMD Radeon HD 7450M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6470M"}
};
static constexpr Model dev6761[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6430M"}
};
static constexpr Model dev6768[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6400M"}
};
static constexpr Model dev6770[] {
{Model::DetectSub, 0x17aa, 0x308d, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x17aa, 0x3658, 0x0000, "AMD Radeon HD 7470A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6450A"}
};
static constexpr Model dev6779[] {
{Model::DetectSub, 0x103c, 0x2aee, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x1462, 0x2346, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1462, 0x2496, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x148c, 0x7450, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x148c, 0x8450, 0x0000, "AMD Radeon HD 8450"},
{Model::DetectSub, 0x1545, 0x7470, 0x0000, "AMD Radeon HD 7470"},
{Model::DetectSub, 0x1642, 0x3a66, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1642, 0x3a76, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1682, 0x3200, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x174b, 0x7450, 0x0000, "AMD Radeon HD 7450"},
{Model::DetectSub, 0x1b0a, 0x90a8, 0x0000, "AMD Radeon HD 6450A"},
{Model::DetectSub, 0x1b0a, 0x90b3, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectSub, 0x1b0a, 0x90bb, 0x0000, "AMD Radeon HD 7450A"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 6450"}
};
static constexpr Model dev6780[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W9000"}
};
static constexpr Model dev6790[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970"}
};
static constexpr Model dev6798[] {
{Model::DetectSub, 0x1002, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1002, 0x4000, 0x0000, "AMD Radeon HD 8970"},
{Model::DetectSub, 0x1043, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x3006, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x3005, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1462, 0x2775, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1682, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1043, 0x9999, 0x0000, "ASUS ARES II"},
{Model::DetectSub, 0x148C, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1458, 0x3001, 0x0000, "AMD Radeon R9 280X"},
{Model::DetectSub, 0x1787, 0x2317, 0x0000, "AMD Radeon HD 7990"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970"}
};
static constexpr Model dev679a[] {
{Model::DetectSub, 0x1002, 0x3000, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x174b, 0x3000, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1043, 0x047e, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1043, 0x0424, 0x0000, "AMD Radeon HD 7950"},
{Model::DetectSub, 0x1462, 0x277c, 0x0000, "AMD Radeon R9 280"},
{Model::DetectSub, 0x174b, 0xa003, 0x0000, "AMD Radeon R9 280"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8950"}
};
static constexpr Model dev679e[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870"}
};
static constexpr Model dev67b0[] {
{Model::DetectSub, 0x1028, 0x0b00, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x103c, 0x6566, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x0476, 0x0000, "ASUS ARES III"},
{Model::DetectSub, 0x1043, 0x04d7, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04db, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04df, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1043, 0x04e9, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1458, 0x22bc, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1458, 0x22c1, 0x0000, "AMD Radeon R9 390"},
{Model::DetectSub, 0x1462, 0x2015, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x148c, 0x2347, 0x0000, "Devil 13 Dual Core R9 290X"},
{Model::DetectSub, 0x148c, 0x2357, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1682, 0x9395, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x174b, 0x0e34, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x174b, 0xe324, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectSub, 0x1787, 0x2357, 0x0000, "AMD Radeon R9 390X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 290X"}
};
static constexpr Model dev67c0[] {
{Model::DetectRev, 0x0000, 0x0000, 0x0080, "AMD Radeon E9550"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 7100"}
};
static constexpr Model dev67c4[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 7100"}
};
static constexpr Model dev67c7[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 5100"}
};
static constexpr Model dev67df[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00e1, "Radeon RX 590"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c2, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c3, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c4, "Radeon RX 480"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c5, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c6, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c7, "Radeon RX 480"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00d7, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e0, "Radeon RX 470"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e7, "Radeon RX 580"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon RX 570"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 470"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon RX 480"}
};
static constexpr Model dev67e0[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon Pro WX 7100"}
};
static constexpr Model dev67e3[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 4100"}
};
static constexpr Model dev67ef[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon Pro 460/560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c5, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c7, "Radeon Pro 455/555"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 460"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e0, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e5, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00e7, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon Pro 450/550"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 460"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro 460"}
};
static constexpr Model dev67ff[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon Pro 465"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon Pro 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00cf, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ef, "Radeon RX 560"},
{Model::DetectRev, 0x0000, 0x0000, 0x00ff, "Radeon RX 550"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro 560"}
};
static constexpr Model dev6800[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7970M"}
};
static constexpr Model dev6801[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8970M"}
};
static constexpr Model dev6806[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W7000"}
};
static constexpr Model dev6808[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro W7000"}
};
static constexpr Model dev6810[] {
{Model::DetectSub, 0x1458, 0x2272, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x1462, 0x3033, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x174b, 0xe271, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x1787, 0x201c, 0x0000, "AMD Radeon R9 270X"},
{Model::DetectSub, 0x148c, 0x0908, 0x0000, "AMD Radeon R9 370"},
{Model::DetectSub, 0x1682, 0x7370, 0x0000, "AMD Radeon R7 370"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 370X"}
};
static constexpr Model dev6818[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870"}
};
static constexpr Model dev6819[] {
{Model::DetectSub, 0x174b, 0xe218, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x174b, 0xe221, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x1458, 0x255a, 0x0000, "AMD Radeon HD 7850"},
{Model::DetectSub, 0x1462, 0x3058, 0x0000, "AMD Radeon R7 265"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 270"}
};
static constexpr Model dev6820[] {
{Model::DetectSub, 0x103c, 0x1851, 0x0000, "AMD Radeon HD 7750M"},
{Model::DetectSub, 0x17aa, 0x3643, 0x0000, "AMD Radeon R9 A375"},
{Model::DetectSub, 0x17aa, 0x3801, 0x0000, "AMD Radeon R9 M275"},
{Model::DetectSub, 0x1028, 0x06da, 0x0000, "AMD FirePro W5170M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M375"}
};
static constexpr Model dev6821[] {
{Model::DetectSub, 0x1002, 0x031e, 0x0000, "AMD FirePro SX4000"},
{Model::DetectSub, 0x1028, 0x05cc, 0x0000, "AMD FirePro M5100"},
{Model::DetectSub, 0x1028, 0x15cc, 0x0000, "AMD FirePro M5100"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M370X"}
};
static constexpr Model dev6823[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8850M/R9 M265X"}
};
static constexpr Model dev6825[] {
{Model::DetectSub, 0x1028, 0x053f, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x1028, 0x05cd, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x1028, 0x15cd, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x103c, 0x176c, 0x0000, "AMD FirePro M6000"},
{Model::DetectSub, 0x8086, 0x2111, 0x0000, "AMD Radeon HD 7730M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7870M"}
};
static constexpr Model dev6827[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7850M/8850M"}
};
static constexpr Model dev682b[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 8830M"}
};
static constexpr Model dev682d[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD FirePro M4000"}
};
static constexpr Model dev682f[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7730M"}
};
static constexpr Model dev6835[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 255"}
};
static constexpr Model dev6839[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7700"}
};
static constexpr Model dev683b[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7700"}
};
static constexpr Model dev683d[] {
{Model::DetectSub, 0x1002, 0x0030, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1019, 0x0030, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x103c, 0x6890, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1043, 0x8760, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectSub, 0x1462, 0x2710, 0x0000, "AMD Radeon HD 7770"},
{Model::DetectSub, 0x174b, 0x8304, 0x0000, "AMD Radeon HD 8760"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7770"}
};
static constexpr Model dev683f[] {
{Model::DetectSub, 0x1462, 0x2790, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectSub, 0x1462, 0x2791, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectSub, 0x1642, 0x3b97, 0x0000, "AMD Radeon HD 8740"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7750"}
};
static constexpr Model dev6840[] {
{Model::DetectSub, 0x1025, 0x0696, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0697, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0698, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x1025, 0x0699, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x103c, 0x1789, 0x0000, "AMD FirePro M2000"},
{Model::DetectSub, 0x103c, 0x17f1, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x17f4, 0x0000, "AMD Radeon HD 7650M"},
{Model::DetectSub, 0x103c, 0x1813, 0x0000, "AMD Radeon HD 7590M"},
{Model::DetectSub, 0x144d, 0xc0c5, 0x0000, "AMD Radeon HD 7690M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7670M"}
};
static constexpr Model dev6841[] {
{Model::DetectSub, 0x1028, 0x057f, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x17f1, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x103c, 0x1813, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0x0001, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0x0002, 0x0000, "AMD Radeon HD 7570M"},
{Model::DetectSub, 0x1179, 0xfb43, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb91, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb92, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfb93, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfba2, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x1179, 0xfba3, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectSub, 0x144d, 0xc0c7, 0x0000, "AMD Radeon HD 7550M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon HD 7650M"}
};
static constexpr Model dev6861[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Pro WX 9100"}
};
static constexpr Model dev6863[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon Vega Frontier Edition"}
};
static constexpr Model dev687f[] {
{Model::DetectRev, 0x0000, 0x0000, 0x00c0, "Radeon RX Vega 64"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c1, "Radeon RX Vega 64"},
{Model::DetectRev, 0x0000, 0x0000, 0x00c3, "Radeon RX Vega 56"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "Radeon RX Vega 64"}
};
static constexpr Model dev6898[] {
{Model::DetectSub, 0x174b, 0x6870, 0x0000, "AMD Radeon HD 6870"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5870"}
};
static constexpr Model dev6899[] {
{Model::DetectSub, 0x174b, 0x237b, 0x0000, "ATI Radeon HD 5850 (x2)"},
{Model::DetectSub, 0x174b, 0x6850, 0x0000, "AMD Radeon HD 6850"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5850"}
};
static constexpr Model dev68a0[] {
{Model::DetectSub, 0x1028, 0x12ef, 0x0000, "ATI FirePro M7820"},
{Model::DetectSub, 0x103c, 0x1520, 0x0000, "ATI FirePro M7820"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5870"}
};
static constexpr Model dev68a1[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5850"}
};
static constexpr Model dev68b0[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68b1[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68b8[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5770"}
};
static constexpr Model dev68c0[] {
{Model::DetectSub, 0x103c, 0x1521, 0x0000, "ATI FirePro M5800"},
{Model::DetectSub, 0x17aa, 0x3978, 0x0000, "AMD Radeon HD 6570M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5730"}
};
static constexpr Model dev68c1[] {
{Model::DetectSub, 0x1025, 0x0347, 0x0000, "ATI Mobility Radeon HD 5470"},
{Model::DetectSub, 0x1025, 0x0517, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051a, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051b, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x051d, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0525, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0526, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x052b, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x052c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053c, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053d, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053e, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x053f, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x1025, 0x0607, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectSub, 0x103c, 0x1521, 0x0000, "ATI FirePro M5800"},
{Model::DetectSub, 0x103c, 0xfd52, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfd63, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfd65, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x103c, 0xfdd2, 0x0000, "AMD Radeon HD 6530M"},
{Model::DetectSub, 0x17aa, 0x3977, 0x0000, "AMD Radeon HD 6550M"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5650"}
};
static constexpr Model dev68d8[] {
{Model::DetectSub, 0x1028, 0x68e0, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x174b, 0x5690, 0x0000, "ATI Radeon HD 5690"},
{Model::DetectSub, 0x174b, 0xe151, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x174b, 0xe166, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x1043, 0x0356, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x1787, 0x200d, 0x0000, "ATI Radeon HD 5670"},
{Model::DetectSub, 0x17af, 0x3011, 0x0000, "ATI Radeon HD 5690"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5730"}
};
static constexpr Model dev68d9[] {
{Model::DetectSub, 0x148c, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x148c, 0x3001, 0x0000, "AMD Radeon HD 6610"},
{Model::DetectSub, 0x1545, 0x7570, 0x0000, "AMD Radeon HD 7570"},
{Model::DetectSub, 0x174b, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x174b, 0x6510, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x174b, 0x6610, 0x0000, "AMD Radeon HD 6610"},
{Model::DetectSub, 0x1787, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x17af, 0x3000, 0x0000, "AMD Radeon HD 6510"},
{Model::DetectSub, 0x17af, 0x3010, 0x0000, "ATI Radeon HD 5630"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5570"}
};
static constexpr Model dev68e0[] {
{Model::DetectSub, 0x1682, 0x9e52, 0x0000, "ATI FirePro M3800"},
{Model::DetectSub, 0x1682, 0x9e53, 0x0000, "ATI FirePro M3800"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Mobility Radeon HD 5450"}
};
static constexpr Model dev68e1[] {
{Model::DetectSub, 0x148c, 0x3001, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x148c, 0x3002, 0x0000, "AMD Radeon HD 6250"},
{Model::DetectSub, 0x148c, 0x3003, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x148c, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x148c, 0x8350, 0x0000, "AMD Radeon HD 8350"},
{Model::DetectSub, 0x1545, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x1682, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x174b, 0x5470, 0x0000, "ATI Radeon HD 5470"},
{Model::DetectSub, 0x174b, 0x6230, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x174b, 0x6350, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x174b, 0x7350, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x17af, 0x3001, 0x0000, "AMD Radeon HD 6230"},
{Model::DetectSub, 0x17af, 0x3014, 0x0000, "AMD Radeon HD 6350"},
{Model::DetectSub, 0x17af, 0x3015, 0x0000, "AMD Radeon HD 7350"},
{Model::DetectSub, 0x17af, 0x8350, 0x0000, "AMD Radeon HD 8350"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "ATI Radeon HD 5450"}
};
static constexpr Model dev6920[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M395"}
};
static constexpr Model dev6921[] {
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 M295X"}
};
static constexpr Model dev6938[] {
{Model::DetectSub, 0x106b, 0x013a, 0x0000, "AMD Radeon R9 M295X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 380X"}
};
static constexpr Model dev6939[] {
{Model::DetectSub, 0x148c, 0x9380, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x174b, 0xe308, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x1043, 0x0498, 0x0000, "AMD Radeon R9 380"},
{Model::DetectSub, 0x1462, 0x2015, 0x0000, "AMD Radeon R9 380"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon R9 285"}
};
static constexpr Model dev7300[] {
{Model::DetectSub, 0x1002, 0x1b36, 0x0000, "AMD Radeon Pro Duo"},
{Model::DetectSub, 0x1043, 0x04a0, 0x0000, "AMD Radeon FURY X"},
{Model::DetectSub, 0x1002, 0x0b36, 0x0000, "AMD Radeon FURY X"},
{Model::DetectDef, 0x0000, 0x0000, 0x0000, "AMD Radeon FURY"}
};
static constexpr DevicePair devices[] {
{0x6640, dev6640, arrsize(dev6640)},
{0x6641, dev6641, arrsize(dev6641)},
{0x6646, dev6646, arrsize(dev6646)},
{0x6647, dev6647, arrsize(dev6647)},
{0x665c, dev665c, arrsize(dev665c)},
{0x665d, dev665d, arrsize(dev665d)},
{0x66af, dev66af, arrsize(dev66af)},
{0x6704, dev6704, arrsize(dev6704)},
{0x6718, dev6718, arrsize(dev6718)},
{0x6719, dev6719, arrsize(dev6719)},
{0x6720, dev6720, arrsize(dev6720)},
{0x6722, dev6722, arrsize(dev6722)},
{0x6738, dev6738, arrsize(dev6738)},
{0x6739, dev6739, arrsize(dev6739)},
{0x6740, dev6740, arrsize(dev6740)},
{0x6741, dev6741, arrsize(dev6741)},
{0x6745, dev6745, arrsize(dev6745)},
{0x6750, dev6750, arrsize(dev6750)},
{0x6758, dev6758, arrsize(dev6758)},
{0x6759, dev6759, arrsize(dev6759)},
{0x6760, dev6760, arrsize(dev6760)},
{0x6761, dev6761, arrsize(dev6761)},
{0x6768, dev6768, arrsize(dev6768)},
{0x6770, dev6770, arrsize(dev6770)},
{0x6779, dev6779, arrsize(dev6779)},
{0x6780, dev6780, arrsize(dev6780)},
{0x6790, dev6790, arrsize(dev6790)},
{0x6798, dev6798, arrsize(dev6798)},
{0x679a, dev679a, arrsize(dev679a)},
{0x679e, dev679e, arrsize(dev679e)},
{0x67b0, dev67b0, arrsize(dev67b0)},
{0x67c0, dev67c0, arrsize(dev67c0)},
{0x67c4, dev67c4, arrsize(dev67c4)},
{0x67c7, dev67c7, arrsize(dev67c7)},
{0x67df, dev67df, arrsize(dev67df)},
{0x67e0, dev67e0, arrsize(dev67e0)},
{0x67e3, dev67e3, arrsize(dev67e3)},
{0x67ef, dev67ef, arrsize(dev67ef)},
{0x67ff, dev67ff, arrsize(dev67ff)},
{0x6800, dev6800, arrsize(dev6800)},
{0x6801, dev6801, arrsize(dev6801)},
{0x6806, dev6806, arrsize(dev6806)},
{0x6808, dev6808, arrsize(dev6808)},
{0x6810, dev6810, arrsize(dev6810)},
{0x6818, dev6818, arrsize(dev6818)},
{0x6819, dev6819, arrsize(dev6819)},
{0x6820, dev6820, arrsize(dev6820)},
{0x6821, dev6821, arrsize(dev6821)},
{0x6823, dev6823, arrsize(dev6823)},
{0x6825, dev6825, arrsize(dev6825)},
{0x6827, dev6827, arrsize(dev6827)},
{0x682b, dev682b, arrsize(dev682b)},
{0x682d, dev682d, arrsize(dev682d)},
{0x682f, dev682f, arrsize(dev682f)},
{0x6835, dev6835, arrsize(dev6835)},
{0x6839, dev6839, arrsize(dev6839)},
{0x683b, dev683b, arrsize(dev683b)},
{0x683d, dev683d, arrsize(dev683d)},
{0x683f, dev683f, arrsize(dev683f)},
{0x6840, dev6840, arrsize(dev6840)},
{0x6841, dev6841, arrsize(dev6841)},
{0x6861, dev6861, arrsize(dev6861)},
{0x6863, dev6863, arrsize(dev6863)},
{0x687f, dev687f, arrsize(dev687f)},
{0x6898, dev6898, arrsize(dev6898)},
{0x6899, dev6899, arrsize(dev6899)},
{0x68a0, dev68a0, arrsize(dev68a0)},
{0x68a1, dev68a1, arrsize(dev68a1)},
{0x68b0, dev68b0, arrsize(dev68b0)},
{0x68b1, dev68b1, arrsize(dev68b1)},
{0x68b8, dev68b8, arrsize(dev68b8)},
{0x68c0, dev68c0, arrsize(dev68c0)},
{0x68c1, dev68c1, arrsize(dev68c1)},
{0x68d8, dev68d8, arrsize(dev68d8)},
{0x68d9, dev68d9, arrsize(dev68d9)},
{0x68e0, dev68e0, arrsize(dev68e0)},
{0x68e1, dev68e1, arrsize(dev68e1)},
{0x6920, dev6920, arrsize(dev6920)},
{0x6921, dev6921, arrsize(dev6921)},
{0x6938, dev6938, arrsize(dev6938)},
{0x6939, dev6939, arrsize(dev6939)},
{0x7300, dev7300, arrsize(dev7300)}
};
static BuiltinModel devIntel[] {
// For Sandy only 0x0116 and 0x0126 controllers are properly supported by AppleIntelSNBGraphicsFB.
// 0x0102 and 0x0106 are implemented as AppleIntelSNBGraphicsController/AppleIntelSNBGraphicsController2.
// AppleIntelHD3000Graphics actually supports more (0x0106, 0x0601, 0x0102, 0x0116, 0x0126).
// To make sure we have at least acceleration we fake unsupported ones as 0x0102.
// 0x0106 is likely a typo from 0x0106 or a fulty device (AppleIntelHD3000Graphics)
{ 0x0106, 0x0000, "Intel HD Graphics 2000" },
{ 0x0601, 0x0106, "Intel HD Graphics 2000" },
{ 0x0102, 0x0000, "Intel HD Graphics 2000" },
{ 0x0112, 0x0116, "Intel HD Graphics 2000" },
{ 0x0116, 0x0000, "Intel HD Graphics 3000" },
{ 0x0122, 0x0126, "Intel HD Graphics 2000" },
{ 0x0126, 0x0000, "Intel HD Graphics 3000" },
{ 0x0152, 0x0000, "Intel HD Graphics 2500" },
{ 0x015A, 0x0152, "Intel HD Graphics P2500" },
{ 0x0156, 0x0000, "Intel HD Graphics 2500" },
{ 0x0162, 0x0000, "Intel HD Graphics 4000" },
{ 0x016A, 0x0162, "Intel HD Graphics P4000" },
{ 0x0166, 0x0000, "Intel HD Graphics 4000" },
{ 0x0D26, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D22, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2A, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2B, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0D2E, 0x0000, "Intel Iris Pro Graphics 5200" },
{ 0x0A26, 0x0000, "Intel HD Graphics 5000" },
{ 0x0A2A, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0A2B, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0A2E, 0x0000, "Intel Iris Graphics 5100" },
{ 0x0412, 0x0000, "Intel HD Graphics 4600" },
{ 0x0416, 0x0412, "Intel HD Graphics 4600" },
{ 0x041A, 0x0412, "Intel HD Graphics P4600" },
{ 0x041B, 0x0412, nullptr },
{ 0x041E, 0x0412, "Intel HD Graphics 4400" },
{ 0x0A12, 0x0412, nullptr },
{ 0x0A16, 0x0412, "Intel HD Graphics 4400" },
{ 0x0A1A, 0x0412, nullptr },
{ 0x0A1E, 0x0412, "Intel HD Graphics 4200" },
{ 0x0A22, 0x0A2E, "Intel Iris Graphics 5100" },
{ 0x0D12, 0x0412, "Intel HD Graphics 4600" },
{ 0x0D16, 0x0412, "Intel HD Graphics 4600" },
{ 0x1612, 0x0000, "Intel HD Graphics 5600" },
{ 0x1616, 0x0000, "Intel HD Graphics 5500" },
{ 0x161E, 0x0000, "Intel HD Graphics 5300" },
{ 0x1622, 0x0000, "Intel Iris Pro Graphics 6200" },
{ 0x1626, 0x0000, "Intel HD Graphics 6000" },
{ 0x162B, 0x0000, "Intel Iris Graphics 6100" },
{ 0x162A, 0x0000, "Intel Iris Pro Graphics P6300" },
{ 0x162D, 0x0000, "Intel Iris Pro Graphics P6300" },
// Reserved/unused/generic Broadwell },
// { 0x0BD1, 0x0000, nullptr },
// { 0x0BD2, 0x0000, nullptr },
// { 0x0BD3, 0x0000, nullptr },
// { 0x1602, 0x0000, nullptr },
// { 0x1606, 0x0000, nullptr },
// { 0x160B, 0x0000, nullptr },
// { 0x160A, 0x0000, nullptr },
// { 0x160D, 0x0000, nullptr },
// { 0x160E, 0x0000, nullptr },
// { 0x161B, 0x0000, nullptr },
// { 0x161A, 0x0000, nullptr },
// { 0x161D, 0x0000, nullptr },
// { 0x162E, 0x0000, nullptr },
// { 0x1632, 0x0000, nullptr },
// { 0x1636, 0x0000, nullptr },
// { 0x163B, 0x0000, nullptr },
// { 0x163A, 0x0000, nullptr },
// { 0x163D, 0x0000, nullptr },
// { 0x163E, 0x0000, nullptr },
{ 0x1902, 0x0000, "Intel HD Graphics 510" },
{ 0x1906, 0x0000, "Intel HD Graphics 510" },
{ 0x190B, 0x0000, "Intel HD Graphics 510" },
{ 0x191E, 0x0000, "Intel HD Graphics 515" },
{ 0x1916, 0x0000, "Intel HD Graphics 520" },
{ 0x1921, 0x0000, "Intel HD Graphics 520" },
{ 0x1912, 0x0000, "Intel HD Graphics 530" },
{ 0x191B, 0x0000, "Intel HD Graphics 530" },
{ 0x191D, 0x191B, "Intel HD Graphics P530" },
{ 0x1923, 0x191B, "Intel HD Graphics 535" },
{ 0x1926, 0x0000, "Intel Iris Graphics 540" },
{ 0x1927, 0x0000, "Intel Iris Graphics 550" },
{ 0x192B, 0x0000, "Intel Iris Graphics 555" },
{ 0x192D, 0x1927, "Intel Iris Graphics P555" },
{ 0x1932, 0x0000, "Intel Iris Pro Graphics 580" },
{ 0x193A, 0x193B, "Intel Iris Pro Graphics P580" },
{ 0x193B, 0x0000, "Intel Iris Pro Graphics 580" },
{ 0x193D, 0x193B, "Intel Iris Pro Graphics P580" },
// Reserved/unused/generic Skylake },
// { 0x0901, 0x0000, nullptr },
// { 0x0902, 0x0000, nullptr },
// { 0x0903, 0x0000, nullptr },
// { 0x0904, 0x0000, nullptr },
// { 0x190E, 0x0000, nullptr },
// { 0x1913, 0x0000, nullptr },
// { 0x1915, 0x0000, nullptr },
// { 0x1917, 0x0000, nullptr },
{ 0x5902, 0x591E, "Intel HD Graphics 610" },
{ 0x591E, 0x0000, "Intel HD Graphics 615" },
{ 0x5916, 0x0000, "Intel HD Graphics 620" },
{ 0x5917, 0x5916, "Intel UHD Graphics 620" },
{ 0x5912, 0x0000, "Intel HD Graphics 630" },
{ 0x591B, 0x0000, "Intel HD Graphics 630" },
{ 0x591C, 0x0000, "Intel UHD Graphics 615" },
{ 0x591D, 0x591B, "Intel HD Graphics P630" },
{ 0x5923, 0x0000, "Intel HD Graphics 635" },
{ 0x5926, 0x0000, "Intel Iris Plus Graphics 640" },
{ 0x5927, 0x0000, "Intel Iris Plus Graphics 650" },
{ 0x3E90, 0x3E92, "Intel UHD Graphics 610" },
{ 0x3E91, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E92, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E93, 0x3E92, "Intel UHD Graphics 610" },
{ 0x3E98, 0x0000, "Intel UHD Graphics 630" },
{ 0x3E9B, 0x0000, "Intel UHD Graphics 630" },
{ 0x3EA5, 0x0000, "Intel Iris Plus Graphics 655" },
{ 0x3EA0, 0x3EA5, "Intel UHD Graphics 620" },
{ 0x87C0, 0x0000, "Intel UHD Graphics 617" },
// Reserved/unused/generic Kaby Lake / Coffee Lake },
};
const char *WEG::getIntelModel(uint32_t dev, uint32_t &fakeId) {
fakeId = 0;
for (size_t i = 0; i < arrsize(devIntel); i++) {
if (devIntel[i].device == dev) {
fakeId = devIntel[i].fake;
return devIntel[i].name;
}
}
return nullptr;
}
const char *WEG::getRadeonModel(uint16_t dev, uint16_t rev, uint16_t subven, uint16_t sub) {
for (auto &device : devices) {
if (device.dev == dev) {
for (size_t j = 0; j < device.modelNum; j++) {
auto &model = device.models[j];
if (model.mode & Model::DetectSub && (model.subven != subven || model.sub != sub))
continue;
if (model.mode & Model::DetectRev && (model.rev != rev))
continue;
return model.name;
}
break;
}
}
return nullptr;
}
|
// 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/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/test/test_file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_file_manager.h"
#include "chrome/browser/download/download_item.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/history/download_history_info.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/net/url_request_slow_download_job.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/active_downloads_ui.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/cancelable_request.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/page_transition_types.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Construction of this class defines a system state, based on some number
// of downloads being seen in a particular state + other events that
// may occur in the download system. That state will be recorded if it
// occurs at any point after construction. When that state occurs, the class
// is considered finished. Callers may either probe for the finished state, or
// wait on it.
//
// TODO(rdsmith): Detect manager going down, remove pointer to
// DownloadManager, transition to finished. (For right now we
// just use a scoped_refptr<> to keep it around, but that may cause
// timeouts on waiting if a DownloadManager::Shutdown() occurs which
// cancels our in-progress downloads.)
class DownloadsObserver : public DownloadManager::Observer,
public DownloadItem::Observer {
public:
// Create an object that will be considered finished when |wait_count|
// download items have entered state |download_finished_state|.
// If |finish_on_select_file| is true, the object will also be
// considered finished if the DownloadManager raises a
// SelectFileDialogDisplayed() notification.
// TODO(rdsmith): Add option of "dangerous accept/reject dialog" as
// a unblocking event; if that shows up when you aren't expecting it,
// it'll result in a hang/timeout as we'll never get to final rename.
// This probably means rewriting the interface to take a list of events
// to treat as completion events.
DownloadsObserver(DownloadManager* download_manager,
size_t wait_count,
DownloadItem::DownloadState download_finished_state,
bool finish_on_select_file)
: download_manager_(download_manager),
wait_count_(wait_count),
finished_downloads_at_construction_(0),
waiting_(false),
download_finished_state_(download_finished_state),
finish_on_select_file_(finish_on_select_file),
select_file_dialog_seen_(false) {
download_manager_->AddObserver(this); // Will call initial ModelChanged().
finished_downloads_at_construction_ = finished_downloads_.size();
}
~DownloadsObserver() {
std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
for (; it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
download_manager_->RemoveObserver(this);
}
// State accessors.
bool select_file_dialog_seen() { return select_file_dialog_seen_; }
// Wait for whatever state was specified in the constructor.
void WaitForFinished() {
if (!IsFinished()) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
waiting_ = false;
}
}
// Return true if everything's happened that we're configured for.
bool IsFinished() {
if (finished_downloads_.size() - finished_downloads_at_construction_
>= wait_count_)
return true;
return (finish_on_select_file_ && select_file_dialog_seen_);
}
// DownloadItem::Observer
virtual void OnDownloadUpdated(DownloadItem* download) {
if (download->state() == download_finished_state_)
DownloadInFinalState(download);
}
virtual void OnDownloadOpened(DownloadItem* download) {}
// DownloadManager::Observer
virtual void ModelChanged() {
// Regenerate DownloadItem observers. If there are any download items
// in our final state, note them in |finished_downloads_|
// (done by |OnDownloadUpdated()|).
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
std::vector<DownloadItem*>::iterator it = downloads.begin();
for (; it != downloads.end(); ++it) {
OnDownloadUpdated(*it); // Safe to call multiple times; checks state.
std::set<DownloadItem*>::const_iterator
finished_it(finished_downloads_.find(*it));
std::set<DownloadItem*>::iterator
observed_it(downloads_observed_.find(*it));
// If it isn't finished and we're aren't observing it, start.
if (finished_it == finished_downloads_.end() &&
observed_it == downloads_observed_.end()) {
(*it)->AddObserver(this);
downloads_observed_.insert(*it);
continue;
}
// If it is finished and we are observing it, stop.
if (finished_it != finished_downloads_.end() &&
observed_it != downloads_observed_.end()) {
(*it)->RemoveObserver(this);
downloads_observed_.erase(observed_it);
continue;
}
}
}
virtual void SelectFileDialogDisplayed(int32 /* id */) {
select_file_dialog_seen_ = true;
SignalIfFinished();
}
private:
// Called when we know that a download item is in a final state.
// Note that this is not the same as it first transitioning in to the
// final state; multiple notifications may occur once the item is in
// that state. So we keep our own track of transitions into final.
void DownloadInFinalState(DownloadItem* download) {
if (finished_downloads_.find(download) != finished_downloads_.end()) {
// We've already seen terminal state on this download.
return;
}
// Record the transition.
finished_downloads_.insert(download);
SignalIfFinished();
}
void SignalIfFinished() {
if (waiting_ && IsFinished())
MessageLoopForUI::current()->Quit();
}
// The observed download manager.
scoped_refptr<DownloadManager> download_manager_;
// The set of DownloadItem's that have transitioned to their finished state
// since construction of this object. When the size of this array
// reaches wait_count_, we're done.
std::set<DownloadItem*> finished_downloads_;
// The set of DownloadItem's we are currently observing. Generally there
// won't be any overlap with the above; once we see the final state
// on a DownloadItem, we'll stop observing it.
std::set<DownloadItem*> downloads_observed_;
// The number of downloads to wait on completing.
size_t wait_count_;
// The number of downloads entered in final state in initial
// ModelChanged(). We use |finished_downloads_| to track the incoming
// transitions to final state we should ignore, and to track the
// number of final state transitions that occurred between
// construction and return from wait. But some downloads may be in our
// final state (and thus be entered into |finished_downloads_|) when we
// construct this class. We don't want to count those in our transition
// to finished.
int finished_downloads_at_construction_;
// Whether an internal message loop has been started and must be quit upon
// all downloads completing.
bool waiting_;
// The state on which to consider the DownloadItem finished.
DownloadItem::DownloadState download_finished_state_;
// True if we should transition the DownloadsObserver to finished if
// the select file dialog comes up.
bool finish_on_select_file_;
// True if we've seen the select file dialog.
bool select_file_dialog_seen_;
DISALLOW_COPY_AND_ASSIGN(DownloadsObserver);
};
// WaitForFlush() returns after:
// * There are no IN_PROGRESS download items remaining on the
// DownloadManager.
// * There have been two round trip messages through the file and
// IO threads.
// This almost certainly means that a Download cancel has propagated through
// the system.
class DownloadsFlushObserver
: public DownloadManager::Observer,
public DownloadItem::Observer,
public base::RefCountedThreadSafe<DownloadsFlushObserver> {
public:
explicit DownloadsFlushObserver(DownloadManager* download_manager)
: download_manager_(download_manager),
waiting_for_zero_inprogress_(true) { }
void WaitForFlush() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
download_manager_->AddObserver(this);
ui_test_utils::RunMessageLoop();
}
// DownloadsManager observer methods.
virtual void ModelChanged() {
// Model has changed, so there may be more DownloadItems to observe.
CheckDownloadsInProgress(true);
}
// DownloadItem observer methods.
virtual void OnDownloadUpdated(DownloadItem* download) {
// No change in DownloadItem set on manager.
CheckDownloadsInProgress(false);
}
virtual void OnDownloadOpened(DownloadItem* download) {}
protected:
friend class base::RefCountedThreadSafe<DownloadsFlushObserver>;
virtual ~DownloadsFlushObserver() {
download_manager_->RemoveObserver(this);
for (std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
}
private:
// If we're waiting for that flush point, check the number
// of downloads in the IN_PROGRESS state and take appropriate
// action. If requested, also observes all downloads while iterating.
void CheckDownloadsInProgress(bool observe_downloads) {
if (waiting_for_zero_inprogress_) {
int count = 0;
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
std::vector<DownloadItem*>::iterator it = downloads.begin();
for (; it != downloads.end(); ++it) {
if ((*it)->state() == DownloadItem::IN_PROGRESS)
count++;
if (observe_downloads) {
if (downloads_observed_.find(*it) == downloads_observed_.end()) {
(*it)->AddObserver(this);
}
// Download items are forever, and we don't want to make
// assumptions about future state transitions, so once we
// start observing them, we don't stop until destruction.
}
}
if (count == 0) {
waiting_for_zero_inprogress_ = false;
// Stop observing DownloadItems. We maintain the observation
// of DownloadManager so that we don't have to independently track
// whether we are observing it for conditional destruction.
for (std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
downloads_observed_.clear();
// Trigger next step. We need to go past the IO thread twice, as
// there's a self-task posting in the IO thread cancel path.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this,
&DownloadsFlushObserver::PingFileThread, 2));
}
}
}
void PingFileThread(int cycle) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &DownloadsFlushObserver::PingIOThread,
cycle));
}
void PingIOThread(int cycle) {
if (--cycle) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &DownloadsFlushObserver::PingFileThread,
cycle));
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, new MessageLoop::QuitTask());
}
}
DownloadManager* download_manager_;
std::set<DownloadItem*> downloads_observed_;
bool waiting_for_zero_inprogress_;
DISALLOW_COPY_AND_ASSIGN(DownloadsFlushObserver);
};
// Collect the information from FILE and IO threads needed for the Cancel
// Test, specifically the number of outstanding requests on the
// ResourceDispatcherHost and the number of pending downloads on the
// DownloadFileManager.
class CancelTestDataCollector
: public base::RefCountedThreadSafe<CancelTestDataCollector> {
public:
CancelTestDataCollector()
: resource_dispatcher_host_(
g_browser_process->resource_dispatcher_host()),
rdh_pending_requests_(0),
dfm_pending_downloads_(0) { }
void WaitForDataCollected() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &CancelTestDataCollector::IOInfoCollector));
ui_test_utils::RunMessageLoop();
}
int rdh_pending_requests() { return rdh_pending_requests_; }
int dfm_pending_downloads() { return dfm_pending_downloads_; }
protected:
friend class base::RefCountedThreadSafe<CancelTestDataCollector>;
virtual ~CancelTestDataCollector() {}
private:
void IOInfoCollector() {
download_file_manager_ = resource_dispatcher_host_->download_file_manager();
rdh_pending_requests_ = resource_dispatcher_host_->pending_requests();
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &CancelTestDataCollector::FileInfoCollector));
}
void FileInfoCollector() {
dfm_pending_downloads_ = download_file_manager_->NumberOfActiveDownloads();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, new MessageLoop::QuitTask());
}
ResourceDispatcherHost* resource_dispatcher_host_;
DownloadFileManager* download_file_manager_;
int rdh_pending_requests_;
int dfm_pending_downloads_;
DISALLOW_COPY_AND_ASSIGN(CancelTestDataCollector);
};
class DownloadTest : public InProcessBrowserTest {
public:
enum SelectExpectation {
EXPECT_NO_SELECT_DIALOG = -1,
EXPECT_NOTHING,
EXPECT_SELECT_DIALOG
};
DownloadTest() {
EnableDOMAutomation();
}
// Returning false indicates a failure of the setup, and should be asserted
// in the caller.
virtual bool InitialSetup(bool prompt_for_download) {
bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
EXPECT_TRUE(have_test_dir);
if (!have_test_dir)
return false;
// Sanity check default values for window / tab count and shelf visibility.
int window_count = BrowserList::size();
EXPECT_EQ(1, window_count);
EXPECT_EQ(1, browser()->tab_count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Set up the temporary download folder.
bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
EXPECT_TRUE(created_downloads_dir);
if (!created_downloads_dir)
return false;
browser()->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
prompt_for_download);
DownloadManager* manager = browser()->profile()->GetDownloadManager();
manager->download_prefs()->ResetAutoOpen();
manager->RemoveAllDownloads();
return true;
}
protected:
enum SizeTestType {
SIZE_TEST_TYPE_KNOWN,
SIZE_TEST_TYPE_UNKNOWN,
};
// Location of the file source (the place from which it is downloaded).
FilePath OriginFile(FilePath file) {
return test_dir_.Append(file);
}
// Location of the file destination (place to which it is downloaded).
FilePath DestinationFile(Browser* browser, FilePath file) {
return GetDownloadDirectory(browser).Append(file);
}
// Must be called after browser creation. Creates a temporary
// directory for downloads that is auto-deleted on destruction.
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CreateAndSetDownloadsDirectory(Browser* browser) {
if (!browser)
return false;
if (!downloads_directory_.CreateUniqueTempDir())
return false;
browser->profile()->GetPrefs()->SetFilePath(
prefs::kDownloadDefaultDirectory,
downloads_directory_.path());
return true;
}
DownloadPrefs* GetDownloadPrefs(Browser* browser) {
return browser->profile()->GetDownloadManager()->download_prefs();
}
FilePath GetDownloadDirectory(Browser* browser) {
DownloadManager* download_mananger =
browser->profile()->GetDownloadManager();
return download_mananger->download_prefs()->download_path();
}
// Create a DownloadsObserver that will wait for the
// specified number of downloads to finish.
DownloadsObserver* CreateWaiter(Browser* browser, int num_downloads) {
DownloadManager* download_manager =
browser->profile()->GetDownloadManager();
return new DownloadsObserver(
download_manager, num_downloads,
DownloadItem::COMPLETE, // Really done
true); // Bail on select file
}
// Create a DownloadsObserver that will wait for the
// specified number of downloads to start.
DownloadsObserver* CreateInProgressWaiter(Browser* browser,
int num_downloads) {
DownloadManager* download_manager =
browser->profile()->GetDownloadManager();
return new DownloadsObserver(
download_manager, num_downloads,
DownloadItem::IN_PROGRESS, // Has started
true); // Bail on select file
}
// Download |url|, then wait for the download to finish.
// |disposition| indicates where the navigation occurs (current tab, new
// foreground tab, etc).
// |expectation| indicates whether or not a Select File dialog should be
// open when the download is finished, or if we don't care.
// If the dialog appears, the routine exits. The only effect |expectation|
// has is whether or not the test succeeds.
// |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
// values in the ui_test_utils::BrowserTestWaitFlags enum.
void DownloadAndWaitWithDisposition(Browser* browser,
const GURL& url,
WindowOpenDisposition disposition,
SelectExpectation expectation,
int browser_test_flags) {
// Setup notification, navigate, and block.
scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
// This call will block until the condition specified by
// |browser_test_flags|, but will not wait for the download to finish.
ui_test_utils::NavigateToURLWithDisposition(browser,
url,
disposition,
browser_test_flags);
// Waits for the download to complete.
observer->WaitForFinished();
// If specified, check the state of the select file dialog.
if (expectation != EXPECT_NOTHING) {
EXPECT_EQ(expectation == EXPECT_SELECT_DIALOG,
observer->select_file_dialog_seen());
}
}
// Download a file in the current tab, then wait for the download to finish.
void DownloadAndWait(Browser* browser,
const GURL& url,
SelectExpectation expectation) {
DownloadAndWaitWithDisposition(
browser,
url,
CURRENT_TAB,
expectation,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
}
// Should only be called when the download is known to have finished
// (in error or not).
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CheckDownload(Browser* browser,
const FilePath& downloaded_filename,
const FilePath& origin_filename) {
// Find the path to which the data will be downloaded.
FilePath downloaded_file(DestinationFile(browser, downloaded_filename));
// Find the origin path (from which the data comes).
FilePath origin_file(OriginFile(origin_filename));
bool origin_file_exists = file_util::PathExists(origin_file);
EXPECT_TRUE(origin_file_exists);
if (!origin_file_exists)
return false;
// Confirm the downloaded data file exists.
bool downloaded_file_exists = file_util::PathExists(downloaded_file);
EXPECT_TRUE(downloaded_file_exists);
if (!downloaded_file_exists)
return false;
int64 origin_file_size = 0;
int64 downloaded_file_size = 0;
EXPECT_TRUE(file_util::GetFileSize(origin_file, &origin_file_size));
EXPECT_TRUE(file_util::GetFileSize(downloaded_file, &downloaded_file_size));
EXPECT_EQ(origin_file_size, downloaded_file_size);
EXPECT_TRUE(file_util::ContentsEqual(downloaded_file, origin_file));
// Delete the downloaded copy of the file.
bool downloaded_file_deleted =
file_util::DieFileDie(downloaded_file, false);
EXPECT_TRUE(downloaded_file_deleted);
return downloaded_file_deleted;
}
bool RunSizeTest(Browser* browser,
SizeTestType type,
const std::string& partial_indication,
const std::string& total_indication) {
if (!InitialSetup(false))
return false;
EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
return false;
GURL url(type == SIZE_TEST_TYPE_KNOWN ?
URLRequestSlowDownloadJob::kKnownSizeUrl :
URLRequestSlowDownloadJob::kUnknownSizeUrl);
// TODO(ahendrickson) -- |expected_title_in_progress| and
// |expected_title_finished| need to be checked.
FilePath filename;
net::FileURLToFilePath(url, &filename);
string16 expected_title_in_progress(
ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
string16 expected_title_finished(
ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
// Download a partial web page in a background tab and wait.
// The mock system will not complete until it gets a special URL.
scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
ui_test_utils::NavigateToURL(browser, url);
// TODO(ahendrickson): check download status text before downloading.
// Need to:
// - Add a member function to the |DownloadShelf| interface class, that
// indicates how many members it has.
// - Add a member function to |DownloadShelf| to get the status text
// of a given member (for example, via the name in |DownloadItemView|'s
// GetAccessibleState() member function), by index.
// - Iterate over browser->window()->GetDownloadShelf()'s members
// to see if any match the status text we want. Start with the last one.
// Allow the request to finish. We do this by loading a second URL in a
// separate tab.
GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
ui_test_utils::NavigateToURLWithDisposition(
browser,
finish_url,
NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
observer->WaitForFinished();
EXPECT_EQ(2, browser->tab_count());
// TODO(ahendrickson): check download status text after downloading.
// Make sure the download shelf is showing.
CheckDownloadUIVisible(browser, true, true);
FilePath basefilename(filename.BaseName());
net::FileURLToFilePath(url, &filename);
FilePath download_path = downloads_directory_.path().Append(basefilename);
bool downloaded_path_exists = file_util::PathExists(download_path);
EXPECT_TRUE(downloaded_path_exists);
if (!downloaded_path_exists)
return false;
// Delete the file we just downloaded.
EXPECT_TRUE(file_util::DieFileDie(download_path, true));
EXPECT_FALSE(file_util::PathExists(download_path));
return true;
}
void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
DCHECK(downloads);
DownloadManager* manager = browser->profile()->GetDownloadManager();
manager->SearchDownloads(string16(), downloads);
}
// Figure out if the appropriate download visibility was done. A
// utility function to support ChromeOS variations.
static void CheckDownloadUIVisible(Browser* browser,
bool expected_non_chromeos,
bool expected_chromeos) {
#if defined(OS_CHROMEOS)
EXPECT_EQ(expected_chromeos,
ActiveDownloadsUI::GetPopup(browser->profile()));
#else
EXPECT_EQ(expected_non_chromeos,
browser->window()->IsDownloadShelfVisible());
#endif
}
static void ExpectWindowCountAfterDownload(size_t expected) {
#if defined(OS_CHROMEOS)
// On ChromeOS, a download panel is created to display
// download information, and this counts as a window.
expected++;
#endif
EXPECT_EQ(expected, BrowserList::size());
}
private:
// Location of the test data.
FilePath test_dir_;
// Location of the downloads directory for these tests
ScopedTempDir downloads_directory_;
};
// Get History Information.
class DownloadsHistoryDataCollector {
public:
explicit DownloadsHistoryDataCollector(int64 download_db_handle,
DownloadManager* manager)
: result_valid_(false),
download_db_handle_(download_db_handle) {
HistoryService* hs =
manager->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
DCHECK(hs);
hs->QueryDownloads(
&callback_consumer_,
NewCallback(this,
&DownloadsHistoryDataCollector::OnQueryDownloadsComplete));
// Cannot complete immediately because the history backend runs on a
// separate thread, so we can assume that the RunMessageLoop below will
// be exited by the Quit in OnQueryDownloadsComplete.
ui_test_utils::RunMessageLoop();
}
bool GetDownloadsHistoryEntry(DownloadHistoryInfo* result) {
DCHECK(result);
*result = result_;
return result_valid_;
}
private:
void OnQueryDownloadsComplete(
std::vector<DownloadHistoryInfo>* entries) {
result_valid_ = false;
for (std::vector<DownloadHistoryInfo>::const_iterator it = entries->begin();
it != entries->end(); ++it) {
if (it->db_handle == download_db_handle_) {
result_ = *it;
result_valid_ = true;
}
}
MessageLoopForUI::current()->Quit();
}
DownloadHistoryInfo result_;
bool result_valid_;
int64 download_db_handle_;
CancelableRequestConsumer callback_consumer_;
DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
};
} // namespace
// While an object of this class exists, it will mock out download
// opening for all downloads created on the specified download manager.
class MockDownloadOpeningObserver : public DownloadManager::Observer {
public:
explicit MockDownloadOpeningObserver(DownloadManager* manager)
: download_manager_(manager) {
download_manager_->AddObserver(this);
}
~MockDownloadOpeningObserver() {
download_manager_->RemoveObserver(this);
}
// DownloadManager::Observer
virtual void ModelChanged() {
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
for (std::vector<DownloadItem*>::iterator it = downloads.begin();
it != downloads.end(); ++it) {
(*it)->TestMockDownloadOpen();
}
}
private:
DownloadManager* download_manager_;
DISALLOW_COPY_AND_ASSIGN(MockDownloadOpeningObserver);
};
// NOTES:
//
// Files for these tests are found in DIR_TEST_DATA (currently
// "chrome\test\data\", see chrome_paths.cc).
// Mock responses have extension .mock-http-headers appended to the file name.
// Download a file due to the associated MIME type.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
}
#if defined(OS_WIN)
// Download a file and confirm that the zone identifier (on windows)
// is set to internet.
IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Check state. Special file state must be checked before CheckDownload,
// as CheckDownload will delete the output file.
EXPECT_EQ(1, browser()->tab_count());
FilePath downloaded_file(DestinationFile(browser(), file));
if (file_util::VolumeSupportsADS(downloaded_file))
EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file));
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
}
#endif
// Put up a Select File dialog when the file is downloaded, due to its MIME
// type.
//
// This test runs correctly, but leaves behind turds in the test user's
// download directory because of http://crbug.com/62099. No big loss; it
// was primarily confirming DownloadsObserver wait on select file dialog
// functionality anyway.
IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DownloadMimeTypeSelect) {
ASSERT_TRUE(InitialSetup(true));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We expect the Select File dialog to appear
// due to the MIME type.
DownloadAndWait(browser(), url, EXPECT_SELECT_DIALOG);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
// Since we exited while the Select File dialog was visible, there should not
// be anything in the download shelf and so it should not be visible.
CheckDownloadUIVisible(browser(), false, false);
}
// Access a file with a viewable mime-type, verify that a download
// did not initiate.
IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath file_path(DestinationFile(browser(), file));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Check that we did not download the web page.
EXPECT_FALSE(file_util::PathExists(file_path));
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), false, false);
}
// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header. This also ensures we properly handle empty file downloads.
// The download shelf should be visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
}
#if !defined(OS_CHROMEOS) // Download shelf is not per-window on ChromeOS.
// Test that the download shelf is per-window by starting a download in one
// tab, opening a second tab, closing the shelf, going back to the first tab,
// and checking that the shelf is closed.
IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
// Open a second tab and wait.
EXPECT_NE(static_cast<TabContentsWrapper*>(NULL),
browser()->AddSelectedTabWithURL(GURL(), PageTransition::TYPED));
EXPECT_EQ(2, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
// Hide the download shelf.
browser()->window()->GetDownloadShelf()->Close();
CheckDownloadUIVisible(browser(), false, false);
// Go to the first tab.
browser()->ActivateTabAt(0, true);
EXPECT_EQ(2, browser()->tab_count());
// The download shelf should not be visible.
CheckDownloadUIVisible(browser(), false, false);
}
#endif // !OS_CHROMEOS
// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish". At that time, the download will finish.
// These tests don't currently test much due to holes in |RunSizeTest()|. See
// comments in that routine for details.
IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
"32.0 KB - ", "100% - "));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
"71% - ", "100% - "));
}
// Test that when downloading an item in Incognito mode, we don't crash when
// closing the last Incognito window (http://crbug.com/13983).
// Also check that the download shelf is not visible after closing the
// Incognito window.
IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
ASSERT_TRUE(InitialSetup(false));
// Open an Incognito window.
Browser* incognito = CreateIncognitoBrowser(); // Waits.
ASSERT_TRUE(incognito);
int window_count = BrowserList::size();
EXPECT_EQ(2, window_count);
// Download a file in the Incognito window and wait.
CreateAndSetDownloadsDirectory(incognito);
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Since |incognito| is a separate browser, we have to set it up explicitly.
incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
false);
DownloadAndWait(incognito, url, EXPECT_NO_SELECT_DIALOG);
// We should still have 2 windows.
ExpectWindowCountAfterDownload(2);
// Verify that the download shelf is showing for the Incognito window.
CheckDownloadUIVisible(incognito, true, true);
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(incognito));
#endif
// Close the Incognito window and don't crash.
incognito->CloseWindow();
#if !defined(OS_MACOSX)
signal.Wait();
ExpectWindowCountAfterDownload(1);
#endif
// Verify that the regular window does not have a download shelf.
CheckDownloadUIVisible(browser(), false, false);
CheckDownload(browser(), file, file);
}
// Navigate to a new background page, but don't download. Confirm that the
// download shelf is not visible and that we have two tabs.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// We should have two tabs now.
EXPECT_EQ(2, browser()->tab_count());
CheckDownloadUIVisible(browser(), false, false);
}
// Download a file in a background tab. Verify that the tab is closed
// automatically, and that the download shelf is visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
ASSERT_TRUE(InitialSetup(false));
// Download a file in a new background tab and wait. The tab is automatically
// closed when the download begins.
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file in another tab via
// a Javascript call.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page1.html page contains an openNew() function that opens a
// tab and then downloads download-test1.lib.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait (via Javascript).
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should have two tabs.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(2, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, open another tab via a Javascript call,
// then download a file in the new tab.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page2.html page contains an openNew() function that opens a
// tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url1);
// Open a new tab and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
EXPECT_EQ(2, browser()->tab_count());
// Download a file and wait.
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(browser(),
url,
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, we should have two tabs.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(2, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file via Javascript,
// which will do so in a temporary tab.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page3.html page contains an openNew() function that opens a
// tab with download-test1.lib in the URL. When the URL is determined to be
// a download, the tab is closed automatically.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file and wait.
// The file to download is "download-test1.lib".
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then call Javascript via a button to
// download a file in a new tab, which is closed automatically when the
// download begins.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page4.html page contains a form with download-test1.lib as the
// action.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait. The tab will automatically close
// when the download begins.
// The file to download is "download-test1.lib".
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(
browser(),
GURL("javascript:document.getElementById('form').submit()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Download a file in a new window.
// Verify that we have 2 windows, and the download shelf is not visible in the
// first window, but is visible in the second window.
// Close the new window.
// Verify that we have 1 window, and the download shelf is not visible.
//
// Regression test for http://crbug.com/44454
IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
#if !defined(OS_MACOSX)
// See below.
Browser* first_browser = browser();
#endif
// Download a file in a new window and wait.
DownloadAndWaitWithDisposition(browser(),
url,
NEW_WINDOW,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, the download shelf SHOULD NOT be visible in
// the first window.
ExpectWindowCountAfterDownload(2);
EXPECT_EQ(1, browser()->tab_count());
// Except on Chrome OS, where the download window sticks around.
CheckDownloadUIVisible(browser(), false, true);
// The download shelf SHOULD be visible in the second window.
std::set<Browser*> original_browsers;
original_browsers.insert(browser());
Browser* download_browser =
ui_test_utils::GetBrowserNotInSet(original_browsers);
ASSERT_TRUE(download_browser != NULL);
EXPECT_NE(download_browser, browser());
EXPECT_EQ(1, download_browser->tab_count());
CheckDownloadUIVisible(download_browser, true, true);
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(download_browser));
#endif
// Close the new window.
download_browser->CloseWindow();
#if !defined(OS_MACOSX)
signal.Wait();
EXPECT_EQ(first_browser, browser());
ExpectWindowCountAfterDownload(1);
#endif
EXPECT_EQ(1, browser()->tab_count());
// On ChromeOS, the popup sticks around.
CheckDownloadUIVisible(browser(), false, true);
CheckDownload(browser(), file, file);
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadCancelled) {
ASSERT_TRUE(InitialSetup(false));
EXPECT_EQ(1, browser()->tab_count());
// TODO(rdsmith): Fragile code warning! The code below relies on the
// DownloadsObserver only finishing when the new download has reached
// the state of being entered into the history and being user-visible
// (that's what's required for the Remove to be valid and for the
// download shelf to be visible). By the pure semantics of
// DownloadsObserver, that's not guaranteed; DownloadItems are created
// in the IN_PROGRESS state and made known to the DownloadManager
// immediately, so any ModelChanged event on the DownloadManager after
// navigation would allow the observer to return. However, the only
// ModelChanged() event the code will currently fire is in
// OnCreateDownloadEntryComplete, at which point the download item will
// be in the state we need.
// The right way to fix this is to create finer grained states on the
// DownloadItem, and wait for the state that indicates the item has been
// entered in the history and made visible in the UI.
// Create a download, wait until it's started, and confirm
// we're in the expected state.
scoped_ptr<DownloadsObserver> observer(CreateInProgressWaiter(browser(), 1));
ui_test_utils::NavigateToURL(
browser(), GURL(URLRequestSlowDownloadJob::kUnknownSizeUrl));
observer->WaitForFinished();
std::vector<DownloadItem*> downloads;
browser()->profile()->GetDownloadManager()->SearchDownloads(
string16(), &downloads);
ASSERT_EQ(1u, downloads.size());
ASSERT_EQ(DownloadItem::IN_PROGRESS, downloads[0]->state());
CheckDownloadUIVisible(browser(), true, true);
// Cancel the download and wait for download system quiesce.
downloads[0]->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);
scoped_refptr<DownloadsFlushObserver> flush_observer(
new DownloadsFlushObserver(browser()->profile()->GetDownloadManager()));
flush_observer->WaitForFlush();
// Get the important info from other threads and check it.
scoped_refptr<CancelTestDataCollector> info(new CancelTestDataCollector());
info->WaitForDataCollected();
EXPECT_EQ(0, info->rdh_pending_requests());
EXPECT_EQ(0, info->dfm_pending_downloads());
// Using "DownloadItem::Remove" follows the discard dangerous download path,
// which completely removes the browser from the shelf and closes the shelf
// if it was there. Chrome OS is an exception to this, where if we
// bring up the downloads panel, it stays there.
CheckDownloadUIVisible(browser(), false, true);
}
// Confirm a download makes it into the history properly.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath origin_file(OriginFile(file));
int64 origin_size;
file_util::GetFileSize(origin_file, &origin_size);
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Get details of what downloads have just happened.
std::vector<DownloadItem*> downloads;
GetDownloads(browser(), &downloads);
ASSERT_EQ(1u, downloads.size());
int64 db_handle = downloads[0]->db_handle();
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
// Check history results.
DownloadsHistoryDataCollector history_collector(
db_handle,
browser()->profile()->GetDownloadManager());
DownloadHistoryInfo info;
EXPECT_TRUE(history_collector.GetDownloadsHistoryEntry(&info)) << db_handle;
EXPECT_EQ(file, info.path.BaseName());
EXPECT_EQ(url, info.url);
// Ignore start_time.
EXPECT_EQ(origin_size, info.received_bytes);
EXPECT_EQ(origin_size, info.total_bytes);
EXPECT_EQ(DownloadItem::COMPLETE, info.state);
}
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
GURL flags_url(chrome::kAboutFlagsURL);
GURL extensions_url(chrome::kChromeUIExtensionsURL);
ui_test_utils::NavigateToURL(browser(), flags_url);
DownloadAndWait(browser(), download_url, EXPECT_NO_SELECT_DIALOG);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool webui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.webui_responded_);",
&webui_responded));
EXPECT_TRUE(webui_responded);
}
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// After several correct executions, this test starts failing on the build
// bots and then continues to fail consistently.
// As of 2011/05/22, it's crashing, so it is getting disabled.
// http://crbug.com/82278
IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url(chrome::kAboutFlagsURL);
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
DownloadAndWait(browser(), download_url, EXPECT_NO_SELECT_DIALOG);
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser()));
browser()->CloseWindow();
signal.Wait();
}
// Test to make sure auto-open works.
IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
ASSERT_TRUE(
GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
// Mokc out external opening on all downloads until end of test.
MockDownloadOpeningObserver observer(
browser()->profile()->GetDownloadManager());
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Find the download and confirm it was opened.
std::vector<DownloadItem*> downloads;
browser()->profile()->GetDownloadManager()->SearchDownloads(
string16(), &downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->state());
EXPECT_TRUE(downloads[0]->opened());
// As long as we're here, confirmed everything else is good.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
// Dissapears on most UIs, but the download panel sticks around for
// chrome os.
CheckDownloadUIVisible(browser(), false, true);
}
Fix AutoOpen test to be correct on ChromeOS.
Also cleaned up ifdefs around ChromeOS Download UI visibility.
R=achuith@chromium.org
R=phajdan.jr@chromium.org
BUG=84058
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=87317
Review URL: http://codereview.chromium.org/7074031
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@87321 0039d316-1c4b-4281-b951-d872f2087c98
// 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/file_path.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/test/test_file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_file_manager.h"
#include "chrome/browser/download/download_item.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/history/download_history_info.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/net/url_request_slow_download_job.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/active_downloads_ui.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/cancelable_request.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/page_transition_types.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Construction of this class defines a system state, based on some number
// of downloads being seen in a particular state + other events that
// may occur in the download system. That state will be recorded if it
// occurs at any point after construction. When that state occurs, the class
// is considered finished. Callers may either probe for the finished state, or
// wait on it.
//
// TODO(rdsmith): Detect manager going down, remove pointer to
// DownloadManager, transition to finished. (For right now we
// just use a scoped_refptr<> to keep it around, but that may cause
// timeouts on waiting if a DownloadManager::Shutdown() occurs which
// cancels our in-progress downloads.)
class DownloadsObserver : public DownloadManager::Observer,
public DownloadItem::Observer {
public:
// Create an object that will be considered finished when |wait_count|
// download items have entered state |download_finished_state|.
// If |finish_on_select_file| is true, the object will also be
// considered finished if the DownloadManager raises a
// SelectFileDialogDisplayed() notification.
// TODO(rdsmith): Add option of "dangerous accept/reject dialog" as
// a unblocking event; if that shows up when you aren't expecting it,
// it'll result in a hang/timeout as we'll never get to final rename.
// This probably means rewriting the interface to take a list of events
// to treat as completion events.
DownloadsObserver(DownloadManager* download_manager,
size_t wait_count,
DownloadItem::DownloadState download_finished_state,
bool finish_on_select_file)
: download_manager_(download_manager),
wait_count_(wait_count),
finished_downloads_at_construction_(0),
waiting_(false),
download_finished_state_(download_finished_state),
finish_on_select_file_(finish_on_select_file),
select_file_dialog_seen_(false) {
download_manager_->AddObserver(this); // Will call initial ModelChanged().
finished_downloads_at_construction_ = finished_downloads_.size();
}
~DownloadsObserver() {
std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
for (; it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
download_manager_->RemoveObserver(this);
}
// State accessors.
bool select_file_dialog_seen() { return select_file_dialog_seen_; }
// Wait for whatever state was specified in the constructor.
void WaitForFinished() {
if (!IsFinished()) {
waiting_ = true;
ui_test_utils::RunMessageLoop();
waiting_ = false;
}
}
// Return true if everything's happened that we're configured for.
bool IsFinished() {
if (finished_downloads_.size() - finished_downloads_at_construction_
>= wait_count_)
return true;
return (finish_on_select_file_ && select_file_dialog_seen_);
}
// DownloadItem::Observer
virtual void OnDownloadUpdated(DownloadItem* download) {
if (download->state() == download_finished_state_)
DownloadInFinalState(download);
}
virtual void OnDownloadOpened(DownloadItem* download) {}
// DownloadManager::Observer
virtual void ModelChanged() {
// Regenerate DownloadItem observers. If there are any download items
// in our final state, note them in |finished_downloads_|
// (done by |OnDownloadUpdated()|).
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
std::vector<DownloadItem*>::iterator it = downloads.begin();
for (; it != downloads.end(); ++it) {
OnDownloadUpdated(*it); // Safe to call multiple times; checks state.
std::set<DownloadItem*>::const_iterator
finished_it(finished_downloads_.find(*it));
std::set<DownloadItem*>::iterator
observed_it(downloads_observed_.find(*it));
// If it isn't finished and we're aren't observing it, start.
if (finished_it == finished_downloads_.end() &&
observed_it == downloads_observed_.end()) {
(*it)->AddObserver(this);
downloads_observed_.insert(*it);
continue;
}
// If it is finished and we are observing it, stop.
if (finished_it != finished_downloads_.end() &&
observed_it != downloads_observed_.end()) {
(*it)->RemoveObserver(this);
downloads_observed_.erase(observed_it);
continue;
}
}
}
virtual void SelectFileDialogDisplayed(int32 /* id */) {
select_file_dialog_seen_ = true;
SignalIfFinished();
}
private:
// Called when we know that a download item is in a final state.
// Note that this is not the same as it first transitioning in to the
// final state; multiple notifications may occur once the item is in
// that state. So we keep our own track of transitions into final.
void DownloadInFinalState(DownloadItem* download) {
if (finished_downloads_.find(download) != finished_downloads_.end()) {
// We've already seen terminal state on this download.
return;
}
// Record the transition.
finished_downloads_.insert(download);
SignalIfFinished();
}
void SignalIfFinished() {
if (waiting_ && IsFinished())
MessageLoopForUI::current()->Quit();
}
// The observed download manager.
scoped_refptr<DownloadManager> download_manager_;
// The set of DownloadItem's that have transitioned to their finished state
// since construction of this object. When the size of this array
// reaches wait_count_, we're done.
std::set<DownloadItem*> finished_downloads_;
// The set of DownloadItem's we are currently observing. Generally there
// won't be any overlap with the above; once we see the final state
// on a DownloadItem, we'll stop observing it.
std::set<DownloadItem*> downloads_observed_;
// The number of downloads to wait on completing.
size_t wait_count_;
// The number of downloads entered in final state in initial
// ModelChanged(). We use |finished_downloads_| to track the incoming
// transitions to final state we should ignore, and to track the
// number of final state transitions that occurred between
// construction and return from wait. But some downloads may be in our
// final state (and thus be entered into |finished_downloads_|) when we
// construct this class. We don't want to count those in our transition
// to finished.
int finished_downloads_at_construction_;
// Whether an internal message loop has been started and must be quit upon
// all downloads completing.
bool waiting_;
// The state on which to consider the DownloadItem finished.
DownloadItem::DownloadState download_finished_state_;
// True if we should transition the DownloadsObserver to finished if
// the select file dialog comes up.
bool finish_on_select_file_;
// True if we've seen the select file dialog.
bool select_file_dialog_seen_;
DISALLOW_COPY_AND_ASSIGN(DownloadsObserver);
};
// WaitForFlush() returns after:
// * There are no IN_PROGRESS download items remaining on the
// DownloadManager.
// * There have been two round trip messages through the file and
// IO threads.
// This almost certainly means that a Download cancel has propagated through
// the system.
class DownloadsFlushObserver
: public DownloadManager::Observer,
public DownloadItem::Observer,
public base::RefCountedThreadSafe<DownloadsFlushObserver> {
public:
explicit DownloadsFlushObserver(DownloadManager* download_manager)
: download_manager_(download_manager),
waiting_for_zero_inprogress_(true) { }
void WaitForFlush() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
download_manager_->AddObserver(this);
ui_test_utils::RunMessageLoop();
}
// DownloadsManager observer methods.
virtual void ModelChanged() {
// Model has changed, so there may be more DownloadItems to observe.
CheckDownloadsInProgress(true);
}
// DownloadItem observer methods.
virtual void OnDownloadUpdated(DownloadItem* download) {
// No change in DownloadItem set on manager.
CheckDownloadsInProgress(false);
}
virtual void OnDownloadOpened(DownloadItem* download) {}
protected:
friend class base::RefCountedThreadSafe<DownloadsFlushObserver>;
virtual ~DownloadsFlushObserver() {
download_manager_->RemoveObserver(this);
for (std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
}
private:
// If we're waiting for that flush point, check the number
// of downloads in the IN_PROGRESS state and take appropriate
// action. If requested, also observes all downloads while iterating.
void CheckDownloadsInProgress(bool observe_downloads) {
if (waiting_for_zero_inprogress_) {
int count = 0;
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
std::vector<DownloadItem*>::iterator it = downloads.begin();
for (; it != downloads.end(); ++it) {
if ((*it)->state() == DownloadItem::IN_PROGRESS)
count++;
if (observe_downloads) {
if (downloads_observed_.find(*it) == downloads_observed_.end()) {
(*it)->AddObserver(this);
}
// Download items are forever, and we don't want to make
// assumptions about future state transitions, so once we
// start observing them, we don't stop until destruction.
}
}
if (count == 0) {
waiting_for_zero_inprogress_ = false;
// Stop observing DownloadItems. We maintain the observation
// of DownloadManager so that we don't have to independently track
// whether we are observing it for conditional destruction.
for (std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
it != downloads_observed_.end(); ++it) {
(*it)->RemoveObserver(this);
}
downloads_observed_.clear();
// Trigger next step. We need to go past the IO thread twice, as
// there's a self-task posting in the IO thread cancel path.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this,
&DownloadsFlushObserver::PingFileThread, 2));
}
}
}
void PingFileThread(int cycle) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &DownloadsFlushObserver::PingIOThread,
cycle));
}
void PingIOThread(int cycle) {
if (--cycle) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &DownloadsFlushObserver::PingFileThread,
cycle));
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, new MessageLoop::QuitTask());
}
}
DownloadManager* download_manager_;
std::set<DownloadItem*> downloads_observed_;
bool waiting_for_zero_inprogress_;
DISALLOW_COPY_AND_ASSIGN(DownloadsFlushObserver);
};
// Collect the information from FILE and IO threads needed for the Cancel
// Test, specifically the number of outstanding requests on the
// ResourceDispatcherHost and the number of pending downloads on the
// DownloadFileManager.
class CancelTestDataCollector
: public base::RefCountedThreadSafe<CancelTestDataCollector> {
public:
CancelTestDataCollector()
: resource_dispatcher_host_(
g_browser_process->resource_dispatcher_host()),
rdh_pending_requests_(0),
dfm_pending_downloads_(0) { }
void WaitForDataCollected() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &CancelTestDataCollector::IOInfoCollector));
ui_test_utils::RunMessageLoop();
}
int rdh_pending_requests() { return rdh_pending_requests_; }
int dfm_pending_downloads() { return dfm_pending_downloads_; }
protected:
friend class base::RefCountedThreadSafe<CancelTestDataCollector>;
virtual ~CancelTestDataCollector() {}
private:
void IOInfoCollector() {
download_file_manager_ = resource_dispatcher_host_->download_file_manager();
rdh_pending_requests_ = resource_dispatcher_host_->pending_requests();
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &CancelTestDataCollector::FileInfoCollector));
}
void FileInfoCollector() {
dfm_pending_downloads_ = download_file_manager_->NumberOfActiveDownloads();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, new MessageLoop::QuitTask());
}
ResourceDispatcherHost* resource_dispatcher_host_;
DownloadFileManager* download_file_manager_;
int rdh_pending_requests_;
int dfm_pending_downloads_;
DISALLOW_COPY_AND_ASSIGN(CancelTestDataCollector);
};
class DownloadTest : public InProcessBrowserTest {
public:
enum SelectExpectation {
EXPECT_NO_SELECT_DIALOG = -1,
EXPECT_NOTHING,
EXPECT_SELECT_DIALOG
};
DownloadTest() {
EnableDOMAutomation();
}
// Returning false indicates a failure of the setup, and should be asserted
// in the caller.
virtual bool InitialSetup(bool prompt_for_download) {
bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
EXPECT_TRUE(have_test_dir);
if (!have_test_dir)
return false;
// Sanity check default values for window / tab count and shelf visibility.
int window_count = BrowserList::size();
EXPECT_EQ(1, window_count);
EXPECT_EQ(1, browser()->tab_count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Set up the temporary download folder.
bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
EXPECT_TRUE(created_downloads_dir);
if (!created_downloads_dir)
return false;
browser()->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
prompt_for_download);
DownloadManager* manager = browser()->profile()->GetDownloadManager();
manager->download_prefs()->ResetAutoOpen();
manager->RemoveAllDownloads();
return true;
}
protected:
enum SizeTestType {
SIZE_TEST_TYPE_KNOWN,
SIZE_TEST_TYPE_UNKNOWN,
};
// Location of the file source (the place from which it is downloaded).
FilePath OriginFile(FilePath file) {
return test_dir_.Append(file);
}
// Location of the file destination (place to which it is downloaded).
FilePath DestinationFile(Browser* browser, FilePath file) {
return GetDownloadDirectory(browser).Append(file);
}
// Must be called after browser creation. Creates a temporary
// directory for downloads that is auto-deleted on destruction.
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CreateAndSetDownloadsDirectory(Browser* browser) {
if (!browser)
return false;
if (!downloads_directory_.CreateUniqueTempDir())
return false;
browser->profile()->GetPrefs()->SetFilePath(
prefs::kDownloadDefaultDirectory,
downloads_directory_.path());
return true;
}
DownloadPrefs* GetDownloadPrefs(Browser* browser) {
return browser->profile()->GetDownloadManager()->download_prefs();
}
FilePath GetDownloadDirectory(Browser* browser) {
DownloadManager* download_mananger =
browser->profile()->GetDownloadManager();
return download_mananger->download_prefs()->download_path();
}
// Create a DownloadsObserver that will wait for the
// specified number of downloads to finish.
DownloadsObserver* CreateWaiter(Browser* browser, int num_downloads) {
DownloadManager* download_manager =
browser->profile()->GetDownloadManager();
return new DownloadsObserver(
download_manager, num_downloads,
DownloadItem::COMPLETE, // Really done
true); // Bail on select file
}
// Create a DownloadsObserver that will wait for the
// specified number of downloads to start.
DownloadsObserver* CreateInProgressWaiter(Browser* browser,
int num_downloads) {
DownloadManager* download_manager =
browser->profile()->GetDownloadManager();
return new DownloadsObserver(
download_manager, num_downloads,
DownloadItem::IN_PROGRESS, // Has started
true); // Bail on select file
}
// Download |url|, then wait for the download to finish.
// |disposition| indicates where the navigation occurs (current tab, new
// foreground tab, etc).
// |expectation| indicates whether or not a Select File dialog should be
// open when the download is finished, or if we don't care.
// If the dialog appears, the routine exits. The only effect |expectation|
// has is whether or not the test succeeds.
// |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
// values in the ui_test_utils::BrowserTestWaitFlags enum.
void DownloadAndWaitWithDisposition(Browser* browser,
const GURL& url,
WindowOpenDisposition disposition,
SelectExpectation expectation,
int browser_test_flags) {
// Setup notification, navigate, and block.
scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
// This call will block until the condition specified by
// |browser_test_flags|, but will not wait for the download to finish.
ui_test_utils::NavigateToURLWithDisposition(browser,
url,
disposition,
browser_test_flags);
// Waits for the download to complete.
observer->WaitForFinished();
// If specified, check the state of the select file dialog.
if (expectation != EXPECT_NOTHING) {
EXPECT_EQ(expectation == EXPECT_SELECT_DIALOG,
observer->select_file_dialog_seen());
}
}
// Download a file in the current tab, then wait for the download to finish.
void DownloadAndWait(Browser* browser,
const GURL& url,
SelectExpectation expectation) {
DownloadAndWaitWithDisposition(
browser,
url,
CURRENT_TAB,
expectation,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
}
// Should only be called when the download is known to have finished
// (in error or not).
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CheckDownload(Browser* browser,
const FilePath& downloaded_filename,
const FilePath& origin_filename) {
// Find the path to which the data will be downloaded.
FilePath downloaded_file(DestinationFile(browser, downloaded_filename));
// Find the origin path (from which the data comes).
FilePath origin_file(OriginFile(origin_filename));
bool origin_file_exists = file_util::PathExists(origin_file);
EXPECT_TRUE(origin_file_exists);
if (!origin_file_exists)
return false;
// Confirm the downloaded data file exists.
bool downloaded_file_exists = file_util::PathExists(downloaded_file);
EXPECT_TRUE(downloaded_file_exists);
if (!downloaded_file_exists)
return false;
int64 origin_file_size = 0;
int64 downloaded_file_size = 0;
EXPECT_TRUE(file_util::GetFileSize(origin_file, &origin_file_size));
EXPECT_TRUE(file_util::GetFileSize(downloaded_file, &downloaded_file_size));
EXPECT_EQ(origin_file_size, downloaded_file_size);
EXPECT_TRUE(file_util::ContentsEqual(downloaded_file, origin_file));
// Delete the downloaded copy of the file.
bool downloaded_file_deleted =
file_util::DieFileDie(downloaded_file, false);
EXPECT_TRUE(downloaded_file_deleted);
return downloaded_file_deleted;
}
bool RunSizeTest(Browser* browser,
SizeTestType type,
const std::string& partial_indication,
const std::string& total_indication) {
if (!InitialSetup(false))
return false;
EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
return false;
GURL url(type == SIZE_TEST_TYPE_KNOWN ?
URLRequestSlowDownloadJob::kKnownSizeUrl :
URLRequestSlowDownloadJob::kUnknownSizeUrl);
// TODO(ahendrickson) -- |expected_title_in_progress| and
// |expected_title_finished| need to be checked.
FilePath filename;
net::FileURLToFilePath(url, &filename);
string16 expected_title_in_progress(
ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
string16 expected_title_finished(
ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
// Download a partial web page in a background tab and wait.
// The mock system will not complete until it gets a special URL.
scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
ui_test_utils::NavigateToURL(browser, url);
// TODO(ahendrickson): check download status text before downloading.
// Need to:
// - Add a member function to the |DownloadShelf| interface class, that
// indicates how many members it has.
// - Add a member function to |DownloadShelf| to get the status text
// of a given member (for example, via the name in |DownloadItemView|'s
// GetAccessibleState() member function), by index.
// - Iterate over browser->window()->GetDownloadShelf()'s members
// to see if any match the status text we want. Start with the last one.
// Allow the request to finish. We do this by loading a second URL in a
// separate tab.
GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
ui_test_utils::NavigateToURLWithDisposition(
browser,
finish_url,
NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
observer->WaitForFinished();
EXPECT_EQ(2, browser->tab_count());
// TODO(ahendrickson): check download status text after downloading.
// Make sure the download shelf is showing.
CheckDownloadUIVisible(browser, true, true);
FilePath basefilename(filename.BaseName());
net::FileURLToFilePath(url, &filename);
FilePath download_path = downloads_directory_.path().Append(basefilename);
bool downloaded_path_exists = file_util::PathExists(download_path);
EXPECT_TRUE(downloaded_path_exists);
if (!downloaded_path_exists)
return false;
// Delete the file we just downloaded.
EXPECT_TRUE(file_util::DieFileDie(download_path, true));
EXPECT_FALSE(file_util::PathExists(download_path));
return true;
}
void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
DCHECK(downloads);
DownloadManager* manager = browser->profile()->GetDownloadManager();
manager->SearchDownloads(string16(), downloads);
}
// Figure out if the appropriate download visibility was done. A
// utility function to support ChromeOS variations.
static void CheckDownloadUIVisible(Browser* browser,
bool expected_non_chromeos,
bool expected_chromeos) {
#if defined(OS_CHROMEOS)
EXPECT_EQ(expected_chromeos,
NULL != ActiveDownloadsUI::GetPopup(browser->profile()));
#else
EXPECT_EQ(expected_non_chromeos,
browser->window()->IsDownloadShelfVisible());
#endif
}
static void ExpectWindowCountAfterDownload(size_t expected) {
#if defined(OS_CHROMEOS)
// On ChromeOS, a download panel is created to display
// download information, and this counts as a window.
expected++;
#endif
EXPECT_EQ(expected, BrowserList::size());
}
private:
// Location of the test data.
FilePath test_dir_;
// Location of the downloads directory for these tests
ScopedTempDir downloads_directory_;
};
// Get History Information.
class DownloadsHistoryDataCollector {
public:
explicit DownloadsHistoryDataCollector(int64 download_db_handle,
DownloadManager* manager)
: result_valid_(false),
download_db_handle_(download_db_handle) {
HistoryService* hs =
manager->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
DCHECK(hs);
hs->QueryDownloads(
&callback_consumer_,
NewCallback(this,
&DownloadsHistoryDataCollector::OnQueryDownloadsComplete));
// Cannot complete immediately because the history backend runs on a
// separate thread, so we can assume that the RunMessageLoop below will
// be exited by the Quit in OnQueryDownloadsComplete.
ui_test_utils::RunMessageLoop();
}
bool GetDownloadsHistoryEntry(DownloadHistoryInfo* result) {
DCHECK(result);
*result = result_;
return result_valid_;
}
private:
void OnQueryDownloadsComplete(
std::vector<DownloadHistoryInfo>* entries) {
result_valid_ = false;
for (std::vector<DownloadHistoryInfo>::const_iterator it = entries->begin();
it != entries->end(); ++it) {
if (it->db_handle == download_db_handle_) {
result_ = *it;
result_valid_ = true;
}
}
MessageLoopForUI::current()->Quit();
}
DownloadHistoryInfo result_;
bool result_valid_;
int64 download_db_handle_;
CancelableRequestConsumer callback_consumer_;
DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
};
} // namespace
// While an object of this class exists, it will mock out download
// opening for all downloads created on the specified download manager.
class MockDownloadOpeningObserver : public DownloadManager::Observer {
public:
explicit MockDownloadOpeningObserver(DownloadManager* manager)
: download_manager_(manager) {
download_manager_->AddObserver(this);
}
~MockDownloadOpeningObserver() {
download_manager_->RemoveObserver(this);
}
// DownloadManager::Observer
virtual void ModelChanged() {
std::vector<DownloadItem*> downloads;
download_manager_->SearchDownloads(string16(), &downloads);
for (std::vector<DownloadItem*>::iterator it = downloads.begin();
it != downloads.end(); ++it) {
(*it)->TestMockDownloadOpen();
}
}
private:
DownloadManager* download_manager_;
DISALLOW_COPY_AND_ASSIGN(MockDownloadOpeningObserver);
};
// NOTES:
//
// Files for these tests are found in DIR_TEST_DATA (currently
// "chrome\test\data\", see chrome_paths.cc).
// Mock responses have extension .mock-http-headers appended to the file name.
// Download a file due to the associated MIME type.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
}
#if defined(OS_WIN)
// Download a file and confirm that the zone identifier (on windows)
// is set to internet.
IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Check state. Special file state must be checked before CheckDownload,
// as CheckDownload will delete the output file.
EXPECT_EQ(1, browser()->tab_count());
FilePath downloaded_file(DestinationFile(browser(), file));
if (file_util::VolumeSupportsADS(downloaded_file))
EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file));
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
}
#endif
// Put up a Select File dialog when the file is downloaded, due to its MIME
// type.
//
// This test runs correctly, but leaves behind turds in the test user's
// download directory because of http://crbug.com/62099. No big loss; it
// was primarily confirming DownloadsObserver wait on select file dialog
// functionality anyway.
IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DownloadMimeTypeSelect) {
ASSERT_TRUE(InitialSetup(true));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We expect the Select File dialog to appear
// due to the MIME type.
DownloadAndWait(browser(), url, EXPECT_SELECT_DIALOG);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
// Since we exited while the Select File dialog was visible, there should not
// be anything in the download shelf and so it should not be visible.
CheckDownloadUIVisible(browser(), false, false);
}
// Access a file with a viewable mime-type, verify that a download
// did not initiate.
IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath file_path(DestinationFile(browser(), file));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Check that we did not download the web page.
EXPECT_FALSE(file_util::PathExists(file_path));
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), false, false);
}
// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header. This also ensures we properly handle empty file downloads.
// The download shelf should be visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
}
#if !defined(OS_CHROMEOS) // Download shelf is not per-window on ChromeOS.
// Test that the download shelf is per-window by starting a download in one
// tab, opening a second tab, closing the shelf, going back to the first tab,
// and checking that the shelf is closed.
IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
// Open a second tab and wait.
EXPECT_NE(static_cast<TabContentsWrapper*>(NULL),
browser()->AddSelectedTabWithURL(GURL(), PageTransition::TYPED));
EXPECT_EQ(2, browser()->tab_count());
CheckDownloadUIVisible(browser(), true, true);
// Hide the download shelf.
browser()->window()->GetDownloadShelf()->Close();
CheckDownloadUIVisible(browser(), false, false);
// Go to the first tab.
browser()->ActivateTabAt(0, true);
EXPECT_EQ(2, browser()->tab_count());
// The download shelf should not be visible.
CheckDownloadUIVisible(browser(), false, false);
}
#endif // !OS_CHROMEOS
// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish". At that time, the download will finish.
// These tests don't currently test much due to holes in |RunSizeTest()|. See
// comments in that routine for details.
IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
"32.0 KB - ", "100% - "));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
"71% - ", "100% - "));
}
// Test that when downloading an item in Incognito mode, we don't crash when
// closing the last Incognito window (http://crbug.com/13983).
// Also check that the download shelf is not visible after closing the
// Incognito window.
IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
ASSERT_TRUE(InitialSetup(false));
// Open an Incognito window.
Browser* incognito = CreateIncognitoBrowser(); // Waits.
ASSERT_TRUE(incognito);
int window_count = BrowserList::size();
EXPECT_EQ(2, window_count);
// Download a file in the Incognito window and wait.
CreateAndSetDownloadsDirectory(incognito);
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Since |incognito| is a separate browser, we have to set it up explicitly.
incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
false);
DownloadAndWait(incognito, url, EXPECT_NO_SELECT_DIALOG);
// We should still have 2 windows.
ExpectWindowCountAfterDownload(2);
// Verify that the download shelf is showing for the Incognito window.
CheckDownloadUIVisible(incognito, true, true);
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(incognito));
#endif
// Close the Incognito window and don't crash.
incognito->CloseWindow();
#if !defined(OS_MACOSX)
signal.Wait();
ExpectWindowCountAfterDownload(1);
#endif
// Verify that the regular window does not have a download shelf.
CheckDownloadUIVisible(browser(), false, false);
CheckDownload(browser(), file, file);
}
// Navigate to a new background page, but don't download. Confirm that the
// download shelf is not visible and that we have two tabs.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// We should have two tabs now.
EXPECT_EQ(2, browser()->tab_count());
CheckDownloadUIVisible(browser(), false, false);
}
// Download a file in a background tab. Verify that the tab is closed
// automatically, and that the download shelf is visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
ASSERT_TRUE(InitialSetup(false));
// Download a file in a new background tab and wait. The tab is automatically
// closed when the download begins.
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file in another tab via
// a Javascript call.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page1.html page contains an openNew() function that opens a
// tab and then downloads download-test1.lib.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait (via Javascript).
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should have two tabs.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(2, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, open another tab via a Javascript call,
// then download a file in the new tab.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page2.html page contains an openNew() function that opens a
// tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url1);
// Open a new tab and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
EXPECT_EQ(2, browser()->tab_count());
// Download a file and wait.
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(browser(),
url,
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, we should have two tabs.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(2, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file via Javascript,
// which will do so in a temporary tab.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page3.html page contains an openNew() function that opens a
// tab with download-test1.lib in the URL. When the URL is determined to be
// a download, the tab is closed automatically.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file and wait.
// The file to download is "download-test1.lib".
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then call Javascript via a button to
// download a file in a new tab, which is closed automatically when the
// download begins.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page4.html page contains a form with download-test1.lib as the
// action.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
ASSERT_TRUE(InitialSetup(false));
// Because it's an HTML link, it should open a web page rather than
// downloading.
FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait. The tab will automatically close
// when the download begins.
// The file to download is "download-test1.lib".
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(
browser(),
GURL("javascript:document.getElementById('form').submit()"),
CURRENT_TAB,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
CheckDownloadUIVisible(browser(), true, true);
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
}
// Download a file in a new window.
// Verify that we have 2 windows, and the download shelf is not visible in the
// first window, but is visible in the second window.
// Close the new window.
// Verify that we have 1 window, and the download shelf is not visible.
//
// Regression test for http://crbug.com/44454
IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
#if !defined(OS_MACOSX)
// See below.
Browser* first_browser = browser();
#endif
// Download a file in a new window and wait.
DownloadAndWaitWithDisposition(browser(),
url,
NEW_WINDOW,
EXPECT_NO_SELECT_DIALOG,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, the download shelf SHOULD NOT be visible in
// the first window.
ExpectWindowCountAfterDownload(2);
EXPECT_EQ(1, browser()->tab_count());
// Except on Chrome OS, where the download window sticks around.
CheckDownloadUIVisible(browser(), false, true);
// The download shelf SHOULD be visible in the second window.
std::set<Browser*> original_browsers;
original_browsers.insert(browser());
Browser* download_browser =
ui_test_utils::GetBrowserNotInSet(original_browsers);
ASSERT_TRUE(download_browser != NULL);
EXPECT_NE(download_browser, browser());
EXPECT_EQ(1, download_browser->tab_count());
CheckDownloadUIVisible(download_browser, true, true);
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(download_browser));
#endif
// Close the new window.
download_browser->CloseWindow();
#if !defined(OS_MACOSX)
signal.Wait();
EXPECT_EQ(first_browser, browser());
ExpectWindowCountAfterDownload(1);
#endif
EXPECT_EQ(1, browser()->tab_count());
// On ChromeOS, the popup sticks around.
CheckDownloadUIVisible(browser(), false, true);
CheckDownload(browser(), file, file);
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadCancelled) {
ASSERT_TRUE(InitialSetup(false));
EXPECT_EQ(1, browser()->tab_count());
// TODO(rdsmith): Fragile code warning! The code below relies on the
// DownloadsObserver only finishing when the new download has reached
// the state of being entered into the history and being user-visible
// (that's what's required for the Remove to be valid and for the
// download shelf to be visible). By the pure semantics of
// DownloadsObserver, that's not guaranteed; DownloadItems are created
// in the IN_PROGRESS state and made known to the DownloadManager
// immediately, so any ModelChanged event on the DownloadManager after
// navigation would allow the observer to return. However, the only
// ModelChanged() event the code will currently fire is in
// OnCreateDownloadEntryComplete, at which point the download item will
// be in the state we need.
// The right way to fix this is to create finer grained states on the
// DownloadItem, and wait for the state that indicates the item has been
// entered in the history and made visible in the UI.
// Create a download, wait until it's started, and confirm
// we're in the expected state.
scoped_ptr<DownloadsObserver> observer(CreateInProgressWaiter(browser(), 1));
ui_test_utils::NavigateToURL(
browser(), GURL(URLRequestSlowDownloadJob::kUnknownSizeUrl));
observer->WaitForFinished();
std::vector<DownloadItem*> downloads;
browser()->profile()->GetDownloadManager()->SearchDownloads(
string16(), &downloads);
ASSERT_EQ(1u, downloads.size());
ASSERT_EQ(DownloadItem::IN_PROGRESS, downloads[0]->state());
CheckDownloadUIVisible(browser(), true, true);
// Cancel the download and wait for download system quiesce.
downloads[0]->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);
scoped_refptr<DownloadsFlushObserver> flush_observer(
new DownloadsFlushObserver(browser()->profile()->GetDownloadManager()));
flush_observer->WaitForFlush();
// Get the important info from other threads and check it.
scoped_refptr<CancelTestDataCollector> info(new CancelTestDataCollector());
info->WaitForDataCollected();
EXPECT_EQ(0, info->rdh_pending_requests());
EXPECT_EQ(0, info->dfm_pending_downloads());
// Using "DownloadItem::Remove" follows the discard dangerous download path,
// which completely removes the browser from the shelf and closes the shelf
// if it was there. Chrome OS is an exception to this, where if we
// bring up the downloads panel, it stays there.
CheckDownloadUIVisible(browser(), false, true);
}
// Confirm a download makes it into the history properly.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
FilePath origin_file(OriginFile(file));
int64 origin_size;
file_util::GetFileSize(origin_file, &origin_size);
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Get details of what downloads have just happened.
std::vector<DownloadItem*> downloads;
GetDownloads(browser(), &downloads);
ASSERT_EQ(1u, downloads.size());
int64 db_handle = downloads[0]->db_handle();
// Check state.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
CheckDownloadUIVisible(browser(), true, true);
// Check history results.
DownloadsHistoryDataCollector history_collector(
db_handle,
browser()->profile()->GetDownloadManager());
DownloadHistoryInfo info;
EXPECT_TRUE(history_collector.GetDownloadsHistoryEntry(&info)) << db_handle;
EXPECT_EQ(file, info.path.BaseName());
EXPECT_EQ(url, info.url);
// Ignore start_time.
EXPECT_EQ(origin_size, info.received_bytes);
EXPECT_EQ(origin_size, info.total_bytes);
EXPECT_EQ(DownloadItem::COMPLETE, info.state);
}
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
GURL flags_url(chrome::kAboutFlagsURL);
GURL extensions_url(chrome::kChromeUIExtensionsURL);
ui_test_utils::NavigateToURL(browser(), flags_url);
DownloadAndWait(browser(), download_url, EXPECT_NO_SELECT_DIALOG);
ui_test_utils::NavigateToURL(browser(), extensions_url);
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool webui_responded = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.domAutomationController.send(window.webui_responded_);",
&webui_responded));
EXPECT_TRUE(webui_responded);
}
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// After several correct executions, this test starts failing on the build
// bots and then continues to fail consistently.
// As of 2011/05/22, it's crashing, so it is getting disabled.
// http://crbug.com/82278
IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_BrowserCloseAfterDownload) {
GURL downloads_url(chrome::kAboutFlagsURL);
FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
ui_test_utils::NavigateToURL(browser(), downloads_url);
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(),
L"",
L"window.onunload = function() { var do_nothing = 0; }; "
L"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
DownloadAndWait(browser(), download_url, EXPECT_NO_SELECT_DIALOG);
ui_test_utils::WindowedNotificationObserver signal(
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser()));
browser()->CloseWindow();
signal.Wait();
}
// Test to make sure auto-open works.
IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
ASSERT_TRUE(InitialSetup(false));
FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
ASSERT_TRUE(
GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
// Mokc out external opening on all downloads until end of test.
MockDownloadOpeningObserver observer(
browser()->profile()->GetDownloadManager());
DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
// Find the download and confirm it was opened.
std::vector<DownloadItem*> downloads;
browser()->profile()->GetDownloadManager()->SearchDownloads(
string16(), &downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->state());
EXPECT_TRUE(downloads[0]->opened());
// As long as we're here, confirmed everything else is good.
EXPECT_EQ(1, browser()->tab_count());
CheckDownload(browser(), file, file);
// Dissapears on most UIs, but the download panel sticks around for
// chrome os.
CheckDownloadUIVisible(browser(), false, true);
}
|
#pragma once
#include <eosio/chain/action.hpp>
#include <numeric>
namespace eosio { namespace chain {
struct deferred_transaction_generation_context : fc::reflect_init {
static constexpr uint16_t extension_id() { return 0; }
static constexpr bool enforce_unique() { return true; }
deferred_transaction_generation_context() = default;
deferred_transaction_generation_context( const transaction_id_type& sender_trx_id, uint128_t sender_id, account_name sender )
:sender_trx_id( sender_trx_id )
,sender_id( sender_id )
,sender( sender )
{}
void reflector_init();
transaction_id_type sender_trx_id;
uint128_t sender_id;
account_name sender;
};
namespace detail {
template<typename... Ts>
struct transaction_extension_types {
using transaction_extension_t = fc::static_variant< Ts... >;
using decompose_t = decompose< Ts... >;
};
}
using transaction_extension_types = detail::transaction_extension_types<
deferred_transaction_generation_context
>;
using transaction_extension = transaction_extension_types::transaction_extension_t;
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
transaction_header() = default;
explicit transaction_header( const transaction_header& ) = default;
transaction_header( transaction_header&& ) = default;
transaction_header& operator=(const transaction_header&) = delete;
transaction_header& operator=(transaction_header&&) = default;
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t ref_block_num = 0U; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0UL; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
fc::unsigned_int max_net_usage_words = 0UL; /// upper limit on total network bandwidth (in 8 byte words) billed for this transaction
uint8_t max_cpu_usage_ms = 0; /// upper limit on the total CPU time billed for this transaction
fc::unsigned_int delay_sec = 0UL; /// number of seconds to delay this transaction for during which it may be canceled.
/**
* @return the absolute block number given the relative ref_block_num
*/
block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
}
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
void validate()const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
transaction() = default;
explicit transaction( const transaction& ) = default;
transaction( transaction&& ) = default;
transaction& operator=(const transaction&) = delete;
transaction& operator=(transaction&&) = default;
vector<action> context_free_actions;
vector<action> actions;
extensions_type transaction_extensions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
fc::microseconds get_signature_keys( const vector<signature_type>& signatures,
const chain_id_type& chain_id,
fc::time_point deadline,
const vector<bytes>& cfd,
flat_set<public_key_type>& recovered_pub_keys,
bool allow_duplicate_keys = false) const;
uint32_t total_actions()const { return context_free_actions.size() + actions.size(); }
account_name first_authorizer()const {
for( const auto& a : actions ) {
for( const auto& u : a.authorization )
return u.actor;
}
return account_name();
}
flat_multimap<uint16_t, transaction_extension> validate_and_extract_extensions()const;
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
explicit signed_transaction( const signed_transaction& ) = default;
signed_transaction( signed_transaction&& ) = default;
signed_transaction& operator=(const signed_transaction&) = delete;
signed_transaction& operator=(signed_transaction&&) = default;
signed_transaction( transaction trx, vector<signature_type> signatures, vector<bytes> context_free_data)
: transaction(std::move(trx))
, signatures(std::move(signatures))
, context_free_data(std::move(context_free_data))
{}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
fc::microseconds get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline,
flat_set<public_key_type>& recovered_pub_keys,
bool allow_duplicate_keys = false )const;
};
struct packed_transaction_v0 : fc::reflect_init {
enum class compression_type {
none = 0,
zlib = 1,
};
packed_transaction_v0() = default;
packed_transaction_v0(packed_transaction_v0&&) = default;
explicit packed_transaction_v0(const packed_transaction_v0&) = default;
packed_transaction_v0& operator=(const packed_transaction_v0&) = delete;
packed_transaction_v0& operator=(packed_transaction_v0&&) = default;
explicit packed_transaction_v0(const signed_transaction& t, compression_type _compression = compression_type::none)
:signatures(t.signatures), compression(_compression), unpacked_trx(t), trx_id(unpacked_trx.id())
{
local_pack_transaction();
local_pack_context_free_data();
}
explicit packed_transaction_v0(signed_transaction&& t, compression_type _compression = compression_type::none)
:signatures(t.signatures), compression(_compression), unpacked_trx(std::move(t)), trx_id(unpacked_trx.id())
{
local_pack_transaction();
local_pack_context_free_data();
}
packed_transaction_v0(const bytes& packed_txn, const vector<signature_type>& sigs, const bytes& packed_cfd, compression_type _compression);
// used by abi_serializer
packed_transaction_v0( bytes&& packed_txn, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression );
packed_transaction_v0( bytes&& packed_txn, vector<signature_type>&& sigs, vector<bytes>&& cfd, compression_type _compression );
packed_transaction_v0( transaction&& t, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression );
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
digest_type packed_digest()const;
const transaction_id_type& id()const { return trx_id; }
time_point_sec expiration()const { return unpacked_trx.expiration; }
const vector<bytes>& get_context_free_data()const { return unpacked_trx.context_free_data; }
const transaction& get_transaction()const { return unpacked_trx; }
const signed_transaction& get_signed_transaction()const { return unpacked_trx; }
const vector<signature_type>& get_signatures()const { return signatures; }
const fc::enum_type<uint8_t,compression_type>& get_compression()const { return compression; }
const bytes& get_packed_context_free_data()const { return packed_context_free_data; }
const bytes& get_packed_transaction()const { return packed_trx; }
private:
void local_unpack_transaction(vector<bytes>&& context_free_data);
void local_unpack_context_free_data();
void local_pack_transaction();
void local_pack_context_free_data();
friend struct fc::reflector<packed_transaction_v0>;
friend struct fc::reflector_init_visitor<packed_transaction_v0>;
friend struct fc::has_reflector_init<packed_transaction_v0>;
friend struct packed_transaction;
void reflector_init();
private:
friend struct pruned_transaction;
friend struct prunable_transaction_data;
vector<signature_type> signatures;
fc::enum_type<uint8_t, compression_type> compression;
bytes packed_context_free_data;
bytes packed_trx;
private:
// cache unpacked trx, for thread safety do not modify after construction
signed_transaction unpacked_trx;
transaction_id_type trx_id;
};
using packed_transaction_v0_ptr = std::shared_ptr<const packed_transaction_v0>;
struct prunable_transaction_data {
enum class compression_type : uint8_t {
none = 0,
zlib = 1,
COMPRESSION_TYPE_COUNT
};
// Do not exceed 127 as that will break compatibility in serialization format
static_assert( static_cast<uint8_t>(compression_type::COMPRESSION_TYPE_COUNT) <= 127 );
struct none {
digest_type prunable_digest;
};
struct signatures_only {
std::vector<signature_type> signatures;
digest_type context_free_mroot;
};
using segment_type = fc::static_variant<digest_type, bytes>;
struct partial {
std::vector<signature_type> signatures;
std::vector<segment_type> context_free_segments;
};
struct full {
std::vector<signature_type> signatures;
std::vector<bytes> context_free_segments;
};
struct full_legacy {
std::vector<signature_type> signatures;
bytes packed_context_free_data;
vector<bytes> context_free_segments;
};
using prunable_data_type = fc::static_variant< full_legacy,
none,
signatures_only,
partial,
full >;
prunable_transaction_data prune_all() const;
digest_type digest() const;
// Returns the maximum pack size of any prunable_transaction_data that is reachable
// by pruning this object.
std::size_t maximum_pruned_pack_size( compression_type segment_compression ) const;
prunable_data_type prunable_data;
};
struct packed_transaction : fc::reflect_init {
using compression_type = packed_transaction_v0::compression_type;
using cf_compression_type = prunable_transaction_data::compression_type;
packed_transaction() = default;
packed_transaction(packed_transaction&&) = default;
explicit packed_transaction(const packed_transaction&) = default;
packed_transaction& operator=(const packed_transaction&) = delete;
packed_transaction& operator=(packed_transaction&&) = default;
packed_transaction(const packed_transaction_v0& other, bool legacy);
packed_transaction(packed_transaction_v0&& other, bool legacy);
explicit packed_transaction(signed_transaction t, bool legacy, compression_type _compression = compression_type::none);
packed_transaction_v0_ptr to_packed_transaction_v0() const;
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
uint32_t get_estimated_size()const { return estimated_size; }
digest_type packed_digest()const;
const transaction_id_type& id()const { return trx_id; }
time_point_sec expiration()const { return unpacked_trx.expiration; }
const transaction& get_transaction()const { return unpacked_trx; }
// Returns nullptr if the signatures were pruned
const vector<signature_type>* get_signatures()const;
// Returns nullptr if any context_free_data segment was pruned
const vector<bytes>* get_context_free_data()const;
// Returns nullptr if the context_free_data segment was pruned or segment_ordinal is out of range.
const bytes* get_context_free_data(std::size_t segment_ordinal)const;
const fc::enum_type<uint8_t,compression_type>& get_compression()const { return compression; }
const bytes& get_packed_transaction()const { return packed_trx; }
const prunable_transaction_data& get_prunable_data() const { return prunable_data; }
void prune_all();
std::size_t maximum_pruned_pack_size( cf_compression_type segment_compression ) const;
private:
friend struct fc::reflector<packed_transaction>;
friend struct fc::reflector_init_visitor<packed_transaction>;
friend struct fc::has_reflector_init<packed_transaction>;
void reflector_init();
uint32_t calculate_estimated_size() const;
private:
uint32_t estimated_size = 0;
fc::enum_type<uint8_t,compression_type> compression;
prunable_transaction_data prunable_data;
bytes packed_trx; // packed and compressed (according to compression) transaction
private:
// cache unpacked trx, for thread safety do not modify any attributes after construction
transaction unpacked_trx;
transaction_id_type trx_id;
};
using packed_transaction_ptr = std::shared_ptr<const packed_transaction>;
uint128_t transaction_id_to_sender_id( const transaction_id_type& tid );
} } /// namespace eosio::chain
FC_REFLECT(eosio::chain::deferred_transaction_generation_context, (sender_trx_id)(sender_id)(sender) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(ref_block_num)(ref_block_prefix)
(max_net_usage_words)(max_cpu_usage_ms)(delay_sec) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions)(transaction_extensions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction_v0::compression_type, (none)(zlib))
// @ignore unpacked_trx
FC_REFLECT( eosio::chain::packed_transaction_v0, (signatures)(compression)(packed_context_free_data)(packed_trx) )
FC_REFLECT( eosio::chain::packed_transaction, (compression)(prunable_data)(packed_trx) )
FC_REFLECT( eosio::chain::prunable_transaction_data, (prunable_data));
FC_REFLECT( eosio::chain::prunable_transaction_data::none, (prunable_digest))
FC_REFLECT( eosio::chain::prunable_transaction_data::signatures_only, (signatures)(context_free_mroot))
FC_REFLECT( eosio::chain::prunable_transaction_data::partial, (signatures)(context_free_segments))
FC_REFLECT( eosio::chain::prunable_transaction_data::full, (signatures)(context_free_segments))
FC_REFLECT( eosio::chain::prunable_transaction_data::full_legacy, (signatures)(packed_context_free_data))
Remove unused method
#pragma once
#include <eosio/chain/action.hpp>
#include <numeric>
namespace eosio { namespace chain {
struct deferred_transaction_generation_context : fc::reflect_init {
static constexpr uint16_t extension_id() { return 0; }
static constexpr bool enforce_unique() { return true; }
deferred_transaction_generation_context() = default;
deferred_transaction_generation_context( const transaction_id_type& sender_trx_id, uint128_t sender_id, account_name sender )
:sender_trx_id( sender_trx_id )
,sender_id( sender_id )
,sender( sender )
{}
void reflector_init();
transaction_id_type sender_trx_id;
uint128_t sender_id;
account_name sender;
};
namespace detail {
template<typename... Ts>
struct transaction_extension_types {
using transaction_extension_t = fc::static_variant< Ts... >;
using decompose_t = decompose< Ts... >;
};
}
using transaction_extension_types = detail::transaction_extension_types<
deferred_transaction_generation_context
>;
using transaction_extension = transaction_extension_types::transaction_extension_t;
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
transaction_header() = default;
explicit transaction_header( const transaction_header& ) = default;
transaction_header( transaction_header&& ) = default;
transaction_header& operator=(const transaction_header&) = delete;
transaction_header& operator=(transaction_header&&) = default;
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t ref_block_num = 0U; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0UL; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
fc::unsigned_int max_net_usage_words = 0UL; /// upper limit on total network bandwidth (in 8 byte words) billed for this transaction
uint8_t max_cpu_usage_ms = 0; /// upper limit on the total CPU time billed for this transaction
fc::unsigned_int delay_sec = 0UL; /// number of seconds to delay this transaction for during which it may be canceled.
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
void validate()const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
transaction() = default;
explicit transaction( const transaction& ) = default;
transaction( transaction&& ) = default;
transaction& operator=(const transaction&) = delete;
transaction& operator=(transaction&&) = default;
vector<action> context_free_actions;
vector<action> actions;
extensions_type transaction_extensions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
fc::microseconds get_signature_keys( const vector<signature_type>& signatures,
const chain_id_type& chain_id,
fc::time_point deadline,
const vector<bytes>& cfd,
flat_set<public_key_type>& recovered_pub_keys,
bool allow_duplicate_keys = false) const;
uint32_t total_actions()const { return context_free_actions.size() + actions.size(); }
account_name first_authorizer()const {
for( const auto& a : actions ) {
for( const auto& u : a.authorization )
return u.actor;
}
return account_name();
}
flat_multimap<uint16_t, transaction_extension> validate_and_extract_extensions()const;
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
explicit signed_transaction( const signed_transaction& ) = default;
signed_transaction( signed_transaction&& ) = default;
signed_transaction& operator=(const signed_transaction&) = delete;
signed_transaction& operator=(signed_transaction&&) = default;
signed_transaction( transaction trx, vector<signature_type> signatures, vector<bytes> context_free_data)
: transaction(std::move(trx))
, signatures(std::move(signatures))
, context_free_data(std::move(context_free_data))
{}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
fc::microseconds get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline,
flat_set<public_key_type>& recovered_pub_keys,
bool allow_duplicate_keys = false )const;
};
struct packed_transaction_v0 : fc::reflect_init {
enum class compression_type {
none = 0,
zlib = 1,
};
packed_transaction_v0() = default;
packed_transaction_v0(packed_transaction_v0&&) = default;
explicit packed_transaction_v0(const packed_transaction_v0&) = default;
packed_transaction_v0& operator=(const packed_transaction_v0&) = delete;
packed_transaction_v0& operator=(packed_transaction_v0&&) = default;
explicit packed_transaction_v0(const signed_transaction& t, compression_type _compression = compression_type::none)
:signatures(t.signatures), compression(_compression), unpacked_trx(t), trx_id(unpacked_trx.id())
{
local_pack_transaction();
local_pack_context_free_data();
}
explicit packed_transaction_v0(signed_transaction&& t, compression_type _compression = compression_type::none)
:signatures(t.signatures), compression(_compression), unpacked_trx(std::move(t)), trx_id(unpacked_trx.id())
{
local_pack_transaction();
local_pack_context_free_data();
}
packed_transaction_v0(const bytes& packed_txn, const vector<signature_type>& sigs, const bytes& packed_cfd, compression_type _compression);
// used by abi_serializer
packed_transaction_v0( bytes&& packed_txn, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression );
packed_transaction_v0( bytes&& packed_txn, vector<signature_type>&& sigs, vector<bytes>&& cfd, compression_type _compression );
packed_transaction_v0( transaction&& t, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression );
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
digest_type packed_digest()const;
const transaction_id_type& id()const { return trx_id; }
time_point_sec expiration()const { return unpacked_trx.expiration; }
const vector<bytes>& get_context_free_data()const { return unpacked_trx.context_free_data; }
const transaction& get_transaction()const { return unpacked_trx; }
const signed_transaction& get_signed_transaction()const { return unpacked_trx; }
const vector<signature_type>& get_signatures()const { return signatures; }
const fc::enum_type<uint8_t,compression_type>& get_compression()const { return compression; }
const bytes& get_packed_context_free_data()const { return packed_context_free_data; }
const bytes& get_packed_transaction()const { return packed_trx; }
private:
void local_unpack_transaction(vector<bytes>&& context_free_data);
void local_unpack_context_free_data();
void local_pack_transaction();
void local_pack_context_free_data();
friend struct fc::reflector<packed_transaction_v0>;
friend struct fc::reflector_init_visitor<packed_transaction_v0>;
friend struct fc::has_reflector_init<packed_transaction_v0>;
friend struct packed_transaction;
void reflector_init();
private:
friend struct pruned_transaction;
friend struct prunable_transaction_data;
vector<signature_type> signatures;
fc::enum_type<uint8_t, compression_type> compression;
bytes packed_context_free_data;
bytes packed_trx;
private:
// cache unpacked trx, for thread safety do not modify after construction
signed_transaction unpacked_trx;
transaction_id_type trx_id;
};
using packed_transaction_v0_ptr = std::shared_ptr<const packed_transaction_v0>;
struct prunable_transaction_data {
enum class compression_type : uint8_t {
none = 0,
zlib = 1,
COMPRESSION_TYPE_COUNT
};
// Do not exceed 127 as that will break compatibility in serialization format
static_assert( static_cast<uint8_t>(compression_type::COMPRESSION_TYPE_COUNT) <= 127 );
struct none {
digest_type prunable_digest;
};
struct signatures_only {
std::vector<signature_type> signatures;
digest_type context_free_mroot;
};
using segment_type = fc::static_variant<digest_type, bytes>;
struct partial {
std::vector<signature_type> signatures;
std::vector<segment_type> context_free_segments;
};
struct full {
std::vector<signature_type> signatures;
std::vector<bytes> context_free_segments;
};
struct full_legacy {
std::vector<signature_type> signatures;
bytes packed_context_free_data;
vector<bytes> context_free_segments;
};
using prunable_data_type = fc::static_variant< full_legacy,
none,
signatures_only,
partial,
full >;
prunable_transaction_data prune_all() const;
digest_type digest() const;
// Returns the maximum pack size of any prunable_transaction_data that is reachable
// by pruning this object.
std::size_t maximum_pruned_pack_size( compression_type segment_compression ) const;
prunable_data_type prunable_data;
};
struct packed_transaction : fc::reflect_init {
using compression_type = packed_transaction_v0::compression_type;
using cf_compression_type = prunable_transaction_data::compression_type;
packed_transaction() = default;
packed_transaction(packed_transaction&&) = default;
explicit packed_transaction(const packed_transaction&) = default;
packed_transaction& operator=(const packed_transaction&) = delete;
packed_transaction& operator=(packed_transaction&&) = default;
packed_transaction(const packed_transaction_v0& other, bool legacy);
packed_transaction(packed_transaction_v0&& other, bool legacy);
explicit packed_transaction(signed_transaction t, bool legacy, compression_type _compression = compression_type::none);
packed_transaction_v0_ptr to_packed_transaction_v0() const;
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
uint32_t get_estimated_size()const { return estimated_size; }
digest_type packed_digest()const;
const transaction_id_type& id()const { return trx_id; }
time_point_sec expiration()const { return unpacked_trx.expiration; }
const transaction& get_transaction()const { return unpacked_trx; }
// Returns nullptr if the signatures were pruned
const vector<signature_type>* get_signatures()const;
// Returns nullptr if any context_free_data segment was pruned
const vector<bytes>* get_context_free_data()const;
// Returns nullptr if the context_free_data segment was pruned or segment_ordinal is out of range.
const bytes* get_context_free_data(std::size_t segment_ordinal)const;
const fc::enum_type<uint8_t,compression_type>& get_compression()const { return compression; }
const bytes& get_packed_transaction()const { return packed_trx; }
const prunable_transaction_data& get_prunable_data() const { return prunable_data; }
void prune_all();
std::size_t maximum_pruned_pack_size( cf_compression_type segment_compression ) const;
private:
friend struct fc::reflector<packed_transaction>;
friend struct fc::reflector_init_visitor<packed_transaction>;
friend struct fc::has_reflector_init<packed_transaction>;
void reflector_init();
uint32_t calculate_estimated_size() const;
private:
uint32_t estimated_size = 0;
fc::enum_type<uint8_t,compression_type> compression;
prunable_transaction_data prunable_data;
bytes packed_trx; // packed and compressed (according to compression) transaction
private:
// cache unpacked trx, for thread safety do not modify any attributes after construction
transaction unpacked_trx;
transaction_id_type trx_id;
};
using packed_transaction_ptr = std::shared_ptr<const packed_transaction>;
uint128_t transaction_id_to_sender_id( const transaction_id_type& tid );
} } /// namespace eosio::chain
FC_REFLECT(eosio::chain::deferred_transaction_generation_context, (sender_trx_id)(sender_id)(sender) )
FC_REFLECT( eosio::chain::transaction_header, (expiration)(ref_block_num)(ref_block_prefix)
(max_net_usage_words)(max_cpu_usage_ms)(delay_sec) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions)(transaction_extensions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction_v0::compression_type, (none)(zlib))
// @ignore unpacked_trx
FC_REFLECT( eosio::chain::packed_transaction_v0, (signatures)(compression)(packed_context_free_data)(packed_trx) )
FC_REFLECT( eosio::chain::packed_transaction, (compression)(prunable_data)(packed_trx) )
FC_REFLECT( eosio::chain::prunable_transaction_data, (prunable_data));
FC_REFLECT( eosio::chain::prunable_transaction_data::none, (prunable_digest))
FC_REFLECT( eosio::chain::prunable_transaction_data::signatures_only, (signatures)(context_free_mroot))
FC_REFLECT( eosio::chain::prunable_transaction_data::partial, (signatures)(context_free_segments))
FC_REFLECT( eosio::chain::prunable_transaction_data::full, (signatures)(context_free_segments))
FC_REFLECT( eosio::chain::prunable_transaction_data::full_legacy, (signatures)(packed_context_free_data))
|
Fix a browser crash when an extension with multiple active pages crashes.
BUG=63038
TEST=Install an extension with a bg page and a popup. Right-click the browser action and inspect the popup. In the task manager, kill the extension process. The browser should not crash.
Review URL: http://codereview.chromium.org/5038004
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@66342 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
Fix a race bug where content scripts would not apply to the first page load.
BUG=11547
Review URL: http://codereview.chromium.org/302011
git-svn-id: http://src.chromium.org/svn/trunk/src@29555 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: ba9088f66416e228884ddd20a73a77db7912e40f
|
// 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/simple_message_box.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
namespace {
void SetDialogTitle(GtkWidget* dialog, const string16& title) {
gtk_window_set_title(GTK_WINDOW(dialog), UTF16ToUTF8(title).c_str());
// The following code requires the dialog to be realized.
gtk_widget_realize(dialog);
// Make sure it's big enough to show the title.
GtkRequisition req;
gtk_widget_size_request(dialog, &req);
int width;
gtk_util::GetWidgetSizeFromCharacters(dialog, title.length(), 0,
&width, NULL);
// The fudge factor accounts for extra space needed by the frame
// decorations as well as width differences between average text and the
// actual title text.
width = width * 1.2 + 50;
if (width > req.width)
gtk_widget_set_size_request(dialog, width, -1);
}
int g_dialog_response;
void HandleOnResponseDialog(GtkWidget* widget, int response, void* user_data) {
g_dialog_response = response;
gtk_widget_destroy(widget);
MessageLoop::current()->QuitNow();
}
} // namespace
namespace browser {
void ShowErrorBox(gfx::NativeWindow parent,
const string16& title,
const string16& message) {
GtkWidget* dialog = gtk_message_dialog_new(parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
"%s",
UTF16ToUTF8(message).c_str());
gtk_util::ApplyMessageDialogQuirks(dialog);
SetDialogTitle(dialog, title);
gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL);
gtk_util::ShowDialog(dialog);
}
bool ShowYesNoBox(gfx::NativeWindow parent,
const string16& title,
const string16& message) {
GtkWidget* dialog = gtk_message_dialog_new(parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"%s",
UTF16ToUTF8(message).c_str());
gtk_util::ApplyMessageDialogQuirks(dialog);
SetDialogTitle(dialog, title);
gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_YES);
g_signal_connect(dialog,
"response",
G_CALLBACK(HandleOnResponseDialog),
NULL);
gtk_util::ShowDialog(dialog);
// Not gtk_dialog_run as it prevents timers from running in the unit tests.
MessageLoop::current()->Run();
return g_dialog_response == GTK_RESPONSE_YES;
}
} // namespace browser
gtk: Change the message type of the ShowErrorBox() function to "warning".
This patch changes the message type from error to warning. This is to match with
what views, win and cocoa is already doing.
I know the name of this function is misleading, I plan to rename it in a follow
up CL.
R=erg@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10035035
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@132847 0039d316-1c4b-4281-b951-d872f2087c98
// 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/simple_message_box.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
namespace {
void SetDialogTitle(GtkWidget* dialog, const string16& title) {
gtk_window_set_title(GTK_WINDOW(dialog), UTF16ToUTF8(title).c_str());
// The following code requires the dialog to be realized.
gtk_widget_realize(dialog);
// Make sure it's big enough to show the title.
GtkRequisition req;
gtk_widget_size_request(dialog, &req);
int width;
gtk_util::GetWidgetSizeFromCharacters(dialog, title.length(), 0,
&width, NULL);
// The fudge factor accounts for extra space needed by the frame
// decorations as well as width differences between average text and the
// actual title text.
width = width * 1.2 + 50;
if (width > req.width)
gtk_widget_set_size_request(dialog, width, -1);
}
int g_dialog_response;
void HandleOnResponseDialog(GtkWidget* widget, int response, void* user_data) {
g_dialog_response = response;
gtk_widget_destroy(widget);
MessageLoop::current()->QuitNow();
}
} // namespace
namespace browser {
void ShowErrorBox(gfx::NativeWindow parent,
const string16& title,
const string16& message) {
GtkWidget* dialog = gtk_message_dialog_new(parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_OK,
"%s",
UTF16ToUTF8(message).c_str());
gtk_util::ApplyMessageDialogQuirks(dialog);
SetDialogTitle(dialog, title);
gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL);
gtk_util::ShowDialog(dialog);
}
bool ShowYesNoBox(gfx::NativeWindow parent,
const string16& title,
const string16& message) {
GtkWidget* dialog = gtk_message_dialog_new(parent,
GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"%s",
UTF16ToUTF8(message).c_str());
gtk_util::ApplyMessageDialogQuirks(dialog);
SetDialogTitle(dialog, title);
gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_YES);
g_signal_connect(dialog,
"response",
G_CALLBACK(HandleOnResponseDialog),
NULL);
gtk_util::ShowDialog(dialog);
// Not gtk_dialog_run as it prevents timers from running in the unit tests.
MessageLoop::current()->Run();
return g_dialog_response == GTK_RESPONSE_YES;
}
} // namespace browser
|
// Filename: INSStaggeredVelocityBcCoef.C
// Last modified: <06.Oct.2008 17:51:26 griffith@box230.cims.nyu.edu>
// Created on 22 Jul 2008 by Boyce Griffith (griffith@box230.cims.nyu.edu)
#include "INSStaggeredVelocityBcCoef.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBTK INCLUDES
#include <ibtk/PhysicalBoundaryUtilities.h>
// SAMRAI INCLUDES
#include <CartesianPatchGeometry.h>
#include <CellData.h>
#include <SideData.h>
#include <tbox/Utilities.h>
// C++ STDLIB INCLUDES
#include <limits>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
INSStaggeredVelocityBcCoef::INSStaggeredVelocityBcCoef(
const int comp_idx,
const INSCoefs& problem_coefs,
const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs,
const bool homogeneous_bc)
: d_comp_idx(comp_idx),
d_problem_coefs(problem_coefs),
d_u_bc_coefs(NDIM,static_cast<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>(NULL)),
d_current_time(std::numeric_limits<double>::quiet_NaN()),
d_new_time(std::numeric_limits<double>::quiet_NaN()),
d_target_idx(-1),
d_homogeneous_bc(false)
{
setVelocityPhysicalBcCoefs(u_bc_coefs);
setHomogeneousBc(homogeneous_bc);
return;
}// INSStaggeredVelocityBcCoef
INSStaggeredVelocityBcCoef::~INSStaggeredVelocityBcCoef()
{
// intentionally blank
return;
}// ~INSStaggeredVelocityBcCoef
void
INSStaggeredVelocityBcCoef::setVelocityPhysicalBcCoefs(
const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs)
{
if (u_bc_coefs.size() != NDIM)
{
TBOX_ERROR("INSStaggeredVelocityBcCoef::setVelocityPhysicalBcCoefs():\n"
<< " precisely NDIM boundary condition objects must be provided." << std::endl);
}
d_u_bc_coefs = u_bc_coefs;
return;
}// setVelocityPhysicalBcCoefs
void
INSStaggeredVelocityBcCoef::setTimeInterval(
const double current_time,
const double new_time)
{
d_current_time = current_time;
d_new_time = new_time;
return;
}// setTimeInterval
void
INSStaggeredVelocityBcCoef::setTargetPatchDataIndex(
const int target_idx)
{
d_target_idx = target_idx;
return;
}// setTargetPatchDataIndex
void
INSStaggeredVelocityBcCoef::setHomogeneousBc(
const bool homogeneous_bc)
{
d_homogeneous_bc = homogeneous_bc;
return;
}// setHomogeneousBc
void
INSStaggeredVelocityBcCoef::setBcCoefs(
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
const SAMRAI::hier::Patch<NDIM>& patch,
const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
double fill_time) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(d_u_bc_coefs.size() == NDIM);
for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
{
TBOX_ASSERT(d_u_bc_coefs[l] != NULL);
}
#endif
// Set the unmodified velocity bc coefs.
d_u_bc_coefs[d_comp_idx]->setBcCoefs(
acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
// We do not make any further modifications to the values of acoef_data and
// bcoef_data beyond this point.
if (gcoef_data.isNull()) return;
// Ensure homogeneous boundary conditions are enforced.
if (d_homogeneous_bc) gcoef_data->fillAll(0.0);
// Modify Neumann boundary conditions to correspond to traction (stress)
// boundary conditions.
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!acoef_data.isNull());
TBOX_ASSERT(!bcoef_data.isNull());
TBOX_ASSERT(!gcoef_data.isNull());
#endif
const int location_index = bdry_box.getLocationIndex();
const int bdry_normal_axis = location_index/2;
const bool is_lower = location_index%2 == 0;
const SAMRAI::hier::Box<NDIM>& bc_coef_box = acoef_data->getBox();
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(bc_coef_box == acoef_data->getBox());
TBOX_ASSERT(bc_coef_box == bcoef_data->getBox());
TBOX_ASSERT(bc_coef_box == gcoef_data->getBox());
#endif
SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM,double> > u_data =
patch.checkAllocated(d_target_idx)
? patch.getPatchData(d_target_idx)
: SAMRAI::tbox::Pointer<SAMRAI::hier::PatchData<NDIM> >(NULL);
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!u_data.isNull());
TBOX_ASSERT(u_data->getGhostCellWidth().max() == u_data->getGhostCellWidth().min());
#endif
const SAMRAI::hier::Box<NDIM>& ghost_box = u_data->getGhostBox();
SAMRAI::tbox::Pointer<SAMRAI::geom::CartesianPatchGeometry<NDIM> > pgeom = patch.getPatchGeometry();
const double* const dx = pgeom->getDx();
const double mu = d_problem_coefs.getMu();
for (SAMRAI::hier::Box<NDIM>::Iterator it(bc_coef_box); it; it++)
{
const SAMRAI::hier::Index<NDIM>& i = it();
const double& alpha = (*acoef_data)(i,0);
const double& beta = (*bcoef_data)(i,0);
double& gamma = (*gcoef_data)(i,0);
const bool velocity_bc = SAMRAI::tbox::MathUtilities<double>::equalEps(alpha,1.0);
const bool traction_bc = SAMRAI::tbox::MathUtilities<double>::equalEps(beta ,1.0);
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT((velocity_bc || traction_bc) && !(velocity_bc && traction_bc));
#endif
if (velocity_bc)
{
// intentionally blank
}
else if (traction_bc)
{
if (d_comp_idx == bdry_normal_axis)
{
SAMRAI::hier::Index<NDIM> i_intr0 = i;
SAMRAI::hier::Index<NDIM> i_intr1 = i;
if (is_lower)
{
i_intr0(bdry_normal_axis) += 0;
i_intr1(bdry_normal_axis) += 1;
}
else
{
i_intr0(bdry_normal_axis) -= 1;
i_intr1(bdry_normal_axis) -= 2;
}
for (int d = 0; d < NDIM; ++d)
{
if (d != bdry_normal_axis)
{
i_intr0(d) = std::max(i_intr0(d),ghost_box.lower()(d));
i_intr0(d) = std::min(i_intr0(d),ghost_box.upper()(d));
i_intr1(d) = std::max(i_intr1(d),ghost_box.lower()(d));
i_intr1(d) = std::min(i_intr1(d),ghost_box.upper()(d));
}
}
// Specify a Neumann boundary condition which corresponds to a
// finite difference approximation to the divergence free
// condition at the boundary of the domain using extrapolated
// values of the tangential velocities.
double du_norm_dx_norm = 0.0;
for (int axis = 0; axis < NDIM; ++axis)
{
if (axis != bdry_normal_axis)
{
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr0_upper(i_intr0, axis, SAMRAI::pdat::SideIndex<NDIM>::Upper);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr1_upper(i_intr1, axis, SAMRAI::pdat::SideIndex<NDIM>::Upper);
const double u_tan_upper = 1.5*(*u_data)(i_s_intr0_upper)-0.5*(*u_data)(i_s_intr1_upper);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr0_lower(i_intr0, axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr1_lower(i_intr1, axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const double u_tan_lower = 1.5*(*u_data)(i_s_intr0_lower)-0.5*(*u_data)(i_s_intr1_lower);
du_norm_dx_norm -= (u_tan_upper-u_tan_lower)/dx[axis];
}
}
gamma = (is_lower ? -1.0 : +1.0)*du_norm_dx_norm;
}
else
{
// Compute the tangential derivative of the normal component of
// the velocity at the boundary.
SAMRAI::hier::Index<NDIM> i_lower(i), i_upper(i);
i_lower(d_comp_idx) = std::max(ghost_box.lower()(d_comp_idx),i(d_comp_idx)-1);
i_upper(d_comp_idx) = std::min(ghost_box.upper()(d_comp_idx),i(d_comp_idx) );
const SAMRAI::pdat::SideIndex<NDIM> i_s_lower(i_lower, bdry_normal_axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const SAMRAI::pdat::SideIndex<NDIM> i_s_upper(i_upper, bdry_normal_axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const double du_norm_dtan = (is_lower ? -1.0 : +1.0)*((*u_data)(i_s_upper)-(*u_data)(i_s_lower))/dx[d_comp_idx];
// Correct the boundary condition value.
gamma = gamma/mu - du_norm_dtan;
}
}
else
{
TBOX_ERROR("this statement should not be reached!\n");
}
}
return;
}// setBcCoefs
SAMRAI::hier::IntVector<NDIM>
INSStaggeredVelocityBcCoef::numberOfExtensionsFillable() const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(d_u_bc_coefs.size() == NDIM);
for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
{
TBOX_ASSERT(d_u_bc_coefs[l] != NULL);
}
#endif
SAMRAI::hier::IntVector<NDIM> ret_val(std::numeric_limits<int>::max());
for (int d = 0; d < NDIM; ++d)
{
ret_val = SAMRAI::hier::IntVector<NDIM>::min(
ret_val, d_u_bc_coefs[d]->numberOfExtensionsFillable());
}
return ret_val;
}// numberOfExtensionsFillable
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
}// namespace IBAMR
/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////
//////////////////////////////////////////////////////////////////////////////
simplified bc code
// Filename: INSStaggeredVelocityBcCoef.C
// Last modified: <06.Oct.2008 21:13:18 griffith@box230.cims.nyu.edu>
// Created on 22 Jul 2008 by Boyce Griffith (griffith@box230.cims.nyu.edu)
#include "INSStaggeredVelocityBcCoef.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBTK INCLUDES
#include <ibtk/PhysicalBoundaryUtilities.h>
// SAMRAI INCLUDES
#include <CartesianPatchGeometry.h>
#include <CellData.h>
#include <SideData.h>
#include <tbox/Utilities.h>
// C++ STDLIB INCLUDES
#include <limits>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
INSStaggeredVelocityBcCoef::INSStaggeredVelocityBcCoef(
const int comp_idx,
const INSCoefs& problem_coefs,
const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs,
const bool homogeneous_bc)
: d_comp_idx(comp_idx),
d_problem_coefs(problem_coefs),
d_u_bc_coefs(NDIM,static_cast<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>(NULL)),
d_current_time(std::numeric_limits<double>::quiet_NaN()),
d_new_time(std::numeric_limits<double>::quiet_NaN()),
d_target_idx(-1),
d_homogeneous_bc(false)
{
setVelocityPhysicalBcCoefs(u_bc_coefs);
setHomogeneousBc(homogeneous_bc);
return;
}// INSStaggeredVelocityBcCoef
INSStaggeredVelocityBcCoef::~INSStaggeredVelocityBcCoef()
{
// intentionally blank
return;
}// ~INSStaggeredVelocityBcCoef
void
INSStaggeredVelocityBcCoef::setVelocityPhysicalBcCoefs(
const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs)
{
if (u_bc_coefs.size() != NDIM)
{
TBOX_ERROR("INSStaggeredVelocityBcCoef::setVelocityPhysicalBcCoefs():\n"
<< " precisely NDIM boundary condition objects must be provided." << std::endl);
}
d_u_bc_coefs = u_bc_coefs;
return;
}// setVelocityPhysicalBcCoefs
void
INSStaggeredVelocityBcCoef::setTimeInterval(
const double current_time,
const double new_time)
{
d_current_time = current_time;
d_new_time = new_time;
return;
}// setTimeInterval
void
INSStaggeredVelocityBcCoef::setTargetPatchDataIndex(
const int target_idx)
{
d_target_idx = target_idx;
return;
}// setTargetPatchDataIndex
void
INSStaggeredVelocityBcCoef::setHomogeneousBc(
const bool homogeneous_bc)
{
d_homogeneous_bc = homogeneous_bc;
return;
}// setHomogeneousBc
void
INSStaggeredVelocityBcCoef::setBcCoefs(
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
const SAMRAI::hier::Patch<NDIM>& patch,
const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
double fill_time) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(d_u_bc_coefs.size() == NDIM);
for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
{
TBOX_ASSERT(d_u_bc_coefs[l] != NULL);
}
#endif
// Set the unmodified velocity bc coefs.
d_u_bc_coefs[d_comp_idx]->setBcCoefs(
acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
// We do not make any further modifications to the values of acoef_data and
// bcoef_data beyond this point.
if (gcoef_data.isNull()) return;
// Ensure homogeneous boundary conditions are enforced.
if (d_homogeneous_bc) gcoef_data->fillAll(0.0);
// Modify Neumann boundary conditions to correspond to traction (stress)
// boundary conditions.
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!acoef_data.isNull());
TBOX_ASSERT(!bcoef_data.isNull());
TBOX_ASSERT(!gcoef_data.isNull());
#endif
const int location_index = bdry_box.getLocationIndex();
const int bdry_normal_axis = location_index/2;
const bool is_lower = location_index%2 == 0;
const SAMRAI::hier::Box<NDIM>& bc_coef_box = acoef_data->getBox();
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(bc_coef_box == acoef_data->getBox());
TBOX_ASSERT(bc_coef_box == bcoef_data->getBox());
TBOX_ASSERT(bc_coef_box == gcoef_data->getBox());
#endif
SAMRAI::tbox::Pointer<SAMRAI::pdat::SideData<NDIM,double> > u_data =
patch.checkAllocated(d_target_idx)
? patch.getPatchData(d_target_idx)
: SAMRAI::tbox::Pointer<SAMRAI::hier::PatchData<NDIM> >(NULL);
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(!u_data.isNull());
TBOX_ASSERT(u_data->getGhostCellWidth().max() == u_data->getGhostCellWidth().min());
#endif
const SAMRAI::hier::Box<NDIM>& ghost_box = u_data->getGhostBox();
SAMRAI::tbox::Pointer<SAMRAI::geom::CartesianPatchGeometry<NDIM> > pgeom = patch.getPatchGeometry();
const double* const dx = pgeom->getDx();
const double mu = d_problem_coefs.getMu();
for (SAMRAI::hier::Box<NDIM>::Iterator it(bc_coef_box); it; it++)
{
const SAMRAI::hier::Index<NDIM>& i = it();
const double& alpha = (*acoef_data)(i,0);
const double& beta = (*bcoef_data)(i,0);
double& gamma = (*gcoef_data)(i,0);
const bool velocity_bc = SAMRAI::tbox::MathUtilities<double>::equalEps(alpha,1.0);
const bool traction_bc = SAMRAI::tbox::MathUtilities<double>::equalEps(beta ,1.0);
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT((velocity_bc || traction_bc) && !(velocity_bc && traction_bc));
#endif
if (velocity_bc)
{
// intentionally blank
}
else if (traction_bc)
{
if (d_comp_idx == bdry_normal_axis)
{
SAMRAI::hier::Index<NDIM> i_intr0 = i;
SAMRAI::hier::Index<NDIM> i_intr1 = i;
if (is_lower)
{
i_intr0(bdry_normal_axis) += 0;
i_intr1(bdry_normal_axis) += 1;
}
else
{
i_intr0(bdry_normal_axis) -= 1;
i_intr1(bdry_normal_axis) -= 2;
}
for (int d = 0; d < NDIM; ++d)
{
if (d != bdry_normal_axis)
{
i_intr0(d) = std::max(i_intr0(d),ghost_box.lower()(d));
i_intr0(d) = std::min(i_intr0(d),ghost_box.upper()(d));
i_intr1(d) = std::max(i_intr1(d),ghost_box.lower()(d));
i_intr1(d) = std::min(i_intr1(d),ghost_box.upper()(d));
}
}
// Specify a Neumann boundary condition which corresponds to a
// finite difference approximation to the divergence free
// condition at the boundary of the domain using extrapolated
// values of the tangential velocities.
double du_norm_dx_norm = 0.0;
for (int axis = 0; axis < NDIM; ++axis)
{
if (axis != bdry_normal_axis)
{
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr0_upper(i_intr0, axis, SAMRAI::pdat::SideIndex<NDIM>::Upper);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr1_upper(i_intr1, axis, SAMRAI::pdat::SideIndex<NDIM>::Upper);
const double u_tan_upper = 1.5*(*u_data)(i_s_intr0_upper)-0.5*(*u_data)(i_s_intr1_upper);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr0_lower(i_intr0, axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const SAMRAI::pdat::SideIndex<NDIM> i_s_intr1_lower(i_intr1, axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const double u_tan_lower = 1.5*(*u_data)(i_s_intr0_lower)-0.5*(*u_data)(i_s_intr1_lower);
du_norm_dx_norm -= (u_tan_upper-u_tan_lower)/dx[axis];
}
}
gamma = (is_lower ? -1.0 : +1.0)*du_norm_dx_norm;
}
else
{
// Compute the tangential derivative of the normal component of
// the velocity at the boundary.
SAMRAI::hier::Index<NDIM> i_lower(i), i_upper(i);
i_lower(d_comp_idx) = std::max(ghost_box.lower()(d_comp_idx),i(d_comp_idx)-1);
i_upper(d_comp_idx) = std::min(ghost_box.upper()(d_comp_idx),i(d_comp_idx) );
const SAMRAI::pdat::SideIndex<NDIM> i_s_lower(i_lower, bdry_normal_axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const SAMRAI::pdat::SideIndex<NDIM> i_s_upper(i_upper, bdry_normal_axis, SAMRAI::pdat::SideIndex<NDIM>::Lower);
const double du_norm_dx_tan = ((*u_data)(i_s_upper)-(*u_data)(i_s_lower))/dx[d_comp_idx];
// Correct the boundary condition value.
gamma = (is_lower ? -1.0 : +1.0)*(gamma/mu - du_norm_dx_tan);
}
}
else
{
TBOX_ERROR("this statement should not be reached!\n");
}
}
return;
}// setBcCoefs
SAMRAI::hier::IntVector<NDIM>
INSStaggeredVelocityBcCoef::numberOfExtensionsFillable() const
{
#ifdef DEBUG_CHECK_ASSERTIONS
TBOX_ASSERT(d_u_bc_coefs.size() == NDIM);
for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
{
TBOX_ASSERT(d_u_bc_coefs[l] != NULL);
}
#endif
SAMRAI::hier::IntVector<NDIM> ret_val(std::numeric_limits<int>::max());
for (int d = 0; d < NDIM; ++d)
{
ret_val = SAMRAI::hier::IntVector<NDIM>::min(
ret_val, d_u_bc_coefs[d]->numberOfExtensionsFillable());
}
return ret_val;
}// numberOfExtensionsFillable
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
}// namespace IBAMR
/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////
//////////////////////////////////////////////////////////////////////////////
|
Adding missing line ending which breaks the trybots..
TBR=tommi
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@46107 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
//Copyright (c) 2013 Robert Markwick
//See the file license.txt for copying permission
#include "XPINSParser.h"
#include <math.h>
using namespace std;
const kMajor=0;
const kMinor=2;
//Read Variable Index for Function Parameters
int readFuncParameter(char* scriptText,int *startIndex,char varType,char expectedEnd){
i++;
if (scriptText[i]!='$'||scriptText[i+1]!=varType) {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=2;
int index=readVarIndex(scriptText, &i, expectedEnd);
*startIndex=i;
return index;
}
//Helper functions
//read index of a variable:
// scriptText: the script
// startIndex: the starting index of the variable
// expectedEnd: the character expected immediately after the variable
int readVarIndex(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
while(scriptText[i]!=expectedEnd){
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]!='0')index/=10;
i++;
}
*startIndex=i;
return index;
}
//Read an int constant
// scriptText: the script
// startIndex: the starting index of the INT
// expectedEnd: the character expected immediately after the INT
int readInt(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
bool isNeg=scriptText[i]=='-';//Make negative if approrpriate
while(scriptText[i]!=expectedEnd){
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]!='0')index/=10;
i++;
}
if(isNeg)index*=-1;
*startIndex=i;
return index;
}
//read a float constant
// scriptText: the script
// startIndex: the starting index of the FLOAT
// expectedEnd: the character expected immediately after the FLOAT
float readFloat(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
int fpartDig=0;
bool fpart=false;
bool isNeg=scriptText[i]=='-';
while(scriptText[i]!=expectedEnd){
if(fpart)fpartDig++;//record decimal place
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]=='.')fpart=true;//Start recording decimal places
else if(scriptText[i]!='0')index/=10;
i++;
}
while (fpartDig) {//put decimal point in correct place
index/=10;
fpartDig--;
}
if(isNeg)index*=-1;
*startIndex=i;
return index;
}
//Check to make sure script is compatible
// script: the script
bool checkVersion(char* script){
for(int i=0;true;i++){
if(script[i]=='@'&&script[i+1]=='P'&&script[i+2]=='A'&&script[i+3]=='R'&&script[i+4]=='S'&&script[i+5]=='E'&&script[i+6]=='R'){
while(script[i]!='[')i++;
int MAJOR=readVarIndex(script, &i, '.');
int MINOR=readVarIndex(script, &i, ']');
if(MAJOR!=kMajor){
cout<<"INCOMPATIBLE VERSION. FAILING";
return false;
}
if(MINOR<kMinor){
cout<<"INCOMPATIBLE VERSION. FAILING";
return false;
}
return true;
}
}
cout<<"SCRIPT MISSING VERSION. FAILING";
return false;
}
//Primary Function
//See header for parameter descriptions
void XPINSParser::parseScript(char* scriptText,varSpace *vars,params *parameters,bool isRECURSIVE,int start,int stop){
//SET UP VAR SPACE
bool initialized_varSpace=false;
if(vars==NULL){
vars=new varSpace;
vars->bVars=vector<bool>();
vars->iVars=vector<int>();
vars->fVars=vector<float>();
vars->vVars=vector<XPINSScriptableMath::Vector*>();
vars->pVars=vector<void*>();
initialized_varSpace=true;
}
int bSize=vars->bVars.size();
int iSize=vars->iVars.size();
int fSize=vars->fVars.size();
int vSize=vars->vVars.size();
int pSize=vars->pVars.size();
//RUN SCRIPT
int i=0;//index of char in script
if(isRECURSIVE)i=start;
//Validate start of script
if(!isRECURSIVE){
if(!checkVersion(scriptText))return;
while (scriptText[i]!='\n')i++;
while(scriptText[i]!='@')i++;
if(scriptText[i+1]!='C'||
scriptText[i+2]!='O'||
scriptText[i+3]!='D'||
scriptText[i+4]!='E'){
printf("\nERROR:INVALID SCRIPT:MISSING @CODE!\n");
return;
}
}
while(true){
//get to next line
while(scriptText[i]!='\n')i++;
i++;
//reaching the end of the Script
if((scriptText[i]!='@'&&
scriptText[i+1]!='E'&&
scriptText[i+2]!='N'&&
scriptText[i+3]!='D')||
(isRECURSIVE&&i==stop)){
break;
}
//Declaring new vars
if(scriptText[i]=='B'){
vars->bVars.resize(vars->bVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='I'){
vars->iVars.resize(vars->iVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='F'){
vars->fVars.resize(vars->fVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='V'){
vars->vVars.resize(vars->vVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='*'){
vars->pVars.resize(vars->pVars.size()+1);
while(scriptText[i]!='$')i++;
}
if(scriptText[i]=='$'){
i++;
if(scriptText[i]=='B'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='B') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPE DOESN'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->bVars[index]=vars->bVars[index2];
}
else if(scriptText[i]=='^'){
if(scriptText[i+1]=='T')
vars->bVars[index]=true;
else if(scriptText[i+1]=='F')
vars->bVars[index]=false;
else{
printf("\nERROR:INVALID SCRIPT:INVALID BOOL CONSTANT!\n");
return;
}
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_AND
if(scriptText[i+1]=='A'&&scriptText[i+2]=='N'&&scriptText[i+3]=='D'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->bVars[index2]&&vars->bVars[index3];
}
//X_OR
else if(scriptText[i+1]=='O'&&scriptText[i+2]=='R'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->bVars[index2]||vars->bVars[index3];
}
//X_NOT
else if(scriptText[i+1]=='N'&&scriptText[i+2]=='O'&&scriptText[i+3]=='T'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=!vars->bVars[index2];
}
//X_ILESS
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='L'&&scriptText[i+3]=='E'&&scriptText[i+4]=='S'&&scriptText[i+5]=='S'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]<vars->iVars[index3];
}
//X_FLESS
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='L'&&scriptText[i+3]=='E'&&scriptText[i+4]=='S'&&scriptText[i+5]=='S'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]<vars->fVars[index3];
}
//X_IMORE
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='M'&&scriptText[i+3]=='O'&&scriptText[i+4]=='R'&&scriptText[i+5]=='E'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]>vars->iVars[index3];
}
//X_FMORE
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='M'&&scriptText[i+3]=='O'&&scriptText[i+4]=='R'&&scriptText[i+5]=='E'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]>vars->fVars[index3];
}
//X_IEQUAL
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='E'&&scriptText[i+3]=='Q'&&scriptText[i+4]=='U'&&scriptText[i+5]=='A'&&scriptText[i+5]=='L'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]==vars->iVars[index3];
}
//X_FEQUAL
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='E'&&scriptText[i+3]=='Q'&&scriptText[i+4]=='U'&&scriptText[i+5]=='A'&&scriptText[i+5]=='L'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]==vars->fVars[index3];
}
else{
printf("\nERROR:INVALID SCRIPT:UNDEFINED FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='I'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='I') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->iVars[index]=vars->iVars[index2];
}
else if(scriptText[i]=='^'){
i++;
int n=readInt(scriptText,&i,'\n');
vars->iVars[index]=n;
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_IADD
if(scriptText[i+1]=='I'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]+vars->iVars[index3];
}
//X_ISUB
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]-vars->iVars[index3];
}
//X_IMULT
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='M'&&scriptText[i+3]=='U'&&scriptText[i+4]=='L'&&scriptText[i+4]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]*vars->iVars[index3];
}
//X_IDIV
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='V'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]/vars->iVars[index3];
}
//X_RAND
else if(scriptText[i+1]=='P'&&scriptText[i+2]=='O'&&scriptText[i+3]=='W'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->iVars[index]=arc4random()%(vars->iVars[index3]-vars->iVars[index2])+vars->fVars[index2];
}
else{
printf("\nERROR:INVALID SCRIPT:NONEXISTENT FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='F'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->fVars[index]=vars->fVars[index2];
}
else if(scriptText[i]=='^'){
i++;
float n=readFloat(scriptText,&i,'\n');
vars->fVars[index]=n;
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_FADD
if(scriptText[i+1]=='F'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]+vars->fVars[index3];
}
//X_FSUB
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]-vars->fVars[index3];
}
//X_FMULT
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='M'&&scriptText[i+3]=='U'&&scriptText[i+4]=='L'&&scriptText[i+4]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]*vars->fVars[index3];
}
//X_FDIV
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='V'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]/vars->fVars[index3];
}
//X_VMAG
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='M'&&scriptText[i+3]=='A'&&scriptText[i+4]=='G'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->vVars[index2]->magnitude();
}
//X_VDIR
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='R'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->vVars[index2]->direction();
}
//X_VX
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='X'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
float f=0;
vars->vVars[index2]->RectCoords(&f, NULL);
vars->fVars[index]=f;
}
//X_VY
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='Y'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
float f=0;
vars->vVars[index2]->RectCoords(NULL, &f);
vars->fVars[index]=f;
}
//X_VANG
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='N'&&scriptText[i+4]=='G'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::Vector::angleBetweenVectors(vars->vVars[index2], vars->vVars[index3]);
}
//X_VADDPOLAR
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'&&scriptText[i+5]=='P'&&scriptText[i+6]=='O'&&scriptText[i+7]=='L'&&scriptText[i+8]=='A'&&scriptText[i+9]=='R'){
i+=10;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::addPolar(vars->fVars[index2], vars->fVars[index3]);
}
//X_VDIST
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='S'&&scriptText[i+5]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::dist(vars->fVars[index2], vars->fVars[index3]);
}
//X_TSIN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='S'&&scriptText[i+3]=='I'&&scriptText[i+4]=='N'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=sinf(vars->fVars[index2]);
}
//X_TCOS
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='C'&&scriptText[i+3]=='O'&&scriptText[i+4]=='S'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=cosf(vars->fVars[index2]);
}
//X_TTAN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='T'&&scriptText[i+3]=='A'&&scriptText[i+4]=='N'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=tanf(vars->fVars[index2]);
}
//X_TATAN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='A'&&scriptText[i+3]=='T'&&scriptText[i+4]=='A'&&scriptText[i+5]=='N'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=atan2f(index2, index3);
}
//X_POW
else if(scriptText[i+1]=='P'&&scriptText[i+2]=='O'&&scriptText[i+3]=='W'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=powf(index2, index3);
}
else{
printf("\nERROR:INVALID SCRIPT!\n");
return;
}
}
}
}
else if(scriptText[i]=='V'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='V') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->vVars[index]=vars->vVars[index2]->copy();
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//X_VREC
if(scriptText[i+1]=='V'&&scriptText[i+2]=='R'&&scriptText[i+3]=='E'&&scriptText[i+4]=='C'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=new XPINSScriptableMath::Vector(vars->fVars[index2],vars->fVars[index3]);
}
//X_VPOL
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='R'&&scriptText[i+3]=='E'&&scriptText[i+4]=='C'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::PolarVector(vars->fVars[index2], vars->fVars[index3]);
}
//X_VADD
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::addVectors(vars->vVars[index2], vars->vVars[index3]);
}
//X_VSUB
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
XPINSScriptableMath::Vector *temp=XPINSScriptableMath::Vector::scaledVector(vars->vVars[index3], -1);
vars->vVars[index]=XPINSScriptableMath::Vector::addVectors(vars->vVars[index2], temp);
delete temp;
}
//X_VSCALE
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='S'&&scriptText[i+3]=='C'&&scriptText[i+4]=='A'&&scriptText[i+5]=='L'&&scriptText[i+6]=='E'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::scaledVector(vars->vVars[index2], vars->fVars[index3]);
}
else{
printf("\nERROR:INVALID SCRIPT:UNDECLARED FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='P'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='P') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->pVars[index]=vars->pVars[index2];
}
else if(scriptText[i]=='#'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
}
}
else if(scriptText[i]=='#'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
}
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,0);
}
else if(scriptText[i]=='@'){
i++;
//IF STATEMENT
if(scriptText[i]=='I'&&scriptText[i+1]=='F'){
while (scriptText[i]!='$') i++;
if(scriptText[i+1]!='B'){
printf("WARNING:VARIABLE NOT BOOL, SKIPPING IF BLOCK");
}
else{
i+=2;
int index=readVarIndex(scriptText, &i, ']');
if(!vars->bVars[index]){
while (scriptText[i]!='{')i++;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
while (scriptText[i]!='\n')i++;
//execute else if applicable
if(scriptText[i]=='@'&&scriptText[i+1]=='E'&&scriptText[i+2]=='L'&&scriptText[i+3]=='S'&&scriptText[i+4]=='E'){
while (scriptText[i]!='{')i++;
i++;
}
}
else{
while (scriptText[i]!='{')i++;
i++;
}
}
}
//WHILE LOOP
else if(scriptText[i]=='W'&&scriptText[i+1]=='H'&&scriptText[i+2]=='I'&&scriptText[i+3]=='L'&&scriptText[i+4]=='E'){
while (scriptText[i]!='$') i++;
if(scriptText[i+1]!='B'){
printf("WARNING:VARIABLE NOT BOOL, SKIPPING WHILE LOOP");
}
else{
i+=2;
int index=readVarIndex(scriptText, &i, ']');
while (scriptText[i]!='{')i++;
int loopStart=i;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
int loopStop=i-1;
while (vars->bVars[index]) {
ScriptParser::parseScript(scriptText, vars, parameters, true, loopStart, loopStop);
}
}
}
//ELSE (BYPASS because IF was executed)
else if(scriptText[i]=='E'&&scriptText[i+1]=='L'&&scriptText[i+2]=='S'&&scriptText[i+3]=='E'){
while (scriptText[i]!='{')i++;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
}
}
}
if(initialized_varSpace) delete vars;
else{//wipe declared variables
int bSize2=vars->bVars.size();
int iSize2=vars->iVars.size();
int fSize2=vars->fVars.size();
int vSize2=vars->vVars.size();
int pSize2=vars->pVars.size();
vars->bVars.resize(bSize);
vars->iVars.resize(iSize);
vars->fVars.resize(fSize);
vars->vVars.resize(vSize);
vars->pVars.resize(pSize);
vars->bVars.resize(bSize2);
vars->iVars.resize(iSize2);
vars->fVars.resize(fSize2);
vars->vVars.resize(vSize2);
vars->pVars.resize(pSize2);
}
}
added X_VDOT and X_VPROJ to the parser
//Copyright (c) 2013 Robert Markwick
//See the file license.txt for copying permission
#include "XPINSParser.h"
#include <math.h>
using namespace std;
const kMajor=0;
const kMinor=2;
//Read Variable Index for Function Parameters
int readFuncParameter(char* scriptText,int *startIndex,char varType,char expectedEnd){
i++;
if (scriptText[i]!='$'||scriptText[i+1]!=varType) {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=2;
int index=readVarIndex(scriptText, &i, expectedEnd);
*startIndex=i;
return index;
}
//Helper functions
//read index of a variable:
// scriptText: the script
// startIndex: the starting index of the variable
// expectedEnd: the character expected immediately after the variable
int readVarIndex(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
while(scriptText[i]!=expectedEnd){
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]!='0')index/=10;
i++;
}
*startIndex=i;
return index;
}
//Read an int constant
// scriptText: the script
// startIndex: the starting index of the INT
// expectedEnd: the character expected immediately after the INT
int readInt(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
bool isNeg=scriptText[i]=='-';//Make negative if approrpriate
while(scriptText[i]!=expectedEnd){
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]!='0')index/=10;
i++;
}
if(isNeg)index*=-1;
*startIndex=i;
return index;
}
//read a float constant
// scriptText: the script
// startIndex: the starting index of the FLOAT
// expectedEnd: the character expected immediately after the FLOAT
float readFloat(char* scriptText,int *startIndex,char expectedEnd){
int i=*startIndex;
int index=0;
int fpartDig=0;
bool fpart=false;
bool isNeg=scriptText[i]=='-';
while(scriptText[i]!=expectedEnd){
if(fpart)fpartDig++;//record decimal place
index*=10;
if(scriptText[i]=='1')index+=1;
else if(scriptText[i]=='2')index+=2;
else if(scriptText[i]=='3')index+=3;
else if(scriptText[i]=='4')index+=4;
else if(scriptText[i]=='5')index+=5;
else if(scriptText[i]=='6')index+=6;
else if(scriptText[i]=='7')index+=7;
else if(scriptText[i]=='8')index+=8;
else if(scriptText[i]=='9')index+=9;
else if(scriptText[i]=='.')fpart=true;//Start recording decimal places
else if(scriptText[i]!='0')index/=10;
i++;
}
while (fpartDig) {//put decimal point in correct place
index/=10;
fpartDig--;
}
if(isNeg)index*=-1;
*startIndex=i;
return index;
}
//Check to make sure script is compatible
// script: the script
bool checkVersion(char* script){
for(int i=0;true;i++){
if(script[i]=='@'&&script[i+1]=='P'&&script[i+2]=='A'&&script[i+3]=='R'&&script[i+4]=='S'&&script[i+5]=='E'&&script[i+6]=='R'){
while(script[i]!='[')i++;
int MAJOR=readVarIndex(script, &i, '.');
int MINOR=readVarIndex(script, &i, ']');
if(MAJOR!=kMajor){
cout<<"INCOMPATIBLE VERSION. FAILING";
return false;
}
if(MINOR<kMinor){
cout<<"INCOMPATIBLE VERSION. FAILING";
return false;
}
return true;
}
}
cout<<"SCRIPT MISSING VERSION. FAILING";
return false;
}
//Primary Function
//See header for parameter descriptions
void XPINSParser::parseScript(char* scriptText,varSpace *vars,params *parameters,bool isRECURSIVE,int start,int stop){
//SET UP VAR SPACE
bool initialized_varSpace=false;
if(vars==NULL){
vars=new varSpace;
vars->bVars=vector<bool>();
vars->iVars=vector<int>();
vars->fVars=vector<float>();
vars->vVars=vector<XPINSScriptableMath::Vector*>();
vars->pVars=vector<void*>();
initialized_varSpace=true;
}
int bSize=vars->bVars.size();
int iSize=vars->iVars.size();
int fSize=vars->fVars.size();
int vSize=vars->vVars.size();
int pSize=vars->pVars.size();
//RUN SCRIPT
int i=0;//index of char in script
if(isRECURSIVE)i=start;
//Validate start of script
if(!isRECURSIVE){
if(!checkVersion(scriptText))return;
while (scriptText[i]!='\n')i++;
while(scriptText[i]!='@')i++;
if(scriptText[i+1]!='C'||
scriptText[i+2]!='O'||
scriptText[i+3]!='D'||
scriptText[i+4]!='E'){
printf("\nERROR:INVALID SCRIPT:MISSING @CODE!\n");
return;
}
}
while(true){
//get to next line
while(scriptText[i]!='\n')i++;
i++;
//reaching the end of the Script
if((scriptText[i]!='@'&&
scriptText[i+1]!='E'&&
scriptText[i+2]!='N'&&
scriptText[i+3]!='D')||
(isRECURSIVE&&i==stop)){
break;
}
//Declaring new vars
if(scriptText[i]=='B'){
vars->bVars.resize(vars->bVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='I'){
vars->iVars.resize(vars->iVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='F'){
vars->fVars.resize(vars->fVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='V'){
vars->vVars.resize(vars->vVars.size()+1);
while(scriptText[i]!='$')i++;
}
else if( scriptText[i]=='*'){
vars->pVars.resize(vars->pVars.size()+1);
while(scriptText[i]!='$')i++;
}
if(scriptText[i]=='$'){
i++;
if(scriptText[i]=='B'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='B') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPE DOESN'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->bVars[index]=vars->bVars[index2];
}
else if(scriptText[i]=='^'){
if(scriptText[i+1]=='T')
vars->bVars[index]=true;
else if(scriptText[i+1]=='F')
vars->bVars[index]=false;
else{
printf("\nERROR:INVALID SCRIPT:INVALID BOOL CONSTANT!\n");
return;
}
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_AND
if(scriptText[i+1]=='A'&&scriptText[i+2]=='N'&&scriptText[i+3]=='D'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->bVars[index2]&&vars->bVars[index3];
}
//X_OR
else if(scriptText[i+1]=='O'&&scriptText[i+2]=='R'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->bVars[index2]||vars->bVars[index3];
}
//X_NOT
else if(scriptText[i+1]=='N'&&scriptText[i+2]=='O'&&scriptText[i+3]=='T'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='B') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=!vars->bVars[index2];
}
//X_ILESS
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='L'&&scriptText[i+3]=='E'&&scriptText[i+4]=='S'&&scriptText[i+5]=='S'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]<vars->iVars[index3];
}
//X_FLESS
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='L'&&scriptText[i+3]=='E'&&scriptText[i+4]=='S'&&scriptText[i+5]=='S'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]<vars->fVars[index3];
}
//X_IMORE
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='M'&&scriptText[i+3]=='O'&&scriptText[i+4]=='R'&&scriptText[i+5]=='E'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]>vars->iVars[index3];
}
//X_FMORE
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='M'&&scriptText[i+3]=='O'&&scriptText[i+4]=='R'&&scriptText[i+5]=='E'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]>vars->fVars[index3];
}
//X_IEQUAL
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='E'&&scriptText[i+3]=='Q'&&scriptText[i+4]=='U'&&scriptText[i+5]=='A'&&scriptText[i+5]=='L'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->iVars[index2]==vars->iVars[index3];
}
//X_FEQUAL
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='E'&&scriptText[i+3]=='Q'&&scriptText[i+4]=='U'&&scriptText[i+5]=='A'&&scriptText[i+5]=='L'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:ICORRECT PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->bVars[index]=vars->fVars[index2]==vars->fVars[index3];
}
else{
printf("\nERROR:INVALID SCRIPT:UNDEFINED FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='I'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='I') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->iVars[index]=vars->iVars[index2];
}
else if(scriptText[i]=='^'){
i++;
int n=readInt(scriptText,&i,'\n');
vars->iVars[index]=n;
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_IADD
if(scriptText[i+1]=='I'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]+vars->iVars[index3];
}
//X_ISUB
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]-vars->iVars[index3];
}
//X_IMULT
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='M'&&scriptText[i+3]=='U'&&scriptText[i+4]=='L'&&scriptText[i+4]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]*vars->iVars[index3];
}
//X_IDIV
else if(scriptText[i+1]=='I'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='V'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->iVars[index]=vars->iVars[index2]/vars->iVars[index3];
}
//X_RAND
else if(scriptText[i+1]=='P'&&scriptText[i+2]=='O'&&scriptText[i+3]=='W'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='I') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->iVars[index]=arc4random()%(vars->iVars[index3]-vars->iVars[index2])+vars->fVars[index2];
}
else{
printf("\nERROR:INVALID SCRIPT:NONEXISTENT FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='F'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->fVars[index]=vars->fVars[index2];
}
else if(scriptText[i]=='^'){
i++;
float n=readFloat(scriptText,&i,'\n');
vars->fVars[index]=n;
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//BUILT IN FUNCTIONS
//X_FADD
if(scriptText[i+1]=='F'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]+vars->fVars[index3];
}
//X_FSUB
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]-vars->fVars[index3];
}
//X_FMULT
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='M'&&scriptText[i+3]=='U'&&scriptText[i+4]=='L'&&scriptText[i+4]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]*vars->fVars[index3];
}
//X_FDIV
else if(scriptText[i+1]=='F'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='V'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->fVars[index2]/vars->fVars[index3];
}
//X_VMAG
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='M'&&scriptText[i+3]=='A'&&scriptText[i+4]=='G'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->vVars[index2]->magnitude();
}
//X_VDIR
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='R'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=vars->vVars[index2]->direction();
}
//X_VX
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='X'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
float f=0;
vars->vVars[index2]->RectCoords(&f, NULL);
vars->fVars[index]=f;
}
//X_VY
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='Y'){
i+=3;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ')');
float f=0;
vars->vVars[index2]->RectCoords(NULL, &f);
vars->fVars[index]=f;
}
//X_VANG
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='N'&&scriptText[i+4]=='G'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::Vector::angleBetweenVectors(vars->vVars[index2], vars->vVars[index3]);
}
//X_VDOT
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='D'&&scriptText[i+3]=='O'&&scriptText[i+4]=='T'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::Vector::dotProduct(vars->vVars[index2], vars->vVars[index3]);
}
//X_VADDPOLAR
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'&&scriptText[i+5]=='P'&&scriptText[i+6]=='O'&&scriptText[i+7]=='L'&&scriptText[i+8]=='A'&&scriptText[i+9]=='R'){
i+=10;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::addPolar(vars->fVars[index2], vars->fVars[index3]);
}
//X_VDIST
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='D'&&scriptText[i+3]=='I'&&scriptText[i+4]=='S'&&scriptText[i+5]=='T'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->fVars[index]=XPINSScriptableMath::dist(vars->fVars[index2], vars->fVars[index3]);
}
//X_TSIN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='S'&&scriptText[i+3]=='I'&&scriptText[i+4]=='N'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=sinf(vars->fVars[index2]);
}
//X_TCOS
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='C'&&scriptText[i+3]=='O'&&scriptText[i+4]=='S'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=cosf(vars->fVars[index2]);
}
//X_TTAN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='T'&&scriptText[i+3]=='A'&&scriptText[i+4]=='N'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=tanf(vars->fVars[index2]);
}
//X_TATAN
else if(scriptText[i+1]=='T'&&scriptText[i+2]=='A'&&scriptText[i+3]=='T'&&scriptText[i+4]=='A'&&scriptText[i+5]=='N'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=atan2f(index2, index3);
}
//X_POW
else if(scriptText[i+1]=='P'&&scriptText[i+2]=='O'&&scriptText[i+3]=='W'){
i+=4;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ',');
vars->fVars[index]=powf(index2, index3);
}
else{
printf("\nERROR:INVALID SCRIPT!\n");
return;
}
}
}
}
else if(scriptText[i]=='V'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='V') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->vVars[index]=vars->vVars[index2]->copy();
}
else if(scriptText[i]=='#'||scriptText[i]=='X'){
if ((scriptText[i]!='#'||scriptText[i+1]!='F')&&(scriptText[i]!='X'||scriptText[i+1]!='_')) {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
if(scriptText[i]=='#'&&scriptText[i+1]=='F'){
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
else{
i+=2;
//X_VREC
if(scriptText[i+1]=='V'&&scriptText[i+2]=='R'&&scriptText[i+3]=='E'&&scriptText[i+4]=='C'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=new XPINSScriptableMath::Vector(vars->fVars[index2],vars->fVars[index3]);
}
//X_VPOL
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='R'&&scriptText[i+3]=='E'&&scriptText[i+4]=='C'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::PolarVector(vars->fVars[index2], vars->fVars[index3]);
}
//X_VADD
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='A'&&scriptText[i+3]=='D'&&scriptText[i+4]=='D'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::addVectors(vars->vVars[index2], vars->vVars[index3]);
}
//X_VSUB
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='S'&&scriptText[i+3]=='U'&&scriptText[i+4]=='B'){
i+=5;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
XPINSScriptableMath::Vector *temp=XPINSScriptableMath::Vector::scaledVector(vars->vVars[index3], -1);
vars->vVars[index]=XPINSScriptableMath::Vector::addVectors(vars->vVars[index2], temp);
delete temp;
}
//X_VSCALE
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='S'&&scriptText[i+3]=='C'&&scriptText[i+4]=='A'&&scriptText[i+5]=='L'&&scriptText[i+6]=='E'){
i+=7;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!=','||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::scaledVector(vars->vVars[index2], vars->fVars[index3]);
}
//X_VPROJ
else if(scriptText[i+1]=='V'&&scriptText[i+2]=='P'&&scriptText[i+3]=='R'&&scriptText[i+4]=='O'&&scriptText[i+4]=='J'){
i+=6;
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='V') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index2=readVarIndex(scriptText, &i, ',');
if (scriptText[i]!='('||scriptText[i+1]!='$'||scriptText[i+2]!='F') {
printf("\nERROR:INVALID SCRIPT:INVALID PARAMETER FORMAT!\n");
return;
}
i+=3;
int index3=readVarIndex(scriptText, &i, ')');
vars->vVars[index]=XPINSScriptableMath::Vector::projectionInDirection(vars->vVars[index2], vars->fVars[index3]);
}
else{
printf("\nERROR:INVALID SCRIPT:UNDECLARED FUNCTION!\n");
return;
}
}
}
}
else if(scriptText[i]=='P'){
i++;
int index=readVarIndex(scriptText, &i, '=');
while(scriptText[i]!='#'&&scriptText[i]!='$'&&scriptText[i]!='^')i++;
if(scriptText[i]=='$'){
if (scriptText[i+1]!='P') {
printf("\nERROR:INVALID SCRIPT:DECLARED VARIABLE TYPES DON'T MATCH!\n");
return;
}
i+=2;
int index2=readVarIndex(scriptText, &i, '\n');
vars->pVars[index]=vars->pVars[index2];
}
else if(scriptText[i]=='#'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
return;
}
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,index);
}
}
}
else if(scriptText[i]=='#'){
if (scriptText[i+1]!='F') {
printf("\nERROR:INVALID SCRIPT:NOT A FUNCTION NAME!\n");
}
i+=2;
int fNum=readVarIndex(scriptText, &i, '(');
XPINSBridge::bridgeFunction(fNum, parameters, vars, scriptText, &i,0);
}
else if(scriptText[i]=='@'){
i++;
//IF STATEMENT
if(scriptText[i]=='I'&&scriptText[i+1]=='F'){
while (scriptText[i]!='$') i++;
if(scriptText[i+1]!='B'){
printf("WARNING:VARIABLE NOT BOOL, SKIPPING IF BLOCK");
}
else{
i+=2;
int index=readVarIndex(scriptText, &i, ']');
if(!vars->bVars[index]){
while (scriptText[i]!='{')i++;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
while (scriptText[i]!='\n')i++;
//execute else if applicable
if(scriptText[i]=='@'&&scriptText[i+1]=='E'&&scriptText[i+2]=='L'&&scriptText[i+3]=='S'&&scriptText[i+4]=='E'){
while (scriptText[i]!='{')i++;
i++;
}
}
else{
while (scriptText[i]!='{')i++;
i++;
}
}
}
//WHILE LOOP
else if(scriptText[i]=='W'&&scriptText[i+1]=='H'&&scriptText[i+2]=='I'&&scriptText[i+3]=='L'&&scriptText[i+4]=='E'){
while (scriptText[i]!='$') i++;
if(scriptText[i+1]!='B'){
printf("WARNING:VARIABLE NOT BOOL, SKIPPING WHILE LOOP");
}
else{
i+=2;
int index=readVarIndex(scriptText, &i, ']');
while (scriptText[i]!='{')i++;
int loopStart=i;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
int loopStop=i-1;
while (vars->bVars[index]) {
ScriptParser::parseScript(scriptText, vars, parameters, true, loopStart, loopStop);
}
}
}
//ELSE (BYPASS because IF was executed)
else if(scriptText[i]=='E'&&scriptText[i+1]=='L'&&scriptText[i+2]=='S'&&scriptText[i+3]=='E'){
while (scriptText[i]!='{')i++;
int num=1;
//skip if block
while(num>0){
if(scriptText[i]=='{')num++;
else if(scriptText[i]=='}')num--;
i++;
}
}
}
}
if(initialized_varSpace) delete vars;
else{//wipe declared variables
int bSize2=vars->bVars.size();
int iSize2=vars->iVars.size();
int fSize2=vars->fVars.size();
int vSize2=vars->vVars.size();
int pSize2=vars->pVars.size();
vars->bVars.resize(bSize);
vars->iVars.resize(iSize);
vars->fVars.resize(fSize);
vars->vVars.resize(vSize);
vars->pVars.resize(pSize);
vars->bVars.resize(bSize2);
vars->iVars.resize(iSize2);
vars->fVars.resize(fSize2);
vars->vVars.resize(vSize2);
vars->pVars.resize(pSize2);
}
}
|
/*
* Copyright 2010 Google Inc.
*
* 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.
*/
// Author: jmarantz@google.com (Joshua Marantz)
#include "pagespeed/kernel/base/stdio_file_system.h"
#ifdef WIN32
#include <windows.h>
#else
#include <dirent.h>
#endif // WIN32
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include "base/logging.h"
#include "pagespeed/kernel/base/timer.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/debug.h"
#include "pagespeed/kernel/base/file_system.h"
#include "pagespeed/kernel/base/message_handler.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
namespace {
// The st_blocks field returned by stat is the number of 512B blocks allocated
// for the files. (While POSIX doesn't specify this, it's the proper value on
// at least Linux, FreeBSD, and OS X).
const int kBlockSize = 512;
} // namespace
namespace net_instaweb {
// Helper class to factor out common implementation details between Input and
// Output files, in lieu of multiple inheritance.
class StdioFileHelper {
public:
StdioFileHelper(FILE* f, const StringPiece& filename)
: file_(f),
line_(1) {
filename.CopyToString(&filename_);
}
~StdioFileHelper() {
CHECK(file_ == NULL);
}
void CountNewlines(const char* buf, int size) {
for (int i = 0; i < size; ++i, ++buf) {
line_ += (*buf == '\n');
}
}
void ReportError(MessageHandler* message_handler, const char* format) {
message_handler->Error(filename_.c_str(), line_, format, strerror(errno));
}
bool Close(MessageHandler* message_handler) {
bool ret = true;
if (file_ != stdout && file_ != stderr && file_ != stdin) {
if (fclose(file_) != 0) {
ReportError(message_handler, "closing file: %s");
ret = false;
}
}
file_ = NULL;
return ret;
}
FILE* file_;
GoogleString filename_;
int line_;
private:
DISALLOW_COPY_AND_ASSIGN(StdioFileHelper);
};
class StdioInputFile : public FileSystem::InputFile {
public:
StdioInputFile(FILE* f, const StringPiece& filename)
: file_helper_(f, filename) {
}
virtual int Read(char* buf, int size, MessageHandler* message_handler) {
int ret = fread(buf, 1, size, file_helper_.file_);
file_helper_.CountNewlines(buf, ret);
if ((ret == 0) && (ferror(file_helper_.file_) != 0)) {
file_helper_.ReportError(message_handler, "reading file: %s");
}
return ret;
}
virtual bool Close(MessageHandler* message_handler) {
return file_helper_.Close(message_handler);
}
virtual const char* filename() { return file_helper_.filename_.c_str(); }
private:
StdioFileHelper file_helper_;
DISALLOW_COPY_AND_ASSIGN(StdioInputFile);
};
class StdioOutputFile : public FileSystem::OutputFile {
public:
StdioOutputFile(FILE* f, const StringPiece& filename)
: file_helper_(f, filename) {
}
virtual bool Write(const StringPiece& buf, MessageHandler* handler) {
size_t bytes_written =
fwrite(buf.data(), 1, buf.size(), file_helper_.file_);
file_helper_.CountNewlines(buf.data(), bytes_written);
bool ret = (bytes_written == buf.size());
if (!ret) {
file_helper_.ReportError(handler, "writing file: %s");
}
return ret;
}
virtual bool Flush(MessageHandler* message_handler) {
bool ret = true;
if (fflush(file_helper_.file_) != 0) {
file_helper_.ReportError(message_handler, "flushing file: %s");
ret = false;
}
return ret;
}
virtual bool Close(MessageHandler* message_handler) {
return file_helper_.Close(message_handler);
}
virtual const char* filename() { return file_helper_.filename_.c_str(); }
virtual bool SetWorldReadable(MessageHandler* message_handler) {
bool ret = true;
int fd = fileno(file_helper_.file_);
int status = fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (status != 0) {
ret = false;
file_helper_.ReportError(message_handler, "setting world-readble: %s");
}
return ret;
}
private:
StdioFileHelper file_helper_;
DISALLOW_COPY_AND_ASSIGN(StdioOutputFile);
};
StdioFileSystem::~StdioFileSystem() {
}
int StdioFileSystem::MaxPathLength(const StringPiece& base) const {
const int kMaxInt = std::numeric_limits<int>::max();
long limit = pathconf(base.as_string().c_str(), _PC_PATH_MAX); // NOLINT
if (limit < 0) {
// pathconf failed.
return FileSystem::MaxPathLength(base);
} else if (limit > kMaxInt) {
// As pathconf returns a long, we may have to clamp it.
return kMaxInt;
} else {
return limit;
}
}
FileSystem::InputFile* StdioFileSystem::OpenInputFile(
const char* filename, MessageHandler* message_handler) {
FileSystem::InputFile* input_file = NULL;
FILE* f = fopen(filename, "r");
if (f == NULL) {
message_handler->Error(filename, 0, "opening input file: %s",
strerror(errno));
} else {
input_file = new StdioInputFile(f, filename);
}
return input_file;
}
FileSystem::OutputFile* StdioFileSystem::OpenOutputFileHelper(
const char* filename, bool append, MessageHandler* message_handler) {
FileSystem::OutputFile* output_file = NULL;
if (strcmp(filename, "-") == 0) {
output_file = new StdioOutputFile(stdout, "<stdout>");
} else {
const char* mode = append ? "a" : "w";
FILE* f = fopen(filename, mode);
if (f == NULL) {
message_handler->Error(filename, 0,
"opening output file: %s", strerror(errno));
} else {
output_file = new StdioOutputFile(f, filename);
}
}
return output_file;
}
FileSystem::OutputFile* StdioFileSystem::OpenTempFileHelper(
const StringPiece& prefix, MessageHandler* message_handler) {
// TODO(jmarantz): As jmaessen points out, mkstemp warns "Don't use
// this function, use tmpfile(3) instead. It is better defined and
// more portable." However, tmpfile does not allow a location to be
// specified. I'm not 100% sure if that's going to be work well for
// us. More importantly, our usage scenario is that we will be
// closing the file and renaming it to a permanent name. tmpfiles
// automatically are deleted when they are closed.
int prefix_len = prefix.length();
static char mkstemp_hook[] = "XXXXXX";
char* template_name = new char[prefix_len + sizeof(mkstemp_hook)];
memcpy(template_name, prefix.data(), prefix_len);
memcpy(template_name + prefix_len, mkstemp_hook, sizeof(mkstemp_hook));
int fd = mkstemp(template_name);
OutputFile* output_file = NULL;
if (fd < 0) {
message_handler->Error(template_name, 0,
"opening temp file: %s", strerror(errno));
} else {
FILE* f = fdopen(fd, "w");
if (f == NULL) {
close(fd);
message_handler->Error(template_name, 0,
"re-opening temp file: %s", strerror(errno));
} else {
output_file = new StdioOutputFile(f, template_name);
}
}
delete [] template_name;
return output_file;
}
bool StdioFileSystem::RemoveFile(const char* filename,
MessageHandler* handler) {
bool ret = (remove(filename) == 0);
if (!ret) {
handler->Message(kError, "Failed to delete file %s: %s",
filename, strerror(errno));
}
return ret;
}
bool StdioFileSystem::RenameFileHelper(const char* old_file,
const char* new_file,
MessageHandler* handler) {
bool ret = (rename(old_file, new_file) == 0);
if (!ret) {
handler->Message(kError, "Failed to rename file %s to %s: %s",
old_file, new_file, strerror(errno));
}
return ret;
}
bool StdioFileSystem::MakeDir(const char* path, MessageHandler* handler) {
// Mode 0777 makes the file use standard umask permissions.
bool ret = (mkdir(path, 0777) == 0);
if (!ret) {
handler->Message(kError, "Failed to make directory %s: %s",
path, strerror(errno));
}
return ret;
}
bool StdioFileSystem::RemoveDir(const char* path, MessageHandler* handler) {
bool ret = (rmdir(path) == 0);
if (!ret) {
handler->Message(kError, "Failed to remove directory %s: %s",
path, strerror(errno));
}
return ret;
}
BoolOrError StdioFileSystem::Exists(const char* path, MessageHandler* handler) {
struct stat statbuf;
BoolOrError ret(stat(path, &statbuf) == 0);
if (ret.is_false() && errno != ENOENT) { // Not error if file doesn't exist.
handler->Message(kError, "Failed to stat %s: %s",
path, strerror(errno));
ret.set_error();
}
return ret;
}
BoolOrError StdioFileSystem::IsDir(const char* path, MessageHandler* handler) {
struct stat statbuf;
BoolOrError ret(false);
if (stat(path, &statbuf) == 0) {
ret.set(S_ISDIR(statbuf.st_mode));
} else if (errno != ENOENT) { // Not an error if file doesn't exist.
handler->Message(kError, "Failed to stat %s: %s",
path, strerror(errno));
ret.set_error();
}
return ret;
}
bool StdioFileSystem::ListContents(const StringPiece& dir, StringVector* files,
MessageHandler* handler) {
#ifdef WIN32
const char kDirSeparator[] = "\\";
GoogleString dir_string = dir.as_string();
if (!dir_string.ends_with(kDirSeparator)) {
dir_string.append(kDirSeparator);
}
char sys_err[1024];
strcpy(sys_err, "UNKNOWN ERROR"); // In case strerror_s fails.
WIN32_FIND_DATA entry;
HANDLE iter = FindFirstFile(dir_string + "*", &entry);
if (iter == INVALID_HANDLE_VALUE) {
strerror_s(sys_err, sizeof(sys_err), GetLastError());
handler->Error(dir_string.c_str(), 0,
"Failed to FindFirstFile: %s", sys_err);
return false;
}
do {
if ((strcmp(entry.cFileName, ".") != 0) &&
(strcmp(entry.cFileName, "..") != 0)) {
files->push_back(dir_string + entry.cFileName);
}
} while (FindNextFile(iter, &entry) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
strerror_s(sys_err, sizeof(sys_err), GetLastError());
handler->Error(dir_string.c_str(), 0,
"Failed to FindNextFile: %s", sys_err);
FindClose(iter);
return false;
}
FindClose(iter);
return true;
#else
GoogleString dir_string = dir.as_string();
EnsureEndsInSlash(&dir_string);
const char* dirname = dir_string.c_str();
DIR* mydir = opendir(dirname);
if (mydir == NULL) {
handler->Error(dirname, 0, "Failed to opendir: %s", strerror(errno));
return false;
} else {
dirent* entry = NULL;
dirent buffer;
while (readdir_r(mydir, &buffer, &entry) == 0 && entry != NULL) {
if ((strcmp(entry->d_name, ".") != 0) &&
(strcmp(entry->d_name, "..") != 0)) {
files->push_back(dir_string + entry->d_name);
}
}
if (closedir(mydir) != 0) {
handler->Error(dirname, 0, "Failed to closedir: %s", strerror(errno));
return false;
}
return true;
}
#endif // WIN32
}
bool StdioFileSystem::Stat(const StringPiece& path, struct stat* statbuf,
MessageHandler* handler) {
const GoogleString path_string = path.as_string();
const char* path_str = path_string.c_str();
if (stat(path_str, statbuf) == 0) {
return true;
} else {
handler->Message(kError, "Failed to stat %s: %s",
path_str, strerror(errno));
return false;
}
}
// TODO(abliss): there are some situations where this doesn't work
// -- e.g. if the filesystem is mounted noatime. We should try to
// detect that and provide a workaround.
bool StdioFileSystem::Atime(const StringPiece& path, int64* timestamp_sec,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*timestamp_sec = statbuf.st_atime;
}
return ret;
}
bool StdioFileSystem::Mtime(const StringPiece& path, int64* timestamp_sec,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*timestamp_sec = statbuf.st_mtime;
}
return ret;
}
bool StdioFileSystem::Size(const StringPiece& path, int64* size,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*size = statbuf.st_blocks * kBlockSize;
}
return ret;
}
BoolOrError StdioFileSystem::TryLock(const StringPiece& lock_name,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
const char* lock_str = lock_string.c_str();
// POSIX mkdir is widely believed to be atomic, although I have
// found no reliable documentation of this fact.
if (mkdir(lock_str, 0777) == 0) {
return BoolOrError(true);
} else if (errno == EEXIST) {
return BoolOrError(false);
} else {
handler->Message(kError, "Failed to mkdir %s: %s",
lock_str, strerror(errno));
return BoolOrError();
}
}
BoolOrError StdioFileSystem::TryLockWithTimeout(const StringPiece& lock_name,
int64 timeout_ms,
const Timer* timer,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
BoolOrError result = TryLock(lock_name, handler);
if (result.is_true() || result.is_error()) {
// We got the lock, or the lock is ungettable.
return result;
}
int64 m_time_sec;
if (!Mtime(lock_name, &m_time_sec, handler)) {
// We can't stat the lockfile.
return BoolOrError();
}
int64 now_us = timer->NowUs();
int64 elapsed_since_lock_us = now_us - Timer::kSecondUs * m_time_sec;
int64 timeout_us = Timer::kMsUs * timeout_ms;
if (elapsed_since_lock_us < timeout_us) {
// The lock is held and timeout hasn't elapsed.
return BoolOrError(false);
}
// Lock has timed out. We have two options here:
// 1) Leave the lock in its present state and assume we've taken ownership.
// This is kind to the file system, but causes lots of repeated work at
// timeout, as subsequent threads also see a timed-out lock.
// 2) Force-unlock the lock and re-lock it. This resets the timeout period,
// but is hard on the file system metadata log.
const char* lock_str = lock_string.c_str();
if (!Unlock(lock_name, handler)) {
// We couldn't break the lock. Maybe someone else beat us to it.
// We optimistically forge ahead anyhow (1), since we know we've timed out.
handler->Info(lock_str, 0,
"Breaking lock without reset! now-ctime=%d-%d > %d (sec)\n%s",
static_cast<int>(now_us / Timer::kSecondUs),
static_cast<int>(m_time_sec),
static_cast<int>(timeout_ms / Timer::kSecondMs),
StackTraceString().c_str());
return BoolOrError(true);
}
handler->Info(lock_str, 0, "Broke lock! now-ctime=%d-%d > %d (sec)\n%s",
static_cast<int>(now_us / Timer::kSecondUs),
static_cast<int>(m_time_sec),
static_cast<int>(timeout_ms / Timer::kSecondMs),
StackTraceString().c_str());
result = TryLock(lock_name, handler);
if (!result.is_true()) {
// Someone else grabbed the lock after we broke it.
handler->Info(lock_str, 0, "Failed to take lock after breaking it!");
}
return result;
}
bool StdioFileSystem::Unlock(const StringPiece& lock_name,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
const char* lock_str = lock_string.c_str();
if (rmdir(lock_str) == 0) {
return true;
} else {
handler->Message(kError, "Failed to rmdir %s: %s",
lock_str, strerror(errno));
return false;
}
}
FileSystem::InputFile* StdioFileSystem::Stdin() {
return new StdioInputFile(stdin, "stdin");
}
FileSystem::OutputFile* StdioFileSystem::Stdout() {
return new StdioOutputFile(stdout, "stdout");
}
FileSystem::OutputFile* StdioFileSystem::Stderr() {
return new StdioOutputFile(stderr, "stderr");
}
} // namespace net_instaweb
More windows build fixes.
/*
* Copyright 2010 Google Inc.
*
* 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.
*/
// Author: jmarantz@google.com (Joshua Marantz)
#include "pagespeed/kernel/base/stdio_file_system.h"
#ifndef WIN32
#include <dirent.h>
#endif // WIN32
#include <errno.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <windows.h>
#endif // WIN32
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include "base/logging.h"
#include "pagespeed/kernel/base/timer.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/debug.h"
#include "pagespeed/kernel/base/file_system.h"
#include "pagespeed/kernel/base/message_handler.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
namespace {
// The st_blocks field returned by stat is the number of 512B blocks allocated
// for the files. (While POSIX doesn't specify this, it's the proper value on
// at least Linux, FreeBSD, and OS X).
const int kBlockSize = 512;
} // namespace
namespace net_instaweb {
// Helper class to factor out common implementation details between Input and
// Output files, in lieu of multiple inheritance.
class StdioFileHelper {
public:
StdioFileHelper(FILE* f, const StringPiece& filename)
: file_(f),
line_(1) {
filename.CopyToString(&filename_);
}
~StdioFileHelper() {
CHECK(file_ == NULL);
}
void CountNewlines(const char* buf, int size) {
for (int i = 0; i < size; ++i, ++buf) {
line_ += (*buf == '\n');
}
}
void ReportError(MessageHandler* message_handler, const char* format) {
message_handler->Error(filename_.c_str(), line_, format, strerror(errno));
}
bool Close(MessageHandler* message_handler) {
bool ret = true;
if (file_ != stdout && file_ != stderr && file_ != stdin) {
if (fclose(file_) != 0) {
ReportError(message_handler, "closing file: %s");
ret = false;
}
}
file_ = NULL;
return ret;
}
FILE* file_;
GoogleString filename_;
int line_;
private:
DISALLOW_COPY_AND_ASSIGN(StdioFileHelper);
};
class StdioInputFile : public FileSystem::InputFile {
public:
StdioInputFile(FILE* f, const StringPiece& filename)
: file_helper_(f, filename) {
}
virtual int Read(char* buf, int size, MessageHandler* message_handler) {
int ret = fread(buf, 1, size, file_helper_.file_);
file_helper_.CountNewlines(buf, ret);
if ((ret == 0) && (ferror(file_helper_.file_) != 0)) {
file_helper_.ReportError(message_handler, "reading file: %s");
}
return ret;
}
virtual bool Close(MessageHandler* message_handler) {
return file_helper_.Close(message_handler);
}
virtual const char* filename() { return file_helper_.filename_.c_str(); }
private:
StdioFileHelper file_helper_;
DISALLOW_COPY_AND_ASSIGN(StdioInputFile);
};
class StdioOutputFile : public FileSystem::OutputFile {
public:
StdioOutputFile(FILE* f, const StringPiece& filename)
: file_helper_(f, filename) {
}
virtual bool Write(const StringPiece& buf, MessageHandler* handler) {
size_t bytes_written =
fwrite(buf.data(), 1, buf.size(), file_helper_.file_);
file_helper_.CountNewlines(buf.data(), bytes_written);
bool ret = (bytes_written == buf.size());
if (!ret) {
file_helper_.ReportError(handler, "writing file: %s");
}
return ret;
}
virtual bool Flush(MessageHandler* message_handler) {
bool ret = true;
if (fflush(file_helper_.file_) != 0) {
file_helper_.ReportError(message_handler, "flushing file: %s");
ret = false;
}
return ret;
}
virtual bool Close(MessageHandler* message_handler) {
return file_helper_.Close(message_handler);
}
virtual const char* filename() { return file_helper_.filename_.c_str(); }
virtual bool SetWorldReadable(MessageHandler* message_handler) {
bool ret = true;
int fd = fileno(file_helper_.file_);
int status = fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (status != 0) {
ret = false;
file_helper_.ReportError(message_handler, "setting world-readble: %s");
}
return ret;
}
private:
StdioFileHelper file_helper_;
DISALLOW_COPY_AND_ASSIGN(StdioOutputFile);
};
StdioFileSystem::~StdioFileSystem() {
}
int StdioFileSystem::MaxPathLength(const StringPiece& base) const {
const int kMaxInt = std::numeric_limits<int>::max();
long limit = pathconf(base.as_string().c_str(), _PC_PATH_MAX); // NOLINT
if (limit < 0) {
// pathconf failed.
return FileSystem::MaxPathLength(base);
} else if (limit > kMaxInt) {
// As pathconf returns a long, we may have to clamp it.
return kMaxInt;
} else {
return limit;
}
}
FileSystem::InputFile* StdioFileSystem::OpenInputFile(
const char* filename, MessageHandler* message_handler) {
FileSystem::InputFile* input_file = NULL;
FILE* f = fopen(filename, "r");
if (f == NULL) {
message_handler->Error(filename, 0, "opening input file: %s",
strerror(errno));
} else {
input_file = new StdioInputFile(f, filename);
}
return input_file;
}
FileSystem::OutputFile* StdioFileSystem::OpenOutputFileHelper(
const char* filename, bool append, MessageHandler* message_handler) {
FileSystem::OutputFile* output_file = NULL;
if (strcmp(filename, "-") == 0) {
output_file = new StdioOutputFile(stdout, "<stdout>");
} else {
const char* mode = append ? "a" : "w";
FILE* f = fopen(filename, mode);
if (f == NULL) {
message_handler->Error(filename, 0,
"opening output file: %s", strerror(errno));
} else {
output_file = new StdioOutputFile(f, filename);
}
}
return output_file;
}
FileSystem::OutputFile* StdioFileSystem::OpenTempFileHelper(
const StringPiece& prefix, MessageHandler* message_handler) {
// TODO(jmarantz): As jmaessen points out, mkstemp warns "Don't use
// this function, use tmpfile(3) instead. It is better defined and
// more portable." However, tmpfile does not allow a location to be
// specified. I'm not 100% sure if that's going to be work well for
// us. More importantly, our usage scenario is that we will be
// closing the file and renaming it to a permanent name. tmpfiles
// automatically are deleted when they are closed.
int prefix_len = prefix.length();
static char mkstemp_hook[] = "XXXXXX";
char* template_name = new char[prefix_len + sizeof(mkstemp_hook)];
memcpy(template_name, prefix.data(), prefix_len);
memcpy(template_name + prefix_len, mkstemp_hook, sizeof(mkstemp_hook));
int fd = mkstemp(template_name);
OutputFile* output_file = NULL;
if (fd < 0) {
message_handler->Error(template_name, 0,
"opening temp file: %s", strerror(errno));
} else {
FILE* f = fdopen(fd, "w");
if (f == NULL) {
close(fd);
message_handler->Error(template_name, 0,
"re-opening temp file: %s", strerror(errno));
} else {
output_file = new StdioOutputFile(f, template_name);
}
}
delete [] template_name;
return output_file;
}
bool StdioFileSystem::RemoveFile(const char* filename,
MessageHandler* handler) {
bool ret = (remove(filename) == 0);
if (!ret) {
handler->Message(kError, "Failed to delete file %s: %s",
filename, strerror(errno));
}
return ret;
}
bool StdioFileSystem::RenameFileHelper(const char* old_file,
const char* new_file,
MessageHandler* handler) {
bool ret = (rename(old_file, new_file) == 0);
if (!ret) {
handler->Message(kError, "Failed to rename file %s to %s: %s",
old_file, new_file, strerror(errno));
}
return ret;
}
bool StdioFileSystem::MakeDir(const char* path, MessageHandler* handler) {
// Mode 0777 makes the file use standard umask permissions.
bool ret = (mkdir(path, 0777) == 0);
if (!ret) {
handler->Message(kError, "Failed to make directory %s: %s",
path, strerror(errno));
}
return ret;
}
bool StdioFileSystem::RemoveDir(const char* path, MessageHandler* handler) {
bool ret = (rmdir(path) == 0);
if (!ret) {
handler->Message(kError, "Failed to remove directory %s: %s",
path, strerror(errno));
}
return ret;
}
BoolOrError StdioFileSystem::Exists(const char* path, MessageHandler* handler) {
struct stat statbuf;
BoolOrError ret(stat(path, &statbuf) == 0);
if (ret.is_false() && errno != ENOENT) { // Not error if file doesn't exist.
handler->Message(kError, "Failed to stat %s: %s",
path, strerror(errno));
ret.set_error();
}
return ret;
}
BoolOrError StdioFileSystem::IsDir(const char* path, MessageHandler* handler) {
struct stat statbuf;
BoolOrError ret(false);
if (stat(path, &statbuf) == 0) {
ret.set(S_ISDIR(statbuf.st_mode));
} else if (errno != ENOENT) { // Not an error if file doesn't exist.
handler->Message(kError, "Failed to stat %s: %s",
path, strerror(errno));
ret.set_error();
}
return ret;
}
bool StdioFileSystem::ListContents(const StringPiece& dir, StringVector* files,
MessageHandler* handler) {
#ifdef WIN32
const char kDirSeparator[] = "\\";
GoogleString dir_string = dir.as_string();
if (!dir_string.ends_with(kDirSeparator)) {
dir_string.append(kDirSeparator);
}
char sys_err[1024];
strcpy(sys_err, "UNKNOWN ERROR"); // In case strerror_s fails.
WIN32_FIND_DATA entry;
HANDLE iter = FindFirstFile(dir_string + "*", &entry);
if (iter == INVALID_HANDLE_VALUE) {
strerror_s(sys_err, sizeof(sys_err), GetLastError());
handler->Error(dir_string.c_str(), 0,
"Failed to FindFirstFile: %s", sys_err);
return false;
}
do {
if ((strcmp(entry.cFileName, ".") != 0) &&
(strcmp(entry.cFileName, "..") != 0)) {
files->push_back(dir_string + entry.cFileName);
}
} while (FindNextFile(iter, &entry) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
strerror_s(sys_err, sizeof(sys_err), GetLastError());
handler->Error(dir_string.c_str(), 0,
"Failed to FindNextFile: %s", sys_err);
FindClose(iter);
return false;
}
FindClose(iter);
return true;
#else
GoogleString dir_string = dir.as_string();
EnsureEndsInSlash(&dir_string);
const char* dirname = dir_string.c_str();
DIR* mydir = opendir(dirname);
if (mydir == NULL) {
handler->Error(dirname, 0, "Failed to opendir: %s", strerror(errno));
return false;
} else {
dirent* entry = NULL;
dirent buffer;
while (readdir_r(mydir, &buffer, &entry) == 0 && entry != NULL) {
if ((strcmp(entry->d_name, ".") != 0) &&
(strcmp(entry->d_name, "..") != 0)) {
files->push_back(dir_string + entry->d_name);
}
}
if (closedir(mydir) != 0) {
handler->Error(dirname, 0, "Failed to closedir: %s", strerror(errno));
return false;
}
return true;
}
#endif // WIN32
}
bool StdioFileSystem::Stat(const StringPiece& path, struct stat* statbuf,
MessageHandler* handler) {
const GoogleString path_string = path.as_string();
const char* path_str = path_string.c_str();
if (stat(path_str, statbuf) == 0) {
return true;
} else {
handler->Message(kError, "Failed to stat %s: %s",
path_str, strerror(errno));
return false;
}
}
// TODO(abliss): there are some situations where this doesn't work
// -- e.g. if the filesystem is mounted noatime. We should try to
// detect that and provide a workaround.
bool StdioFileSystem::Atime(const StringPiece& path, int64* timestamp_sec,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*timestamp_sec = statbuf.st_atime;
}
return ret;
}
bool StdioFileSystem::Mtime(const StringPiece& path, int64* timestamp_sec,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*timestamp_sec = statbuf.st_mtime;
}
return ret;
}
bool StdioFileSystem::Size(const StringPiece& path, int64* size,
MessageHandler* handler) {
struct stat statbuf;
bool ret = Stat(path, &statbuf, handler);
if (ret) {
*size = statbuf.st_blocks * kBlockSize;
}
return ret;
}
BoolOrError StdioFileSystem::TryLock(const StringPiece& lock_name,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
const char* lock_str = lock_string.c_str();
// POSIX mkdir is widely believed to be atomic, although I have
// found no reliable documentation of this fact.
if (mkdir(lock_str, 0777) == 0) {
return BoolOrError(true);
} else if (errno == EEXIST) {
return BoolOrError(false);
} else {
handler->Message(kError, "Failed to mkdir %s: %s",
lock_str, strerror(errno));
return BoolOrError();
}
}
BoolOrError StdioFileSystem::TryLockWithTimeout(const StringPiece& lock_name,
int64 timeout_ms,
const Timer* timer,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
BoolOrError result = TryLock(lock_name, handler);
if (result.is_true() || result.is_error()) {
// We got the lock, or the lock is ungettable.
return result;
}
int64 m_time_sec;
if (!Mtime(lock_name, &m_time_sec, handler)) {
// We can't stat the lockfile.
return BoolOrError();
}
int64 now_us = timer->NowUs();
int64 elapsed_since_lock_us = now_us - Timer::kSecondUs * m_time_sec;
int64 timeout_us = Timer::kMsUs * timeout_ms;
if (elapsed_since_lock_us < timeout_us) {
// The lock is held and timeout hasn't elapsed.
return BoolOrError(false);
}
// Lock has timed out. We have two options here:
// 1) Leave the lock in its present state and assume we've taken ownership.
// This is kind to the file system, but causes lots of repeated work at
// timeout, as subsequent threads also see a timed-out lock.
// 2) Force-unlock the lock and re-lock it. This resets the timeout period,
// but is hard on the file system metadata log.
const char* lock_str = lock_string.c_str();
if (!Unlock(lock_name, handler)) {
// We couldn't break the lock. Maybe someone else beat us to it.
// We optimistically forge ahead anyhow (1), since we know we've timed out.
handler->Info(lock_str, 0,
"Breaking lock without reset! now-ctime=%d-%d > %d (sec)\n%s",
static_cast<int>(now_us / Timer::kSecondUs),
static_cast<int>(m_time_sec),
static_cast<int>(timeout_ms / Timer::kSecondMs),
StackTraceString().c_str());
return BoolOrError(true);
}
handler->Info(lock_str, 0, "Broke lock! now-ctime=%d-%d > %d (sec)\n%s",
static_cast<int>(now_us / Timer::kSecondUs),
static_cast<int>(m_time_sec),
static_cast<int>(timeout_ms / Timer::kSecondMs),
StackTraceString().c_str());
result = TryLock(lock_name, handler);
if (!result.is_true()) {
// Someone else grabbed the lock after we broke it.
handler->Info(lock_str, 0, "Failed to take lock after breaking it!");
}
return result;
}
bool StdioFileSystem::Unlock(const StringPiece& lock_name,
MessageHandler* handler) {
const GoogleString lock_string = lock_name.as_string();
const char* lock_str = lock_string.c_str();
if (rmdir(lock_str) == 0) {
return true;
} else {
handler->Message(kError, "Failed to rmdir %s: %s",
lock_str, strerror(errno));
return false;
}
}
FileSystem::InputFile* StdioFileSystem::Stdin() {
return new StdioInputFile(stdin, "stdin");
}
FileSystem::OutputFile* StdioFileSystem::Stdout() {
return new StdioOutputFile(stdout, "stdout");
}
FileSystem::OutputFile* StdioFileSystem::Stderr() {
return new StdioOutputFile(stderr, "stderr");
}
} // namespace net_instaweb
|
#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct DissassemblyData
{
char* code;
uint64_t location;
uint8_t locationSize;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
static void buildAddressString(char* output, uint64_t address, uint8_t size)
{
switch (size)
{
case 0:
output[0] = 0; break;
case 1:
sprintf(output, "%02x", (uint8_t)address); break;
case 2:
sprintf(output, "%04x", (uint16_t)address); break;
case 4:
sprintf(output, "%08x", (uint32_t)address); break;
case 8:
sprintf(output, "%016llx", (uint64_t)address); break;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void drawCallback(void* userData, PDRect* viewRect, PDUIPainter* painter)
{
int fontX;
int fontY;
char locationAddress[128];
DissassemblyData* data = (DissassemblyData*)userData;
PDUIPaint_fontMetrics(painter, &fontX, &fontY);
PDUIPaint_fillRect(painter, viewRect, 0x7f7f);
PDUIPaint_setPen(painter, 0x1fffffff);
buildAddressString(locationAddress, data->location, data->locationSize);
if (data->code)
{
int y = 30;
char* tempCode = strdup(data->code);
char* pch = strtok(tempCode, "\n");
while (pch != NULL)
{
if (strstr(pch, locationAddress) == pch)
PDUIPaint_setPen(painter, 0x1f1f1fff);
else
PDUIPaint_setPen(painter, 0x1fffffff);
PDUIPaint_drawText(painter, viewRect->x, y, pch);
pch = strtok(NULL, "\n");
y += fontX + 2;
}
free(tempCode);
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
DissassemblyData* userData = (DissassemblyData*)malloc(sizeof(DissassemblyData));
memset(userData, 0, sizeof(DissassemblyData));
(void)uiFuncs;
(void)serviceFunc;
//userData->view = PDUICustomView_create(uiFuncs, userData, drawCallback);
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setDisassemblyCode(DissassemblyData* data, PDReader* inEvents)
{
const char* stringBuffer;
PDRead_findString(inEvents, &stringBuffer, "string_buffer", 0);
//printf("Got disassembly\n");
//printf("disassembly %s\n", stringBuffer);
free(data->code);
if (!stringBuffer)
return;
data->code = strdup(stringBuffer);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
(void)uiFuncs;
DissassemblyData* data = (DissassemblyData*)userData;
(void)writer;
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setDisassembly:
{
setDisassemblyCode(data, inEvents);
//PDUICustomView_repaint(uiFuncs, data->view);
break;
}
case PDEventType_setExceptionLocation:
{
PDRead_findU64(inEvents, &data->location, "address", 0);
PDRead_findU8(inEvents, &data->locationSize, "address_size", 0);
}
}
}
// TODO: Make sure to only request data if the debugger is in break/exception state
/*
PDWrite_eventBegin(writer, PDEventType_getDisassembly);
PDWrite_u64(writer, "address_start", 0);
PDWrite_u32(writer, "instruction_count", (uint32_t)10);
PDWrite_eventEnd(writer);
*/
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Disassembly",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Some work to get disassembly plugin working
#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct DissassemblyData
{
char* code;
uint64_t location;
uint8_t locationSize;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
static void buildAddressString(char* output, uint64_t address, uint8_t size)
{
switch (size)
{
case 0:
output[0] = 0; break;
case 1:
sprintf(output, "%02x", (uint8_t)address); break;
case 2:
sprintf(output, "%04x", (uint16_t)address); break;
case 4:
sprintf(output, "%08x", (uint32_t)address); break;
case 8:
sprintf(output, "%016llx", (uint64_t)address); break;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void drawCallback(void* userData, PDRect* viewRect, PDUIPainter* painter)
{
int fontX;
int fontY;
char locationAddress[128];
DissassemblyData* data = (DissassemblyData*)userData;
PDUIPaint_fontMetrics(painter, &fontX, &fontY);
PDUIPaint_fillRect(painter, viewRect, 0x7f7f);
PDUIPaint_setPen(painter, 0x1fffffff);
buildAddressString(locationAddress, data->location, data->locationSize);
if (data->code)
{
int y = 30;
char* tempCode = strdup(data->code);
char* pch = strtok(tempCode, "\n");
while (pch != NULL)
{
if (strstr(pch, locationAddress) == pch)
PDUIPaint_setPen(painter, 0x1f1f1fff);
else
PDUIPaint_setPen(painter, 0x1fffffff);
PDUIPaint_drawText(painter, viewRect->x, y, pch);
pch = strtok(NULL, "\n");
y += fontX + 2;
}
free(tempCode);
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
DissassemblyData* userData = (DissassemblyData*)malloc(sizeof(DissassemblyData));
memset(userData, 0, sizeof(DissassemblyData));
(void)uiFuncs;
(void)serviceFunc;
//userData->view = PDUICustomView_create(uiFuncs, userData, drawCallback);
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setDisassemblyCode(DissassemblyData* data, PDReader* inEvents)
{
const char* stringBuffer;
PDRead_findString(inEvents, &stringBuffer, "string_buffer", 0);
//printf("Got disassembly\n");
//printf("disassembly %s\n", stringBuffer);
free(data->code);
if (!stringBuffer)
return;
data->code = strdup(stringBuffer);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void renderUI(DissassemblyData* data, PDUI* uiFuncs)
{
if (!data->code)
return;
uiFuncs->text(""); // TODO: Temporary
uiFuncs->text(data->code);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
DissassemblyData* data = (DissassemblyData*)userData;
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setDisassembly:
{
setDisassemblyCode(data, inEvents);
break;
}
case PDEventType_setExceptionLocation:
{
PDRead_findU64(inEvents, &data->location, "address", 0);
PDRead_findU8(inEvents, &data->locationSize, "address_size", 0);
}
}
}
renderUI(data, uiFuncs);
// Temporary req
PDWrite_eventBegin(writer, PDEventType_getDisassembly);
PDWrite_u64(writer, "address_start", 0);
PDWrite_u32(writer, "instruction_count", (uint32_t)10);
PDWrite_eventEnd(writer);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Disassembly",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "kitinformation.h"
#include "devicesupport/desktopdevice.h"
#include "devicesupport/devicemanager.h"
#include "projectexplorerconstants.h"
#include "kit.h"
#include "kitinformationconfigwidget.h"
#include "toolchain.h"
#include "toolchainmanager.h"
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/abi.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
namespace ProjectExplorer {
// --------------------------------------------------------------------------
// SysRootInformation:
// --------------------------------------------------------------------------
SysRootKitInformation::SysRootKitInformation()
{
setObjectName(QLatin1String("SysRootInformation"));
setId(SysRootKitInformation::id());
setPriority(31000);
}
QVariant SysRootKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k)
return QString();
}
QList<Task> SysRootKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const Utils::FileName dir = SysRootKitInformation::sysRoot(k);
if (!dir.toFileInfo().isDir() && SysRootKitInformation::hasSysRoot(k)) {
result << Task(Task::Error, tr("Sys Root \"%1\" is not a directory.").arg(dir.toUserOutput()),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));
}
return result;
}
KitConfigWidget *SysRootKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::SysRootInformationConfigWidget(k, this);
}
KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const
{
return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput());
}
Core::Id SysRootKitInformation::id()
{
return "PE.Profile.SysRoot";
}
bool SysRootKitInformation::hasSysRoot(const Kit *k)
{
if (k)
return !k->value(SysRootKitInformation::id()).toString().isEmpty();
return false;
}
Utils::FileName SysRootKitInformation::sysRoot(const Kit *k)
{
if (!k)
return Utils::FileName();
return Utils::FileName::fromString(k->value(SysRootKitInformation::id()).toString());
}
void SysRootKitInformation::setSysRoot(Kit *k, const Utils::FileName &v)
{
k->setValue(SysRootKitInformation::id(), v.toString());
}
// --------------------------------------------------------------------------
// ToolChainInformation:
// --------------------------------------------------------------------------
ToolChainKitInformation::ToolChainKitInformation()
{
setObjectName(QLatin1String("ToolChainInformation"));
setId(ToolChainKitInformation::id());
setPriority(30000);
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
QVariant ToolChainKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
QList<ToolChain *> tcList = ToolChainManager::toolChains();
if (tcList.isEmpty())
return QString();
Abi abi = Abi::hostAbi();
foreach (ToolChain *tc, tcList) {
if (tc->targetAbi() == abi)
return tc->id();
}
return tcList.at(0)->id();
}
QList<Task> ToolChainKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const ToolChain* toolchain = toolChain(k);
if (!toolchain) {
result << Task(Task::Error, ToolChainKitInformation::msgNoToolChainInTarget(),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));
} else {
result << toolchain->validateKit(k);
}
return result;
}
void ToolChainKitInformation::fix(Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return);
if (toolChain(k))
return;
qWarning("No tool chain set from kit \"%s\".",
qPrintable(k->displayName()));
setToolChain(k, 0); // make sure to clear out no longer known tool chains
}
void ToolChainKitInformation::setup(Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return);
const QString id = k->value(ToolChainKitInformation::id()).toString();
if (id.isEmpty())
return;
ToolChain *tc = ToolChainManager::findToolChain(id);
if (tc)
return;
// ID is not found: Might be an ABI string...
foreach (ToolChain *current, ToolChainManager::toolChains()) {
if (current->targetAbi().toString() == id)
return setToolChain(k, current);
}
}
KitConfigWidget *ToolChainKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::ToolChainInformationConfigWidget(k, this);
}
QString ToolChainKitInformation::displayNamePostfix(const Kit *k) const
{
ToolChain *tc = toolChain(k);
return tc ? tc->displayName() : QString();
}
KitInformation::ItemList ToolChainKitInformation::toUserOutput(const Kit *k) const
{
ToolChain *tc = toolChain(k);
return ItemList() << qMakePair(tr("Compiler"), tc ? tc->displayName() : tr("None"));
}
void ToolChainKitInformation::addToEnvironment(const Kit *k, Utils::Environment &env) const
{
ToolChain *tc = toolChain(k);
if (tc)
tc->addToEnvironment(env);
}
IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const
{
ToolChain *tc = toolChain(k);
if (tc)
return tc->outputParser();
return 0;
}
Core::Id ToolChainKitInformation::id()
{
return "PE.Profile.ToolChain";
}
ToolChain *ToolChainKitInformation::toolChain(const Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return 0);
if (!k)
return 0;
return ToolChainManager::findToolChain(k->value(ToolChainKitInformation::id()).toString());
}
void ToolChainKitInformation::setToolChain(Kit *k, ToolChain *tc)
{
k->setValue(ToolChainKitInformation::id(), tc ? tc->id() : QString());
}
QString ToolChainKitInformation::msgNoToolChainInTarget()
{
return tr("No compiler set in kit.");
}
void ToolChainKitInformation::kitsWereLoaded()
{
foreach (Kit *k, KitManager::kits())
fix(k);
connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*)));
connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}
void ToolChainKitInformation::toolChainUpdated(ToolChain *tc)
{
foreach (Kit *k, KitManager::matchingKits(ToolChainMatcher(tc)))
notifyAboutUpdate(k);
}
void ToolChainKitInformation::toolChainRemoved(ToolChain *tc)
{
Q_UNUSED(tc);
foreach (Kit *k, KitManager::kits())
fix(k);
}
// --------------------------------------------------------------------------
// DeviceTypeInformation:
// --------------------------------------------------------------------------
DeviceTypeKitInformation::DeviceTypeKitInformation()
{
setObjectName(QLatin1String("DeviceTypeInformation"));
setId(DeviceTypeKitInformation::id());
setPriority(33000);
}
QVariant DeviceTypeKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
return QByteArray(Constants::DESKTOP_DEVICE_TYPE);
}
QList<Task> DeviceTypeKitInformation::validate(const Kit *k) const
{
Q_UNUSED(k);
return QList<Task>();
}
KitConfigWidget *DeviceTypeKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::DeviceTypeInformationConfigWidget(k, this);
}
KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) const
{
Core::Id type = deviceTypeId(k);
QString typeDisplayName = tr("Unknown device type");
if (type.isValid()) {
QList<IDeviceFactory *> factories
= ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
if (factory->availableCreationIds().contains(type)) {
typeDisplayName = factory->displayNameForId(type);
break;
}
}
}
return ItemList() << qMakePair(tr("Device type"), typeDisplayName);
}
const Core::Id DeviceTypeKitInformation::id()
{
return "PE.Profile.DeviceType";
}
const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k)
{
return k ? Core::Id::fromSetting(k->value(DeviceTypeKitInformation::id())) : Core::Id();
}
void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type)
{
k->setValue(DeviceTypeKitInformation::id(), type.toSetting());
}
// --------------------------------------------------------------------------
// DeviceInformation:
// --------------------------------------------------------------------------
DeviceKitInformation::DeviceKitInformation()
{
setObjectName(QLatin1String("DeviceInformation"));
setId(DeviceKitInformation::id());
setPriority(32000);
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
QVariant DeviceKitInformation::defaultValue(Kit *k) const
{
Core::Id type = DeviceTypeKitInformation::deviceTypeId(k);
IDevice::ConstPtr dev = DeviceManager::instance()->defaultDevice(type);
return dev.isNull() ? QString() : dev->id().toString();
}
QList<Task> DeviceKitInformation::validate(const Kit *k) const
{
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
QList<Task> result;
if (!dev.isNull() && dev->type() != DeviceTypeKitInformation::deviceTypeId(k))
result.append(Task(Task::Error, tr("Device does not match device type."),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
if (dev.isNull())
result.append(Task(Task::Warning, tr("No device set."),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
return result;
}
void DeviceKitInformation::fix(Kit *k)
{
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k))
return;
qWarning("Device is no longer known, removing from kit \"%s\".", qPrintable(k->displayName()));
setDeviceId(k, Core::Id());
}
void DeviceKitInformation::setup(Kit *k)
{
QTC_ASSERT(DeviceManager::instance()->isLoaded(), return);
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k))
return;
setDeviceId(k, Core::Id::fromSetting(defaultValue(k)));
}
KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::DeviceInformationConfigWidget(k, this);
}
QString DeviceKitInformation::displayNamePostfix(const Kit *k) const
{
IDevice::ConstPtr dev = device(k);
return dev.isNull() ? QString() : dev->displayName();
}
KitInformation::ItemList DeviceKitInformation::toUserOutput(const Kit *k) const
{
IDevice::ConstPtr dev = device(k);
return ItemList() << qMakePair(tr("Device"), dev.isNull() ? tr("Unconfigured") : dev->displayName());
}
Core::Id DeviceKitInformation::id()
{
return "PE.Profile.Device";
}
IDevice::ConstPtr DeviceKitInformation::device(const Kit *k)
{
QTC_ASSERT(DeviceManager::instance()->isLoaded(), return IDevice::ConstPtr());
return DeviceManager::instance()->find(deviceId(k));
}
Core::Id DeviceKitInformation::deviceId(const Kit *k)
{
return k ? Core::Id::fromSetting(k->value(DeviceKitInformation::id())) : Core::Id();
}
void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev)
{
setDeviceId(k, dev ? dev->id() : Core::Id());
}
void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id)
{
k->setValue(DeviceKitInformation::id(), id.toSetting());
}
void DeviceKitInformation::kitsWereLoaded()
{
foreach (Kit *k, KitManager::kits())
fix(k);
DeviceManager *dm = DeviceManager::instance();
connect(dm, SIGNAL(deviceListReplaced()), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceAdded(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceRemoved(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceUpdated(Core::Id)), this, SLOT(deviceUpdated(Core::Id)));
connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
this, SLOT(kitUpdated(ProjectExplorer::Kit*)));
connect(KitManager::instance(), SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)),
this, SLOT(kitUpdated(ProjectExplorer::Kit*)));
}
void DeviceKitInformation::deviceUpdated(const Core::Id &id)
{
foreach (Kit *k, KitManager::kits()) {
if (deviceId(k) == id)
notifyAboutUpdate(k);
}
}
void DeviceKitInformation::kitUpdated(Kit *k)
{
setup(k); // Set default device if necessary
}
void DeviceKitInformation::devicesChanged()
{
foreach (Kit *k, KitManager::kits())
setup(k); // Set default device if necessary
}
} // namespace ProjectExplorer
KitInformation: Fix warning about invalid devices
Do not warn if no device is set at all: No device is a valid value,
no reason to warn about that.
Change-Id: I2aaedb54b6400a4c7d2c711a0d004b33aba0c4cb
Reviewed-by: Daniel Teske <d8a411aec9a206efedb4d45b75fe8d13f1e2b628@digia.com>
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "kitinformation.h"
#include "devicesupport/desktopdevice.h"
#include "devicesupport/devicemanager.h"
#include "projectexplorerconstants.h"
#include "kit.h"
#include "kitinformationconfigwidget.h"
#include "toolchain.h"
#include "toolchainmanager.h"
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/abi.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
namespace ProjectExplorer {
// --------------------------------------------------------------------------
// SysRootInformation:
// --------------------------------------------------------------------------
SysRootKitInformation::SysRootKitInformation()
{
setObjectName(QLatin1String("SysRootInformation"));
setId(SysRootKitInformation::id());
setPriority(31000);
}
QVariant SysRootKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k)
return QString();
}
QList<Task> SysRootKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const Utils::FileName dir = SysRootKitInformation::sysRoot(k);
if (!dir.toFileInfo().isDir() && SysRootKitInformation::hasSysRoot(k)) {
result << Task(Task::Error, tr("Sys Root \"%1\" is not a directory.").arg(dir.toUserOutput()),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));
}
return result;
}
KitConfigWidget *SysRootKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::SysRootInformationConfigWidget(k, this);
}
KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const
{
return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput());
}
Core::Id SysRootKitInformation::id()
{
return "PE.Profile.SysRoot";
}
bool SysRootKitInformation::hasSysRoot(const Kit *k)
{
if (k)
return !k->value(SysRootKitInformation::id()).toString().isEmpty();
return false;
}
Utils::FileName SysRootKitInformation::sysRoot(const Kit *k)
{
if (!k)
return Utils::FileName();
return Utils::FileName::fromString(k->value(SysRootKitInformation::id()).toString());
}
void SysRootKitInformation::setSysRoot(Kit *k, const Utils::FileName &v)
{
k->setValue(SysRootKitInformation::id(), v.toString());
}
// --------------------------------------------------------------------------
// ToolChainInformation:
// --------------------------------------------------------------------------
ToolChainKitInformation::ToolChainKitInformation()
{
setObjectName(QLatin1String("ToolChainInformation"));
setId(ToolChainKitInformation::id());
setPriority(30000);
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
QVariant ToolChainKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
QList<ToolChain *> tcList = ToolChainManager::toolChains();
if (tcList.isEmpty())
return QString();
Abi abi = Abi::hostAbi();
foreach (ToolChain *tc, tcList) {
if (tc->targetAbi() == abi)
return tc->id();
}
return tcList.at(0)->id();
}
QList<Task> ToolChainKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const ToolChain* toolchain = toolChain(k);
if (!toolchain) {
result << Task(Task::Error, ToolChainKitInformation::msgNoToolChainInTarget(),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));
} else {
result << toolchain->validateKit(k);
}
return result;
}
void ToolChainKitInformation::fix(Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return);
if (toolChain(k))
return;
qWarning("No tool chain set from kit \"%s\".",
qPrintable(k->displayName()));
setToolChain(k, 0); // make sure to clear out no longer known tool chains
}
void ToolChainKitInformation::setup(Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return);
const QString id = k->value(ToolChainKitInformation::id()).toString();
if (id.isEmpty())
return;
ToolChain *tc = ToolChainManager::findToolChain(id);
if (tc)
return;
// ID is not found: Might be an ABI string...
foreach (ToolChain *current, ToolChainManager::toolChains()) {
if (current->targetAbi().toString() == id)
return setToolChain(k, current);
}
}
KitConfigWidget *ToolChainKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::ToolChainInformationConfigWidget(k, this);
}
QString ToolChainKitInformation::displayNamePostfix(const Kit *k) const
{
ToolChain *tc = toolChain(k);
return tc ? tc->displayName() : QString();
}
KitInformation::ItemList ToolChainKitInformation::toUserOutput(const Kit *k) const
{
ToolChain *tc = toolChain(k);
return ItemList() << qMakePair(tr("Compiler"), tc ? tc->displayName() : tr("None"));
}
void ToolChainKitInformation::addToEnvironment(const Kit *k, Utils::Environment &env) const
{
ToolChain *tc = toolChain(k);
if (tc)
tc->addToEnvironment(env);
}
IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const
{
ToolChain *tc = toolChain(k);
if (tc)
return tc->outputParser();
return 0;
}
Core::Id ToolChainKitInformation::id()
{
return "PE.Profile.ToolChain";
}
ToolChain *ToolChainKitInformation::toolChain(const Kit *k)
{
QTC_ASSERT(ToolChainManager::isLoaded(), return 0);
if (!k)
return 0;
return ToolChainManager::findToolChain(k->value(ToolChainKitInformation::id()).toString());
}
void ToolChainKitInformation::setToolChain(Kit *k, ToolChain *tc)
{
k->setValue(ToolChainKitInformation::id(), tc ? tc->id() : QString());
}
QString ToolChainKitInformation::msgNoToolChainInTarget()
{
return tr("No compiler set in kit.");
}
void ToolChainKitInformation::kitsWereLoaded()
{
foreach (Kit *k, KitManager::kits())
fix(k);
connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*)));
connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}
void ToolChainKitInformation::toolChainUpdated(ToolChain *tc)
{
foreach (Kit *k, KitManager::matchingKits(ToolChainMatcher(tc)))
notifyAboutUpdate(k);
}
void ToolChainKitInformation::toolChainRemoved(ToolChain *tc)
{
Q_UNUSED(tc);
foreach (Kit *k, KitManager::kits())
fix(k);
}
// --------------------------------------------------------------------------
// DeviceTypeInformation:
// --------------------------------------------------------------------------
DeviceTypeKitInformation::DeviceTypeKitInformation()
{
setObjectName(QLatin1String("DeviceTypeInformation"));
setId(DeviceTypeKitInformation::id());
setPriority(33000);
}
QVariant DeviceTypeKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
return QByteArray(Constants::DESKTOP_DEVICE_TYPE);
}
QList<Task> DeviceTypeKitInformation::validate(const Kit *k) const
{
Q_UNUSED(k);
return QList<Task>();
}
KitConfigWidget *DeviceTypeKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::DeviceTypeInformationConfigWidget(k, this);
}
KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) const
{
Core::Id type = deviceTypeId(k);
QString typeDisplayName = tr("Unknown device type");
if (type.isValid()) {
QList<IDeviceFactory *> factories
= ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
if (factory->availableCreationIds().contains(type)) {
typeDisplayName = factory->displayNameForId(type);
break;
}
}
}
return ItemList() << qMakePair(tr("Device type"), typeDisplayName);
}
const Core::Id DeviceTypeKitInformation::id()
{
return "PE.Profile.DeviceType";
}
const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k)
{
return k ? Core::Id::fromSetting(k->value(DeviceTypeKitInformation::id())) : Core::Id();
}
void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type)
{
k->setValue(DeviceTypeKitInformation::id(), type.toSetting());
}
// --------------------------------------------------------------------------
// DeviceInformation:
// --------------------------------------------------------------------------
DeviceKitInformation::DeviceKitInformation()
{
setObjectName(QLatin1String("DeviceInformation"));
setId(DeviceKitInformation::id());
setPriority(32000);
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
QVariant DeviceKitInformation::defaultValue(Kit *k) const
{
Core::Id type = DeviceTypeKitInformation::deviceTypeId(k);
IDevice::ConstPtr dev = DeviceManager::instance()->defaultDevice(type);
return dev.isNull() ? QString() : dev->id().toString();
}
QList<Task> DeviceKitInformation::validate(const Kit *k) const
{
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
QList<Task> result;
if (!dev.isNull() && dev->type() != DeviceTypeKitInformation::deviceTypeId(k))
result.append(Task(Task::Error, tr("Device does not match device type."),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
if (dev.isNull())
result.append(Task(Task::Warning, tr("No device set."),
Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
return result;
}
void DeviceKitInformation::fix(Kit *k)
{
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
if (!dev.isNull() && dev->type() != DeviceTypeKitInformation::deviceTypeId(k)) {
qWarning("Device is no longer known, removing from kit \"%s\".", qPrintable(k->displayName()));
setDeviceId(k, Core::Id());
}
}
void DeviceKitInformation::setup(Kit *k)
{
QTC_ASSERT(DeviceManager::instance()->isLoaded(), return);
IDevice::ConstPtr dev = DeviceKitInformation::device(k);
if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k))
return;
setDeviceId(k, Core::Id::fromSetting(defaultValue(k)));
}
KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const
{
return new Internal::DeviceInformationConfigWidget(k, this);
}
QString DeviceKitInformation::displayNamePostfix(const Kit *k) const
{
IDevice::ConstPtr dev = device(k);
return dev.isNull() ? QString() : dev->displayName();
}
KitInformation::ItemList DeviceKitInformation::toUserOutput(const Kit *k) const
{
IDevice::ConstPtr dev = device(k);
return ItemList() << qMakePair(tr("Device"), dev.isNull() ? tr("Unconfigured") : dev->displayName());
}
Core::Id DeviceKitInformation::id()
{
return "PE.Profile.Device";
}
IDevice::ConstPtr DeviceKitInformation::device(const Kit *k)
{
QTC_ASSERT(DeviceManager::instance()->isLoaded(), return IDevice::ConstPtr());
return DeviceManager::instance()->find(deviceId(k));
}
Core::Id DeviceKitInformation::deviceId(const Kit *k)
{
return k ? Core::Id::fromSetting(k->value(DeviceKitInformation::id())) : Core::Id();
}
void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev)
{
setDeviceId(k, dev ? dev->id() : Core::Id());
}
void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id)
{
k->setValue(DeviceKitInformation::id(), id.toSetting());
}
void DeviceKitInformation::kitsWereLoaded()
{
foreach (Kit *k, KitManager::kits())
fix(k);
DeviceManager *dm = DeviceManager::instance();
connect(dm, SIGNAL(deviceListReplaced()), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceAdded(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceRemoved(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceUpdated(Core::Id)), this, SLOT(deviceUpdated(Core::Id)));
connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
this, SLOT(kitUpdated(ProjectExplorer::Kit*)));
connect(KitManager::instance(), SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)),
this, SLOT(kitUpdated(ProjectExplorer::Kit*)));
}
void DeviceKitInformation::deviceUpdated(const Core::Id &id)
{
foreach (Kit *k, KitManager::kits()) {
if (deviceId(k) == id)
notifyAboutUpdate(k);
}
}
void DeviceKitInformation::kitUpdated(Kit *k)
{
setup(k); // Set default device if necessary
}
void DeviceKitInformation::devicesChanged()
{
foreach (Kit *k, KitManager::kits())
setup(k); // Set default device if necessary
}
} // namespace ProjectExplorer
|
//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
// Copyright 2013 Thibaut Gridel <tgridel@free.fr>
// Copyright 2014 Calin Cruceru <crucerucalincristian@gmail.com>
//
// Self
#include "AreaAnnotation.h"
// Qt
#include <qmath.h>
#include <QPair>
// Marble
#include "GeoDataPlacemark.h"
#include "GeoDataTypes.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "SceneGraphicsTypes.h"
#include "MarbleMath.h"
#include "MergingNodesAnimation.h"
namespace Marble {
class PolygonNode {
public:
enum PolyNodeFlag {
NoOption = 0x0,
NodeIsSelected = 0x1,
NodeIsInnerTmp = 0x2,
NodeIsMerged = 0x4,
NodeIsEditingHighlighted = 0x8,
NodeIsMergingHighlighted = 0x10
};
Q_DECLARE_FLAGS(PolyNodeFlags, PolyNodeFlag)
explicit PolygonNode( QRegion region, PolyNodeFlags flags = 0 );
~PolygonNode();
bool isSelected() const;
bool isInnerTmp() const;
bool isBeingMerged() const;
bool isEditingHighlighted() const;
bool isMergingHighlighted() const;
PolyNodeFlags flags() const;
void setFlag( PolyNodeFlag flag, bool enabled = true );
void setFlags( PolyNodeFlags flags );
void setRegion( QRegion newRegion );
bool containsPoint( const QPoint &eventPos ) const;
private:
QRegion m_region;
PolyNodeFlags m_flags;
};
PolygonNode::PolygonNode( QRegion region, PolyNodeFlags flags ) :
m_region( region ),
m_flags( flags )
{
// nothing to do
}
PolygonNode::~PolygonNode()
{
// nothing to do
}
bool PolygonNode::isSelected() const
{
return m_flags & NodeIsSelected;
}
bool PolygonNode::isInnerTmp() const
{
return m_flags & NodeIsInnerTmp;
}
bool PolygonNode::isBeingMerged() const
{
return m_flags & NodeIsMerged;
}
bool PolygonNode::isEditingHighlighted() const
{
return m_flags & NodeIsEditingHighlighted;
}
bool PolygonNode::isMergingHighlighted() const
{
return m_flags & NodeIsMergingHighlighted;
}
void PolygonNode::setRegion( QRegion newRegion )
{
m_region = newRegion;
}
PolygonNode::PolyNodeFlags PolygonNode::flags() const
{
return m_flags;
}
void PolygonNode::setFlag( PolyNodeFlag flag, bool enabled )
{
if ( enabled ) {
m_flags |= flag;
} else {
m_flags &= ~flag;
}
}
void PolygonNode::setFlags( PolyNodeFlags flags )
{
m_flags = flags;
}
bool PolygonNode::containsPoint( const QPoint &eventPos ) const
{
return m_region.contains( eventPos );
}
const int AreaAnnotation::regularDim = 15;
const int AreaAnnotation::selectedDim = 15;
const int AreaAnnotation::mergedDim = 20;
const int AreaAnnotation::hoveredDim = 20;
const QColor AreaAnnotation::regularColor = Oxygen::aluminumGray3;
const QColor AreaAnnotation::selectedColor = Oxygen::aluminumGray6;
const QColor AreaAnnotation::mergedColor = Oxygen::emeraldGreen6;
const QColor AreaAnnotation::hoveredColor = Oxygen::grapeViolet6;
AreaAnnotation::AreaAnnotation( GeoDataPlacemark *placemark ) :
SceneGraphicsItem( placemark ),
m_geopainter( 0 ),
m_viewport( 0 ),
m_regionsInitialized( false ),
m_busy( false ),
m_hoveredNode( -1, -1 ),
m_interactingObj( InteractingNothing ),
m_virtualHovered( -1, -1 )
{
// nothing to do
}
AreaAnnotation::~AreaAnnotation()
{
delete m_animation;
}
void AreaAnnotation::paint( GeoPainter *painter, const ViewportParams *viewport )
{
m_viewport = viewport;
m_geopainter = painter;
Q_ASSERT( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType );
painter->save();
if ( !m_regionsInitialized ) {
setupRegionsLists( painter );
m_regionsInitialized = true;
} else {
updateRegions( painter );
}
drawNodes( painter );
painter->restore();
}
bool AreaAnnotation::containsPoint( const QPoint &point ) const
{
if ( state() == SceneGraphicsItem::Editing ) {
return outerNodeContains( point ) != -1 || polygonContains( point ) ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return polygonContains( point ) && outerNodeContains( point ) == -1 &&
innerNodeContains( point ) == QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return outerNodeContains( point ) != -1 ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return virtualNodeContains( point ) != QPair<int, int>( -1, -1 ) ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 ) ||
outerNodeContains( point ) != -1 ||
polygonContains( point );
}
return false;
}
void AreaAnnotation::dealWithItemChange( const SceneGraphicsItem *other )
{
Q_UNUSED( other );
// So far we only deal with item changes when hovering virtual nodes, so that
// they do not remain hovered when changing the item we interact with.
if ( state() == SceneGraphicsItem::Editing ) {
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsEditingHighlighted, false );
} else {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsEditingHighlighted, false );
}
}
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
} else {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
}
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
m_virtualHovered = QPair<int, int>( -1, -1 );
}
}
void AreaAnnotation::setBusy( bool enabled )
{
m_busy = enabled;
if ( !enabled ) {
if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
}
delete m_animation;
}
}
void AreaAnnotation::deselectAllNodes()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
for ( int i = 0 ; i < m_outerNodesList.size(); ++i ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected, false );
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsSelected, false );
}
}
}
void AreaAnnotation::deleteAllSelectedNodes()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If it proves inefficient, try something different.
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> initialInnerRings = polygon->innerBoundaries();
QList<PolygonNode> initialOuterNodes = m_outerNodesList;
QList< QList<PolygonNode> > initialInnerNodes = m_innerNodesList;
for ( int i = 0; i < outerRing.size(); ++i ) {
if ( m_outerNodesList.at(i).isSelected() ) {
if ( m_outerNodesList.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return;
}
m_outerNodesList.removeAt( i );
outerRing.remove( i );
--i;
}
}
for ( int i = 0; i < innerRings.size(); ++i ) {
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
if ( m_innerNodesList.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
--i;
break;
}
innerRings[i].remove( j );
m_innerNodesList[i].removeAt( j );
--j;
}
}
}
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
polygon->innerBoundaries() = initialInnerRings;
m_outerNodesList = initialOuterNodes;
m_innerNodesList = initialInnerNodes;
setRequest( SceneGraphicsItem::InvalidShapeWarning );
}
}
void AreaAnnotation::deleteClickedNode()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If it proves inefficient, try something different.
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> initialInnerRings = polygon->innerBoundaries();
QList<PolygonNode> initialOuterNodes = m_outerNodesList;
QList< QList<PolygonNode> > initialInnerNodes = m_innerNodesList;
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
m_hoveredNode = QPair<int, int>( -1, -1 );
if ( i != -1 && j == -1 ) {
if ( m_outerNodesList.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return;
}
outerRing.remove( i );
m_outerNodesList.removeAt( i );
} else if ( i != -1 && j != -1 ) {
if ( m_innerNodesList.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
return;
}
innerRings[i].remove( j );
m_innerNodesList[i].removeAt( j );
}
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
polygon->innerBoundaries() = initialInnerRings;
m_outerNodesList = initialOuterNodes;
m_innerNodesList = initialInnerNodes;
setRequest( SceneGraphicsItem::InvalidShapeWarning );
}
}
void AreaAnnotation::changeClickedNodeSelection()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( i != -1 && j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected,
!m_outerNodesList.at(i).isSelected() );
} else if ( i != -1 && j != -1 ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsSelected,
!m_innerNodesList.at(i).at(j).isSelected() );
}
}
bool AreaAnnotation::hasNodesSelected() const
{
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
if ( m_outerNodesList.at(i).isSelected() ) {
return true;
}
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
return true;
}
}
}
return false;
}
bool AreaAnnotation::clickedNodeIsSelected() const
{
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
return ( i != -1 && j == -1 && m_outerNodesList.at(i).isSelected() ) ||
( i != -1 && j != -1 && m_innerNodesList.at(i).at(j).isSelected() );
}
QPointer<MergingNodesAnimation> AreaAnnotation::animation()
{
return m_animation;
}
bool AreaAnnotation::mousePressEvent( QMouseEvent *event )
{
if ( !m_viewport || !m_geopainter || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnPress( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnPress( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnPress( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnPress( event );
}
return false;
}
bool AreaAnnotation::mouseMoveEvent( QMouseEvent *event )
{
if ( !m_viewport || !m_geopainter || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnMove( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnMove( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnMove( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnMove( event );
}
return false;
}
bool AreaAnnotation::mouseReleaseEvent( QMouseEvent *event )
{
if ( !m_viewport || !m_geopainter || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnRelease( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnRelease( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnRelease( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnRelease( event );
}
return false;
}
void AreaAnnotation::dealWithStateChange( SceneGraphicsItem::ActionState previousState )
{
// Dealing with cases when exiting a state has an effect on this item.
if ( previousState == SceneGraphicsItem::Editing ) {
m_clickedNodeIndexes = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( previousState == SceneGraphicsItem::AddingPolygonHole ) {
// Check if a polygon hole was being drawn before changing state.
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
QVector<GeoDataLinearRing> &innerBounds = polygon->innerBoundaries();
if ( innerBounds.size() && innerBounds.last().size() &&
m_innerNodesList.last().last().isInnerTmp() ) {
// If only two nodes were added, remove this inner boundary entirely.
if ( innerBounds.last().size() <= 2 ) {
innerBounds.remove( innerBounds.size() - 1 );
m_innerNodesList.removeLast();
return;
}
// Remove the 'NodeIsInnerTmp' flag, to allow ::draw method to paint the nodes.
for ( int i = 0; i < m_innerNodesList.last().size(); ++i ) {
m_innerNodesList.last()[i].setFlag( PolygonNode::NodeIsInnerTmp, false );
}
}
} else if ( previousState == SceneGraphicsItem::MergingPolygonNodes ) {
// If there was only a node selected for being merged and the state changed,
// deselect it.
int i = m_firstMergedNode.first;
int j = m_firstMergedNode.second;
if ( i != -1 && j != -1 ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
} else if ( i != -1 && j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMerged, false );
}
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
delete m_animation;
} else if ( previousState == SceneGraphicsItem::AddingPolygonNodes ) {
m_outerVirtualNodes.clear();
m_innerVirtualNodes.clear();
m_virtualHovered = QPair<int, int>( -1, -1 );
m_adjustedNode = -2;
}
// Dealing with cases when entering a state has an effect on this item, or
// initializations are needed.
if ( state() == SceneGraphicsItem::Editing ) {
m_interactingObj = InteractingNothing;
m_clickedNodeIndexes = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
// Nothing to do so far when entering this state.
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
m_animation = 0;
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
m_virtualHovered = QPair<int, int>( -1, -1 );
m_adjustedNode = -2;
}
}
const char *AreaAnnotation::graphicType() const
{
return SceneGraphicsTypes::SceneGraphicAreaAnnotation;
}
bool AreaAnnotation::isValidPolygon() const
{
const GeoDataPolygon *poly = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const QVector<GeoDataLinearRing> &innerRings = poly->innerBoundaries();
foreach ( const GeoDataLinearRing &innerRing, innerRings ) {
for ( int i = 0; i < innerRing.size(); ++i ) {
if ( !poly->outerBoundary().contains( innerRing.at(i) ) ) {
return false;
}
}
}
return true;
}
void AreaAnnotation::setupRegionsLists( GeoPainter *painter )
{
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
// Add the outer boundary nodes.
QVector<GeoDataCoordinates>::ConstIterator itBegin = outerRing.begin();
QVector<GeoDataCoordinates>::ConstIterator itEnd = outerRing.end();
for ( ; itBegin != itEnd; ++itBegin ) {
PolygonNode newNode = PolygonNode( painter->regionFromEllipse( *itBegin, regularDim, regularDim ) );
m_outerNodesList.append( newNode );
}
// Add the outer boundary to the boundaries list.
m_boundariesList.append( painter->regionFromPolygon( outerRing, Qt::OddEvenFill ) );
}
void AreaAnnotation::updateRegions( GeoPainter *painter )
{
if ( m_busy ) {
return;
}
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
const QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
// Update the PolygonNodes lists after the animation has finished its execution.
int ff = m_firstMergedNode.first;
int fs = m_firstMergedNode.second;
int sf = m_secondMergedNode.first;
int ss = m_secondMergedNode.second;
if ( ff != -1 && fs == -1 && sf != -1 && ss == -1 ) {
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
// Remove the merging node flag and add the NodeIsSelected flag if either one of the
// merged nodes had been selected before merging them.
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_outerNodesList.at(ff).isSelected() ) {
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsSelected );
}
m_outerNodesList.removeAt( ff );
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
} else if ( ff != -1 && fs != -1 && sf != -1 && ss != -1 ) {
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_innerNodesList.at(ff).at(fs).isSelected() ) {
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsSelected );
}
m_innerNodesList[sf].removeAt( fs );
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
}
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
// Create and update virtual nodes lists when being in the AddingPolgonNodes state, to
// avoid overhead in other states.
m_outerVirtualNodes.clear();
QRegion firstRegion( painter->regionFromEllipse( outerRing.at(0).interpolate(
outerRing.last(), 0.5 ), hoveredDim, hoveredDim ) );
m_outerVirtualNodes.append( PolygonNode( firstRegion ) );
for ( int i = 0; i < outerRing.size() - 1; ++i ) {
QRegion newRegion( painter->regionFromEllipse( outerRing.at(i).interpolate(
outerRing.at(i+1), 0.5 ), hoveredDim, hoveredDim ) );
m_outerVirtualNodes.append( PolygonNode( newRegion ) );
}
m_innerVirtualNodes.clear();
for ( int i = 0; i < innerRings.size(); ++i ) {
m_innerVirtualNodes.append( QList<PolygonNode>() );
QRegion firstRegion( painter->regionFromEllipse( innerRings.at(i).at(0).interpolate(
innerRings.at(i).last(), 0.5 ), hoveredDim, hoveredDim ) );
m_innerVirtualNodes[i].append( PolygonNode( firstRegion ) );
for ( int j = 0; j < innerRings.at(i).size() - 1; ++j ) {
QRegion newRegion( painter->regionFromEllipse( innerRings.at(i).at(j).interpolate(
innerRings.at(i).at(j+1), 0.5 ), hoveredDim, hoveredDim ) );
m_innerVirtualNodes[i].append( PolygonNode( newRegion ) );
}
}
}
// Update the boundaries list.
m_boundariesList.clear();
m_boundariesList.append( m_geopainter->regionFromPolygon( outerRing, Qt::OddEvenFill ) );
foreach ( const GeoDataLinearRing &ring, innerRings ) {
m_boundariesList.append( m_geopainter->regionFromPolygon( ring, Qt::OddEvenFill ) );
}
// Update the outer and inner nodes lists.
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
QRegion newRegion;
if ( m_outerNodesList.at(i).isSelected() ) {
newRegion = painter->regionFromEllipse( outerRing.at(i),
selectedDim, selectedDim );
} else {
newRegion = painter->regionFromEllipse( outerRing.at(i),
regularDim, regularDim );
}
m_outerNodesList[i].setRegion( newRegion );
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
QRegion newRegion;
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
newRegion = painter->regionFromEllipse( innerRings.at(i).at(j),
selectedDim, selectedDim );
} else {
newRegion = painter->regionFromEllipse( innerRings.at(i).at(j),
regularDim, regularDim );
}
m_innerNodesList[i][j].setRegion( newRegion );
}
}
}
void AreaAnnotation::drawNodes( GeoPainter *painter )
{
// These are the 'real' dimensions of the drawn nodes. The ones which have class scope are used
// to generate the regions and they are a little bit larger, because, for example, it would be
// a little bit too hard to select nodes.
static const int d_regularDim = 10;
static const int d_selectedDim = 10;
static const int d_mergedDim = 20;
static const int d_hoveredDim = 20;
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
const QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
for ( int i = 0; i < outerRing.size(); ++i ) {
// The order here is important, because a merged node can be at the same time selected.
if ( m_outerNodesList.at(i).isBeingMerged() ) {
painter->setBrush( mergedColor );
painter->drawEllipse( outerRing.at(i), d_mergedDim, d_mergedDim );
} else if ( m_outerNodesList.at(i).isSelected() ) {
painter->setBrush( selectedColor );
painter->drawEllipse( outerRing.at(i), d_selectedDim, d_selectedDim );
if ( m_outerNodesList.at(i).isEditingHighlighted() ||
m_outerNodesList.at(i).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_outerNodesList.at(i).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( outerRing.at(i), d_selectedDim + 2, d_selectedDim + 2 );
painter->setPen( defaultPen );
}
} else {
painter->setBrush( regularColor );
painter->drawEllipse( outerRing.at(i), d_regularDim, d_regularDim );
if ( m_outerNodesList.at(i).isEditingHighlighted() ||
m_outerNodesList.at(i).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_outerNodesList.at(i).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setPen( newPen );
painter->setBrush( Qt::NoBrush );
painter->drawEllipse( outerRing.at(i), d_regularDim + 2, d_regularDim + 2 );
painter->setPen( defaultPen );
}
}
}
for ( int i = 0; i < innerRings.size(); ++i ) {
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isBeingMerged() ) {
painter->setBrush( mergedColor );
painter->drawEllipse( innerRings.at(i).at(j), d_mergedDim, d_mergedDim );
} else if ( m_innerNodesList.at(i).at(j).isSelected() ) {
painter->setBrush( selectedColor );
painter->drawEllipse( innerRings.at(i).at(j), d_selectedDim, d_selectedDim );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ||
m_innerNodesList.at(i).at(j).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( innerRings.at(i).at(j), d_selectedDim + 2, d_selectedDim + 2 );
painter->setPen( defaultPen );
}
} else if ( m_innerNodesList.at(i).at(j).isInnerTmp() ) {
// Do not draw inner nodes until the 'process' of adding these nodes ends
// (aka while being in the 'Adding Polygon Hole').
continue;
} else {
painter->setBrush( regularColor );
painter->drawEllipse( innerRings.at(i).at(j), d_regularDim, d_regularDim );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ||
m_innerNodesList.at(i).at(j).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( innerRings.at(i).at(j), d_regularDim + 2, d_regularDim + 2 );
painter->setPen( defaultPen );
}
}
}
}
if ( m_virtualHovered != QPair<int, int>( -1, -1 ) ) {
int i = m_virtualHovered.first;
int j = m_virtualHovered.second;
painter->setBrush( hoveredColor );
if ( i != -1 && j == -1 ) {
GeoDataCoordinates newCoords;
if ( i ) {
newCoords = outerRing.at(i).interpolate( outerRing.at(i - 1), 0.5 );
} else {
newCoords = outerRing.at(0).interpolate( outerRing.last(), 0.5 );
}
painter->drawEllipse( newCoords, d_hoveredDim, d_hoveredDim );
} else {
Q_ASSERT( i != -1 && j != -1 );
GeoDataCoordinates newCoords;
if ( j ) {
newCoords = innerRings.at(i).at(j).interpolate( innerRings.at(i).at(j - 1), 0.5 );
} else {
newCoords = innerRings.at(i).at(0).interpolate( innerRings.at(i).last(), 0.5 );
}
painter->drawEllipse( newCoords, d_hoveredDim, d_hoveredDim );
}
}
}
int AreaAnnotation::outerNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
if ( m_outerNodesList.at(i).containsPoint( point ) ) {
return i;
}
}
return -1;
}
QPair<int, int> AreaAnnotation::innerNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).containsPoint( point ) ) {
return QPair<int, int>( i, j );
}
}
}
return QPair<int, int>( -1, -1 );
}
QPair<int, int> AreaAnnotation::virtualNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_outerVirtualNodes.size(); ++i ) {
if ( m_outerVirtualNodes.at(i).containsPoint( point ) ) {
return QPair<int, int>( i, -1 );
}
}
for ( int i = 0; i < m_innerVirtualNodes.size(); ++i ) {
for ( int j = 0; j < m_innerVirtualNodes.at(i).size(); ++j ) {
if ( m_innerVirtualNodes.at(i).at(j).containsPoint( point ) ) {
return QPair<int, int>( i, j );
}
}
}
return QPair<int, int>( -1, -1 );
}
int AreaAnnotation::innerBoundsContain( const QPoint &point ) const
{
// There are no inner boundaries.
if ( m_boundariesList.size() == 1 ) {
return -1;
}
// Starting from 1 because on index 0 is stored the region representing the whole polygon.
for ( int i = 1; i < m_boundariesList.size(); ++i ) {
if ( m_boundariesList.at(i).contains( point ) ) {
return i;
}
}
return -1;
}
bool AreaAnnotation::polygonContains( const QPoint &point ) const
{
return m_boundariesList.at(0).contains( point ) && innerBoundsContain( point ) == -1;
}
bool AreaAnnotation::processEditingOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton && mouseEvent->button() != Qt::RightButton ) {
return false;
}
qreal lat, lon;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
m_movedPointCoords.set( lon, lat );
// First check if one of the nodes from outer boundary has been clicked.
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 ) {
m_clickedNodeIndexes = QPair<int, int>( outerIndex, -1 );
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowNodeRmbMenu );
} else {
m_interactingObj = InteractingNode;
}
return true;
}
// Then check if one of the nodes which form an inner boundary has been clicked.
QPair<int, int> innerIndexes = innerNodeContains( mouseEvent->pos() );
if ( innerIndexes.first != -1 && innerIndexes.second != -1 ) {
m_clickedNodeIndexes = innerIndexes;
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowNodeRmbMenu );
} else {
m_interactingObj = InteractingNode;
}
return true;
}
// If neither outer boundary nodes nor inner boundary nodes contain the event position,
// then check if the interior of the polygon (excepting its 'holes') contains this point.
if ( polygonContains( mouseEvent->pos() ) ) {
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowPolygonRmbMenu );
} else {
m_interactingObj = InteractingPolygon;
}
return true;
}
return false;
}
bool AreaAnnotation::processEditingOnMove( QMouseEvent *mouseEvent )
{
if ( !m_viewport || !m_geopainter ) {
return false;
}
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
if ( m_interactingObj == InteractingNode ) {
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( j == -1 ) {
outerRing[i] = newCoords;
} else {
Q_ASSERT( i != -1 && j != -1 );
innerRings[i].at(j) = newCoords;
}
return true;
} else if ( m_interactingObj == InteractingPolygon ) {
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> innerRings = polygon->innerBoundaries();
const qreal bearing = m_movedPointCoords.bearing( newCoords );
const qreal distance = distanceSphere( newCoords, m_movedPointCoords );
polygon->outerBoundary().clear();
polygon->innerBoundaries().clear();
for ( int i = 0; i < outerRing.size(); ++i ) {
GeoDataCoordinates movedPoint = outerRing.at(i).moveByBearing( bearing, distance );
qreal lon = movedPoint.longitude();
qreal lat = movedPoint.latitude();
GeoDataCoordinates::normalizeLonLat( lon, lat );
movedPoint.setLongitude( lon );
movedPoint.setLatitude( lat );
polygon->outerBoundary().append( movedPoint );
}
for ( int i = 0; i < innerRings.size(); ++i ) {
GeoDataLinearRing newRing( Tessellate );
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
GeoDataCoordinates movedPoint = innerRings.at(i).at(j).moveByBearing( bearing, distance );
qreal lon = movedPoint.longitude();
qreal lat = movedPoint.latitude();
GeoDataCoordinates::normalizeLonLat( lon, lat );
movedPoint.setLongitude( lon );
movedPoint.setLatitude( lat );
newRing.append( movedPoint );
}
polygon->innerBoundaries().append( newRing );
}
m_movedPointCoords = newCoords;
return true;
} else if ( m_interactingObj == InteractingNothing ) {
return dealWithHovering( mouseEvent );
}
return false;
}
bool AreaAnnotation::processEditingOnRelease( QMouseEvent *mouseEvent )
{
static const int mouseMoveOffset = 1;
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
if ( m_interactingObj == InteractingNode ) {
qreal x, y;
m_viewport->screenCoordinates( m_movedPointCoords.longitude(),
m_movedPointCoords.latitude(),
x, y );
// The node gets selected only if it is clicked and not moved.
if ( qFabs(mouseEvent->pos().x() - x) > mouseMoveOffset ||
qFabs(mouseEvent->pos().y() - y) > mouseMoveOffset ) {
m_interactingObj = InteractingNothing;
return true;
}
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected,
!m_outerNodesList[i].isSelected() );
} else {
m_innerNodesList[i][j].setFlag ( PolygonNode::NodeIsSelected,
!m_innerNodesList.at(i).at(j).isSelected() );
}
m_interactingObj = InteractingNothing;
return true;
} else if ( m_interactingObj == InteractingPolygon ) {
// Nothing special happens at polygon release.
m_interactingObj = InteractingNothing;
return true;
}
return false;
}
bool AreaAnnotation::processAddingHoleOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
QVector<GeoDataLinearRing> &innerBounds = polygon->innerBoundaries();
// Check if this is the first node which is being added as a new polygon inner boundary.
if ( !innerBounds.size() || !m_innerNodesList.last().last().isInnerTmp() ) {
polygon->innerBoundaries().append( GeoDataLinearRing( Tessellate ) );
m_innerNodesList.append( QList<PolygonNode>() );
}
innerBounds.last().append( newCoords );
m_innerNodesList.last().append( PolygonNode( QRegion(), PolygonNode::NodeIsInnerTmp ) );
return true;
}
bool AreaAnnotation::processAddingHoleOnMove( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processAddingHoleOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processMergingOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
int outerIndex = outerNodeContains( mouseEvent->pos() );
// If the selected node is an outer boundary node.
if ( outerIndex != -1 ) {
// If this is the first node selected to be merged.
if ( m_firstMergedNode.first == -1 && m_firstMergedNode.second == -1 ) {
m_firstMergedNode = QPair<int, int>( outerIndex, -1 );
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged );
// If the first selected node was an inner boundary node, raise the request for showing
// warning.
} else if ( m_firstMergedNode.first != -1 && m_firstMergedNode.second != -1 ) {
setRequest( SceneGraphicsItem::OuterInnerMergingWarning );
m_innerNodesList[m_firstMergedNode.first][m_firstMergedNode.second].setFlag(
PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 ) {
// We can be sure that the hovered node is an outer node.
Q_ASSERT( m_hoveredNode.second == -1 );
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
} else {
Q_ASSERT( m_firstMergedNode.first != -1 && m_firstMergedNode.second == -1 );
// Clicking two times the same node results in unmarking it for merging.
if ( m_firstMergedNode.first == outerIndex ) {
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged, false );
m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// If two nodes which form a triangle are merged, the whole triangle should be
// destroyed.
if ( outerRing.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return true;
}
outerRing[outerIndex] = outerRing.at(m_firstMergedNode.first).interpolate( outerRing.at(outerIndex),
0.5 );
outerRing.remove( m_firstMergedNode.first );
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
m_outerNodesList[m_firstMergedNode.first].setFlag( PolygonNode::NodeIsMerged, false );
// Remove highlight effect before showing warning
if ( m_hoveredNode.first != -1 ) {
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
setRequest( SceneGraphicsItem::InvalidShapeWarning );
return true;
}
// Do not modify it here. The animation has access to the object. It will modify the polygon.
polygon->outerBoundary() = initialOuterRing;
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged );
m_secondMergedNode = QPair<int, int>( outerIndex, -1 );
delete m_animation;
m_animation = new MergingNodesAnimation( this );
setRequest( SceneGraphicsItem::StartAnimation );
}
return true;
}
// If the selected node is an inner boundary node.
QPair<int, int> innerIndexes = innerNodeContains( mouseEvent->pos() );
if ( innerIndexes.first != -1 && innerIndexes.second != -1 ) {
int i = m_firstMergedNode.first;
int j = m_firstMergedNode.second;
// If this is the first selected node.
if ( i == -1 && j == -1 ) {
m_firstMergedNode = innerIndexes;
m_innerNodesList[innerIndexes.first][innerIndexes.second].setFlag( PolygonNode::NodeIsMerged );
// If the first selected node has been an outer boundary one, raise the request for showing warning.
} else if ( i != -1 && j == -1 ) {
setRequest( SceneGraphicsItem::OuterInnerMergingWarning );
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 ) {
// We can now be sure that the highlighted node is a node from polygon's outer boundary
Q_ASSERT( m_hoveredNode.second != -1 );
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_firstMergedNode = QPair<int, int>( -1, -1 );
} else {
Q_ASSERT( i != -1 && j != -1 );
if ( i != innerIndexes.first ) {
setRequest( SceneGraphicsItem::InnerInnerMergingWarning );
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 && m_hoveredNode.second != -1 ) {
m_innerNodesList[m_hoveredNode.first][m_hoveredNode.second].setFlag(
PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// Clicking two times the same node results in unmarking it for merging.
if ( m_firstMergedNode == innerIndexes ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// If two nodes which form an inner boundary of a polygon with a size smaller than
// 3 are merged, remove the whole inner boundary.
if ( innerRings.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
m_firstMergedNode = m_secondMergedNode = m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
m_innerNodesList[innerIndexes.first][innerIndexes.second].setFlag( PolygonNode::NodeIsMerged );
m_secondMergedNode = innerIndexes;
m_animation = new MergingNodesAnimation( this );
setRequest( SceneGraphicsItem::StartAnimation );
}
return true;
}
return false;
}
bool AreaAnnotation::processMergingOnMove( QMouseEvent *mouseEvent )
{
return dealWithHovering( mouseEvent );
}
bool AreaAnnotation::processMergingOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processAddingNodesOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If a virtual node has just been clicked, add it to the polygon's outer boundary
// and start 'adjusting' its position.
QPair<int, int> index = virtualNodeContains( mouseEvent->pos() );
if ( index != QPair<int, int>( -1, -1 ) && m_adjustedNode == -2 ) {
Q_ASSERT( m_virtualHovered == index );
int i = index.first;
int j = index.second;
if ( i != -1 && j == -1 ) {
GeoDataLinearRing newRing( Tessellate );
QList<PolygonNode> newList;
for ( int k = i; k < i + outerRing.size(); ++k ) {
newRing.append( outerRing.at(k % outerRing.size()) );
newList.append( PolygonNode( QRegion(), m_outerNodesList.at(k % outerRing.size()).flags() ) );
}
GeoDataCoordinates newCoords = newRing.at(0).interpolate( newRing.last(), 0.5 );
newRing.append( newCoords );
m_outerNodesList = newList;
m_outerNodesList.append( PolygonNode( QRegion() ) );
polygon->outerBoundary() = newRing;
m_adjustedNode = -1;
} else {
Q_ASSERT( i != -1 && j != -1 );
GeoDataLinearRing newRing( Tessellate );
QList<PolygonNode> newList;
for ( int k = j; k < j + innerRings.at(i).size(); ++k ) {
newRing.append( innerRings.at(i).at(k % innerRings.at(i).size()) );
newList.append( PolygonNode( QRegion(),
m_innerNodesList.at(i).at(k % innerRings.at(i).size()).flags() ) );
}
GeoDataCoordinates newCoords = newRing.at(0).interpolate( newRing.last(), 0.5 );
newRing.append( newCoords );
m_innerNodesList[i] = newList;
m_innerNodesList[i].append( PolygonNode( QRegion() ) );
polygon->innerBoundaries()[i] = newRing;
m_adjustedNode = i;
}
m_virtualHovered = QPair<int, int>( -1, -1 );
return true;
}
// If a virtual node which has been previously clicked and selected to become a
// 'real node' is clicked one more time, it stops from being 'adjusted'.
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 && m_adjustedNode != -2 ) {
m_adjustedNode = -2;
return true;
}
QPair<int,int> innerIndex = innerNodeContains( mouseEvent->pos() );
if ( innerIndex != QPair<int, int>( -1, -1 ) && m_adjustedNode != -2 ) {
m_adjustedNode = -2;
return true;
}
return false;
}
bool AreaAnnotation::processAddingNodesOnMove( QMouseEvent *mouseEvent )
{
Q_ASSERT( mouseEvent->button() == Qt::NoButton );
QPair<int, int> index = virtualNodeContains( mouseEvent->pos() );
// If we are adjusting a virtual node which has just been clicked and became real, just
// change its coordinates when moving it, as we do with nodes in Editing state on move.
if ( m_adjustedNode != -2 ) {
// The virtual node which has just been added is always the last within
// GeoDataLinearRing's container.qreal lon, lat;
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
if ( m_adjustedNode == -1 ) {
polygon->outerBoundary().last() = newCoords;
} else {
Q_ASSERT( m_adjustedNode >= 0 );
polygon->innerBoundaries()[m_adjustedNode].last() = newCoords;
}
return true;
// If we are hovering a virtual node, store its index in order to be painted in drawNodes
// method.
} else if ( index != QPair<int, int>( -1, -1 ) ) {
m_virtualHovered = index;
return true;
}
// This means that the interior of the polygon has been hovered. Let the event propagate
// since there may be overlapping polygons.
return false;
}
bool AreaAnnotation::processAddingNodesOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return m_adjustedNode == -2;
}
bool AreaAnnotation::dealWithHovering( QMouseEvent *mouseEvent )
{
PolygonNode::PolyNodeFlag flag = state() == SceneGraphicsItem::Editing ?
PolygonNode::NodeIsEditingHighlighted :
PolygonNode::NodeIsMergingHighlighted;
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 ) {
if ( !m_outerNodesList.at(outerIndex).isEditingHighlighted() &&
!m_outerNodesList.at(outerIndex).isMergingHighlighted() ) {
// Deal with the case when two nodes are very close to each other.
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( flag, false );
} else {
m_innerNodesList[i][j].setFlag( flag, false );
}
}
m_hoveredNode = QPair<int, int>( outerIndex, -1 );
m_outerNodesList[outerIndex].setFlag( flag );
}
return true;
} else if ( m_hoveredNode != QPair<int, int>( -1, -1 ) && m_hoveredNode.second == -1 ) {
m_outerNodesList[m_hoveredNode.first].setFlag( flag, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
QPair<int, int> innerIndex = innerNodeContains( mouseEvent->pos() );
if ( innerIndex != QPair<int, int>( -1, -1 ) ) {
if ( !m_innerNodesList.at(innerIndex.first).at(innerIndex.second).isEditingHighlighted() &&
!m_innerNodesList.at(innerIndex.first).at(innerIndex.second).isMergingHighlighted()) {
// Deal with the case when two nodes are very close to each other.
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( flag, false );
} else {
m_innerNodesList[i][j].setFlag( flag, false );
}
}
m_hoveredNode = innerIndex;
m_innerNodesList[innerIndex.first][innerIndex.second].setFlag( flag );
}
return true;
} else if ( m_hoveredNode != QPair<int, int>( -1, -1 ) && m_hoveredNode.second != -1 ) {
m_innerNodesList[m_hoveredNode.first][m_hoveredNode.second].setFlag( flag, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
return false;
}
}
Replace m_geopainter with the GeoPainter each
method receives as parameter
//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
// Copyright 2013 Thibaut Gridel <tgridel@free.fr>
// Copyright 2014 Calin Cruceru <crucerucalincristian@gmail.com>
//
// Self
#include "AreaAnnotation.h"
// Qt
#include <qmath.h>
#include <QPair>
// Marble
#include "GeoDataPlacemark.h"
#include "GeoDataTypes.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "SceneGraphicsTypes.h"
#include "MarbleMath.h"
#include "MergingNodesAnimation.h"
namespace Marble {
class PolygonNode {
public:
enum PolyNodeFlag {
NoOption = 0x0,
NodeIsSelected = 0x1,
NodeIsInnerTmp = 0x2,
NodeIsMerged = 0x4,
NodeIsEditingHighlighted = 0x8,
NodeIsMergingHighlighted = 0x10
};
Q_DECLARE_FLAGS(PolyNodeFlags, PolyNodeFlag)
explicit PolygonNode( QRegion region, PolyNodeFlags flags = 0 );
~PolygonNode();
bool isSelected() const;
bool isInnerTmp() const;
bool isBeingMerged() const;
bool isEditingHighlighted() const;
bool isMergingHighlighted() const;
PolyNodeFlags flags() const;
void setFlag( PolyNodeFlag flag, bool enabled = true );
void setFlags( PolyNodeFlags flags );
void setRegion( QRegion newRegion );
bool containsPoint( const QPoint &eventPos ) const;
private:
QRegion m_region;
PolyNodeFlags m_flags;
};
PolygonNode::PolygonNode( QRegion region, PolyNodeFlags flags ) :
m_region( region ),
m_flags( flags )
{
// nothing to do
}
PolygonNode::~PolygonNode()
{
// nothing to do
}
bool PolygonNode::isSelected() const
{
return m_flags & NodeIsSelected;
}
bool PolygonNode::isInnerTmp() const
{
return m_flags & NodeIsInnerTmp;
}
bool PolygonNode::isBeingMerged() const
{
return m_flags & NodeIsMerged;
}
bool PolygonNode::isEditingHighlighted() const
{
return m_flags & NodeIsEditingHighlighted;
}
bool PolygonNode::isMergingHighlighted() const
{
return m_flags & NodeIsMergingHighlighted;
}
void PolygonNode::setRegion( QRegion newRegion )
{
m_region = newRegion;
}
PolygonNode::PolyNodeFlags PolygonNode::flags() const
{
return m_flags;
}
void PolygonNode::setFlag( PolyNodeFlag flag, bool enabled )
{
if ( enabled ) {
m_flags |= flag;
} else {
m_flags &= ~flag;
}
}
void PolygonNode::setFlags( PolyNodeFlags flags )
{
m_flags = flags;
}
bool PolygonNode::containsPoint( const QPoint &eventPos ) const
{
return m_region.contains( eventPos );
}
const int AreaAnnotation::regularDim = 15;
const int AreaAnnotation::selectedDim = 15;
const int AreaAnnotation::mergedDim = 20;
const int AreaAnnotation::hoveredDim = 20;
const QColor AreaAnnotation::regularColor = Oxygen::aluminumGray3;
const QColor AreaAnnotation::selectedColor = Oxygen::aluminumGray6;
const QColor AreaAnnotation::mergedColor = Oxygen::emeraldGreen6;
const QColor AreaAnnotation::hoveredColor = Oxygen::grapeViolet6;
AreaAnnotation::AreaAnnotation( GeoDataPlacemark *placemark ) :
SceneGraphicsItem( placemark ),
m_viewport( 0 ),
m_regionsInitialized( false ),
m_busy( false ),
m_hoveredNode( -1, -1 ),
m_interactingObj( InteractingNothing ),
m_virtualHovered( -1, -1 )
{
// nothing to do
}
AreaAnnotation::~AreaAnnotation()
{
delete m_animation;
}
void AreaAnnotation::paint( GeoPainter *painter, const ViewportParams *viewport )
{
m_viewport = viewport;
Q_ASSERT( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType );
painter->save();
if ( !m_regionsInitialized ) {
setupRegionsLists( painter );
m_regionsInitialized = true;
} else {
updateRegions( painter );
}
drawNodes( painter );
painter->restore();
}
bool AreaAnnotation::containsPoint( const QPoint &point ) const
{
if ( state() == SceneGraphicsItem::Editing ) {
return outerNodeContains( point ) != -1 || polygonContains( point ) ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return polygonContains( point ) && outerNodeContains( point ) == -1 &&
innerNodeContains( point ) == QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return outerNodeContains( point ) != -1 ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return virtualNodeContains( point ) != QPair<int, int>( -1, -1 ) ||
innerNodeContains( point ) != QPair<int, int>( -1, -1 ) ||
outerNodeContains( point ) != -1 ||
polygonContains( point );
}
return false;
}
void AreaAnnotation::dealWithItemChange( const SceneGraphicsItem *other )
{
Q_UNUSED( other );
// So far we only deal with item changes when hovering virtual nodes, so that
// they do not remain hovered when changing the item we interact with.
if ( state() == SceneGraphicsItem::Editing ) {
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsEditingHighlighted, false );
} else {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsEditingHighlighted, false );
}
}
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
} else {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
}
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
m_virtualHovered = QPair<int, int>( -1, -1 );
}
}
void AreaAnnotation::setBusy( bool enabled )
{
m_busy = enabled;
if ( !enabled ) {
if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
}
delete m_animation;
}
}
void AreaAnnotation::deselectAllNodes()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
for ( int i = 0 ; i < m_outerNodesList.size(); ++i ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected, false );
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsSelected, false );
}
}
}
void AreaAnnotation::deleteAllSelectedNodes()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If it proves inefficient, try something different.
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> initialInnerRings = polygon->innerBoundaries();
QList<PolygonNode> initialOuterNodes = m_outerNodesList;
QList< QList<PolygonNode> > initialInnerNodes = m_innerNodesList;
for ( int i = 0; i < outerRing.size(); ++i ) {
if ( m_outerNodesList.at(i).isSelected() ) {
if ( m_outerNodesList.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return;
}
m_outerNodesList.removeAt( i );
outerRing.remove( i );
--i;
}
}
for ( int i = 0; i < innerRings.size(); ++i ) {
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
if ( m_innerNodesList.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
--i;
break;
}
innerRings[i].remove( j );
m_innerNodesList[i].removeAt( j );
--j;
}
}
}
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
polygon->innerBoundaries() = initialInnerRings;
m_outerNodesList = initialOuterNodes;
m_innerNodesList = initialInnerNodes;
setRequest( SceneGraphicsItem::InvalidShapeWarning );
}
}
void AreaAnnotation::deleteClickedNode()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If it proves inefficient, try something different.
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> initialInnerRings = polygon->innerBoundaries();
QList<PolygonNode> initialOuterNodes = m_outerNodesList;
QList< QList<PolygonNode> > initialInnerNodes = m_innerNodesList;
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
m_hoveredNode = QPair<int, int>( -1, -1 );
if ( i != -1 && j == -1 ) {
if ( m_outerNodesList.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return;
}
outerRing.remove( i );
m_outerNodesList.removeAt( i );
} else if ( i != -1 && j != -1 ) {
if ( m_innerNodesList.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
return;
}
innerRings[i].remove( j );
m_innerNodesList[i].removeAt( j );
}
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
polygon->innerBoundaries() = initialInnerRings;
m_outerNodesList = initialOuterNodes;
m_innerNodesList = initialInnerNodes;
setRequest( SceneGraphicsItem::InvalidShapeWarning );
}
}
void AreaAnnotation::changeClickedNodeSelection()
{
if ( state() != SceneGraphicsItem::Editing ) {
return;
}
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( i != -1 && j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected,
!m_outerNodesList.at(i).isSelected() );
} else if ( i != -1 && j != -1 ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsSelected,
!m_innerNodesList.at(i).at(j).isSelected() );
}
}
bool AreaAnnotation::hasNodesSelected() const
{
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
if ( m_outerNodesList.at(i).isSelected() ) {
return true;
}
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
return true;
}
}
}
return false;
}
bool AreaAnnotation::clickedNodeIsSelected() const
{
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
return ( i != -1 && j == -1 && m_outerNodesList.at(i).isSelected() ) ||
( i != -1 && j != -1 && m_innerNodesList.at(i).at(j).isSelected() );
}
QPointer<MergingNodesAnimation> AreaAnnotation::animation()
{
return m_animation;
}
bool AreaAnnotation::mousePressEvent( QMouseEvent *event )
{
if ( !m_viewport || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnPress( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnPress( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnPress( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnPress( event );
}
return false;
}
bool AreaAnnotation::mouseMoveEvent( QMouseEvent *event )
{
if ( !m_viewport || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnMove( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnMove( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnMove( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnMove( event );
}
return false;
}
bool AreaAnnotation::mouseReleaseEvent( QMouseEvent *event )
{
if ( !m_viewport || m_busy ) {
return false;
}
setRequest( SceneGraphicsItem::NoRequest );
if ( state() == SceneGraphicsItem::Editing ) {
return processEditingOnRelease( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
return processAddingHoleOnRelease( event );
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
return processMergingOnRelease( event );
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
return processAddingNodesOnRelease( event );
}
return false;
}
void AreaAnnotation::dealWithStateChange( SceneGraphicsItem::ActionState previousState )
{
// Dealing with cases when exiting a state has an effect on this item.
if ( previousState == SceneGraphicsItem::Editing ) {
m_clickedNodeIndexes = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( previousState == SceneGraphicsItem::AddingPolygonHole ) {
// Check if a polygon hole was being drawn before changing state.
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
QVector<GeoDataLinearRing> &innerBounds = polygon->innerBoundaries();
if ( innerBounds.size() && innerBounds.last().size() &&
m_innerNodesList.last().last().isInnerTmp() ) {
// If only two nodes were added, remove this inner boundary entirely.
if ( innerBounds.last().size() <= 2 ) {
innerBounds.remove( innerBounds.size() - 1 );
m_innerNodesList.removeLast();
return;
}
// Remove the 'NodeIsInnerTmp' flag, to allow ::draw method to paint the nodes.
for ( int i = 0; i < m_innerNodesList.last().size(); ++i ) {
m_innerNodesList.last()[i].setFlag( PolygonNode::NodeIsInnerTmp, false );
}
}
} else if ( previousState == SceneGraphicsItem::MergingPolygonNodes ) {
// If there was only a node selected for being merged and the state changed,
// deselect it.
int i = m_firstMergedNode.first;
int j = m_firstMergedNode.second;
if ( i != -1 && j != -1 ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
} else if ( i != -1 && j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMerged, false );
}
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
delete m_animation;
} else if ( previousState == SceneGraphicsItem::AddingPolygonNodes ) {
m_outerVirtualNodes.clear();
m_innerVirtualNodes.clear();
m_virtualHovered = QPair<int, int>( -1, -1 );
m_adjustedNode = -2;
}
// Dealing with cases when entering a state has an effect on this item, or
// initializations are needed.
if ( state() == SceneGraphicsItem::Editing ) {
m_interactingObj = InteractingNothing;
m_clickedNodeIndexes = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
} else if ( state() == SceneGraphicsItem::AddingPolygonHole ) {
// Nothing to do so far when entering this state.
} else if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
m_hoveredNode = QPair<int, int>( -1, -1 );
m_animation = 0;
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
m_virtualHovered = QPair<int, int>( -1, -1 );
m_adjustedNode = -2;
}
}
const char *AreaAnnotation::graphicType() const
{
return SceneGraphicsTypes::SceneGraphicAreaAnnotation;
}
bool AreaAnnotation::isValidPolygon() const
{
const GeoDataPolygon *poly = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const QVector<GeoDataLinearRing> &innerRings = poly->innerBoundaries();
foreach ( const GeoDataLinearRing &innerRing, innerRings ) {
for ( int i = 0; i < innerRing.size(); ++i ) {
if ( !poly->outerBoundary().contains( innerRing.at(i) ) ) {
return false;
}
}
}
return true;
}
void AreaAnnotation::setupRegionsLists( GeoPainter *painter )
{
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
// Add the outer boundary nodes.
QVector<GeoDataCoordinates>::ConstIterator itBegin = outerRing.begin();
QVector<GeoDataCoordinates>::ConstIterator itEnd = outerRing.end();
for ( ; itBegin != itEnd; ++itBegin ) {
PolygonNode newNode = PolygonNode( painter->regionFromEllipse( *itBegin, regularDim, regularDim ) );
m_outerNodesList.append( newNode );
}
// Add the outer boundary to the boundaries list.
m_boundariesList.append( painter->regionFromPolygon( outerRing, Qt::OddEvenFill ) );
}
void AreaAnnotation::updateRegions( GeoPainter *painter )
{
if ( m_busy ) {
return;
}
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
const QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
if ( state() == SceneGraphicsItem::MergingPolygonNodes ) {
// Update the PolygonNodes lists after the animation has finished its execution.
int ff = m_firstMergedNode.first;
int fs = m_firstMergedNode.second;
int sf = m_secondMergedNode.first;
int ss = m_secondMergedNode.second;
if ( ff != -1 && fs == -1 && sf != -1 && ss == -1 ) {
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
// Remove the merging node flag and add the NodeIsSelected flag if either one of the
// merged nodes had been selected before merging them.
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_outerNodesList.at(ff).isSelected() ) {
m_outerNodesList[sf].setFlag( PolygonNode::NodeIsSelected );
}
m_outerNodesList.removeAt( ff );
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
} else if ( ff != -1 && fs != -1 && sf != -1 && ss != -1 ) {
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_innerNodesList.at(ff).at(fs).isSelected() ) {
m_innerNodesList[sf][ss].setFlag( PolygonNode::NodeIsSelected );
}
m_innerNodesList[sf].removeAt( fs );
m_firstMergedNode = QPair<int, int>( -1, -1 );
m_secondMergedNode = QPair<int, int>( -1, -1 );
}
} else if ( state() == SceneGraphicsItem::AddingPolygonNodes ) {
// Create and update virtual nodes lists when being in the AddingPolgonNodes state, to
// avoid overhead in other states.
m_outerVirtualNodes.clear();
QRegion firstRegion( painter->regionFromEllipse( outerRing.at(0).interpolate(
outerRing.last(), 0.5 ), hoveredDim, hoveredDim ) );
m_outerVirtualNodes.append( PolygonNode( firstRegion ) );
for ( int i = 0; i < outerRing.size() - 1; ++i ) {
QRegion newRegion( painter->regionFromEllipse( outerRing.at(i).interpolate(
outerRing.at(i+1), 0.5 ), hoveredDim, hoveredDim ) );
m_outerVirtualNodes.append( PolygonNode( newRegion ) );
}
m_innerVirtualNodes.clear();
for ( int i = 0; i < innerRings.size(); ++i ) {
m_innerVirtualNodes.append( QList<PolygonNode>() );
QRegion firstRegion( painter->regionFromEllipse( innerRings.at(i).at(0).interpolate(
innerRings.at(i).last(), 0.5 ), hoveredDim, hoveredDim ) );
m_innerVirtualNodes[i].append( PolygonNode( firstRegion ) );
for ( int j = 0; j < innerRings.at(i).size() - 1; ++j ) {
QRegion newRegion( painter->regionFromEllipse( innerRings.at(i).at(j).interpolate(
innerRings.at(i).at(j+1), 0.5 ), hoveredDim, hoveredDim ) );
m_innerVirtualNodes[i].append( PolygonNode( newRegion ) );
}
}
}
// Update the boundaries list.
m_boundariesList.clear();
m_boundariesList.append( painter->regionFromPolygon( outerRing, Qt::OddEvenFill ) );
foreach ( const GeoDataLinearRing &ring, innerRings ) {
m_boundariesList.append( painter->regionFromPolygon( ring, Qt::OddEvenFill ) );
}
// Update the outer and inner nodes lists.
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
QRegion newRegion;
if ( m_outerNodesList.at(i).isSelected() ) {
newRegion = painter->regionFromEllipse( outerRing.at(i),
selectedDim, selectedDim );
} else {
newRegion = painter->regionFromEllipse( outerRing.at(i),
regularDim, regularDim );
}
m_outerNodesList[i].setRegion( newRegion );
}
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
QRegion newRegion;
if ( m_innerNodesList.at(i).at(j).isSelected() ) {
newRegion = painter->regionFromEllipse( innerRings.at(i).at(j),
selectedDim, selectedDim );
} else {
newRegion = painter->regionFromEllipse( innerRings.at(i).at(j),
regularDim, regularDim );
}
m_innerNodesList[i][j].setRegion( newRegion );
}
}
}
void AreaAnnotation::drawNodes( GeoPainter *painter )
{
// These are the 'real' dimensions of the drawn nodes. The ones which have class scope are used
// to generate the regions and they are a little bit larger, because, for example, it would be
// a little bit too hard to select nodes.
static const int d_regularDim = 10;
static const int d_selectedDim = 10;
static const int d_mergedDim = 20;
static const int d_hoveredDim = 20;
const GeoDataPolygon *polygon = static_cast<const GeoDataPolygon*>( placemark()->geometry() );
const GeoDataLinearRing &outerRing = polygon->outerBoundary();
const QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
for ( int i = 0; i < outerRing.size(); ++i ) {
// The order here is important, because a merged node can be at the same time selected.
if ( m_outerNodesList.at(i).isBeingMerged() ) {
painter->setBrush( mergedColor );
painter->drawEllipse( outerRing.at(i), d_mergedDim, d_mergedDim );
} else if ( m_outerNodesList.at(i).isSelected() ) {
painter->setBrush( selectedColor );
painter->drawEllipse( outerRing.at(i), d_selectedDim, d_selectedDim );
if ( m_outerNodesList.at(i).isEditingHighlighted() ||
m_outerNodesList.at(i).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_outerNodesList.at(i).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( outerRing.at(i), d_selectedDim + 2, d_selectedDim + 2 );
painter->setPen( defaultPen );
}
} else {
painter->setBrush( regularColor );
painter->drawEllipse( outerRing.at(i), d_regularDim, d_regularDim );
if ( m_outerNodesList.at(i).isEditingHighlighted() ||
m_outerNodesList.at(i).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_outerNodesList.at(i).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setPen( newPen );
painter->setBrush( Qt::NoBrush );
painter->drawEllipse( outerRing.at(i), d_regularDim + 2, d_regularDim + 2 );
painter->setPen( defaultPen );
}
}
}
for ( int i = 0; i < innerRings.size(); ++i ) {
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).isBeingMerged() ) {
painter->setBrush( mergedColor );
painter->drawEllipse( innerRings.at(i).at(j), d_mergedDim, d_mergedDim );
} else if ( m_innerNodesList.at(i).at(j).isSelected() ) {
painter->setBrush( selectedColor );
painter->drawEllipse( innerRings.at(i).at(j), d_selectedDim, d_selectedDim );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ||
m_innerNodesList.at(i).at(j).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( innerRings.at(i).at(j), d_selectedDim + 2, d_selectedDim + 2 );
painter->setPen( defaultPen );
}
} else if ( m_innerNodesList.at(i).at(j).isInnerTmp() ) {
// Do not draw inner nodes until the 'process' of adding these nodes ends
// (aka while being in the 'Adding Polygon Hole').
continue;
} else {
painter->setBrush( regularColor );
painter->drawEllipse( innerRings.at(i).at(j), d_regularDim, d_regularDim );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ||
m_innerNodesList.at(i).at(j).isMergingHighlighted() ) {
QPen defaultPen = painter->pen();
QPen newPen;
newPen.setWidth( defaultPen.width() + 3 );
if ( m_innerNodesList.at(i).at(j).isEditingHighlighted() ) {
newPen.setColor( QColor( 0, 255, 255, 120 ) );
} else {
newPen.setColor( QColor( 25, 255, 25, 180 ) );
}
painter->setBrush( Qt::NoBrush );
painter->setPen( newPen );
painter->drawEllipse( innerRings.at(i).at(j), d_regularDim + 2, d_regularDim + 2 );
painter->setPen( defaultPen );
}
}
}
}
if ( m_virtualHovered != QPair<int, int>( -1, -1 ) ) {
int i = m_virtualHovered.first;
int j = m_virtualHovered.second;
painter->setBrush( hoveredColor );
if ( i != -1 && j == -1 ) {
GeoDataCoordinates newCoords;
if ( i ) {
newCoords = outerRing.at(i).interpolate( outerRing.at(i - 1), 0.5 );
} else {
newCoords = outerRing.at(0).interpolate( outerRing.last(), 0.5 );
}
painter->drawEllipse( newCoords, d_hoveredDim, d_hoveredDim );
} else {
Q_ASSERT( i != -1 && j != -1 );
GeoDataCoordinates newCoords;
if ( j ) {
newCoords = innerRings.at(i).at(j).interpolate( innerRings.at(i).at(j - 1), 0.5 );
} else {
newCoords = innerRings.at(i).at(0).interpolate( innerRings.at(i).last(), 0.5 );
}
painter->drawEllipse( newCoords, d_hoveredDim, d_hoveredDim );
}
}
}
int AreaAnnotation::outerNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_outerNodesList.size(); ++i ) {
if ( m_outerNodesList.at(i).containsPoint( point ) ) {
return i;
}
}
return -1;
}
QPair<int, int> AreaAnnotation::innerNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_innerNodesList.size(); ++i ) {
for ( int j = 0; j < m_innerNodesList.at(i).size(); ++j ) {
if ( m_innerNodesList.at(i).at(j).containsPoint( point ) ) {
return QPair<int, int>( i, j );
}
}
}
return QPair<int, int>( -1, -1 );
}
QPair<int, int> AreaAnnotation::virtualNodeContains( const QPoint &point ) const
{
for ( int i = 0; i < m_outerVirtualNodes.size(); ++i ) {
if ( m_outerVirtualNodes.at(i).containsPoint( point ) ) {
return QPair<int, int>( i, -1 );
}
}
for ( int i = 0; i < m_innerVirtualNodes.size(); ++i ) {
for ( int j = 0; j < m_innerVirtualNodes.at(i).size(); ++j ) {
if ( m_innerVirtualNodes.at(i).at(j).containsPoint( point ) ) {
return QPair<int, int>( i, j );
}
}
}
return QPair<int, int>( -1, -1 );
}
int AreaAnnotation::innerBoundsContain( const QPoint &point ) const
{
// There are no inner boundaries.
if ( m_boundariesList.size() == 1 ) {
return -1;
}
// Starting from 1 because on index 0 is stored the region representing the whole polygon.
for ( int i = 1; i < m_boundariesList.size(); ++i ) {
if ( m_boundariesList.at(i).contains( point ) ) {
return i;
}
}
return -1;
}
bool AreaAnnotation::polygonContains( const QPoint &point ) const
{
return m_boundariesList.at(0).contains( point ) && innerBoundsContain( point ) == -1;
}
bool AreaAnnotation::processEditingOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton && mouseEvent->button() != Qt::RightButton ) {
return false;
}
qreal lat, lon;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
m_movedPointCoords.set( lon, lat );
// First check if one of the nodes from outer boundary has been clicked.
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 ) {
m_clickedNodeIndexes = QPair<int, int>( outerIndex, -1 );
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowNodeRmbMenu );
} else {
m_interactingObj = InteractingNode;
}
return true;
}
// Then check if one of the nodes which form an inner boundary has been clicked.
QPair<int, int> innerIndexes = innerNodeContains( mouseEvent->pos() );
if ( innerIndexes.first != -1 && innerIndexes.second != -1 ) {
m_clickedNodeIndexes = innerIndexes;
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowNodeRmbMenu );
} else {
m_interactingObj = InteractingNode;
}
return true;
}
// If neither outer boundary nodes nor inner boundary nodes contain the event position,
// then check if the interior of the polygon (excepting its 'holes') contains this point.
if ( polygonContains( mouseEvent->pos() ) ) {
if ( mouseEvent->button() == Qt::RightButton ) {
setRequest( SceneGraphicsItem::ShowPolygonRmbMenu );
} else {
m_interactingObj = InteractingPolygon;
}
return true;
}
return false;
}
bool AreaAnnotation::processEditingOnMove( QMouseEvent *mouseEvent )
{
if ( !m_viewport ) {
return false;
}
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
if ( m_interactingObj == InteractingNode ) {
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( j == -1 ) {
outerRing[i] = newCoords;
} else {
Q_ASSERT( i != -1 && j != -1 );
innerRings[i].at(j) = newCoords;
}
return true;
} else if ( m_interactingObj == InteractingPolygon ) {
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> innerRings = polygon->innerBoundaries();
const qreal bearing = m_movedPointCoords.bearing( newCoords );
const qreal distance = distanceSphere( newCoords, m_movedPointCoords );
polygon->outerBoundary().clear();
polygon->innerBoundaries().clear();
for ( int i = 0; i < outerRing.size(); ++i ) {
GeoDataCoordinates movedPoint = outerRing.at(i).moveByBearing( bearing, distance );
qreal lon = movedPoint.longitude();
qreal lat = movedPoint.latitude();
GeoDataCoordinates::normalizeLonLat( lon, lat );
movedPoint.setLongitude( lon );
movedPoint.setLatitude( lat );
polygon->outerBoundary().append( movedPoint );
}
for ( int i = 0; i < innerRings.size(); ++i ) {
GeoDataLinearRing newRing( Tessellate );
for ( int j = 0; j < innerRings.at(i).size(); ++j ) {
GeoDataCoordinates movedPoint = innerRings.at(i).at(j).moveByBearing( bearing, distance );
qreal lon = movedPoint.longitude();
qreal lat = movedPoint.latitude();
GeoDataCoordinates::normalizeLonLat( lon, lat );
movedPoint.setLongitude( lon );
movedPoint.setLatitude( lat );
newRing.append( movedPoint );
}
polygon->innerBoundaries().append( newRing );
}
m_movedPointCoords = newCoords;
return true;
} else if ( m_interactingObj == InteractingNothing ) {
return dealWithHovering( mouseEvent );
}
return false;
}
bool AreaAnnotation::processEditingOnRelease( QMouseEvent *mouseEvent )
{
static const int mouseMoveOffset = 1;
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
if ( m_interactingObj == InteractingNode ) {
qreal x, y;
m_viewport->screenCoordinates( m_movedPointCoords.longitude(),
m_movedPointCoords.latitude(),
x, y );
// The node gets selected only if it is clicked and not moved.
if ( qFabs(mouseEvent->pos().x() - x) > mouseMoveOffset ||
qFabs(mouseEvent->pos().y() - y) > mouseMoveOffset ) {
m_interactingObj = InteractingNothing;
return true;
}
int i = m_clickedNodeIndexes.first;
int j = m_clickedNodeIndexes.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( PolygonNode::NodeIsSelected,
!m_outerNodesList[i].isSelected() );
} else {
m_innerNodesList[i][j].setFlag ( PolygonNode::NodeIsSelected,
!m_innerNodesList.at(i).at(j).isSelected() );
}
m_interactingObj = InteractingNothing;
return true;
} else if ( m_interactingObj == InteractingPolygon ) {
// Nothing special happens at polygon release.
m_interactingObj = InteractingNothing;
return true;
}
return false;
}
bool AreaAnnotation::processAddingHoleOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
QVector<GeoDataLinearRing> &innerBounds = polygon->innerBoundaries();
// Check if this is the first node which is being added as a new polygon inner boundary.
if ( !innerBounds.size() || !m_innerNodesList.last().last().isInnerTmp() ) {
polygon->innerBoundaries().append( GeoDataLinearRing( Tessellate ) );
m_innerNodesList.append( QList<PolygonNode>() );
}
innerBounds.last().append( newCoords );
m_innerNodesList.last().append( PolygonNode( QRegion(), PolygonNode::NodeIsInnerTmp ) );
return true;
}
bool AreaAnnotation::processAddingHoleOnMove( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processAddingHoleOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processMergingOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing initialOuterRing = polygon->outerBoundary();
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
int outerIndex = outerNodeContains( mouseEvent->pos() );
// If the selected node is an outer boundary node.
if ( outerIndex != -1 ) {
// If this is the first node selected to be merged.
if ( m_firstMergedNode.first == -1 && m_firstMergedNode.second == -1 ) {
m_firstMergedNode = QPair<int, int>( outerIndex, -1 );
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged );
// If the first selected node was an inner boundary node, raise the request for showing
// warning.
} else if ( m_firstMergedNode.first != -1 && m_firstMergedNode.second != -1 ) {
setRequest( SceneGraphicsItem::OuterInnerMergingWarning );
m_innerNodesList[m_firstMergedNode.first][m_firstMergedNode.second].setFlag(
PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 ) {
// We can be sure that the hovered node is an outer node.
Q_ASSERT( m_hoveredNode.second == -1 );
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
} else {
Q_ASSERT( m_firstMergedNode.first != -1 && m_firstMergedNode.second == -1 );
// Clicking two times the same node results in unmarking it for merging.
if ( m_firstMergedNode.first == outerIndex ) {
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged, false );
m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// If two nodes which form a triangle are merged, the whole triangle should be
// destroyed.
if ( outerRing.size() <= 3 ) {
setRequest( SceneGraphicsItem::RemovePolygonRequest );
return true;
}
outerRing[outerIndex] = outerRing.at(m_firstMergedNode.first).interpolate( outerRing.at(outerIndex),
0.5 );
outerRing.remove( m_firstMergedNode.first );
if ( !isValidPolygon() ) {
polygon->outerBoundary() = initialOuterRing;
m_outerNodesList[m_firstMergedNode.first].setFlag( PolygonNode::NodeIsMerged, false );
// Remove highlight effect before showing warning
if ( m_hoveredNode.first != -1 ) {
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
setRequest( SceneGraphicsItem::InvalidShapeWarning );
return true;
}
// Do not modify it here. The animation has access to the object. It will modify the polygon.
polygon->outerBoundary() = initialOuterRing;
m_outerNodesList[outerIndex].setFlag( PolygonNode::NodeIsMerged );
m_secondMergedNode = QPair<int, int>( outerIndex, -1 );
delete m_animation;
m_animation = new MergingNodesAnimation( this );
setRequest( SceneGraphicsItem::StartAnimation );
}
return true;
}
// If the selected node is an inner boundary node.
QPair<int, int> innerIndexes = innerNodeContains( mouseEvent->pos() );
if ( innerIndexes.first != -1 && innerIndexes.second != -1 ) {
int i = m_firstMergedNode.first;
int j = m_firstMergedNode.second;
// If this is the first selected node.
if ( i == -1 && j == -1 ) {
m_firstMergedNode = innerIndexes;
m_innerNodesList[innerIndexes.first][innerIndexes.second].setFlag( PolygonNode::NodeIsMerged );
// If the first selected node has been an outer boundary one, raise the request for showing warning.
} else if ( i != -1 && j == -1 ) {
setRequest( SceneGraphicsItem::OuterInnerMergingWarning );
m_outerNodesList[i].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 ) {
// We can now be sure that the highlighted node is a node from polygon's outer boundary
Q_ASSERT( m_hoveredNode.second != -1 );
m_outerNodesList[m_hoveredNode.first].setFlag( PolygonNode::NodeIsMergingHighlighted, false );
}
m_firstMergedNode = QPair<int, int>( -1, -1 );
} else {
Q_ASSERT( i != -1 && j != -1 );
if ( i != innerIndexes.first ) {
setRequest( SceneGraphicsItem::InnerInnerMergingWarning );
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
if ( m_hoveredNode.first != -1 && m_hoveredNode.second != -1 ) {
m_innerNodesList[m_hoveredNode.first][m_hoveredNode.second].setFlag(
PolygonNode::NodeIsMergingHighlighted, false );
}
m_hoveredNode = m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// Clicking two times the same node results in unmarking it for merging.
if ( m_firstMergedNode == innerIndexes ) {
m_innerNodesList[i][j].setFlag( PolygonNode::NodeIsMerged, false );
m_firstMergedNode = QPair<int, int>( -1, -1 );
return true;
}
// If two nodes which form an inner boundary of a polygon with a size smaller than
// 3 are merged, remove the whole inner boundary.
if ( innerRings.at(i).size() <= 3 ) {
innerRings.remove( i );
m_innerNodesList.removeAt( i );
m_firstMergedNode = m_secondMergedNode = m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
m_innerNodesList[innerIndexes.first][innerIndexes.second].setFlag( PolygonNode::NodeIsMerged );
m_secondMergedNode = innerIndexes;
m_animation = new MergingNodesAnimation( this );
setRequest( SceneGraphicsItem::StartAnimation );
}
return true;
}
return false;
}
bool AreaAnnotation::processMergingOnMove( QMouseEvent *mouseEvent )
{
return dealWithHovering( mouseEvent );
}
bool AreaAnnotation::processMergingOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return true;
}
bool AreaAnnotation::processAddingNodesOnPress( QMouseEvent *mouseEvent )
{
if ( mouseEvent->button() != Qt::LeftButton ) {
return false;
}
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
GeoDataLinearRing &outerRing = polygon->outerBoundary();
QVector<GeoDataLinearRing> &innerRings = polygon->innerBoundaries();
// If a virtual node has just been clicked, add it to the polygon's outer boundary
// and start 'adjusting' its position.
QPair<int, int> index = virtualNodeContains( mouseEvent->pos() );
if ( index != QPair<int, int>( -1, -1 ) && m_adjustedNode == -2 ) {
Q_ASSERT( m_virtualHovered == index );
int i = index.first;
int j = index.second;
if ( i != -1 && j == -1 ) {
GeoDataLinearRing newRing( Tessellate );
QList<PolygonNode> newList;
for ( int k = i; k < i + outerRing.size(); ++k ) {
newRing.append( outerRing.at(k % outerRing.size()) );
newList.append( PolygonNode( QRegion(), m_outerNodesList.at(k % outerRing.size()).flags() ) );
}
GeoDataCoordinates newCoords = newRing.at(0).interpolate( newRing.last(), 0.5 );
newRing.append( newCoords );
m_outerNodesList = newList;
m_outerNodesList.append( PolygonNode( QRegion() ) );
polygon->outerBoundary() = newRing;
m_adjustedNode = -1;
} else {
Q_ASSERT( i != -1 && j != -1 );
GeoDataLinearRing newRing( Tessellate );
QList<PolygonNode> newList;
for ( int k = j; k < j + innerRings.at(i).size(); ++k ) {
newRing.append( innerRings.at(i).at(k % innerRings.at(i).size()) );
newList.append( PolygonNode( QRegion(),
m_innerNodesList.at(i).at(k % innerRings.at(i).size()).flags() ) );
}
GeoDataCoordinates newCoords = newRing.at(0).interpolate( newRing.last(), 0.5 );
newRing.append( newCoords );
m_innerNodesList[i] = newList;
m_innerNodesList[i].append( PolygonNode( QRegion() ) );
polygon->innerBoundaries()[i] = newRing;
m_adjustedNode = i;
}
m_virtualHovered = QPair<int, int>( -1, -1 );
return true;
}
// If a virtual node which has been previously clicked and selected to become a
// 'real node' is clicked one more time, it stops from being 'adjusted'.
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 && m_adjustedNode != -2 ) {
m_adjustedNode = -2;
return true;
}
QPair<int,int> innerIndex = innerNodeContains( mouseEvent->pos() );
if ( innerIndex != QPair<int, int>( -1, -1 ) && m_adjustedNode != -2 ) {
m_adjustedNode = -2;
return true;
}
return false;
}
bool AreaAnnotation::processAddingNodesOnMove( QMouseEvent *mouseEvent )
{
Q_ASSERT( mouseEvent->button() == Qt::NoButton );
QPair<int, int> index = virtualNodeContains( mouseEvent->pos() );
// If we are adjusting a virtual node which has just been clicked and became real, just
// change its coordinates when moving it, as we do with nodes in Editing state on move.
if ( m_adjustedNode != -2 ) {
// The virtual node which has just been added is always the last within
// GeoDataLinearRing's container.qreal lon, lat;
qreal lon, lat;
m_viewport->geoCoordinates( mouseEvent->pos().x(),
mouseEvent->pos().y(),
lon, lat,
GeoDataCoordinates::Radian );
const GeoDataCoordinates newCoords( lon, lat );
GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() );
if ( m_adjustedNode == -1 ) {
polygon->outerBoundary().last() = newCoords;
} else {
Q_ASSERT( m_adjustedNode >= 0 );
polygon->innerBoundaries()[m_adjustedNode].last() = newCoords;
}
return true;
// If we are hovering a virtual node, store its index in order to be painted in drawNodes
// method.
} else if ( index != QPair<int, int>( -1, -1 ) ) {
m_virtualHovered = index;
return true;
}
// This means that the interior of the polygon has been hovered. Let the event propagate
// since there may be overlapping polygons.
return false;
}
bool AreaAnnotation::processAddingNodesOnRelease( QMouseEvent *mouseEvent )
{
Q_UNUSED( mouseEvent );
return m_adjustedNode == -2;
}
bool AreaAnnotation::dealWithHovering( QMouseEvent *mouseEvent )
{
PolygonNode::PolyNodeFlag flag = state() == SceneGraphicsItem::Editing ?
PolygonNode::NodeIsEditingHighlighted :
PolygonNode::NodeIsMergingHighlighted;
int outerIndex = outerNodeContains( mouseEvent->pos() );
if ( outerIndex != -1 ) {
if ( !m_outerNodesList.at(outerIndex).isEditingHighlighted() &&
!m_outerNodesList.at(outerIndex).isMergingHighlighted() ) {
// Deal with the case when two nodes are very close to each other.
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( flag, false );
} else {
m_innerNodesList[i][j].setFlag( flag, false );
}
}
m_hoveredNode = QPair<int, int>( outerIndex, -1 );
m_outerNodesList[outerIndex].setFlag( flag );
}
return true;
} else if ( m_hoveredNode != QPair<int, int>( -1, -1 ) && m_hoveredNode.second == -1 ) {
m_outerNodesList[m_hoveredNode.first].setFlag( flag, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
QPair<int, int> innerIndex = innerNodeContains( mouseEvent->pos() );
if ( innerIndex != QPair<int, int>( -1, -1 ) ) {
if ( !m_innerNodesList.at(innerIndex.first).at(innerIndex.second).isEditingHighlighted() &&
!m_innerNodesList.at(innerIndex.first).at(innerIndex.second).isMergingHighlighted()) {
// Deal with the case when two nodes are very close to each other.
if ( m_hoveredNode != QPair<int, int>( -1, -1 ) ) {
int i = m_hoveredNode.first;
int j = m_hoveredNode.second;
if ( j == -1 ) {
m_outerNodesList[i].setFlag( flag, false );
} else {
m_innerNodesList[i][j].setFlag( flag, false );
}
}
m_hoveredNode = innerIndex;
m_innerNodesList[innerIndex.first][innerIndex.second].setFlag( flag );
}
return true;
} else if ( m_hoveredNode != QPair<int, int>( -1, -1 ) && m_hoveredNode.second != -1 ) {
m_innerNodesList[m_hoveredNode.first][m_hoveredNode.second].setFlag( flag, false );
m_hoveredNode = QPair<int, int>( -1, -1 );
return true;
}
return false;
}
}
|
//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>
//
#include "OverviewMap.h"
#include <QtCore/QRect>
#include <QtGui/QCursor>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
#include <QtSvg/QSvgRenderer>
#include "AbstractProjection.h"
#include "MarbleDirs.h"
#include "MarbleDataFacade.h"
#include "GeoPainter.h"
#include "GeoDataPoint.h"
#include "ViewportParams.h"
#include "MarbleWidget.h"
namespace Marble
{
OverviewMap::OverviewMap( const QPointF &point, const QSizeF &size )
: AbstractFloatItem( point, size ),
m_target(QString()),
m_svgobj(0)
{
}
OverviewMap::~OverviewMap()
{
delete m_svgobj;
}
QStringList OverviewMap::backendTypes() const
{
return QStringList( "overviewmap" );
}
QString OverviewMap::name() const
{
return tr("Overview Map");
}
QString OverviewMap::guiString() const
{
return tr("&Overview Map");
}
QString OverviewMap::nameId() const
{
return QString( "overviewmap" );
}
QString OverviewMap::description() const
{
return tr("This is a float item that provides an overview map.");
}
QIcon OverviewMap::icon () const
{
return QIcon();
}
void OverviewMap::initialize ()
{
}
bool OverviewMap::isInitialized () const
{
return true;
}
void OverviewMap::changeViewport( ViewportParams *viewport )
{
GeoDataLatLonAltBox latLonAltBox = viewport->currentProjection()->latLonAltBox( QRect( QPoint( 0, 0 ), viewport->size() ), viewport );
qreal centerLon, centerLat;
viewport->centerCoordinates( centerLon, centerLat );
QString target = dataFacade()->target();
if ( !( m_latLonAltBox == latLonAltBox
&& m_centerLon == centerLon
&& m_centerLat == centerLat
&& m_target == target ) )
{
m_latLonAltBox = latLonAltBox;
m_centerLon = centerLon;
m_centerLat = centerLat;
update();
}
}
void OverviewMap::paintContent( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer )
{
Q_UNUSED( layer );
Q_UNUSED( renderPos );
painter->save();
painter->autoMapQuality();
QRectF mapRect( contentRect() );
QString target = dataFacade()->target();
if ( target != m_target ) {
changeBackground( target );
}
if ( m_svgobj ) {
// Rerender worldmap pixmap if the size has changed
if ( m_worldmap.size() != mapRect.size().toSize()
|| target != m_target ) {
m_worldmap = QPixmap( mapRect.size().toSize() );
m_worldmap.fill( Qt::transparent );
QPainter mapPainter;
mapPainter.begin(&m_worldmap);
mapPainter.setViewport( m_worldmap.rect() );
m_svgobj->render( &mapPainter );
mapPainter.end();
}
painter->drawPixmap( QPoint( 0, 0 ), m_worldmap );
}
else {
painter->setPen( QPen( Qt::DashLine ) );
painter->drawRect( QRectF( QPoint( 0, 0 ), mapRect.size().toSize() ) );
for ( int y = 1; y < 4; ++y ) {
if ( y == 2 ) {
painter->setPen( QPen( Qt::DashLine ) );
}
else {
painter->setPen( QPen( Qt::DotLine ) );
}
painter->drawLine( 0.0, 0.25 * y * mapRect.height(),
mapRect.width(), 0.25 * y * mapRect.height() );
}
for ( int x = 1; x < 8; ++x ) {
if ( x == 4 ) {
painter->setPen( QPen( Qt::DashLine ) );
}
else {
painter->setPen( QPen( Qt::DotLine ) );
}
painter->drawLine( 0.125 * x * mapRect.width(), 0,
0.125 * x * mapRect.width(), mapRect.height() );
}
}
m_target = target;
// Now draw the latitude longitude bounding box
qreal xWest = mapRect.width() / 2.0
+ mapRect.width() / ( 2.0 * M_PI ) * m_latLonAltBox.west();
qreal xEast = mapRect.width() / 2.0
+ mapRect.width() / ( 2.0 * M_PI ) * m_latLonAltBox.east();
qreal xNorth = mapRect.height() / 2.0
- mapRect.height() / M_PI * m_latLonAltBox.north();
qreal xSouth = mapRect.height() / 2.0
- mapRect.height() / M_PI * m_latLonAltBox.south();
qreal lon, lat;
viewport->centerCoordinates( lon, lat );
GeoDataPoint::normalizeLonLat( lon, lat );
qreal x = mapRect.width() / 2.0 + mapRect.width() / ( 2.0 * M_PI ) * lon;
qreal y = mapRect.height() / 2.0 - mapRect.height() / M_PI * lat;
painter->setPen( QPen( Qt::white ) );
painter->setBrush( QBrush( Qt::transparent ) );
painter->setRenderHint( QPainter::Antialiasing, false );
qreal boxWidth = xEast - xWest;
qreal boxHeight = xSouth - xNorth;
qreal minBoxSize = 2.0;
if ( boxHeight < minBoxSize ) boxHeight = minBoxSize;
if ( m_latLonAltBox.west() <= m_latLonAltBox.east() ) {
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( xWest, xNorth, boxWidth, boxHeight ) );
}
else {
// If the dateline is shown in the viewport and if the poles are not
// then there are two boxes that represent the latLonBox of the view.
boxWidth = xEast;
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( 0, xNorth, boxWidth, boxHeight ) );
boxWidth = mapRect.width() - xWest;
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( xWest, xNorth, boxWidth, boxHeight ) );
}
painter->setPen( QPen( Qt::white ) );
painter->setBrush( QBrush( Qt::white ) );
qreal circleRadius = 2.5;
painter->setRenderHint( QPainter::Antialiasing, true );
painter->drawEllipse( QRectF( x - circleRadius, y - circleRadius , 2 * circleRadius, 2 * circleRadius ) );
painter->restore();
}
bool OverviewMap::eventFilter( QObject *object, QEvent *e )
{
if ( !enabled() || !visible() ) {
return false;
}
MarbleWidget *widget = dynamic_cast<MarbleWidget*>(object);
if ( !widget ) {
return AbstractFloatItem::eventFilter(object,e);
}
bool cursorAboveFloatItem(false);
if ( e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseMove ) {
QMouseEvent *event = static_cast<QMouseEvent*>(e);
QRectF floatItemRect = QRectF( positivePosition(), size() );
if ( floatItemRect.contains(event->pos()) ) {
cursorAboveFloatItem = true;
// Double click triggers recentering the map at the specified position
if ( e->type() == QEvent::MouseButtonDblClick ) {
QRectF mapRect( contentRect() );
QPointF pos = event->pos() - floatItemRect.topLeft()
- QPointF(padding(),padding());
qreal lon = ( pos.x() - mapRect.width() / 2.0 ) / mapRect.width() * 360.0 ;
qreal lat = ( mapRect.height() / 2.0 - pos.y() ) / mapRect.height() * 180.0;
widget->centerOn(lon,lat,true);
return true;
}
}
if ( cursorAboveFloatItem && e->type() == QEvent::MouseMove
&& !event->buttons() & Qt::LeftButton )
{
// Cross hair cursor when moving above the float item without pressing a button
widget->setCursor(QCursor(Qt::CrossCursor));
return true;
}
}
return AbstractFloatItem::eventFilter(object,e);
}
void OverviewMap::changeBackground( const QString& target )
{
delete m_svgobj;
m_svgobj = 0;
if ( target == "moon" ) {
m_svgobj = new QSvgRenderer( MarbleDirs::path( "svg/lunarmap.svg" ),
this );
return;
}
if ( target == "earth" ) {
m_svgobj = new QSvgRenderer( MarbleDirs::path( "svg/worldmap.svg" ),
this );
}
}
}
Q_EXPORT_PLUGIN2( OverviewMap, Marble::OverviewMap )
#include "OverviewMap.moc"
Patch by ariya optimizing marble rendering:
Because of the dynamic nature of the overview map during animation/navigation, caching the item in a pixmap will just put additional burden. Beside, the SVG object is already rendered and stored in a pixmap anyway.
svn path=/trunk/KDE/kdeedu/marble/; revision=1121220
//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>
//
#include "OverviewMap.h"
#include <QtCore/QRect>
#include <QtGui/QCursor>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
#include <QtSvg/QSvgRenderer>
#include "AbstractProjection.h"
#include "MarbleDirs.h"
#include "MarbleDataFacade.h"
#include "GeoPainter.h"
#include "GeoDataPoint.h"
#include "ViewportParams.h"
#include "MarbleWidget.h"
namespace Marble
{
OverviewMap::OverviewMap( const QPointF &point, const QSizeF &size )
: AbstractFloatItem( point, size ),
m_target(QString()),
m_svgobj(0)
{
// cache is no needed because:
// (1) the SVG overview map is already rendered and stored in m_worldmap pixmap
// (2) bounding box and location dot keep changing during navigation
setCacheMode( NoCache );
}
OverviewMap::~OverviewMap()
{
delete m_svgobj;
}
QStringList OverviewMap::backendTypes() const
{
return QStringList( "overviewmap" );
}
QString OverviewMap::name() const
{
return tr("Overview Map");
}
QString OverviewMap::guiString() const
{
return tr("&Overview Map");
}
QString OverviewMap::nameId() const
{
return QString( "overviewmap" );
}
QString OverviewMap::description() const
{
return tr("This is a float item that provides an overview map.");
}
QIcon OverviewMap::icon () const
{
return QIcon();
}
void OverviewMap::initialize ()
{
}
bool OverviewMap::isInitialized () const
{
return true;
}
void OverviewMap::changeViewport( ViewportParams *viewport )
{
GeoDataLatLonAltBox latLonAltBox = viewport->currentProjection()->latLonAltBox( QRect( QPoint( 0, 0 ), viewport->size() ), viewport );
qreal centerLon, centerLat;
viewport->centerCoordinates( centerLon, centerLat );
QString target = dataFacade()->target();
if ( !( m_latLonAltBox == latLonAltBox
&& m_centerLon == centerLon
&& m_centerLat == centerLat
&& m_target == target ) )
{
m_latLonAltBox = latLonAltBox;
m_centerLon = centerLon;
m_centerLat = centerLat;
update();
}
}
void OverviewMap::paintContent( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer )
{
Q_UNUSED( layer );
Q_UNUSED( renderPos );
painter->save();
painter->autoMapQuality();
QRectF mapRect( contentRect() );
QString target = dataFacade()->target();
if ( target != m_target ) {
changeBackground( target );
}
if ( m_svgobj ) {
// Rerender worldmap pixmap if the size has changed
if ( m_worldmap.size() != mapRect.size().toSize()
|| target != m_target ) {
m_worldmap = QPixmap( mapRect.size().toSize() );
m_worldmap.fill( Qt::transparent );
QPainter mapPainter;
mapPainter.begin(&m_worldmap);
mapPainter.setViewport( m_worldmap.rect() );
m_svgobj->render( &mapPainter );
mapPainter.end();
}
painter->drawPixmap( QPoint( 0, 0 ), m_worldmap );
}
else {
painter->setPen( QPen( Qt::DashLine ) );
painter->drawRect( QRectF( QPoint( 0, 0 ), mapRect.size().toSize() ) );
for ( int y = 1; y < 4; ++y ) {
if ( y == 2 ) {
painter->setPen( QPen( Qt::DashLine ) );
}
else {
painter->setPen( QPen( Qt::DotLine ) );
}
painter->drawLine( 0.0, 0.25 * y * mapRect.height(),
mapRect.width(), 0.25 * y * mapRect.height() );
}
for ( int x = 1; x < 8; ++x ) {
if ( x == 4 ) {
painter->setPen( QPen( Qt::DashLine ) );
}
else {
painter->setPen( QPen( Qt::DotLine ) );
}
painter->drawLine( 0.125 * x * mapRect.width(), 0,
0.125 * x * mapRect.width(), mapRect.height() );
}
}
m_target = target;
// Now draw the latitude longitude bounding box
qreal xWest = mapRect.width() / 2.0
+ mapRect.width() / ( 2.0 * M_PI ) * m_latLonAltBox.west();
qreal xEast = mapRect.width() / 2.0
+ mapRect.width() / ( 2.0 * M_PI ) * m_latLonAltBox.east();
qreal xNorth = mapRect.height() / 2.0
- mapRect.height() / M_PI * m_latLonAltBox.north();
qreal xSouth = mapRect.height() / 2.0
- mapRect.height() / M_PI * m_latLonAltBox.south();
qreal lon, lat;
viewport->centerCoordinates( lon, lat );
GeoDataPoint::normalizeLonLat( lon, lat );
qreal x = mapRect.width() / 2.0 + mapRect.width() / ( 2.0 * M_PI ) * lon;
qreal y = mapRect.height() / 2.0 - mapRect.height() / M_PI * lat;
painter->setPen( QPen( Qt::white ) );
painter->setBrush( QBrush( Qt::transparent ) );
painter->setRenderHint( QPainter::Antialiasing, false );
qreal boxWidth = xEast - xWest;
qreal boxHeight = xSouth - xNorth;
qreal minBoxSize = 2.0;
if ( boxHeight < minBoxSize ) boxHeight = minBoxSize;
if ( m_latLonAltBox.west() <= m_latLonAltBox.east() ) {
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( xWest, xNorth, boxWidth, boxHeight ) );
}
else {
// If the dateline is shown in the viewport and if the poles are not
// then there are two boxes that represent the latLonBox of the view.
boxWidth = xEast;
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( 0, xNorth, boxWidth, boxHeight ) );
boxWidth = mapRect.width() - xWest;
// Make sure the latLonBox is still visible
if ( boxWidth < minBoxSize ) boxWidth = minBoxSize;
painter->drawRect( QRectF( xWest, xNorth, boxWidth, boxHeight ) );
}
painter->setPen( QPen( Qt::white ) );
painter->setBrush( QBrush( Qt::white ) );
qreal circleRadius = 2.5;
painter->setRenderHint( QPainter::Antialiasing, true );
painter->drawEllipse( QRectF( x - circleRadius, y - circleRadius , 2 * circleRadius, 2 * circleRadius ) );
painter->restore();
}
bool OverviewMap::eventFilter( QObject *object, QEvent *e )
{
if ( !enabled() || !visible() ) {
return false;
}
MarbleWidget *widget = dynamic_cast<MarbleWidget*>(object);
if ( !widget ) {
return AbstractFloatItem::eventFilter(object,e);
}
bool cursorAboveFloatItem(false);
if ( e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseMove ) {
QMouseEvent *event = static_cast<QMouseEvent*>(e);
QRectF floatItemRect = QRectF( positivePosition(), size() );
if ( floatItemRect.contains(event->pos()) ) {
cursorAboveFloatItem = true;
// Double click triggers recentering the map at the specified position
if ( e->type() == QEvent::MouseButtonDblClick ) {
QRectF mapRect( contentRect() );
QPointF pos = event->pos() - floatItemRect.topLeft()
- QPointF(padding(),padding());
qreal lon = ( pos.x() - mapRect.width() / 2.0 ) / mapRect.width() * 360.0 ;
qreal lat = ( mapRect.height() / 2.0 - pos.y() ) / mapRect.height() * 180.0;
widget->centerOn(lon,lat,true);
return true;
}
}
if ( cursorAboveFloatItem && e->type() == QEvent::MouseMove
&& !event->buttons() & Qt::LeftButton )
{
// Cross hair cursor when moving above the float item without pressing a button
widget->setCursor(QCursor(Qt::CrossCursor));
return true;
}
}
return AbstractFloatItem::eventFilter(object,e);
}
void OverviewMap::changeBackground( const QString& target )
{
delete m_svgobj;
m_svgobj = 0;
if ( target == "moon" ) {
m_svgobj = new QSvgRenderer( MarbleDirs::path( "svg/lunarmap.svg" ),
this );
return;
}
if ( target == "earth" ) {
m_svgobj = new QSvgRenderer( MarbleDirs::path( "svg/worldmap.svg" ),
this );
}
}
}
Q_EXPORT_PLUGIN2( OverviewMap, Marble::OverviewMap )
#include "OverviewMap.moc"
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basecheckoutwizardpage.h"
#include "ui_basecheckoutwizardpage.h"
namespace VCSBase {
struct BaseCheckoutWizardPagePrivate {
BaseCheckoutWizardPagePrivate() : m_valid(false), m_directoryEdited(false) {}
Ui::BaseCheckoutWizardPage ui;
bool m_valid;
bool m_directoryEdited;
};
BaseCheckoutWizardPage::BaseCheckoutWizardPage(QWidget *parent) :
QWizardPage(parent),
d(new BaseCheckoutWizardPagePrivate)
{
d->ui.setupUi(this);
d->ui.pathChooser->setExpectedKind(Utils::PathChooser::Directory);
connect(d->ui.pathChooser, SIGNAL(validChanged()), this, SLOT(slotChanged()));
connect(d->ui.checkoutDirectoryLineEdit, SIGNAL(validChanged()),
this, SLOT(slotChanged()));
connect(d->ui.repositoryLineEdit, SIGNAL(textChanged(QString)), this, SLOT(slotRepositoryChanged(QString)));
connect(d->ui.checkoutDirectoryLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slotDirectoryEdited()));
}
BaseCheckoutWizardPage::~BaseCheckoutWizardPage()
{
delete d;
}
void BaseCheckoutWizardPage::setRepositoryLabel(const QString &l)
{
d->ui.repositoryLabel->setText(l);
}
bool BaseCheckoutWizardPage::isRepositoryReadOnly() const
{
return d->ui.repositoryLineEdit->isReadOnly();
}
void BaseCheckoutWizardPage::setRepositoryReadOnly(bool v)
{
d->ui.repositoryLineEdit->setReadOnly(v);
}
QString BaseCheckoutWizardPage::path() const
{
return d->ui.pathChooser->path();
}
void BaseCheckoutWizardPage::setPath(const QString &p)
{
d->ui.pathChooser->setPath(p);
}
QString BaseCheckoutWizardPage::directory() const
{
return d->ui.checkoutDirectoryLineEdit->text();
}
void BaseCheckoutWizardPage::setDirectory(const QString &dir)
{
d->ui.checkoutDirectoryLineEdit->setText(dir);
}
void BaseCheckoutWizardPage::setDirectoryVisible(bool v)
{
d->ui.checkoutDirectoryLabel->setVisible(v);
d->ui.checkoutDirectoryLineEdit->setVisible(v);
}
QString BaseCheckoutWizardPage::repository() const
{
return d->ui.repositoryLineEdit->text().trimmed();
}
void BaseCheckoutWizardPage::setRepository(const QString &r)
{
d->ui.repositoryLineEdit->setText(r);
}
void BaseCheckoutWizardPage::slotRepositoryChanged(const QString &repo)
{
if (d->m_directoryEdited)
return;
d->ui.checkoutDirectoryLineEdit->setText(directoryFromRepository(repo));
}
QString BaseCheckoutWizardPage::directoryFromRepository(const QString &r) const
{
return r;
}
void BaseCheckoutWizardPage::slotDirectoryEdited()
{
d->m_directoryEdited = true;
}
void BaseCheckoutWizardPage::changeEvent(QEvent *e)
{
QWizardPage::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
d->ui.retranslateUi(this);
break;
default:
break;
}
}
bool BaseCheckoutWizardPage::isComplete() const
{
return d->m_valid;
}
void BaseCheckoutWizardPage::slotChanged()
{
const bool valid = d->ui.pathChooser->isValid()
&& d->ui.checkoutDirectoryLineEdit->isValid()
&& !d->ui.repositoryLineEdit->text().isEmpty();
if (valid != d->m_valid) {
d->m_valid = valid;
emit completeChanged();
}
}
} // namespace VCSBase
Checkout wizard: Enable Next button correctly.
Add some missing updates.
Task-number: QTCREATORBUG-2046
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basecheckoutwizardpage.h"
#include "ui_basecheckoutwizardpage.h"
namespace VCSBase {
struct BaseCheckoutWizardPagePrivate {
BaseCheckoutWizardPagePrivate() : m_valid(false), m_directoryEdited(false) {}
Ui::BaseCheckoutWizardPage ui;
bool m_valid;
bool m_directoryEdited;
};
BaseCheckoutWizardPage::BaseCheckoutWizardPage(QWidget *parent) :
QWizardPage(parent),
d(new BaseCheckoutWizardPagePrivate)
{
d->ui.setupUi(this);
connect(d->ui.repositoryLineEdit, SIGNAL(textChanged(QString)), this, SLOT(slotRepositoryChanged(QString)));
connect(d->ui.checkoutDirectoryLineEdit, SIGNAL(validChanged()),
this, SLOT(slotChanged()));
connect(d->ui.checkoutDirectoryLineEdit, SIGNAL(textEdited(QString)), this, SLOT(slotDirectoryEdited()));
d->ui.pathChooser->setExpectedKind(Utils::PathChooser::Directory);
connect(d->ui.pathChooser, SIGNAL(validChanged()), this, SLOT(slotChanged()));
}
BaseCheckoutWizardPage::~BaseCheckoutWizardPage()
{
delete d;
}
void BaseCheckoutWizardPage::setRepositoryLabel(const QString &l)
{
d->ui.repositoryLabel->setText(l);
}
bool BaseCheckoutWizardPage::isRepositoryReadOnly() const
{
return d->ui.repositoryLineEdit->isReadOnly();
}
void BaseCheckoutWizardPage::setRepositoryReadOnly(bool v)
{
d->ui.repositoryLineEdit->setReadOnly(v);
}
QString BaseCheckoutWizardPage::path() const
{
return d->ui.pathChooser->path();
}
void BaseCheckoutWizardPage::setPath(const QString &p)
{
d->ui.pathChooser->setPath(p);
}
QString BaseCheckoutWizardPage::directory() const
{
return d->ui.checkoutDirectoryLineEdit->text();
}
void BaseCheckoutWizardPage::setDirectory(const QString &dir)
{
d->ui.checkoutDirectoryLineEdit->setText(dir);
}
void BaseCheckoutWizardPage::setDirectoryVisible(bool v)
{
d->ui.checkoutDirectoryLabel->setVisible(v);
d->ui.checkoutDirectoryLineEdit->setVisible(v);
}
QString BaseCheckoutWizardPage::repository() const
{
return d->ui.repositoryLineEdit->text().trimmed();
}
void BaseCheckoutWizardPage::setRepository(const QString &r)
{
d->ui.repositoryLineEdit->setText(r);
}
void BaseCheckoutWizardPage::slotRepositoryChanged(const QString &repo)
{
// Derive directory name from repository unless user manually edited it.
if (!d->m_directoryEdited)
d->ui.checkoutDirectoryLineEdit->setText(directoryFromRepository(repo));
slotChanged();
}
QString BaseCheckoutWizardPage::directoryFromRepository(const QString &r) const
{
return r;
}
void BaseCheckoutWizardPage::slotDirectoryEdited()
{
d->m_directoryEdited = true;
slotChanged();
}
void BaseCheckoutWizardPage::changeEvent(QEvent *e)
{
QWizardPage::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
d->ui.retranslateUi(this);
break;
default:
break;
}
}
bool BaseCheckoutWizardPage::isComplete() const
{
return d->m_valid;
}
void BaseCheckoutWizardPage::slotChanged()
{
const bool valid = d->ui.pathChooser->isValid()
&& d->ui.checkoutDirectoryLineEdit->isValid()
&& !d->ui.repositoryLineEdit->text().isEmpty();
if (valid != d->m_valid) {
d->m_valid = valid;
emit completeChanged();
}
}
} // namespace VCSBase
|
#pragma once
#include "singleton.hpp"
#include "restag.hpp"
#include "optional.hpp"
namespace spi {
//! 名前付きリソースマネージャ
/*!
中身の保持はすべてスマートポインタで行う
シングルスレッド動作
*/
template <class T, class K=std::string>
class ResMgrName {
public:
using value_t = T;
using shared_t = std::shared_ptr<value_t>;
using key_t = K;
private:
using this_t = ResMgrName<T,K>;
using tag_t = ResTag<value_t>;
using Resource = std::unordered_map<key_t, tag_t>;
using Val2Key = std::unordered_map<const value_t*, key_t>;
template <bool B>
class _iterator : public Resource::iterator {
public:
using base_t = typename Resource::iterator;
using base_t::base_t;
using v_t = std::conditional_t<B, const value_t, value_t>;
using s_t = std::shared_ptr<v_t>;
s_t operator *() const {
return base_t::operator*().second.weak.lock();
}
s_t operator ->() const {
return base_t::operator*().second.weak.lock();
}
};
using iterator = _iterator<false>;
using const_iterator = _iterator<true>;
Resource _resource;
Val2Key _v2k;
void _release(value_t* p) noexcept {
const auto itr = _v2k.find(p);
try {
Assert0(itr != _v2k.end());
const auto itr2 = _resource.find(itr->second);
Assert0(itr2 != _resource.end());
_v2k.erase(itr);
_resource.erase(itr2);
p->~value_t();
} catch(...) {}
}
using DeleteF = std::function<void (value_t*)>;
const DeleteF _deleter;
template <class Ar, class T2, class K2>
friend void save(Ar&, const ResMgrName<T2,K2>&);
template <class Ar, class T2, class K2>
friend void load(Ar&, ResMgrName<T2,K2>&);
protected:
//! 継承先のクラスでキーの改変をする必要があればこれをオーバーライドする
virtual void _modifyResourceName(key_t& /*key*/) const {}
public:
ResMgrName():
_deleter([this](value_t* p){
this->_release(p);
})
{}
iterator begin() noexcept { return _resource.begin(); }
iterator end() noexcept { return _resource.end(); }
const_iterator begin() const noexcept { return _resource.begin(); }
const_iterator cbegin() const noexcept { return _resource.cbegin(); }
const_iterator end() const noexcept { return _resource.end(); }
const_iterator cend() const noexcept { return _resource.cend(); }
// (主にデバッグ用)
bool operator == (const ResMgrName& m) const noexcept {
if(_resource.size() == m._resource.size()) {
auto itr0 = _resource.begin(),
itr1 = m._resource.begin();
while(itr0 != _resource.end()) {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
}
return true;
}
return false;
}
bool operator != (const ResMgrName& m) const noexcept {
return !(this->operator == (m));
}
template <class Make>
std::pair<shared_t, bool> acquireWithMake(const key_t& k, Make&& make) {
key_t tk(k);
_modifyResourceName(tk);
// 既に同じ名前でリソースを確保済みならばそれを返す
if(auto ret = get(tk))
return std::make_pair(ret, false);
// 新しくリソースを作成
shared_t p(make(tk), _deleter);
_resource.emplace(tk, p);
_v2k.emplace(p.get(), tk);
return std::make_pair(p, true);
}
template <class T2, class... Ts>
auto emplaceWithType(const key_t& k, Ts&&... ts) {
return acquireWithMake(k, [&ts...](auto&&){
return new T2(std::forward<Ts>(ts)...);
});
}
template <class... Ts>
auto emplace(const key_t& k, Ts&&... ts) {
return emplaceWithType<value_t>(k, std::forward<Ts>(ts)...);
}
Optional<const key_t&> getKey(const shared_t& p) const {
return getKey(p.get());
}
Optional<const key_t&> getKey(const value_t* p) const {
const auto itr = _v2k.find(p);
if(itr != _v2k.end())
return itr->second;
return none;
}
shared_t get(const key_t& k) {
key_t tk(k);
const auto itr = _resource.find(tk);
if(itr != _resource.end()) {
shared_t ret(itr->second.weak.lock());
D_Assert0(ret);
return ret;
}
return nullptr;
}
std::size_t size() const noexcept {
return _resource.size();
}
};
}
ヘッダのインクルード忘れを修正
#pragma once
#include "singleton.hpp"
#include "restag.hpp"
#include "optional.hpp"
#include <unordered_map>
namespace spi {
//! 名前付きリソースマネージャ
/*!
中身の保持はすべてスマートポインタで行う
シングルスレッド動作
*/
template <class T, class K=std::string>
class ResMgrName {
public:
using value_t = T;
using shared_t = std::shared_ptr<value_t>;
using key_t = K;
private:
using this_t = ResMgrName<T,K>;
using tag_t = ResTag<value_t>;
using Resource = std::unordered_map<key_t, tag_t>;
using Val2Key = std::unordered_map<const value_t*, key_t>;
template <bool B>
class _iterator : public Resource::iterator {
public:
using base_t = typename Resource::iterator;
using base_t::base_t;
using v_t = std::conditional_t<B, const value_t, value_t>;
using s_t = std::shared_ptr<v_t>;
s_t operator *() const {
return base_t::operator*().second.weak.lock();
}
s_t operator ->() const {
return base_t::operator*().second.weak.lock();
}
};
using iterator = _iterator<false>;
using const_iterator = _iterator<true>;
Resource _resource;
Val2Key _v2k;
void _release(value_t* p) noexcept {
const auto itr = _v2k.find(p);
try {
Assert0(itr != _v2k.end());
const auto itr2 = _resource.find(itr->second);
Assert0(itr2 != _resource.end());
_v2k.erase(itr);
_resource.erase(itr2);
p->~value_t();
} catch(...) {}
}
using DeleteF = std::function<void (value_t*)>;
const DeleteF _deleter;
template <class Ar, class T2, class K2>
friend void save(Ar&, const ResMgrName<T2,K2>&);
template <class Ar, class T2, class K2>
friend void load(Ar&, ResMgrName<T2,K2>&);
protected:
//! 継承先のクラスでキーの改変をする必要があればこれをオーバーライドする
virtual void _modifyResourceName(key_t& /*key*/) const {}
public:
ResMgrName():
_deleter([this](value_t* p){
this->_release(p);
})
{}
iterator begin() noexcept { return _resource.begin(); }
iterator end() noexcept { return _resource.end(); }
const_iterator begin() const noexcept { return _resource.begin(); }
const_iterator cbegin() const noexcept { return _resource.cbegin(); }
const_iterator end() const noexcept { return _resource.end(); }
const_iterator cend() const noexcept { return _resource.cend(); }
// (主にデバッグ用)
bool operator == (const ResMgrName& m) const noexcept {
if(_resource.size() == m._resource.size()) {
auto itr0 = _resource.begin(),
itr1 = m._resource.begin();
while(itr0 != _resource.end()) {
if(*itr0 != *itr1)
return false;
++itr0;
++itr1;
}
return true;
}
return false;
}
bool operator != (const ResMgrName& m) const noexcept {
return !(this->operator == (m));
}
template <class Make>
std::pair<shared_t, bool> acquireWithMake(const key_t& k, Make&& make) {
key_t tk(k);
_modifyResourceName(tk);
// 既に同じ名前でリソースを確保済みならばそれを返す
if(auto ret = get(tk))
return std::make_pair(ret, false);
// 新しくリソースを作成
shared_t p(make(tk), _deleter);
_resource.emplace(tk, p);
_v2k.emplace(p.get(), tk);
return std::make_pair(p, true);
}
template <class T2, class... Ts>
auto emplaceWithType(const key_t& k, Ts&&... ts) {
return acquireWithMake(k, [&ts...](auto&&){
return new T2(std::forward<Ts>(ts)...);
});
}
template <class... Ts>
auto emplace(const key_t& k, Ts&&... ts) {
return emplaceWithType<value_t>(k, std::forward<Ts>(ts)...);
}
Optional<const key_t&> getKey(const shared_t& p) const {
return getKey(p.get());
}
Optional<const key_t&> getKey(const value_t* p) const {
const auto itr = _v2k.find(p);
if(itr != _v2k.end())
return itr->second;
return none;
}
shared_t get(const key_t& k) {
key_t tk(k);
const auto itr = _resource.find(tk);
if(itr != _resource.end()) {
shared_t ret(itr->second.weak.lock());
D_Assert0(ret);
return ret;
}
return nullptr;
}
std::size_t size() const noexcept {
return _resource.size();
}
};
}
|
/*
* Copyright (c) 2013-2019 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QString>
#include <QTextCodec>
#include <QTcpSocket>
#include <QUrlQuery>
#include <QVariantMap>
#include <QtCore/qmath.h>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "json.h"
#include "product_match.h"
#include "utils/utils.h"
/*! Sensors REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleSensorsApi(const ApiRequest &req, ApiResponse &rsp)
{
if (req.path[2] != QLatin1String("sensors"))
{
return REQ_NOT_HANDLED;
}
// GET /api/<apikey>/sensors
if ((req.path.size() == 3) && (req.hdr.method() == "GET"))
{
return getAllSensors(req, rsp);
}
// GET /api/<apikey>/sensors/new
else if ((req.path.size() == 4) && (req.hdr.method() == "GET") && (req.path[3] == "new"))
{
return getNewSensors(req, rsp);
}
// GET /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "GET"))
{
return getSensor(req, rsp);
}
// GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
else if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "data"))
{
return getSensorData(req, rsp);
}
// POST /api/<apikey>/sensors
else if ((req.path.size() == 3) && (req.hdr.method() == "POST"))
{
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (map.isEmpty())
{
return searchNewSensors(req, rsp);
}
else
{
return createSensor(req, rsp);
}
}
// PUT, PATCH /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH"))
{
return updateSensor(req, rsp);
}
// DELETE /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE"))
{
return deleteSensor(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/config
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "config"))
{
return changeSensorConfig(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/state
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "state"))
{
return changeSensorState(req, rsp);
}
// POST, DELETE /api/<apikey>/sensors/<id>/config/schedule/Wbbb
else if ((req.path.size() == 7) && (req.hdr.method() == "POST" || req.hdr.method() == "DELETE") && (req.path[4] == "config") && (req.path[5] == "schedule"))
{
return changeThermostatSchedule(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! GET /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getAllSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
rsp.httpStatus = HttpStatusOk;
// handle ETag
if (req.hdr.hasKey(QLatin1String("If-None-Match")))
{
QString etag = req.hdr.value(QLatin1String("If-None-Match"));
if (gwSensorsEtag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
std::vector<Sensor>::iterator i = sensors.begin();
std::vector<Sensor>::iterator end = sensors.end();
for (; i != end; ++i)
{
// ignore deleted sensors
if (i->deletedState() == Sensor::StateDeleted)
{
continue;
}
// ignore sensors without attached node
if (i->modelId().startsWith("FLS-NB") && !i->node())
{
continue;
}
if (i->modelId().isEmpty())
{
continue;
}
QVariantMap map;
if (sensorToMap(&*i, map, req))
{
rsp.map[i->id()] = map;
}
}
if (rsp.map.isEmpty())
{
rsp.str = "{}"; // return empty object
}
rsp.etag = gwSensorsEtag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensor(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 4);
if (req.path.size() != 4)
{
return REQ_NOT_HANDLED;
}
const QString &id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
// handle ETag
if (req.hdr.hasKey(QLatin1String("If-None-Match")))
{
QString etag = req.hdr.value(QLatin1String("If-None-Match"));
if (sensor->etag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
sensorToMap(sensor, rsp.map, req);
rsp.httpStatus = HttpStatusOk;
rsp.etag = sensor->etag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensorData(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 5);
if (req.path.size() != 5)
{
return REQ_NOT_HANDLED;
}
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/").arg(id), QString("resource, /sensors/%1/, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
bool ok;
QUrl url(req.hdr.url());
QUrlQuery query(url);
const int maxRecords = query.queryItemValue(QLatin1String("maxrecords")).toInt(&ok);
if (!ok || maxRecords <= 0)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/maxrecords"), QString("invalid value, %1, for parameter, maxrecords").arg(query.queryItemValue("maxrecords"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
QString t = query.queryItemValue(QLatin1String("fromtime"));
QDateTime dt = QDateTime::fromString(t, QLatin1String("yyyy-MM-ddTHH:mm:ss"));
if (!dt.isValid())
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/fromtime"), QString("invalid value, %1, for parameter, fromtime").arg(query.queryItemValue("fromtime"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
const qint64 fromTime = dt.toMSecsSinceEpoch() / 1000;
openDb();
loadSensorDataFromDb(sensor, rsp.list, fromTime, maxRecords);
closeDb();
if (rsp.list.isEmpty())
{
rsp.str = QLatin1String("[]"); // return empty list
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::createSensor(const ApiRequest &req, ApiResponse &rsp)
{
rsp.httpStatus = HttpStatusOk;
bool ok;
QVariant var = Json::parse(req.content, ok);
const QVariantMap map = var.toMap();
const QString type = map["type"].toString();
Sensor sensor;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
userActivity();
if (sensors.size() >= MAX_SENSORS)
{
rsp.list.append(errorToMap(ERR_SENSOR_LIST_FULL , QString("/sensors/"), QString("The Sensor List has reached its maximum capacity of %1 sensors").arg(MAX_SENSORS)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check required parameter
if ((!(map.contains("name")) || !(map.contains("modelid")) || !(map.contains("swversion")) || !(map.contains("type")) || !(map.contains("uniqueid")) || !(map.contains("manufacturername"))))
{
rsp.list.append(errorToMap(ERR_MISSING_PARAMETER, QString("/sensors"), QString("invalid/missing parameters in body")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check invalid parameter
const QStringList allowedAttributes = { "name", "modelid", "swversion", "type", "uniqueid", "manufacturername", "state", "config", "recycle" };
for (const QString &attr : map.keys())
{
if (!allowedAttributes.contains(attr))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(attr), QString("parameter, %1, not available").arg(attr)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (!type.startsWith(QLatin1String("CLIP")))
{
rsp.list.append(errorToMap(ERR_NOT_ALLOWED_SENSOR_TYPE, QString("/sensors"), QString("Not allowed to create sensor type")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItem *item = nullptr;
QVariantMap rspItem;
QVariantMap rspItemState;
// create a new sensor id
openDb();
sensor.setId(QString::number(getFreeSensorId()));
closeDb();
sensor.setName(map["name"].toString().trimmed());
sensor.setManufacturer(map["manufacturername"].toString());
sensor.setModelId(map["modelid"].toString());
sensor.setUniqueId(map["uniqueid"].toString());
sensor.setSwVersion(map["swversion"].toString());
sensor.setType(type);
if (getSensorNodeForUniqueId(sensor.uniqueId()))
{
rsp.list.append(errorToMap(ERR_DUPLICATE_EXIST, QString("/sensors"), QString("sensor with uniqueid, %1, already exists").arg(sensor.uniqueId())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (type == QLatin1String("CLIPAlarm")) { item = sensor.addItem(DataTypeBool, RStateAlarm); item->setValue(false); }
else if (type == QLatin1String("CLIPBattery")) { item = sensor.addItem(DataTypeUInt8, RStateBattery); item->setValue(100); }
else if (type == QLatin1String("CLIPCarbonMonoxide")) { item = sensor.addItem(DataTypeBool, RStateCarbonMonoxide); item->setValue(false); }
else if (type == QLatin1String("CLIPConsumption")) { item = sensor.addItem(DataTypeUInt64, RStateConsumption); item->setValue(0); }
else if (type == QLatin1String("CLIPDaylightOffset")) { item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0);
item = sensor.addItem(DataTypeString, RConfigMode);
item = sensor.addItem(DataTypeTime, RStateLocaltime); }
else if (type == QLatin1String("CLIPFire")) { item = sensor.addItem(DataTypeBool, RStateFire); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericFlag")) { item = sensor.addItem(DataTypeBool, RStateFlag); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericStatus")) { item = sensor.addItem(DataTypeInt32, RStateStatus); item->setValue(0); }
else if (type == QLatin1String("CLIPHumidity")) { item = sensor.addItem(DataTypeUInt16, RStateHumidity); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPLightLevel")) { item = sensor.addItem(DataTypeUInt16, RStateLightLevel); item->setValue(0);
item = sensor.addItem(DataTypeUInt32, RStateLux); item->setValue(0);
item = sensor.addItem(DataTypeBool, RStateDark); item->setValue(true);
item = sensor.addItem(DataTypeBool, RStateDaylight); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigTholdDark); item->setValue(R_THOLDDARK_DEFAULT);
item = sensor.addItem(DataTypeUInt16, RConfigTholdOffset); item->setValue(R_THOLDOFFSET_DEFAULT); }
else if (type == QLatin1String("CLIPOpenClose")) { item = sensor.addItem(DataTypeBool, RStateOpen); item->setValue(false); }
else if (type == QLatin1String("CLIPPower")) { item = sensor.addItem(DataTypeInt16, RStatePower); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateVoltage); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateCurrent); item->setValue(0); }
else if (type == QLatin1String("CLIPPresence")) { item = sensor.addItem(DataTypeBool, RStatePresence); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigDuration); item->setValue(60); }
else if (type == QLatin1String("CLIPPressure")) { item = sensor.addItem(DataTypeInt16, RStatePressure); item->setValue(0); }
else if (type == QLatin1String("CLIPSwitch")) { item = sensor.addItem(DataTypeInt32, RStateButtonEvent); item->setValue(0); }
else if (type == QLatin1String("CLIPTemperature")) { item = sensor.addItem(DataTypeInt16, RStateTemperature); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPVibration")) { item = sensor.addItem(DataTypeBool, RStateVibration); item->setValue(false); }
else if (type == QLatin1String("CLIPWater")) { item = sensor.addItem(DataTypeBool, RStateWater); item->setValue(false); }
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("invalid value, %1, for parameter, type").arg(type)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//setState optional
if (map.contains("state"))
{
//check invalid parameter
const QVariantMap state = map["state"].toMap();
const QStringList allowedKeys = { "alarm", "battery", "buttonevent", "carbonmonoxide", "consumption", "current", "fire", "flag", "humidity", "lightlevel", "localtime", "lowbattery",
"open", "presence", "pressure", "power", "status", "tampered", "temperature", "vibration", "voltage", "water" };
const QStringList optionalKeys = { "lowbattery", "tampered" };
for (const auto &key : state.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("state/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(state.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/state"), QString("invalid value, %1, for parameter %2").arg(state.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
item = sensor.item(RConfigOn);
item->setValue(true); // default
item = sensor.item(RConfigReachable);
item->setValue(true); //default
//setConfig optional
if (map.contains("config"))
{
//check invalid parameter
const QVariantMap config = map["config"].toMap();
const QStringList allowedKeys = { "battery", "duration", "delay", "mode", "offset", "on", "reachable", "url" };
const QStringList optionalKeys = { "battery", "url" };
for (const auto &key : config.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("config/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(config.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/config"), QString("invalid value, %1, for parameter %2").arg(config.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
updateSensorEtag(&sensor);
sensor.setNeedSaveDatabase(true);
sensors.push_back(sensor);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
rspItemState["id"] = sensor.id();
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::updateSensor(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
QString name;
bool ok;
bool error = false;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
if (req.sock)
{
userActivity();
}
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
if (!((pi.key() == "name") || (pi.key() == "modelid") || (pi.key() == "swversion")
|| (pi.key() == "type") || (pi.key() == "uniqueid") || (pi.key() == "manufacturername")
|| (pi.key() == "state") || (pi.key() == "config")
|| (pi.key() == "mode" && (sensor->modelId() == "Lighting Switch" || sensor->modelId().startsWith(QLatin1String("SYMFONISK"))))))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(pi.key()), QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (map.contains("modelid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/modelid"), QString("parameter, modelid, not modifiable")));
}
if (map.contains("swversion"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/swversion"), QString("parameter, swversion, not modifiable")));
}
if (map.contains("type"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/type"), QString("parameter, type, not modifiable")));
}
if (map.contains("uniqueid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/uniqueid"), QString("parameter, uniqueid, not modifiable")));
}
if (map.contains("manufacturername"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/manufacturername"), QString("parameter, manufacturername, not modifiable")));
}
if (map.contains("state"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/state"), QString("parameter, state, not modifiable")));
}
if (error)
{
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (map.contains("name")) // optional
{
name = map["name"].toString().trimmed();
if ((map["name"].type() == QVariant::String) && !(name.isEmpty()) && (name.size() <= MAX_SENSOR_NAME_LENGTH))
{
if (sensor->name() != name)
{
sensor->setName(name);
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
Event e(RSensors, RAttrName, sensor->id(), sensor->item(RAttrName));
enqueueEvent(e);
}
if (!sensor->type().startsWith(QLatin1String("CLIP")))
{
pushSensorInfoToCore(sensor);
}
rspItemState[QString("/sensors/%1/name").arg(id)] = name;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/name").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/name").arg(name).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("mode")) // optional
{
Sensor::SensorMode mode = (Sensor::SensorMode)map["mode"].toUInt(&ok);
if (ok && (map["mode"].type() == QVariant::Double)
&& ((sensor->modelId() == "Lighting Switch" && (mode == Sensor::ModeScenes || mode == Sensor::ModeTwoGroups || mode == Sensor::ModeColorTemperature))
|| (sensor->modelId().startsWith(QLatin1String("SYMFONISK")) && (mode == Sensor::ModeScenes || mode == Sensor::ModeDimmer))))
{
if (sensor->mode() != mode)
{
sensor->setNeedSaveDatabase(true);
sensor->setMode(mode);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
}
rspItemState[QString("/sensors/%1/mode").arg(id)] = (double)mode;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
updateEtag(sensor->etag);
updateEtag(gwConfigEtag);
queSaveDb(DB_SENSORS | DB_GROUPS, DB_SHORT_SAVE_DELAY);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/mode").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/mode").arg((int)mode).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("config")) // optional
{
QStringList path = req.path;
path.append(QLatin1String("config"));
QString content = Json::serialize(map[QLatin1String("config")].toMap());
ApiRequest req2(req.hdr, path, NULL, content);
return changeSensorConfig(req2, rsp);
}
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>/config
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeSensorConfig(const ApiRequest &req, ApiResponse &rsp)
{
TaskItem task;
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
bool ok;
bool updated = false;
quint32 hostFlags = 0;
bool offsetUpdated = false;
qint16 offset = 0;
QMap<quint16, quint32> attributeList;
bool tholdUpdated = false;
quint16 pendingMask = 0;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
// QRegExp latitude("^\\d{3,3}\\.\\d{4,4}(W|E)$");
// QRegExp longitude("^\\d{3,3}\\.\\d{4,4}(N|S)$");
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/config"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool isClip = sensor->type().startsWith(QLatin1String("CLIP"));
if (req.sock)
{
userActivity();
}
// set destination parameters
task.req.dstAddress() = sensor->address();
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
struct KeyValMap {
QLatin1String key;
quint8 value;
};
struct KeyValMapInt {
quint8 key;
quint16 value;
};
struct KeyValMapTuyaSingle {
QLatin1String key;
char value[1];
};
for (; pi != pend; ++pi)
{
ResourceItemDescriptor rid;
ResourceItem *item = 0;
if (getResourceItemDescriptor(QString("config/%1").arg(pi.key()), rid))
{
if (!isClip && (rid.suffix == RConfigBattery || rid.suffix == RConfigReachable))
{
// changing battery or reachable of zigbee sensors is not allowed, trigger error
}
else if (rid.suffix == RConfigPending || rid.suffix == RConfigSensitivityMax || rid.suffix == RConfigHostFlags)
{
// pending and sensitivitymax are read-only
}
//else if (rid.suffix == RConfigDuration && sensor->modelId() == QLatin1String("TRADFRI motion sensor"))
//{
// duration can be written for ikea motion sensor
// values 0, 60 — 600 will be replaced by hardware settings TODO error message
//}
else
{
item = sensor->item(rid.suffix);
}
if (item)
{
QVariant val = map[pi.key()];
bool invalidValue = false;
bool datatypeValid = false;
QString stringValue;
bool boolValue = false;
int intValue = 0;
uint uintValue = 0;
long long realValue = 0.0;
switch (rid.type)
{
case DataTypeBool:
{
if (val.type() == QVariant::Bool)
{
boolValue = val.toBool();
datatypeValid = true;
}
}
break;
case DataTypeUInt8:
case DataTypeUInt16:
case DataTypeUInt32:
case DataTypeUInt64:
{
if (val.type() == QVariant::Double)
{
uintValue = val.toUInt(&ok);
if (ok) { datatypeValid = true; }
}
}
break;
case DataTypeInt8:
case DataTypeInt16:
case DataTypeInt32:
case DataTypeInt64:
{
if (val.type() == QVariant::Double)
{
intValue = val.toInt(&ok);
if (ok) { datatypeValid = true; }
}
}
break;
case DataTypeReal:
{
if (val.type() == QVariant::Double)
{
realValue = val.toReal();
datatypeValid = true;
}
}
break;
case DataTypeTime:
case DataTypeTimePattern:
{
if (val.type() == QVariant::String && !val.toString().isEmpty())
{
stringValue = val.toString();
datatypeValid = true;
}
}
break;
case DataTypeString:
{
if (val.type() == QVariant::String && !val.toString().isEmpty())
{
stringValue = val.toString();
datatypeValid = true;
}
}
break;
case DataTypeUnknown:
{
}
break;
default:
break;
}
if (!datatypeValid)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(map[pi.key()].toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (rid.suffix == RConfigDeviceMode)
{
if (RConfigDeviceModeValues.indexOf(val.toString()) >= 0)
{
pendingMask |= R_PENDING_DEVICEMODE;
sensor->enableRead(WRITE_DEVICEMODE);
sensor->setNextReadTime(WRITE_DEVICEMODE, QTime::currentTime());
updated = true;
}
}
else if (rid.suffix == RConfigTholdDark || rid.suffix == RConfigTholdOffset)
{
tholdUpdated = true;
}
else if (rid.suffix == RConfigDelay && sensor->modelId().startsWith(QLatin1String("SML00"))) // Hue motion sensor
{
pendingMask |= R_PENDING_DELAY;
sensor->enableRead(WRITE_DELAY);
sensor->setNextReadTime(WRITE_DELAY, QTime::currentTime());
}
else if (rid.suffix == RConfigDuration && sensor->modelId().startsWith(QLatin1String("FLS-NB")))
{
DBG_Printf(DBG_INFO, "Force read of occupaction delay for sensor %s\n", qPrintable(sensor->address().toStringExt()));
sensor->enableRead(READ_OCCUPANCY_CONFIG);
sensor->setNextReadTime(READ_OCCUPANCY_CONFIG, queryTime.addSecs(1));
queryTime = queryTime.addSecs(1);
Q_Q(DeRestPlugin);
q->startZclAttributeTimer(0);
}
else if (rid.suffix == RConfigLedIndication)
{
pendingMask |= R_PENDING_LEDINDICATION;
sensor->enableRead(WRITE_LEDINDICATION);
sensor->setNextReadTime(WRITE_LEDINDICATION, QTime::currentTime());
}
else if (rid.suffix == RConfigSensitivity)
{
pendingMask |= R_PENDING_SENSITIVITY;
sensor->enableRead(WRITE_SENSITIVITY);
sensor->setNextReadTime(WRITE_SENSITIVITY, QTime::currentTime());
}
else if (rid.suffix == RConfigUsertest)
{
pendingMask |= R_PENDING_USERTEST;
sensor->enableRead(WRITE_USERTEST);
sensor->setNextReadTime(WRITE_USERTEST, QTime::currentTime());
}
else if (rid.suffix == RConfigAlert) // String
{
const std::array<KeyValMap, 3> RConfigAlertValues = { { {QLatin1String("none"), 0}, {QLatin1String("select"), 2}, {QLatin1String("lselect"), 15} } };
const auto match = getMappedValue2(stringValue, RConfigAlertValues);
if (!match.key.isEmpty())
{
task.identifyTime = match.value;
task.taskType = TaskIdentify;
taskToLocalData(task);
if (addTaskIdentify(task, task.identifyTime))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigLock) // Boolean
{
boolValue ^= boolValue; // Flip bool value as 0 means lock and 1 means unlock
if (addTaskDoorLockUnlock(task, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigMelody) // Unigned integer
{
QByteArray data;
data.append(static_cast<qint8>(uintValue & 0xff));
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_ENUM, DP_IDENTIFIER_MELODY, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigVolume) // Unigned integer
{
if (uintValue > 2) { uintValue = 2; } // Volume level, max = 2
QByteArray data;
data.append(static_cast<qint8>(uintValue & 0xff));
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_ENUM, DP_IDENTIFIER_VOLUME, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigTempMinThreshold || rid.suffix == RConfigTempMaxThreshold || rid.suffix == RConfigHumiMinThreshold || rid.suffix == RConfigHumiMaxThreshold) // Signed integer, really???
{
QByteArray data = QByteArray("\x00\x00\x00",3);
data.append(static_cast<qint8>(intValue));
quint8 dpIdentifier = 0;
//if (intValue <= -25 || intValue >= 25) { invalidValue = true; } // What are the valid boundaries?
if (rid.suffix == RConfigTempMinThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTEMPMINI; }
else if (rid.suffix == RConfigTempMaxThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTEMPMAXI; }
else if (rid.suffix == RConfigHumiMinThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTHUMIMINI; }
else if (rid.suffix == RConfigHumiMaxThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDHUMIMAXI; }
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_VALUE, dpIdentifier, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigOffset) // Signed integer
{
intValue /= 10;
if ((R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV")) ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
QByteArray data;
bool alternative = false;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
if (intValue > 6) { intValue = 6; } // offset, min = -60, max = 60
if (intValue < -6) { intValue = -6; }
alternative = true;
}
else
{
if (intValue > 90) { intValue = 90; } // offset, min = -90, max = 90
if (intValue < -90) { intValue = -90; }
}
data.append((qint8)((offset >> 24) & 0xff));
data.append((qint8)((offset >> 16) & 0xff));
data.append((qint8)((offset >> 8) & 0xff));
data.append((qint8)(offset & 0xff));
if (!alternative)
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_VALUE, 0x2c, data))
{
updated = true;
}
}
else
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_VALUE, 0x1b, data))
{
updated = true;
}
}
}
else if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
if (intValue <= -25 || intValue >= 25) { invalidValue = true; }
else if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x404B, deCONZ::Zcl8BitInt, intValue))
{
updated = true;
}
}
else if (sensor->type() == "ZHAThermostat")
{
if (intValue <= -25 || intValue >= 25) { invalidValue = true; }
else if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0010, deCONZ::Zcl8BitInt, intValue))
{
updated = true;
}
}
else
{
offsetUpdated = true; // Consider offset only for temperature and humidity cluster
}
}
else if (rid.suffix == RConfigScheduleOn) // Boolean
{
if (sensor->modelId() == QLatin1String("Thermostat")) { boolValue ^= boolValue; } // eCozy, flip true and false
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0025, deCONZ::Zcl8BitBitMap, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigHeatSetpoint) // Signed integer
{
if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
// Older models of the Eurotroninc Spirit updated the heat set point via the manufacturer custom attribute 0x4003.
// For newer models it is not possible to write to this attribute.
// Newer models must use the standard Occupied Heating Setpoint value (0x0012) using a default (or none) manufacturer.
// See GitHub issue #1098
// UPD 16-11-2020: Since there is no way to reckognize older and newer models correctly and a new firmware version is on its way this
// 'fix' is changed to a more robust but ugly implementation by simply sending both codes to the device. One of the commands
// will be accepted while the other one will be refused. Let's hope this code can be removed in a future release.
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4003, deCONZ::Zcl16BitInt, intValue) &&
addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_NONE, 0x0012, deCONZ::Zcl16BitInt, intValue))
{
// Setting the heat setpoint disables off/boost modes, but this is not reported back by the thermostat.
// Hence, the off/boost flags will be removed here to reflect the actual operating state.
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
}
hostFlags &= ~0x04; // clear `boost` flag
hostFlags |= 0x10; // set `disable off` flag
updated = true;
}
}
else if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
if (addTaskThermostatCmd(task, VENDOR_DANFOSS, 0x40, intValue, 0))
{
updated = true;
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
intValue = intValue / 10;
QByteArray data = QByteArray("\x00\x00", 2);
qint8 dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_2;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_3;
intValue = intValue / 10;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
ResourceItem *item2 = sensor->item(RConfigMode);
if (item2 && item2->toString() == QLatin1String("heat"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_3;
}
else
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_4;
}
intValue = intValue * 2 / 10;
}
data.append(static_cast<qint8>((intValue >> 8) & 0xff));
data.append(static_cast<qint8>(intValue & 0xff));
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_VALUE , dp, data))
{
updated = true;
}
}
else
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0012, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigCoolSetpoint) // Signed integer
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0011, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigMode) // String
{
if (sensor->modelId() == QLatin1String("Cable outlet")) // Legrand cable outlet
{
static const std::array<KeyValMap, 6> RConfigModeLegrandValues = { { {QLatin1String("confort"), 0}, {QLatin1String("confort-1"), 1}, {QLatin1String("confort-2"), 2},
{QLatin1String("eco"), 3}, {QLatin1String("hors gel"), 4}, {QLatin1String("off"), 5} } };
const auto match = getMappedValue2(stringValue, RConfigModeLegrandValues);
if (!match.key.isEmpty())
{
if (addTaskControlModeCmd(task, 0x00, match.value))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 3> RConfigModeValuesTuya1 = { { {QLatin1String("auto"), {0x00}}, {QLatin1String("heat"), {0x01}}, {QLatin1String("off"), {0x02}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya1);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
quint8 dpIdentifier = DP_IDENTIFIER_THERMOSTAT_MODE_1;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_MODE_2;
}
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_ENUM, dpIdentifier, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
const std::array<KeyValMapTuyaSingle, 2> RConfigModeValuesTuya2 = { { {QLatin1String("off"), {0x00}}, {QLatin1String("heat"), {0x01}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya2);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x01, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 2> RConfigModeValuesTuya2 = { { {QLatin1String("off"), {0x00}}, {QLatin1String("heat"), {0x01}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya2);
if (!match.key.isEmpty())
{
if (match.key == QLatin1String("off"))
{
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x65 , QByteArray("\x00", 1)))
{
updated = true;
}
}
else
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x6c, data) &&
sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x65, QByteArray("\x01", 1)))
{
updated = true;
}
}
}
}
else if (sensor->modelId().startsWith(QLatin1String("S1")) ||
sensor->modelId().startsWith(QLatin1String("S2")) ||
sensor->modelId().startsWith(QLatin1String("J1")))
{
if (addTaskUbisysConfigureSwitch(task))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
}
if (stringValue == QLatin1String("off"))
{
hostFlags |= 0x000020; // set enable off
hostFlags &= 0xffffeb; // clear boost, clear disable off
}
else if (stringValue == QLatin1String("heat"))
{
hostFlags |= 0x000014; // set boost, set disable off
}
else if (stringValue == QLatin1String("auto"))
{
hostFlags &= 0xfffffb; // clear boost
hostFlags |= 0x000010; // set disable off
}
}
else
{
static const std::array<KeyValMap, 9> RConfigModeValues = { { {QLatin1String("off"), 0}, {QLatin1String("auto"), 1}, {QLatin1String("cool"), 3}, {QLatin1String("heat"), 4},
{QLatin1String("emergency heating"), 5}, {QLatin1String("precooling"), 6}, {QLatin1String("fan only"), 7},
{QLatin1String("dry"), 8}, {QLatin1String("sleep"), 9} } };
const auto match = getMappedValue2(stringValue, RConfigModeValues);
if (!match.key.isEmpty())
{
if (sensor->modelId() == QLatin1String("Super TR")) // Set device on/off state through mode via device specific attribute
{
if (match.value != 0x00 && match.value != 0x04) { }
else
{
bool data = match.value == 0x00 ? false : true;
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0406, deCONZ::ZclBoolean, data))
{
updated = true;
}
}
}
else if (sensor->modelId().startsWith(QLatin1String("SLR2")) ||
sensor->modelId() == QLatin1String("SLR1b"))
{
// Change automatically the Setpoint Hold
// Add a timer for Boost mode
if (match.value == 0x00) { attributeList.insert(0x0023, (quint32)0x00); }
else if (match.value == 0x04) { attributeList.insert(0x0023, (quint32)0x01); }
else if (match.value == 0x05)
{
attributeList.insert(0x0023, (quint32)0x01);
attributeList.insert(0x0026, (quint32)0x003C);
}
if (!attributeList.isEmpty())
{
if (addTaskThermostatWriteAttributeList(task, 0, attributeList))
{
updated = true;
}
}
}
else
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x001C, deCONZ::Zcl8BitEnum, uintValue))
{
updated = true;
}
}
}
}
}
else if (rid.suffix == RConfigPreset) // String
{
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 7> RConfigPresetValuesTuya = { { {QLatin1String("holiday"), {0x00}}, {QLatin1String("auto"), {0x01}}, {QLatin1String("manual"), {0x02}},
{QLatin1String("comfort"), {0x04}}, {QLatin1String("eco"), {0x05}}, {QLatin1String("boost"), {0x06}},
{QLatin1String("complex"), {0x07}} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x04, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
static const std::array<KeyValMap, 2> RConfigPresetValuesTuya2 = { { {QLatin1String("auto"), 0}, {QLatin1String("program"), 0} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya2);
if (!match.key.isEmpty())
{
if (match.key == QLatin1String("auto"))
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x02, QByteArray("\x01", 1)) &&
sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x03, QByteArray("\x00", 1)))
{
updated = true;
}
}
else if (match.key == QLatin1String("program"))
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x02, QByteArray("\x00", 1)) &&
sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x03, QByteArray("\x01", 1)))
{
updated = true;
}
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("NAS-AB02B0 Siren"))
{
const std::array<KeyValMap, 4> RConfigPresetValuesTuya3 = { { {QLatin1String("both"), 0}, {QLatin1String("humidity"), 0}, {QLatin1String("temperature"), 0},
{QLatin1String("off"), 0} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya3);
if (!match.key.isEmpty())
{
QByteArray data1;
QByteArray data2;
quint8 dpIdentifier1 = DP_IDENTIFIER_TEMPERATURE_ALARM;
quint8 dpIdentifier2 = DP_IDENTIFIER_HUMIDITY_ALARM;
if (match.key == QLatin1String("both"))
{
data1 = data2 = QByteArray("\x01", 1);
}
else if (match.key == QLatin1String("humidity"))
{
data1 = QByteArray("\x00", 1);
data2 = QByteArray("\x01", 1);
}
else if (match.key == QLatin1String("temperature"))
{
data1 = QByteArray("\x01", 1);
data2 = QByteArray("\x00", 1);
}
else if (match.key == QLatin1String("off"))
{
data1 = data2 = QByteArray("\x00", 1);
}
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_BOOL, dpIdentifier1, data1) &&
sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_BOOL, dpIdentifier2, data2))
{
updated = true;
}
}
}
}
else if (rid.suffix == RConfigLocked) // Boolean
{
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV"))
{
QByteArray data = QByteArray("\x00", 1);
qint8 dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_1;
if (boolValue) { data = QByteArray("\x01", 1); }
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_2;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_3;
}
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_BOOL, dpIdentifier, data))
{
updated = true;
}
}
else if (sensor->modelId() == QLatin1String("Super TR"))
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0413, deCONZ::ZclBoolean, boolValue))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
}
if (boolValue) { hostFlags |= 0x000080; } // set locked
else { hostFlags &= 0xffff6f; } // clear locked, clear disable off
}
else
{
uintValue = boolValue; // Use integer representation
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0001, deCONZ::Zcl8BitEnum, uintValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigDisplayFlipped) // Boolean
{
if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
uintValue = boolValue;
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x4000, deCONZ::Zcl8BitEnum, uintValue, VENDOR_DANFOSS))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
}
if (boolValue) { hostFlags |= 0x000002; } // set flipped
else { hostFlags &= 0xffffed; } // clear flipped, clear disable off
}
}
else if (rid.suffix == RConfigMountingMode) // Boolean
{
uintValue = boolValue; // Use integer representation
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x4013, deCONZ::Zcl8BitEnum, uintValue, VENDOR_DANFOSS))
{
updated = true;
}
}
else if (rid.suffix == RConfigExternalTemperatureSensor) // Signed integer
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x4015, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigExternalWindowOpen) // Boolean
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x4003, deCONZ::ZclBoolean, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigSetValve) // Boolean
{
QByteArray data = QByteArray("\x00", 1);
if (boolValue)
{
data = QByteArray("\x01", 1);
}
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, DP_IDENTIFIER_THERMOSTAT_VALVE , data))
{
updated = true;
}
}
else if (rid.suffix == RConfigTemperatureMeasurement) // String
{
if (sensor->modelId() == QLatin1String("Super TR"))
{
static const std::array<KeyValMap, 5> RConfigTemperatureMeasurementValues = { { {QLatin1String("air sensor"), 0}, {QLatin1String("floor sensor"), 1},
{QLatin1String("floor protection"), 3} } };
const auto match = getMappedValue2(stringValue, RConfigTemperatureMeasurementValues);
if (!match.key.isEmpty())
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0403, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
}
else if (rid.suffix == RConfigWindowOpen) // Boolean
{
QByteArray data = QByteArray("\x00", 1); // Config on / off
if (boolValue) { data = QByteArray("\x01", 1); }
qint8 dpIdentifier = DP_IDENTIFIER_WINDOW_OPEN;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
dpIdentifier = DP_IDENTIFIER_WINDOW_OPEN2;
}
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_BOOL, dpIdentifier, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigSwingMode) // String
{
static const std::array<KeyValMap, 5> RConfigSwingModeValues = { { {QLatin1String("fully closed"), 1}, {QLatin1String("fully open"), 2}, {QLatin1String("quarter open"), 3},
{QLatin1String("half open"), 4}, {QLatin1String("three quarters open"), 5} } };
const auto match = getMappedValue2(stringValue, RConfigSwingModeValues);
if (!match.key.isEmpty())
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0045, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigFanMode) // String
{
static const std::array<KeyValMap, 7> RConfigFanModeValues = { { {QLatin1String("off"), 0}, {QLatin1String("low"), 1}, {QLatin1String("medium"), 2}, {QLatin1String("high"), 3},
{QLatin1String("on"), 4}, {QLatin1String("auto"), 5}, {QLatin1String("smart"), 6}} };
const auto match = getMappedValue2(stringValue, RConfigFanModeValues);
if (!match.key.isEmpty())
{
if (addTaskFanControlReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigControlSequence) // Unsigned integer
{
static const std::array<KeyValMapInt, 6> RConfigControlSequenceValues = { { {1, COOLING_ONLY}, {2, COOLING_WITH_REHEAT}, {3, HEATING_ONLY}, {4, HEATING_WITH_REHEAT},
{5, COOLING_AND_HEATING_4PIPES}, {6, COOLING_AND_HEATING_4PIPES_WITH_REHEAT} } };
const auto match = getMappedValue2(stringValue, RConfigControlSequenceValues);
if (match.key)
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x001B, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigPulseConfiguration) // Unsigned integer
{
if (uintValue <= UINT16_MAX &&
addTaskSimpleMeteringReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0300, deCONZ::Zcl16BitUint, uintValue, VENDOR_DEVELCO))
{
updated = true;
}
}
else if (rid.suffix == RConfigInterfaceMode) // Unsigned integer
{
quint16 data = 0xFFFF;
if (sensor->modelId().startsWith(QLatin1String("EMIZB-1")))
{
static const std::array<KeyValMapInt, 8> RConfigInterfaceModeValuesZHEMI = { { {1, PULSE_COUNTING_ELECTRICITY}, {2, PULSE_COUNTING_GAS}, {3, PULSE_COUNTING_WATER},
{4, KAMSTRUP_KMP}, {5, LINKY}, {6, DLMS_COSEM}, {7, DSMR_23}, {8, DSMR_40} } };
const auto match = getMappedValue2(uintValue, RConfigInterfaceModeValuesZHEMI);
if (match.key)
{
data = match.value;
}
}
else if (sensor->modelId().startsWith(QLatin1String("EMIZB-1")))
{
static const std::array<KeyValMapInt, 5> RConfigInterfaceModeValuesEMIZB = { { {1, NORWEGIAN_HAN}, {2, NORWEGIAN_HAN_EXTRA_LOAD}, {3, AIDON_METER},
{4, KAIFA_KAMSTRUP_METERS}, {5, AUTO_DETECT} } };
const auto match = getMappedValue2(uintValue, RConfigInterfaceModeValuesEMIZB);
if (match.key)
{
data = match.value;
}
}
if (data != 0xFFFF)
{
if (addTaskSimpleMeteringReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0302, deCONZ::Zcl16BitEnum, data, VENDOR_DEVELCO))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigWindowCoveringType) // Unsigned integer
{
if (sensor->modelId().startsWith(QLatin1String("J1")))
{
if (addTaskWindowCoveringCalibrate(task, uintValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigGroup) // String
{
checkSensorBindingsForClientClusters(sensor);
continue;
}
else if (QString(rid.suffix).startsWith("config/ubisys_j1_"))
{
uint16_t mfrCode = VENDOR_UBISYS;
uint16_t attrId;
uint8_t attrType = deCONZ::Zcl16BitUint;
if (rid.suffix == RConfigUbisysJ1Mode)
{
mfrCode = 0x0000;
attrId = 0x0017;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1WindowCoveringType)
{
attrId = 0x0000;
attrType = deCONZ::Zcl8BitEnum;
}
else if (rid.suffix == RConfigUbisysJ1ConfigurationAndStatus)
{
attrId = 0x0007;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitLift)
{
attrId = 0x0010;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitLift)
{
attrId = 0x0011;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitTilt)
{
attrId = 0x0012;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitTilt)
{
attrId = 0x0013;
}
else if (rid.suffix == RConfigUbisysJ1TurnaroundGuardTime)
{
attrId = 0x1000;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps)
{
attrId = 0x1001;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps)
{
attrId = 0x1002;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps2)
{
attrId = 0x1003;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps2)
{
attrId = 0x1004;
}
else if (rid.suffix == RConfigUbisysJ1AdditionalSteps)
{
attrId = 0x1005;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1InactivePowerThreshold)
{
attrId = 0x1006;
}
else if (rid.suffix == RConfigUbisysJ1StartupSteps)
{
attrId = 0x1007;
}
else
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (addTaskWindowCoveringSetAttr(task, mfrCode, attrId, attrType, uintValue))
{
updated = true;
}
}
if (invalidValue)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(map[pi.key()].toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (updated)
{
if (item->setValue(val))
{
if (item->lastChanged() == item->lastSet())
{
updated = true;
}
rspItemState[QString("/sensors/%1/config/%2").arg(id).arg(pi.key())] = val;
rspItem["success"] = rspItemState;
Event e(RSensors, rid.suffix, id, item);
enqueueEvent(e);
}
updated = false;
}
else
{
rsp.list.append(errorToMap(ERR_ACTION_ERROR, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QLatin1String("Could not set attribute")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else // Resource item not found for the device
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else // Non-existing resource item
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
//Make Thermostat Tasks
if (hostFlags != 0 && sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit)
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4008, deCONZ::Zcl24BitUint, hostFlags))
{
updated = true;
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/hostflags"), QString("could not set attribute")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (tholdUpdated)
{
ResourceItem *item = sensor->item(RStateLightLevel);
if (item)
{
quint16 lightlevel = item->toNumber();
item = sensor->item(RConfigTholdDark);
if (item)
{
quint16 tholddark = item->toNumber();
item = sensor->item(RConfigTholdOffset);
if (item)
{
quint16 tholdoffset = item->toNumber();
bool dark = lightlevel <= tholddark;
bool daylight = lightlevel >= tholddark + tholdoffset;
item = sensor->item(RStateDark);
if (!item)
{
item = sensor->addItem(DataTypeBool, RStateDark);
}
if (item && item->setValue(dark))
{
if (item->lastChanged() == item->lastSet())
{
Event e(RSensors, RStateDark, sensor->id(), item);
enqueueEvent(e);
}
}
item = sensor->item(RStateDaylight);
if (!item)
{
item = sensor->addItem(DataTypeBool, RStateDaylight);
}
if (item && item->setValue(daylight))
{
if (item->lastChanged() == item->lastSet())
{
Event e(RSensors, RStateDaylight, sensor->id(), item);
enqueueEvent(e);
}
}
}
}
}
}
if (offsetUpdated)
{
ResourceItem *item = sensor->item(RStateTemperature);
if (item)
{
qint16 temp = item->toNumber();
temp += offset;
if (item->setValue(temp))
{
Event e(RSensors, RStateTemperature, sensor->id(), item);
enqueueEvent(e);
}
}
item = sensor->item(RStateHumidity);
if (item)
{
quint16 humidity = item->toNumber();
qint16 _humidity = humidity + offset;
humidity = _humidity < 0 ? 0 : _humidity > 10000 ? 10000 : _humidity;
if (item->setValue(humidity))
{
Event e(RSensors, RStateHumidity, sensor->id(), item);
enqueueEvent(e);
}
}
}
if (pendingMask)
{
ResourceItem *item = sensor->item(RConfigPending);
if (item)
{
quint16 mask = item->toNumber();
mask |= pendingMask;
item->setValue(mask);
Event e(RSensors, RConfigPending, sensor->id(), item);
enqueueEvent(e);
}
}
rsp.list.append(rspItem);
updateSensorEtag(sensor);
if (updated)
{
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
processTasks();
return REQ_READY_SEND;
}
/*! POST, DELETE /api/<apikey>/sensors/<id>/config/schedule/Wbbb
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeThermostatSchedule(const ApiRequest &req, ApiResponse &rsp)
{
rsp.httpStatus = HttpStatusOk;
// Get the /sensors/id resource.
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
// Check that it has config/schedule.
ResourceItem *item = sensor->item(RConfigSchedule);
if (!item)
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/config/schedule").arg(id), QString("resource, /sensors/%1/config/schedule, not available").arg(id)));
return REQ_READY_SEND;
}
// Check valid weekday pattern
bool ok;
uint bbb = req.path[6].mid(1).toUInt(&ok);
if (req.path[6].left(1) != "W" || !ok || bbb < 1 || bbb > 127)
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("resource, /sensors/%1/config/schedule/%2, not available").arg(id).arg(req.path[6])));
return REQ_READY_SEND;
}
quint8 weekdays = bbb;
// Check body
QString transitions = QString("");
if (req.hdr.method() == "POST")
{
QVariant var = Json::parse(req.content, ok);
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
QVariantList list = var.toList();
// QString transitions = QString("");
if (!serialiseThermostatTransitions(list, &transitions))
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("body contains invalid list of transitions")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (req.sock)
{
userActivity();
}
bool ok2 = false;
// Queue task.
TaskItem task;
task.req.dstAddress() = sensor->address();
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_2);
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_1);
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_4);
}
else
{
ok2 = addTaskThermostatSetWeeklySchedule(task, weekdays, transitions);
}
if (!ok2)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("could not set schedule")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
QVariantMap rspItem;
QVariantMap rspItemState;
if (req.hdr.method() == "POST")
{
QVariantList l;
deserialiseThermostatTransitions(transitions, &l);
rspItemState[QString("/config/schedule/W%1").arg(weekdays)] = l;
rspItem["success"] = rspItemState;
}
else
{
rspItem["success"] = QString("/sensors/%1/config/schedule/W%2 deleted.").arg(id).arg(weekdays);
}
rsp.list.append(rspItem);
updateThermostatSchedule(sensor, weekdays, transitions);
processTasks();
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>/state
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeSensorState(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
bool ok;
bool updated = false;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/state").arg(id), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool isClip = sensor->type().startsWith(QLatin1String("CLIP"));
if (req.sock)
{
userActivity();
}
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
ResourceItem *item = nullptr;
ResourceItemDescriptor rid;
if (getResourceItemDescriptor(QString("state/%1").arg(pi.key()), rid))
{
if (rid.suffix == RStateButtonEvent)
{
// allow modify physical switch buttonevent via api
}
else if (!isClip)
{
continue;
}
if (rid.suffix != RStateLux && rid.suffix != RStateDark && rid.suffix != RStateDaylight)
{
item = sensor->item(rid.suffix);
}
if (item)
{
QVariant val = map[pi.key()];
if (rid.suffix == RStateTemperature || rid.suffix == RStateHumidity)
{
ResourceItem *item2 = sensor->item(RConfigOffset);
if (item2 && item2->toNumber() != 0) {
val = val.toInt() + item2->toNumber();
if (rid.suffix == RStateHumidity)
{
val = val < 0 ? 0 : val > 10000 ? 10000 : val;
}
}
}
if (item->setValue(val))
{
rspItemState[QString("/sensors/%1/state/%2").arg(id).arg(pi.key())] = val;
rspItem["success"] = rspItemState;
if (rid.suffix == RStateButtonEvent || // always fire events for buttons
item->lastChanged() == item->lastSet())
{
updated = true;
Event e(RSensors, rid.suffix, id, item);
enqueueEvent(e);
}
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateLastUpdated, id));
if (rid.suffix == RStateLightLevel)
{
ResourceItem *item2 = 0;
quint16 measuredValue = val.toUInt();
quint16 tholddark = R_THOLDDARK_DEFAULT;
quint16 tholdoffset = R_THOLDOFFSET_DEFAULT;
item2 = sensor->item(RConfigTholdDark);
if (item2)
{
tholddark = item2->toNumber();
}
item2 = sensor->item(RConfigTholdOffset);
if (item2)
{
tholdoffset = item2->toNumber();
}
bool dark = measuredValue <= tholddark;
bool daylight = measuredValue >= tholddark + tholdoffset;
item2 = sensor->item(RStateDark);
if (!item2)
{
item2 = sensor->addItem(DataTypeBool, RStateDark);
}
if (item2->setValue(dark))
{
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateDark, id, item2);
enqueueEvent(e);
}
}
item2 = sensor->item(RStateDaylight);
if (!item2)
{
item2 = sensor->addItem(DataTypeBool, RStateDaylight);
}
if (item2->setValue(daylight))
{
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateDaylight, id, item2);
enqueueEvent(e);
}
}
item2 = sensor->item(RStateLux);
if (!item2)
{
item2 = sensor->addItem(DataTypeUInt32, RStateLux);
}
quint32 lux = 0;
if (measuredValue > 0 && measuredValue < 0xffff)
{
// valid values are 1 - 0xfffe
// 0, too low to measure
// 0xffff invalid value
// ZCL Attribute = 10.000 * log10(Illuminance (lx)) + 1
// lux = 10^((ZCL Attribute - 1)/10.000)
qreal exp = measuredValue - 1;
qreal l = qPow(10, exp / 10000.0f);
l += 0.5; // round value
lux = static_cast<quint32>(l);
}
item2->setValue(lux);
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateLux, id, item2);
enqueueEvent(e);
}
}
else if (rid.suffix == RStatePresence)
{
ResourceItem *item2 = sensor->item(RConfigDuration);
if (item2 && item2->toNumber() > 0)
{
sensor->durationDue = QDateTime::currentDateTime().addSecs(item2->toNumber()).addMSecs(-500);
}
}
}
else // invalid
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/state/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(val.toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
if (!item)
{
// not found
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/state/%2").arg(id).arg(pi.key()), QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
rsp.list.append(rspItem);
updateSensorEtag(sensor);
if (updated)
{
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_HUGE_SAVE_DELAY);
}
return REQ_READY_SEND;
}
/*! DELETE /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::deleteSensor(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
userActivity();
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1").arg(id), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
sensor->setDeletedState(Sensor::StateDeleted);
sensor->setNeedSaveDatabase(true);
Event e(RSensors, REventDeleted, sensor->id());
enqueueEvent(e);
bool hasReset = map.contains("reset");
if (hasReset)
{
if (map["reset"].type() == QVariant::Bool)
{
bool reset = map["reset"].toBool();
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/sensors/%1/reset").arg(id)] = reset;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
if (reset)
{
sensor->setResetRetryCount(10);
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/reset").arg(id), QString("invalid value, %1, for parameter, reset").arg(map["reset"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState["id"] = id;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
rsp.httpStatus = HttpStatusOk;
}
{
Q_Q(DeRestPlugin);
q->nodeUpdated(sensor->address().ext(), QLatin1String("deleted"), QLatin1String(""));
}
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::searchNewSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!isInNetwork())
{
rsp.list.append(errorToMap(ERR_NOT_CONNECTED, QLatin1String("/sensors"), QLatin1String("Not connected")));
rsp.httpStatus = HttpStatusServiceUnavailable;
return REQ_READY_SEND;
}
startSearchSensors();
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QLatin1String("/sensors")] = QLatin1String("Searching for new devices");
rspItemState[QLatin1String("/sensors/duration")] = (double)searchSensorsTimeout;
rspItem[QLatin1String("success")] = rspItemState;
rsp.list.append(rspItem);
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/new
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getNewSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!searchSensorsResult.isEmpty() &&
(searchSensorsState == SearchSensorsActive || searchSensorsState == SearchSensorsDone))
{
rsp.map = searchSensorsResult;
}
if (searchSensorsState == SearchSensorsActive)
{
rsp.map["lastscan"] = QLatin1String("active");
}
else if (searchSensorsState == SearchSensorsDone)
{
rsp.map["lastscan"] = lastSensorsScan;
}
else
{
rsp.map["lastscan"] = QLatin1String("none");
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! Put all sensor parameters in a map.
\return true - on success
false - on error
*/
bool DeRestPluginPrivate::sensorToMap(const Sensor *sensor, QVariantMap &map, const ApiRequest &req)
{
if (!sensor)
{
return false;
}
QVariantMap state;
const ResourceItem *iox = nullptr;
const ResourceItem *ioy = nullptr;
const ResourceItem *ioz = nullptr;
QVariantList orientation;
const ResourceItem *ix = nullptr;
const ResourceItem *iy = nullptr;
QVariantList xy;
QVariantMap config;
const ResourceItem *ilcs = nullptr;
const ResourceItem *ilca = nullptr;
const ResourceItem *ilct = nullptr;
QVariantMap lastchange;
for (int i = 0; i < sensor->itemCount(); i++)
{
const ResourceItem *item = sensor->itemForIndex(static_cast<size_t>(i));
DBG_Assert(item);
const ResourceItemDescriptor &rid = item->descriptor();
if (!item->isPublic())
{
continue;
}
if (rid.suffix == RConfigLat || rid.suffix == RConfigLong)
{
continue; // don't return due privacy reasons
}
if (rid.suffix == RConfigHostFlags)
{
continue; // hidden
}
if (rid.suffix == RConfigReachable &&
sensor->type().startsWith(QLatin1String("ZGP")))
{
continue; // don't provide reachable for green power devices
}
if (strncmp(rid.suffix, "config/", 7) == 0)
{
const char *key = item->descriptor().suffix + 7;
if (rid.suffix == RConfigPending)
{
QVariantList pending;
auto value = item->toNumber();
if (value & R_PENDING_DELAY)
{
pending.append("delay");
}
if (value & R_PENDING_LEDINDICATION)
{
pending.append("ledindication");
}
if (value & R_PENDING_SENSITIVITY)
{
pending.append("sensitivity");
}
if (value & R_PENDING_USERTEST)
{
pending.append("usertest");
}
if (value & R_PENDING_DEVICEMODE)
{
pending.append("devicemode");
}
config[key] = pending;
}
else if (rid.suffix == RConfigLastChangeSource)
{
ilcs = item;
}
else if (rid.suffix == RConfigLastChangeAmount)
{
ilca = item;
}
else if (rid.suffix == RConfigLastChangeTime)
{
ilct = item;
}
else if (rid.suffix == RConfigSchedule)
{
QVariantMap schedule;
deserialiseThermostatSchedule(item->toString(), &schedule);
config[key] = schedule;
}
else
{
config[key] = item->toVariant();
}
}
if (strncmp(rid.suffix, "state/", 6) == 0)
{
const char *key = item->descriptor().suffix + 6;
if (rid.suffix == RStateLastUpdated)
{
if (!item->lastSet().isValid() || item->lastSet().date().year() < 2000)
{
state[key] = QLatin1String("none");
}
else
{
state[key] = item->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ss.zzz");
}
}
else if (rid.suffix == RStateOrientationX)
{
iox = item;
}
else if (rid.suffix == RStateOrientationY)
{
ioy = item;
}
else if (rid.suffix == RStateOrientationZ)
{
ioz = item;
}
else if (rid.suffix == RStateX)
{
ix = item;
}
else if (rid.suffix == RStateY)
{
iy = item;
}
else
{
state[key] = item->toVariant();
}
}
}
if (iox && ioy && ioz)
{
orientation.append(iox->toNumber());
orientation.append(ioy->toNumber());
orientation.append(ioz->toNumber());
state["orientation"] = orientation;
}
if (ix && iy)
{
xy.append(round(ix->toNumber() / 6.5535) / 10000.0);
xy.append(round(iy->toNumber() / 6.5535) / 10000.0);
state["xy"] = xy;
}
if (ilcs && ilca && ilct)
{
lastchange["source"] = RConfigLastChangeSourceValues[ilcs->toNumber()];
lastchange["amount"] = ilca->toNumber();
lastchange["time"] = ilct->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ssZ");
config["lastchange"] = lastchange;
}
//sensor
map["name"] = sensor->name();
map["type"] = sensor->type();
if (sensor->type().startsWith(QLatin1String("Z"))) // ZigBee sensor
{
map["lastseen"] = sensor->lastRx().toUTC().toString("yyyy-MM-ddTHH:mmZ");
}
if (req.path.size() > 2 && req.path[2] == QLatin1String("devices"))
{
// don't add in sub device
}
else
{
if (!sensor->modelId().isEmpty())
{
map["modelid"] = sensor->modelId();
}
if (!sensor->manufacturer().isEmpty())
{
map["manufacturername"] = sensor->manufacturer();
}
if (!sensor->swVersion().isEmpty() && !sensor->type().startsWith(QLatin1String("ZGP")))
{
map["swversion"] = sensor->swVersion();
}
if (sensor->fingerPrint().endpoint != INVALID_ENDPOINT)
{
map["ep"] = sensor->fingerPrint().endpoint;
}
QString etag = sensor->etag;
etag.remove('"'); // no quotes allowed in string
map["etag"] = etag;
}
// whitelist, HueApp crashes on ZHAAlarm and ZHAPressure
if (req.mode == ApiModeHue)
{
if (!(sensor->type() == QLatin1String("Daylight") ||
sensor->type() == QLatin1String("CLIPGenericFlag") ||
sensor->type() == QLatin1String("CLIPGenericStatus") ||
sensor->type() == QLatin1String("CLIPSwitch") ||
sensor->type() == QLatin1String("CLIPOpenClose") ||
sensor->type() == QLatin1String("CLIPPresence") ||
sensor->type() == QLatin1String("CLIPTemperature") ||
sensor->type() == QLatin1String("CLIPHumidity") ||
sensor->type() == QLatin1String("CLIPLightlevel") ||
sensor->type() == QLatin1String("ZGPSwitch") ||
sensor->type() == QLatin1String("ZHASwitch") ||
sensor->type() == QLatin1String("ZHAOpenClose") ||
sensor->type() == QLatin1String("ZHAPresence") ||
sensor->type() == QLatin1String("ZHATemperature") ||
sensor->type() == QLatin1String("ZHAHumidity") ||
sensor->type() == QLatin1String("ZHALightLevel")))
{
return false;
}
// mimic Hue Dimmer Switch
if (sensor->modelId() == QLatin1String("TRADFRI wireless dimmer") ||
sensor->modelId() == QLatin1String("lumi.sensor_switch.aq2"))
{
map["manufacturername"] = "Philips";
map["modelid"] = "RWL021";
}
// mimic Hue motion sensor
else if (false)
{
map["manufacturername"] = "Philips";
map["modelid"] = "SML001";
}
}
if (req.mode != ApiModeNormal &&
sensor->manufacturer().startsWith(QLatin1String("Philips")) &&
sensor->type().startsWith(QLatin1String("ZHA")))
{
QString type = sensor->type();
type.replace(QLatin1String("ZHA"), QLatin1String("ZLL"));
map["type"] = type;
}
if (sensor->mode() != Sensor::ModeNone &&
sensor->type().endsWith(QLatin1String("Switch")))
{
map["mode"] = (double)sensor->mode();
}
const ResourceItem *item = sensor->item(RAttrUniqueId);
if (item)
{
map["uniqueid"] = item->toString();
}
map["state"] = state;
map["config"] = config;
return true;
}
void DeRestPluginPrivate::handleSensorEvent(const Event &e)
{
DBG_Assert(e.resource() == RSensors);
DBG_Assert(e.what() != nullptr);
Sensor *sensor = getSensorNodeForId(e.id());
if (!sensor)
{
return;
}
const QDateTime now = QDateTime::currentDateTime();
// speedup sensor state check
if ((e.what() == RStatePresence || e.what() == RStateButtonEvent) &&
sensor && sensor->durationDue.isValid())
{
sensorCheckFast = CHECK_SENSOR_FAST_ROUNDS;
}
// push sensor state updates through websocket
if (strncmp(e.what(), "state/", 6) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
if (item->descriptor().suffix == RStatePresence && item->toBool())
{
globalLastMotion = item->lastSet(); // remember
}
if (!(item->needPushSet() || item->needPushChange()))
{
DBG_Printf(DBG_INFO_L2, "discard sensor state push for %s: %s (already pushed)\n", qPrintable(e.id()), e.what());
webSocketServer->flush(); // force transmit send buffer
return; // already pushed
}
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap state;
ResourceItem *iox = nullptr;
ResourceItem *ioy = nullptr;
ResourceItem *ioz = nullptr;
ResourceItem *ix = nullptr;
ResourceItem *iy = nullptr;
for (int i = 0; i < sensor->itemCount(); i++)
{
item = sensor->itemForIndex(i);
const ResourceItemDescriptor &rid = item->descriptor();
if (strncmp(rid.suffix, "state/", 6) == 0)
{
const char *key = item->descriptor().suffix + 6;
if (rid.suffix == RStateOrientationX)
{
iox = item;
}
else if (rid.suffix == RStateOrientationY)
{
ioy = item;
}
else if (rid.suffix == RStateOrientationZ)
{
ioz = item;
}
else if (rid.suffix == RStateX)
{
ix = item;
}
else if (rid.suffix == RStateY)
{
iy = item;
}
else if (item->isPublic() && item->lastSet().isValid() && (gwWebSocketNotifyAll || rid.suffix == RStateButtonEvent || item->needPushChange()))
{
state[key] = item->toVariant();
item->clearNeedPush();
}
}
}
if (iox && iox->lastSet().isValid() && ioy && ioy->lastSet().isValid() && ioz && ioz->lastSet().isValid())
{
if (gwWebSocketNotifyAll || iox->needPushChange() || ioy->needPushChange() || ioz->needPushChange())
{
iox->clearNeedPush();
ioy->clearNeedPush();
ioz->clearNeedPush();
QVariantList orientation;
orientation.append(iox->toNumber());
orientation.append(ioy->toNumber());
orientation.append(ioz->toNumber());
state["orientation"] = orientation;
}
}
if (ix && ix->lastSet().isValid() && iy && iy->lastSet().isValid())
{
if (gwWebSocketNotifyAll || ix->needPushChange() || iy->needPushChange())
{
ix->clearNeedPush();
iy->clearNeedPush();
QVariantList xy;
xy.append(round(ix->toNumber() / 6.5535) / 10000.0);
xy.append(round(iy->toNumber() / 6.5535) / 10000.0);
state["xy"] = xy;
}
}
if (!state.isEmpty())
{
map["state"] = state;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
}
else if (strncmp(e.what(), "config/", 7) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
if (!(item->needPushSet() || item->needPushChange()))
{
DBG_Printf(DBG_INFO_L2, "discard sensor config push for %s (already pushed)\n", e.what());
return; // already pushed
}
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap config;
ResourceItem *ilcs = nullptr;
ResourceItem *ilca = nullptr;
ResourceItem *ilct = nullptr;
for (int i = 0; i < sensor->itemCount(); i++)
{
item = sensor->itemForIndex(i);
const ResourceItemDescriptor &rid = item->descriptor();
if (strncmp(rid.suffix, "config/", 7) == 0)
{
const char *key = item->descriptor().suffix + 7;
if (rid.suffix == RConfigHostFlags)
{
continue;
}
else if (rid.suffix == RConfigLastChangeSource)
{
ilcs = item;
}
else if (rid.suffix == RConfigLastChangeAmount)
{
ilca = item;
}
else if (rid.suffix == RConfigLastChangeTime)
{
ilct = item;
}
else if (item->isPublic() && item->lastSet().isValid() && (gwWebSocketNotifyAll || item->needPushChange()))
{
if (rid.suffix == RConfigSchedule)
{
QVariantMap schedule;
deserialiseThermostatSchedule(item->toString(), &schedule);
config[key] = schedule;
}
else if (rid.suffix == RConfigPending)
{
QVariantList pending;
auto value = item->toNumber();
if (value & R_PENDING_DELAY)
{
pending.append("delay");
}
if (value & R_PENDING_LEDINDICATION)
{
pending.append("ledindication");
}
if (value & R_PENDING_SENSITIVITY)
{
pending.append("sensitivity");
}
if (value & R_PENDING_USERTEST)
{
pending.append("usertest");
}
if (value & R_PENDING_DEVICEMODE)
{
pending.append("devicemode");
}
config[key] = pending;
}
else
{
config[key] = item->toVariant();
}
item->clearNeedPush();
}
}
}
if (ilcs && ilcs->lastSet().isValid() && ilca && ilca->lastSet().isValid() && ilct && ilct->lastSet().isValid())
{
if (gwWebSocketNotifyAll || ilcs->needPushChange() || ilca->needPushChange() || ilct->needPushChange())
{
ilcs->clearNeedPush();
ilca->clearNeedPush();
ilct->clearNeedPush();
QVariantMap lastchange;
lastchange["source"] = RConfigLastChangeSourceValues[ilcs->toNumber()];
lastchange["amount"] = ilca->toNumber();
lastchange["time"] = ilct->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ssZ");
config["lastchange"] = lastchange;
}
}
if (!config.isEmpty())
{
map["config"] = config;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
}
else if (strncmp(e.what(), "attr/", 5) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap config;
// For now, don't collect top-level attributes into a single event.
const char *key = item->descriptor().suffix + 5;
map[key] = item->toVariant();
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
else if (e.what() == REventAdded)
{
checkSensorGroup(sensor);
checkSensorBindingsForAttributeReporting(sensor);
checkSensorBindingsForClientClusters(sensor);
pushSensorInfoToCore(sensor);
QVariantMap res;
res["name"] = sensor->name();
searchSensorsResult[sensor->id()] = res;
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("added");
map["r"] = QLatin1String("sensors");
QVariantMap smap;
QHttpRequestHeader hdr; // dummy
QStringList path; // dummy
ApiRequest req(hdr, path, nullptr, QLatin1String("")); // dummy
req.mode = ApiModeNormal;
sensorToMap(sensor, smap, req);
map["id"] = sensor->id();
map["uniqueid"] = sensor->uniqueId();
smap["id"] = sensor->id();
map["sensor"] = smap;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
else if (e.what() == REventDeleted)
{
deleteGroupsWithDeviceMembership(e.id());
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("deleted");
map["r"] = QLatin1String("sensors");
QVariantMap smap;
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
smap["id"] = e.id();
map["sensor"] = smap;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
else if (e.what() == REventValidGroup)
{
checkOldSensorGroups(sensor);
ResourceItem *item = sensor->item(RConfigGroup);
DBG_Assert(item != nullptr);
if (!item)
{
return;
}
QStringList gids = item->toString().split(',', QString::SkipEmptyParts);
for (int j = 0; j < gids.size(); j++) {
const QString gid = gids[j];
if (gid == "0")
{
continue;
}
Group *group = getGroupForId(gid);
if (group && group->state() != Group::StateNormal)
{
DBG_Printf(DBG_INFO, "reanimate group %s for sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
group->setState(Group::StateNormal);
group->setName(sensor->modelId() + QLatin1String(" ") + sensor->id());
updateGroupEtag(group);
queSaveDb(DB_GROUPS, DB_SHORT_SAVE_DELAY);
}
if (group && group->addDeviceMembership(sensor->id()))
{
DBG_Printf(DBG_INFO, "attach group %s to sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
queSaveDb(DB_GROUPS, DB_LONG_SAVE_DELAY);
updateGroupEtag(group);
}
if (!group) // create
{
DBG_Printf(DBG_INFO, "create group %s for sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
Group g;
g.setAddress(gid.toUInt());
g.setName(sensor->modelId() + QLatin1String(" ") + sensor->id());
g.addDeviceMembership(sensor->id());
ResourceItem *item2 = g.addItem(DataTypeString, RAttrUniqueId);
DBG_Assert(item2);
if (item2)
{
// FIXME: use the endpoint from which the group command was sent.
const QString uid = generateUniqueId(sensor->address().ext(), 0, 0);
item2->setValue(uid);
}
groups.push_back(g);
updateGroupEtag(&groups.back());
queSaveDb(DB_GROUPS, DB_SHORT_SAVE_DELAY);
checkSensorBindingsForClientClusters(sensor);
}
}
}
}
/*! Starts the search for new sensors.
*/
void DeRestPluginPrivate::startSearchSensors()
{
if (searchSensorsState == SearchSensorsIdle || searchSensorsState == SearchSensorsDone)
{
pollNodes.clear();
bindingQueue.clear();
sensors.reserve(sensors.size() + 10);
searchSensorsCandidates.clear();
searchSensorsResult.clear();
lastSensorsScan = QDateTime::currentDateTimeUtc().toString(QLatin1String("yyyy-MM-ddTHH:mm:ss"));
QTimer::singleShot(1000, this, SLOT(searchSensorsTimerFired()));
searchSensorGppPairCounter = 0;
searchSensorsState = SearchSensorsActive;
}
else
{
Q_ASSERT(searchSensorsState == SearchSensorsActive);
}
searchSensorsTimeout = gwNetworkOpenDuration;
gwPermitJoinResend = searchSensorsTimeout;
if (!resendPermitJoinTimer->isActive())
{
resendPermitJoinTimer->start(100);
}
}
/*! Handler for search sensors active state.
*/
void DeRestPluginPrivate::searchSensorsTimerFired()
{
if (gwPermitJoinResend == 0)
{
if (gwPermitJoinDuration == 0)
{
searchSensorsTimeout = 0; // done
}
}
if (searchSensorsTimeout > 0)
{
searchSensorsTimeout--;
QTimer::singleShot(1000, this, SLOT(searchSensorsTimerFired()));
}
if (searchSensorsTimeout == 0)
{
DBG_Printf(DBG_INFO, "Search sensors done\n");
fastProbeAddr = deCONZ::Address();
fastProbeIndications.clear();
searchSensorsState = SearchSensorsDone;
}
}
/*! Validate sensor states. */
void DeRestPluginPrivate::checkSensorStateTimerFired()
{
if (sensors.empty())
{
return;
}
if (sensorCheckIter >= sensors.size())
{
sensorCheckIter = 0;
sensorCheckFast = (sensorCheckFast > 0) ? sensorCheckFast - 1 : 0;
}
for (int i = 0; i < CHECK_SENSORS_MAX; i++)
{
if (sensorCheckIter >= sensors.size())
{
break;
}
Sensor *sensor = &sensors[sensorCheckIter];
sensorCheckIter++;
if (sensor->deletedState() != Sensor::StateNormal)
{
continue;
}
if (sensor->durationDue.isValid())
{
QDateTime now = QDateTime::currentDateTime();
if (sensor->modelId() == QLatin1String("TY0202")) // Lidl/SILVERCREST motion sensor
{
continue; // will be only reset via IAS Zone status
}
if (sensor->durationDue <= now)
{
// automatically set presence to false, if not triggered in config.duration
ResourceItem *item = sensor->item(RStatePresence);
if (item && item->toBool())
{
DBG_Printf(DBG_INFO, "sensor %s (%s): disable presence\n", qPrintable(sensor->id()), qPrintable(sensor->modelId()));
item->setValue(false);
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStatePresence, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
for (quint16 clusterId : sensor->fingerPrint().inClusters)
{
if (sensor->modelId().startsWith(QLatin1String("TRADFRI")))
{
clusterId = OCCUPANCY_SENSING_CLUSTER_ID; // workaround
}
if (clusterId == IAS_ZONE_CLUSTER_ID || clusterId == OCCUPANCY_SENSING_CLUSTER_ID)
{
pushZclValueDb(sensor->address().ext(), sensor->fingerPrint().endpoint, clusterId, 0x0000, 0);
break;
}
}
}
else if (!item && sensor->modelId() == QLatin1String("lumi.sensor_switch"))
{
// Xiaomi round button (WXKG01LM)
// generate artificial hold event
item = sensor->item(RStateButtonEvent);
if (item && item->toNumber() == (S_BUTTON_1 + S_BUTTON_ACTION_INITIAL_PRESS))
{
item->setValue(S_BUTTON_1 + S_BUTTON_ACTION_HOLD);
DBG_Printf(DBG_INFO, "[INFO] - Button %u Hold %s\n", item->toNumber(), qPrintable(sensor->modelId()));
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateButtonEvent, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
else if (sensor->modelId() == QLatin1String("FOHSWITCH"))
{
// Friends of Hue switch
// generate artificial hold event
item = sensor->item(RStateButtonEvent);
quint32 btn = item ? static_cast<quint32>(item->toNumber()) : 0;
const quint32 action = btn & 0x03;
if (btn >= S_BUTTON_1 && btn <= S_BUTTON_6 && action == S_BUTTON_ACTION_INITIAL_PRESS)
{
btn &= ~0x03;
item->setValue(btn + S_BUTTON_ACTION_HOLD);
DBG_Printf(DBG_INFO, "FoH switch button %d Hold %s\n", item->toNumber(), qPrintable(sensor->modelId()));
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateButtonEvent, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
else if (!item && sensor->modelId().startsWith(QLatin1String("lumi.vibration")) && sensor->type() == QLatin1String("ZHAVibration"))
{
item = sensor->item(RStateVibration);
if (item && item->toBool())
{
DBG_Printf(DBG_INFO, "sensor %s (%s): disable vibration\n", qPrintable(sensor->id()), qPrintable(sensor->modelId()));
item->setValue(false);
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateVibration, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
sensor->durationDue = QDateTime();
}
else
{
sensorCheckFast = CHECK_SENSOR_FAST_ROUNDS;
}
}
}
// adjust check speed if needed
int interval = (sensorCheckFast > 0) ? CHECK_SENSOR_FAST_INTERVAL
: CHECK_SENSOR_INTERVAL;
if (interval != checkSensorsTimer->interval())
{
DBG_Printf(DBG_INFO, "Set sensor check interval to %d milliseconds\n", interval);
checkSensorsTimer->setInterval(interval);
}
}
/*! Check insta mac address to model identifier.
*/
void DeRestPluginPrivate::checkInstaModelId(Sensor *sensor)
{
if (sensor && existDevicesWithVendorCodeForMacPrefix(sensor->address(), VENDOR_INSTA))
{
if (!sensor->modelId().endsWith(QLatin1String("_1")))
{ // extract model identifier from mac address 6th byte
const quint64 model = (sensor->address().ext() >> 16) & 0xff;
QString modelId;
if (model == 0x01) { modelId = QLatin1String("HS_4f_GJ_1"); }
else if (model == 0x02) { modelId = QLatin1String("WS_4f_J_1"); }
else if (model == 0x03) { modelId = QLatin1String("WS_3f_G_1"); }
if (!modelId.isEmpty() && sensor->modelId() != modelId)
{
sensor->setModelId(modelId);
sensor->setNeedSaveDatabase(true);
updateSensorEtag(sensor);
}
}
}
}
/*! Heuristic to detect the type and configuration of devices.
*/
void DeRestPluginPrivate::handleIndicationSearchSensors(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
if (searchSensorsState != SearchSensorsActive)
{
return;
}
if ((ind.srcAddress().hasExt() && ind.srcAddress().ext() == fastProbeAddr.ext()) ||
(fastProbeAddr.hasExt() && ind.srcAddress().hasNwk() && ind.srcAddress().nwk() == fastProbeAddr.nwk()))
{
DBG_Printf(DBG_INFO, "FP indication 0x%04X / 0x%04X (0x%016llX / 0x%04X)\n", ind.profileId(), ind.clusterId(), ind.srcAddress().ext(), ind.srcAddress().nwk());
DBG_Printf(DBG_INFO, " ... (0x%016llX / 0x%04X)\n", fastProbeAddr.ext(), fastProbeAddr.nwk());
}
if (ind.profileId() == ZDP_PROFILE_ID && ind.clusterId() == ZDP_DEVICE_ANNCE_CLID)
{
QDataStream stream(ind.asdu());
stream.setByteOrder(QDataStream::LittleEndian);
quint8 seq;
quint16 nwk;
quint64 ext;
quint8 macCapabilities;
stream >> seq;
stream >> nwk;
stream >> ext;
stream >> macCapabilities;
DBG_Printf(DBG_INFO, "device announce 0x%016llX (0x%04X) mac capabilities 0x%02X\n", ext, nwk, macCapabilities);
// filter supported devices
// Busch-Jaeger
if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_BUSCH_JAEGER))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_UBISYS))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_SUNRICHER))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_BOSCH))
{ // macCapabilities == 0
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_DEVELCO))
{ // macCapabilities == 0
}
else if (macCapabilities & deCONZ::MacDeviceIsFFD)
{
if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_LDS))
{ // Fix to allow Samsung SmartThings plug sensors to be created (7A-PL-Z-J3, modelId ZB-ONOFFPlug-D0005)
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_JASCO))
{ // Fix to support GE mains powered switches
}
else
{
return;
}
}
else if (macCapabilities == 0)
{
return;
}
if (fastProbeAddr.hasExt())
{
return;
}
DBG_Printf(DBG_INFO, "set fast probe address to 0x%016llX (0x%04X)\n", ext, nwk);
fastProbeAddr.setExt(ext);
fastProbeAddr.setNwk(nwk);
if (!fastProbeTimer->isActive())
{
fastProbeTimer->start(900);
}
fastProbeIndications.clear();
fastProbeIndications.push_back(ind);
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (i->address.ext() == ext || i->address.nwk() == nwk)
{
i->waitIndicationClusterId = 0xffff;
i->timeout.invalidate();
i->address = deCONZ::Address(); // clear
}
}
SensorCandidate sc;
sc.waitIndicationClusterId = 0xffff;
sc.address.setExt(ext);
sc.address.setNwk(nwk);
sc.macCapabilities = macCapabilities;
searchSensorsCandidates.push_back(sc);
return;
}
else if (ind.profileId() == ZDP_PROFILE_ID)
{
if (ind.clusterId() == ZDP_MATCH_DESCRIPTOR_CLID)
{
return;
}
if (!fastProbeAddr.hasExt())
{
return;
}
if (ind.srcAddress().hasExt() && fastProbeAddr.ext() != ind.srcAddress().ext())
{
return;
}
else if (ind.srcAddress().hasNwk() && fastProbeAddr.nwk() != ind.srcAddress().nwk())
{
return;
}
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (i->address.ext() == fastProbeAddr.ext())
{
DBG_Printf(DBG_INFO, "ZDP indication search sensors 0x%016llX (0x%04X) cluster 0x%04X\n", ind.srcAddress().ext(), ind.srcAddress().nwk(), ind.clusterId());
if (ind.clusterId() == i->waitIndicationClusterId && i->timeout.isValid())
{
DBG_Printf(DBG_INFO, "ZDP indication search sensors 0x%016llX (0x%04X) clear timeout on cluster 0x%04X\n", ind.srcAddress().ext(), ind.srcAddress().nwk(), ind.clusterId());
i->timeout.invalidate();
i->waitIndicationClusterId = 0xffff;
}
if (ind.clusterId() & 0x8000)
{
fastProbeIndications.push_back(ind); // remember responses
}
fastProbeTimer->stop();
fastProbeTimer->start(5);
break;
}
}
return;
}
else if (ind.profileId() == ZLL_PROFILE_ID || ind.profileId() == HA_PROFILE_ID)
{
switch (ind.clusterId())
{
case ONOFF_CLUSTER_ID:
case SCENE_CLUSTER_ID:
case LEVEL_CLUSTER_ID:
case VENDOR_CLUSTER_ID:
if ((zclFrame.frameControl() & deCONZ::ZclFCClusterCommand) == 0)
{
return;
}
if (zclFrame.frameControl() & deCONZ::ZclFCDirectionServerToClient)
{
return;
}
break; // ok
case BASIC_CLUSTER_ID:
if (!zclFrame.isProfileWideCommand())
{
return;
}
if (zclFrame.commandId() != deCONZ::ZclReadAttributesResponseId && zclFrame.commandId() != deCONZ::ZclReportAttributesId)
{
return;
}
break; // ok
case IAS_ZONE_CLUSTER_ID:
break; // ok
default:
return;
}
}
else
{
return;
}
if (ind.dstAddressMode() != deCONZ::ApsGroupAddress && ind.dstAddressMode() != deCONZ::ApsNwkAddress)
{
return;
}
SensorCandidate *sc = nullptr;
{
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (ind.srcAddress().hasExt() && i->address.ext() == ind.srcAddress().ext())
{
sc = &*i;
break;
}
if (ind.srcAddress().hasNwk() && i->address.nwk() == ind.srcAddress().nwk())
{
sc = &*i;
break;
}
}
}
if (sc && fastProbeAddr.hasExt() && sc->address.ext() == fastProbeAddr.ext())
{
if (zclFrame.manufacturerCode() == VENDOR_XIAOMI || zclFrame.manufacturerCode() == VENDOR_DSR)
{
DBG_Printf(DBG_INFO, "Remember Xiaomi special for 0x%016llX\n", ind.srcAddress().ext());
fastProbeIndications.push_back(ind); // remember Xiaomi special report
}
if (!fastProbeTimer->isActive())
{
fastProbeTimer->start(5);
}
if (ind.profileId() == ZLL_PROFILE_ID || ind.profileId() == HA_PROFILE_ID)
{
if (ind.clusterId() == sc->waitIndicationClusterId && sc->timeout.isValid())
{
DBG_Printf(DBG_INFO, "Clear fast probe timeout for cluster 0x%04X, 0x%016llX\n", ind.clusterId(), ind.srcAddress().ext());
sc->timeout.invalidate();
sc->waitIndicationClusterId = 0xffff;
}
}
}
quint8 macCapabilities = 0;
deCONZ::Address indAddress;
if (!sc)
{
Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());
if (sensor)
{
indAddress = sensor->address();
if (sensor->node())
{
macCapabilities = (int)sensor->node()->macCapabilities();
}
}
if (apsCtrl && (!sensor || (macCapabilities == 0)))
{
int i = 0;
const deCONZ::Node *node;
while (apsCtrl->getNode(i, &node) == 0)
{
/*if (node->macCapabilities() == 0)
{
// ignore
}
else*/ if (node->address().hasExt() && ind.srcAddress().hasExt() &&
ind.srcAddress().ext() == node->address().ext())
{
indAddress = node->address();
macCapabilities = node->macCapabilities();
break;
}
else if (node->address().hasNwk() && ind.srcAddress().hasNwk() &&
ind.srcAddress().nwk() == node->address().nwk())
{
indAddress = node->address();
macCapabilities = node->macCapabilities();
break;
}
i++;
}
}
}
// currently only end-devices are supported
if (!sc && (macCapabilities == 0 || (macCapabilities & deCONZ::MacDeviceIsFFD)))
{
return;
}
if (!sc && indAddress.hasExt() && indAddress.hasNwk())
{
SensorCandidate sc2;
sc2.address = indAddress;
sc2.macCapabilities = macCapabilities;
searchSensorsCandidates.push_back(sc2);
sc = &searchSensorsCandidates.back();
}
if (!sc) // we need a valid candidate from device announce or cache
{
return;
}
// check for dresden elektronik devices
if (existDevicesWithVendorCodeForMacPrefix(sc->address, VENDOR_DDEL))
{
if (sc->macCapabilities & deCONZ::MacDeviceIsFFD) // end-devices only
return;
if (ind.profileId() != HA_PROFILE_ID)
return;
SensorCommand cmd;
cmd.cluster = ind.clusterId();
cmd.endpoint = ind.srcEndpoint();
cmd.dstGroup = ind.dstAddress().group();
cmd.zclCommand = zclFrame.commandId();
cmd.zclCommandParameter = 0;
// filter
if (cmd.endpoint == 0x01 && cmd.cluster == ONOFF_CLUSTER_ID)
{
// on: Lighting and Scene Switch left button
DBG_Printf(DBG_INFO, "Lighting or Scene Switch left button\n");
}
else if (cmd.endpoint == 0x02 && cmd.cluster == ONOFF_CLUSTER_ID)
{
// on: Lighting Switch right button
DBG_Printf(DBG_INFO, "Lighting Switch right button\n");
}
else if (cmd.endpoint == 0x01 && cmd.cluster == SCENE_CLUSTER_ID && cmd.zclCommand == 0x05
&& zclFrame.payload().size() >= 3 && zclFrame.payload().at(2) == 0x04)
{
// recall scene: Scene Switch
cmd.zclCommandParameter = zclFrame.payload()[2]; // sceneId
DBG_Printf(DBG_INFO, "Scene Switch scene %u\n", cmd.zclCommandParameter);
}
else
{
return;
}
bool found = false;
for (size_t i = 0; i < sc->rxCommands.size(); i++)
{
if (sc->rxCommands[i] == cmd)
{
found = true;
break;
}
}
if (!found)
{
sc->rxCommands.push_back(cmd);
}
bool isLightingSwitch = false;
bool isSceneSwitch = false;
quint16 group1 = 0;
quint16 group2 = 0;
for (size_t i = 0; i < sc->rxCommands.size(); i++)
{
const SensorCommand &c = sc->rxCommands[i];
if (c.cluster == SCENE_CLUSTER_ID && c.zclCommandParameter == 0x04 && c.endpoint == 0x01)
{
group1 = c.dstGroup;
isSceneSwitch = true;
DBG_Printf(DBG_INFO, "Scene Switch group1 0x%04X\n", group1);
break;
}
else if (c.cluster == ONOFF_CLUSTER_ID && c.endpoint == 0x01)
{
group1 = c.dstGroup;
}
else if (c.cluster == ONOFF_CLUSTER_ID && c.endpoint == 0x02)
{
group2 = c.dstGroup;
}
if (!isSceneSwitch && group1 != 0 && group2 != 0)
{
if (group1 > group2)
{
std::swap(group1, group2); // reorder
}
isLightingSwitch = true;
DBG_Printf(DBG_INFO, "Lighting Switch group1 0x%04X, group2 0x%04X\n", group1, group2);
break;
}
}
Sensor *s1 = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x01);
Sensor *s2 = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x02);
if (isSceneSwitch || isLightingSwitch)
{
Sensor sensorNode;
SensorFingerprint &fp = sensorNode.fingerPrint();
fp.endpoint = 0x01;
fp.deviceId = DEV_ID_ZLL_COLOR_CONTROLLER;
fp.profileId = HA_PROFILE_ID;
fp.inClusters.push_back(BASIC_CLUSTER_ID);
fp.inClusters.push_back(COMMISSIONING_CLUSTER_ID);
fp.outClusters.push_back(ONOFF_CLUSTER_ID);
fp.outClusters.push_back(LEVEL_CLUSTER_ID);
fp.outClusters.push_back(SCENE_CLUSTER_ID);
sensorNode.setNode(0);
sensorNode.address() = sc->address;
sensorNode.setType("ZHASwitch");
sensorNode.fingerPrint() = fp;
sensorNode.setUniqueId(generateUniqueId(sensorNode.address().ext(), sensorNode.fingerPrint().endpoint, COMMISSIONING_CLUSTER_ID));
sensorNode.setManufacturer(QLatin1String("dresden elektronik"));
ResourceItem *item;
item = sensorNode.item(RConfigOn);
item->setValue(true);
item = sensorNode.item(RConfigReachable);
item->setValue(true);
sensorNode.addItem(DataTypeInt32, RStateButtonEvent);
sensorNode.updateStateTimestamp();
sensorNode.setNeedSaveDatabase(true);
updateSensorEtag(&sensorNode);
bool update = false;
if (!s1 && isSceneSwitch && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeScenes);
sensorNode.setModelId(QLatin1String("Scene Switch"));
sensorNode.setName(QString("Scene Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensors.push_back(sensorNode);
s1 = &sensors.back();
updateSensorEtag(s1);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
else if (isLightingSwitch)
{
if (!s1 && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeTwoGroups);
sensorNode.setModelId(QLatin1String("Lighting Switch"));
sensorNode.setName(QString("Lighting Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensors.push_back(sensorNode);
s1 = &sensors.back();
updateSensorEtag(s1);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
if (!s2 && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeTwoGroups);
sensorNode.setName(QString("Lighting Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensorNode.fingerPrint().endpoint = 0x02;
sensorNode.setUniqueId(generateUniqueId(sensorNode.address().ext(), sensorNode.fingerPrint().endpoint, COMMISSIONING_CLUSTER_ID));
sensors.push_back(sensorNode);
s2 = &sensors.back();
updateSensorEtag(s2);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
}
// check updated data
if (s1 && s1->modelId().isEmpty())
{
if (isSceneSwitch) { s1->setModelId(QLatin1String("Scene Switch")); }
else if (isLightingSwitch) { s1->setModelId(QLatin1String("Lighting Switch")); }
s1->setNeedSaveDatabase(true);
update = true;
}
if (s2 && s2->modelId().isEmpty())
{
if (isLightingSwitch) { s2->setModelId(QLatin1String("Lighting Switch")); }
s2->setNeedSaveDatabase(true);
update = true;
}
if (s1 && s1->manufacturer().isEmpty())
{
s1->setManufacturer(QLatin1String("dresden elektronik"));
s1->setNeedSaveDatabase(true);
update = true;
}
if (s2 && s2->manufacturer().isEmpty())
{
s2->setManufacturer(QLatin1String("dresden elektronik"));
s2->setNeedSaveDatabase(true);
update = true;
}
// create or update first group
Group *g = (s1 && group1 != 0) ? getGroupForId(group1) : 0;
if (!g && s1 && group1 != 0)
{
// delete older groups of this switch permanently
deleteOldGroupOfSwitch(s1, group1);
//create new switch group
Group group;
group.setAddress(group1);
group.addDeviceMembership(s1->id());
group.setName(QString("%1").arg(s1->name()));
updateGroupEtag(&group);
groups.push_back(group);
update = true;
}
else if (g && s1)
{
if (g->state() == Group::StateDeleted)
{
g->setState(Group::StateNormal);
}
// check for changed device memberships
if (!g->m_deviceMemberships.empty())
{
if (isLightingSwitch || isSceneSwitch) // only support one device member per group
{
if (g->m_deviceMemberships.size() > 1 || g->m_deviceMemberships.front() != s1->id())
{
g->m_deviceMemberships.clear();
}
}
}
if (g->addDeviceMembership(s1->id()))
{
updateGroupEtag(g);
update = true;
}
}
// create or update second group (if needed)
g = (s2 && group2 != 0) ? getGroupForId(group2) : 0;
if (!g && s2 && group2 != 0)
{
// delete older groups of this switch permanently
deleteOldGroupOfSwitch(s2, group2);
//create new switch group
Group group;
group.setAddress(group2);
group.addDeviceMembership(s2->id());
group.setName(QString("%1").arg(s2->name()));
updateGroupEtag(&group);
groups.push_back(group);
}
else if (g && s2)
{
if (g->state() == Group::StateDeleted)
{
g->setState(Group::StateNormal);
}
// check for changed device memberships
if (!g->m_deviceMemberships.empty())
{
if (isLightingSwitch || isSceneSwitch) // only support one device member per group
{
if (g->m_deviceMemberships.size() > 1 || g->m_deviceMemberships.front() != s2->id())
{
g->m_deviceMemberships.clear();
}
}
}
if (g->addDeviceMembership(s2->id()))
{
updateGroupEtag(g);
update = true;
}
}
if (update)
{
queSaveDb(DB_GROUPS | DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
}
}
else if (existDevicesWithVendorCodeForMacPrefix(sc->address, VENDOR_IKEA))
{
if (sc->macCapabilities & deCONZ::MacDeviceIsFFD) // end-devices only
return;
if (ind.profileId() != HA_PROFILE_ID)
return;
// filter for remote control toggle command (large button)
if (ind.srcEndpoint() == 0x01 && ind.clusterId() == SCENE_CLUSTER_ID && zclFrame.manufacturerCode() == VENDOR_IKEA &&
zclFrame.commandId() == 0x07 && zclFrame.payload().at(0) == 0x02)
{
// TODO move following legacy cleanup code in Phoscon App / switch editor
DBG_Printf(DBG_INFO, "ikea remote setup button\n");
Sensor *s = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());
if (!s)
{
return;
}
std::vector<Rule>::iterator ri = rules.begin();
std::vector<Rule>::iterator rend = rules.end();
QString sensorAddress(QLatin1String("/sensors/"));
sensorAddress.append(s->id());
bool changed = false;
for (; ri != rend; ++ri)
{
if (ri->state() != Rule::StateNormal)
{
continue;
}
std::vector<RuleCondition>::const_iterator ci = ri->conditions().begin();
std::vector<RuleCondition>::const_iterator cend = ri->conditions().end();
for (; ci != cend; ++ci)
{
if (ci->address().startsWith(sensorAddress))
{
if (ri->name().startsWith(QLatin1String("default-ct")) && ri->owner() == QLatin1String("deCONZ"))
{
DBG_Printf(DBG_INFO, "ikea remote delete legacy rule %s\n", qPrintable(ri->name()));
ri->setState(Rule::StateDeleted);
changed = true;
}
}
}
}
if (changed)
{
indexRulesTriggers();
queSaveDb(DB_RULES, DB_SHORT_SAVE_DELAY);
}
}
}
}
Updates for Philips and Eurotronic
/*
* Copyright (c) 2013-2019 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QString>
#include <QTextCodec>
#include <QTcpSocket>
#include <QUrlQuery>
#include <QVariantMap>
#include <QtCore/qmath.h>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "json.h"
#include "product_match.h"
#include "utils/utils.h"
/*! Sensors REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleSensorsApi(const ApiRequest &req, ApiResponse &rsp)
{
if (req.path[2] != QLatin1String("sensors"))
{
return REQ_NOT_HANDLED;
}
// GET /api/<apikey>/sensors
if ((req.path.size() == 3) && (req.hdr.method() == "GET"))
{
return getAllSensors(req, rsp);
}
// GET /api/<apikey>/sensors/new
else if ((req.path.size() == 4) && (req.hdr.method() == "GET") && (req.path[3] == "new"))
{
return getNewSensors(req, rsp);
}
// GET /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "GET"))
{
return getSensor(req, rsp);
}
// GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
else if ((req.path.size() == 5) && (req.hdr.method() == "GET") && (req.path[4] == "data"))
{
return getSensorData(req, rsp);
}
// POST /api/<apikey>/sensors
else if ((req.path.size() == 3) && (req.hdr.method() == "POST"))
{
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (map.isEmpty())
{
return searchNewSensors(req, rsp);
}
else
{
return createSensor(req, rsp);
}
}
// PUT, PATCH /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH"))
{
return updateSensor(req, rsp);
}
// DELETE /api/<apikey>/sensors/<id>
else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE"))
{
return deleteSensor(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/config
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "config"))
{
return changeSensorConfig(req, rsp);
}
// PUT, PATCH /api/<apikey>/sensors/<id>/state
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[4] == "state"))
{
return changeSensorState(req, rsp);
}
// POST, DELETE /api/<apikey>/sensors/<id>/config/schedule/Wbbb
else if ((req.path.size() == 7) && (req.hdr.method() == "POST" || req.hdr.method() == "DELETE") && (req.path[4] == "config") && (req.path[5] == "schedule"))
{
return changeThermostatSchedule(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! GET /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getAllSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
rsp.httpStatus = HttpStatusOk;
// handle ETag
if (req.hdr.hasKey(QLatin1String("If-None-Match")))
{
QString etag = req.hdr.value(QLatin1String("If-None-Match"));
if (gwSensorsEtag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
std::vector<Sensor>::iterator i = sensors.begin();
std::vector<Sensor>::iterator end = sensors.end();
for (; i != end; ++i)
{
// ignore deleted sensors
if (i->deletedState() == Sensor::StateDeleted)
{
continue;
}
// ignore sensors without attached node
if (i->modelId().startsWith("FLS-NB") && !i->node())
{
continue;
}
if (i->modelId().isEmpty())
{
continue;
}
QVariantMap map;
if (sensorToMap(&*i, map, req))
{
rsp.map[i->id()] = map;
}
}
if (rsp.map.isEmpty())
{
rsp.str = "{}"; // return empty object
}
rsp.etag = gwSensorsEtag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensor(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 4);
if (req.path.size() != 4)
{
return REQ_NOT_HANDLED;
}
const QString &id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
// handle ETag
if (req.hdr.hasKey(QLatin1String("If-None-Match")))
{
QString etag = req.hdr.value(QLatin1String("If-None-Match"));
if (sensor->etag == etag)
{
rsp.httpStatus = HttpStatusNotModified;
rsp.etag = etag;
return REQ_READY_SEND;
}
}
sensorToMap(sensor, rsp.map, req);
rsp.httpStatus = HttpStatusOk;
rsp.etag = sensor->etag;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/<id>/data?maxrecords=<maxrecords>&fromtime=<ISO 8601>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getSensorData(const ApiRequest &req, ApiResponse &rsp)
{
DBG_Assert(req.path.size() == 5);
if (req.path.size() != 5)
{
return REQ_NOT_HANDLED;
}
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/").arg(id), QString("resource, /sensors/%1/, not available").arg(id)));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
bool ok;
QUrl url(req.hdr.url());
QUrlQuery query(url);
const int maxRecords = query.queryItemValue(QLatin1String("maxrecords")).toInt(&ok);
if (!ok || maxRecords <= 0)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/maxrecords"), QString("invalid value, %1, for parameter, maxrecords").arg(query.queryItemValue("maxrecords"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
QString t = query.queryItemValue(QLatin1String("fromtime"));
QDateTime dt = QDateTime::fromString(t, QLatin1String("yyyy-MM-ddTHH:mm:ss"));
if (!dt.isValid())
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/fromtime"), QString("invalid value, %1, for parameter, fromtime").arg(query.queryItemValue("fromtime"))));
rsp.httpStatus = HttpStatusNotFound;
return REQ_READY_SEND;
}
const qint64 fromTime = dt.toMSecsSinceEpoch() / 1000;
openDb();
loadSensorDataFromDb(sensor, rsp.list, fromTime, maxRecords);
closeDb();
if (rsp.list.isEmpty())
{
rsp.str = QLatin1String("[]"); // return empty list
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::createSensor(const ApiRequest &req, ApiResponse &rsp)
{
rsp.httpStatus = HttpStatusOk;
bool ok;
QVariant var = Json::parse(req.content, ok);
const QVariantMap map = var.toMap();
const QString type = map["type"].toString();
Sensor sensor;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
userActivity();
if (sensors.size() >= MAX_SENSORS)
{
rsp.list.append(errorToMap(ERR_SENSOR_LIST_FULL , QString("/sensors/"), QString("The Sensor List has reached its maximum capacity of %1 sensors").arg(MAX_SENSORS)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check required parameter
if ((!(map.contains("name")) || !(map.contains("modelid")) || !(map.contains("swversion")) || !(map.contains("type")) || !(map.contains("uniqueid")) || !(map.contains("manufacturername"))))
{
rsp.list.append(errorToMap(ERR_MISSING_PARAMETER, QString("/sensors"), QString("invalid/missing parameters in body")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//check invalid parameter
const QStringList allowedAttributes = { "name", "modelid", "swversion", "type", "uniqueid", "manufacturername", "state", "config", "recycle" };
for (const QString &attr : map.keys())
{
if (!allowedAttributes.contains(attr))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(attr), QString("parameter, %1, not available").arg(attr)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (!type.startsWith(QLatin1String("CLIP")))
{
rsp.list.append(errorToMap(ERR_NOT_ALLOWED_SENSOR_TYPE, QString("/sensors"), QString("Not allowed to create sensor type")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItem *item = nullptr;
QVariantMap rspItem;
QVariantMap rspItemState;
// create a new sensor id
openDb();
sensor.setId(QString::number(getFreeSensorId()));
closeDb();
sensor.setName(map["name"].toString().trimmed());
sensor.setManufacturer(map["manufacturername"].toString());
sensor.setModelId(map["modelid"].toString());
sensor.setUniqueId(map["uniqueid"].toString());
sensor.setSwVersion(map["swversion"].toString());
sensor.setType(type);
if (getSensorNodeForUniqueId(sensor.uniqueId()))
{
rsp.list.append(errorToMap(ERR_DUPLICATE_EXIST, QString("/sensors"), QString("sensor with uniqueid, %1, already exists").arg(sensor.uniqueId())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (type == QLatin1String("CLIPAlarm")) { item = sensor.addItem(DataTypeBool, RStateAlarm); item->setValue(false); }
else if (type == QLatin1String("CLIPBattery")) { item = sensor.addItem(DataTypeUInt8, RStateBattery); item->setValue(100); }
else if (type == QLatin1String("CLIPCarbonMonoxide")) { item = sensor.addItem(DataTypeBool, RStateCarbonMonoxide); item->setValue(false); }
else if (type == QLatin1String("CLIPConsumption")) { item = sensor.addItem(DataTypeUInt64, RStateConsumption); item->setValue(0); }
else if (type == QLatin1String("CLIPDaylightOffset")) { item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0);
item = sensor.addItem(DataTypeString, RConfigMode);
item = sensor.addItem(DataTypeTime, RStateLocaltime); }
else if (type == QLatin1String("CLIPFire")) { item = sensor.addItem(DataTypeBool, RStateFire); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericFlag")) { item = sensor.addItem(DataTypeBool, RStateFlag); item->setValue(false); }
else if (type == QLatin1String("CLIPGenericStatus")) { item = sensor.addItem(DataTypeInt32, RStateStatus); item->setValue(0); }
else if (type == QLatin1String("CLIPHumidity")) { item = sensor.addItem(DataTypeUInt16, RStateHumidity); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPLightLevel")) { item = sensor.addItem(DataTypeUInt16, RStateLightLevel); item->setValue(0);
item = sensor.addItem(DataTypeUInt32, RStateLux); item->setValue(0);
item = sensor.addItem(DataTypeBool, RStateDark); item->setValue(true);
item = sensor.addItem(DataTypeBool, RStateDaylight); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigTholdDark); item->setValue(R_THOLDDARK_DEFAULT);
item = sensor.addItem(DataTypeUInt16, RConfigTholdOffset); item->setValue(R_THOLDOFFSET_DEFAULT); }
else if (type == QLatin1String("CLIPOpenClose")) { item = sensor.addItem(DataTypeBool, RStateOpen); item->setValue(false); }
else if (type == QLatin1String("CLIPPower")) { item = sensor.addItem(DataTypeInt16, RStatePower); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateVoltage); item->setValue(0);
item = sensor.addItem(DataTypeUInt16, RStateCurrent); item->setValue(0); }
else if (type == QLatin1String("CLIPPresence")) { item = sensor.addItem(DataTypeBool, RStatePresence); item->setValue(false);
item = sensor.addItem(DataTypeUInt16, RConfigDuration); item->setValue(60); }
else if (type == QLatin1String("CLIPPressure")) { item = sensor.addItem(DataTypeInt16, RStatePressure); item->setValue(0); }
else if (type == QLatin1String("CLIPSwitch")) { item = sensor.addItem(DataTypeInt32, RStateButtonEvent); item->setValue(0); }
else if (type == QLatin1String("CLIPTemperature")) { item = sensor.addItem(DataTypeInt16, RStateTemperature); item->setValue(0);
item = sensor.addItem(DataTypeInt16, RConfigOffset); item->setValue(0); }
else if (type == QLatin1String("CLIPVibration")) { item = sensor.addItem(DataTypeBool, RStateVibration); item->setValue(false); }
else if (type == QLatin1String("CLIPWater")) { item = sensor.addItem(DataTypeBool, RStateWater); item->setValue(false); }
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("invalid value, %1, for parameter, type").arg(type)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//setState optional
if (map.contains("state"))
{
//check invalid parameter
const QVariantMap state = map["state"].toMap();
const QStringList allowedKeys = { "alarm", "battery", "buttonevent", "carbonmonoxide", "consumption", "current", "fire", "flag", "humidity", "lightlevel", "localtime", "lowbattery",
"open", "presence", "pressure", "power", "status", "tampered", "temperature", "vibration", "voltage", "water" };
const QStringList optionalKeys = { "lowbattery", "tampered" };
for (const auto &key : state.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("state/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(state.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/state"), QString("invalid value, %1, for parameter %2").arg(state.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
item = sensor.item(RConfigOn);
item->setValue(true); // default
item = sensor.item(RConfigReachable);
item->setValue(true); //default
//setConfig optional
if (map.contains("config"))
{
//check invalid parameter
const QVariantMap config = map["config"].toMap();
const QStringList allowedKeys = { "battery", "duration", "delay", "mode", "offset", "on", "reachable", "url" };
const QStringList optionalKeys = { "battery", "url" };
for (const auto &key : config.keys())
{
if (!allowedKeys.contains(key))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(key), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
ResourceItemDescriptor rid;
item = nullptr;
if (getResourceItemDescriptor(QString("config/%1").arg(key), rid))
{
item = sensor.item(rid.suffix);
if (!item && optionalKeys.contains(key))
{
item = sensor.addItem(rid.type, rid.suffix);
}
}
if (!item)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors"), QString("parameter, %1, not available").arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!item->setValue(config.value(key)))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/config"), QString("invalid value, %1, for parameter %2").arg(config.value(key).toString()).arg(key)));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
updateSensorEtag(&sensor);
sensor.setNeedSaveDatabase(true);
sensors.push_back(sensor);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
rspItemState["id"] = sensor.id();
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::updateSensor(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
QString name;
bool ok;
bool error = false;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
if (req.sock)
{
userActivity();
}
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
if (!((pi.key() == "name") || (pi.key() == "modelid") || (pi.key() == "swversion")
|| (pi.key() == "type") || (pi.key() == "uniqueid") || (pi.key() == "manufacturername")
|| (pi.key() == "state") || (pi.key() == "config")
|| (pi.key() == "mode" && (sensor->modelId() == "Lighting Switch" || sensor->modelId().startsWith(QLatin1String("SYMFONISK"))))))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%2").arg(pi.key()), QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (map.contains("modelid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/modelid"), QString("parameter, modelid, not modifiable")));
}
if (map.contains("swversion"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/swversion"), QString("parameter, swversion, not modifiable")));
}
if (map.contains("type"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/type"), QString("parameter, type, not modifiable")));
}
if (map.contains("uniqueid"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/uniqueid"), QString("parameter, uniqueid, not modifiable")));
}
if (map.contains("manufacturername"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/manufacturername"), QString("parameter, manufacturername, not modifiable")));
}
if (map.contains("state"))
{
error = true;
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/state"), QString("parameter, state, not modifiable")));
}
if (error)
{
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (map.contains("name")) // optional
{
name = map["name"].toString().trimmed();
if ((map["name"].type() == QVariant::String) && !(name.isEmpty()) && (name.size() <= MAX_SENSOR_NAME_LENGTH))
{
if (sensor->name() != name)
{
sensor->setName(name);
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
Event e(RSensors, RAttrName, sensor->id(), sensor->item(RAttrName));
enqueueEvent(e);
}
if (!sensor->type().startsWith(QLatin1String("CLIP")))
{
pushSensorInfoToCore(sensor);
}
rspItemState[QString("/sensors/%1/name").arg(id)] = name;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/name").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/name").arg(name).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("mode")) // optional
{
Sensor::SensorMode mode = (Sensor::SensorMode)map["mode"].toUInt(&ok);
if (ok && (map["mode"].type() == QVariant::Double)
&& ((sensor->modelId() == "Lighting Switch" && (mode == Sensor::ModeScenes || mode == Sensor::ModeTwoGroups || mode == Sensor::ModeColorTemperature))
|| (sensor->modelId().startsWith(QLatin1String("SYMFONISK")) && (mode == Sensor::ModeScenes || mode == Sensor::ModeDimmer))))
{
if (sensor->mode() != mode)
{
sensor->setNeedSaveDatabase(true);
sensor->setMode(mode);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
}
rspItemState[QString("/sensors/%1/mode").arg(id)] = (double)mode;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
updateEtag(sensor->etag);
updateEtag(gwConfigEtag);
queSaveDb(DB_SENSORS | DB_GROUPS, DB_SHORT_SAVE_DELAY);
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/mode").arg(id), QString("invalid value, %1, for parameter, /sensors/%2/mode").arg((int)mode).arg(id)));
rsp.httpStatus = HttpStatusBadRequest;
}
}
if (map.contains("config")) // optional
{
QStringList path = req.path;
path.append(QLatin1String("config"));
QString content = Json::serialize(map[QLatin1String("config")].toMap());
ApiRequest req2(req.hdr, path, NULL, content);
return changeSensorConfig(req2, rsp);
}
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>/config
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeSensorConfig(const ApiRequest &req, ApiResponse &rsp)
{
TaskItem task;
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
bool ok;
bool updated = false;
quint32 hostFlags = 0;
bool offsetUpdated = false;
qint16 offset = 0;
QMap<quint16, quint32> attributeList;
bool tholdUpdated = false;
quint16 pendingMask = 0;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
// QRegExp latitude("^\\d{3,3}\\.\\d{4,4}(W|E)$");
// QRegExp longitude("^\\d{3,3}\\.\\d{4,4}(N|S)$");
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/config"), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool isClip = sensor->type().startsWith(QLatin1String("CLIP"));
if (req.sock)
{
userActivity();
}
// set destination parameters
task.req.dstAddress() = sensor->address();
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
struct KeyValMap {
QLatin1String key;
quint8 value;
};
struct KeyValMapInt {
quint8 key;
quint16 value;
};
struct KeyValMapTuyaSingle {
QLatin1String key;
char value[1];
};
for (; pi != pend; ++pi)
{
ResourceItemDescriptor rid;
ResourceItem *item = nullptr;
if (getResourceItemDescriptor(QString("config/%1").arg(pi.key()), rid))
{
// Changing these values of zigbee sensors is not allowed, read-only.
if (rid.suffix == RConfigPending || rid.suffix == RConfigSensitivityMax || rid.suffix == RConfigHostFlags || rid.suffix == RConfigLastChangeAmount ||
rid.suffix == RConfigLastChangeSource || rid.suffix == RConfigLastChangeTime || rid.suffix == RConfigEnrolled || rid.suffix == RConfigOn ||
rid.suffix == RConfigLat || rid.suffix == RConfigLong ||
(!isClip && (rid.suffix == RConfigBattery || rid.suffix == RConfigReachable)))
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_MODIFIEABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not modifiable").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
//else if (rid.suffix == RConfigDuration && sensor->modelId() == QLatin1String("TRADFRI motion sensor"))
//{
// duration can be written for ikea motion sensor
// values 0, 60 — 600 will be replaced by hardware settings TODO error message
//}
else
{
item = sensor->item(rid.suffix);
}
if (item)
{
QVariant val = map[pi.key()];
bool invalidValue = false;
bool datatypeValid = false;
QString stringValue;
bool boolValue = false;
int intValue = 0;
uint uintValue = 0;
long long realValue = 0.0;
switch (rid.type)
{
case DataTypeBool:
{
if (val.type() == QVariant::Bool)
{
boolValue = val.toBool();
datatypeValid = true;
}
}
break;
case DataTypeUInt8:
case DataTypeUInt16:
case DataTypeUInt32:
case DataTypeUInt64:
{
if (val.type() == QVariant::Double)
{
uintValue = val.toUInt(&ok);
if (ok) { datatypeValid = true; }
}
}
break;
case DataTypeInt8:
case DataTypeInt16:
case DataTypeInt32:
case DataTypeInt64:
{
if (val.type() == QVariant::Double)
{
intValue = val.toInt(&ok);
if (ok) { datatypeValid = true; }
}
}
break;
case DataTypeReal:
{
if (val.type() == QVariant::Double)
{
realValue = val.toReal();
datatypeValid = true;
}
}
break;
case DataTypeTime:
case DataTypeTimePattern:
{
if (val.type() == QVariant::String && !val.toString().isEmpty())
{
stringValue = val.toString();
datatypeValid = true;
}
}
break;
case DataTypeString:
{
if (val.type() == QVariant::String && !val.toString().isEmpty())
{
stringValue = val.toString();
datatypeValid = true;
}
}
break;
case DataTypeUnknown:
{
}
break;
default:
break;
}
if (!datatypeValid)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(map[pi.key()].toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (rid.suffix == RConfigDeviceMode)
{
if (RConfigDeviceModeValues.indexOf(val.toString()) >= 0)
{
pendingMask |= R_PENDING_DEVICEMODE;
sensor->enableRead(WRITE_DEVICEMODE);
sensor->setNextReadTime(WRITE_DEVICEMODE, QTime::currentTime());
updated = true;
}
}
else if (rid.suffix == RConfigTholdDark || rid.suffix == RConfigTholdOffset)
{
tholdUpdated = true;
}
else if (rid.suffix == RConfigDelay)
{
if (sensor->modelId().startsWith(QLatin1String("SML00"))) // Hue motion sensor
{
pendingMask |= R_PENDING_DELAY;
sensor->enableRead(WRITE_DELAY);
sensor->setNextReadTime(WRITE_DELAY, QTime::currentTime());
}
updated = true;
}
else if (rid.suffix == RConfigDuration)
{
if (sensor->modelId().startsWith(QLatin1String("FLS-NB")))
{
DBG_Printf(DBG_INFO, "Force read of occupaction delay for sensor %s\n", qPrintable(sensor->address().toStringExt()));
sensor->enableRead(READ_OCCUPANCY_CONFIG);
sensor->setNextReadTime(READ_OCCUPANCY_CONFIG, queryTime.addSecs(1));
queryTime = queryTime.addSecs(1);
Q_Q(DeRestPlugin);
q->startZclAttributeTimer(0);
}
updated = true;
}
else if (rid.suffix == RConfigLedIndication)
{
pendingMask |= R_PENDING_LEDINDICATION;
sensor->enableRead(WRITE_LEDINDICATION);
sensor->setNextReadTime(WRITE_LEDINDICATION, QTime::currentTime());
updated = true;
}
else if (rid.suffix == RConfigSensitivity)
{
pendingMask |= R_PENDING_SENSITIVITY;
sensor->enableRead(WRITE_SENSITIVITY);
sensor->setNextReadTime(WRITE_SENSITIVITY, QTime::currentTime());
updated = true;
}
else if (rid.suffix == RConfigUsertest)
{
pendingMask |= R_PENDING_USERTEST;
sensor->enableRead(WRITE_USERTEST);
sensor->setNextReadTime(WRITE_USERTEST, QTime::currentTime());
updated = true;
}
else if (rid.suffix == RConfigAlert) // String
{
const std::array<KeyValMap, 3> RConfigAlertValues = { { {QLatin1String("none"), 0}, {QLatin1String("select"), 2}, {QLatin1String("lselect"), 15} } };
const auto match = getMappedValue2(stringValue, RConfigAlertValues);
if (!match.key.isEmpty())
{
task.identifyTime = match.value;
task.taskType = TaskIdentify;
taskToLocalData(task);
if (addTaskIdentify(task, task.identifyTime))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigLock) // Boolean
{
boolValue ^= boolValue; // Flip bool value as 0 means lock and 1 means unlock
if (addTaskDoorLockUnlock(task, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigMelody) // Unigned integer
{
QByteArray data;
data.append(static_cast<qint8>(uintValue & 0xff));
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_ENUM, DP_IDENTIFIER_MELODY, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigVolume) // Unigned integer
{
if (uintValue > 2) { uintValue = 2; } // Volume level, max = 2
QByteArray data;
data.append(static_cast<qint8>(uintValue & 0xff));
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_ENUM, DP_IDENTIFIER_VOLUME, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigTempMinThreshold || rid.suffix == RConfigTempMaxThreshold || rid.suffix == RConfigHumiMinThreshold || rid.suffix == RConfigHumiMaxThreshold) // Signed integer, really???
{
QByteArray data = QByteArray("\x00\x00\x00",3);
data.append(static_cast<qint8>(intValue));
quint8 dpIdentifier = 0;
//if (intValue <= -25 || intValue >= 25) { invalidValue = true; } // What are the valid boundaries?
if (rid.suffix == RConfigTempMinThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTEMPMINI; }
else if (rid.suffix == RConfigTempMaxThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTEMPMAXI; }
else if (rid.suffix == RConfigHumiMinThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDTHUMIMINI; }
else if (rid.suffix == RConfigHumiMaxThreshold) { dpIdentifier = DP_IDENTIFIER_TRESHOLDHUMIMAXI; }
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_VALUE, dpIdentifier, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigOffset) // Signed integer
{
intValue /= 10;
if ((R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV")) ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
QByteArray data;
bool alternative = false;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
if (intValue > 6) { intValue = 6; } // offset, min = -60, max = 60
if (intValue < -6) { intValue = -6; }
alternative = true;
}
else
{
if (intValue > 90) { intValue = 90; } // offset, min = -90, max = 90
if (intValue < -90) { intValue = -90; }
}
data.append((qint8)((offset >> 24) & 0xff));
data.append((qint8)((offset >> 16) & 0xff));
data.append((qint8)((offset >> 8) & 0xff));
data.append((qint8)(offset & 0xff));
if (!alternative)
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_VALUE, 0x2c, data))
{
updated = true;
}
}
else
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_VALUE, 0x1b, data))
{
updated = true;
}
}
}
else if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
if (intValue <= -25 || intValue >= 25) { invalidValue = true; }
else if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x404B, deCONZ::Zcl8BitInt, intValue))
{
updated = true;
}
}
else if (sensor->type() == "ZHAThermostat")
{
if (intValue <= -25 || intValue >= 25) { invalidValue = true; }
else if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0010, deCONZ::Zcl8BitInt, intValue))
{
updated = true;
}
}
else
{
offsetUpdated = true; // Consider offset only for temperature and humidity cluster
updated = true;
}
}
else if (rid.suffix == RConfigScheduleOn) // Boolean
{
if (sensor->modelId() == QLatin1String("Thermostat")) { boolValue ^= boolValue; } // eCozy, flip true and false
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0025, deCONZ::Zcl8BitBitMap, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigHeatSetpoint) // Signed integer
{
if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
// Older models of the Eurotroninc Spirit updated the heat set point via the manufacturer custom attribute 0x4003.
// For newer models it is not possible to write to this attribute.
// Newer models must use the standard Occupied Heating Setpoint value (0x0012) using a default (or none) manufacturer.
// See GitHub issue #1098
// UPD 16-11-2020: Since there is no way to reckognize older and newer models correctly and a new firmware version is on its way this
// 'fix' is changed to a more robust but ugly implementation by simply sending both codes to the device. One of the commands
// will be accepted while the other one will be refused. Let's hope this code can be removed in a future release.
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4003, deCONZ::Zcl16BitInt, intValue) &&
addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_NONE, 0x0012, deCONZ::Zcl16BitInt, intValue))
{
// Setting the heat setpoint disables off/boost modes, but this is not reported back by the thermostat.
// Hence, the off/boost flags will be removed here to reflect the actual operating state.
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
hostFlags &= ~0x04; // clear `boost` flag
hostFlags |= 0x10; // set `disable off` flag
updated = true;
}
}
}
else if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
if (addTaskThermostatCmd(task, VENDOR_DANFOSS, 0x40, intValue, 0))
{
updated = true;
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
intValue = intValue / 10;
QByteArray data = QByteArray("\x00\x00", 2);
qint8 dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_2;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_3;
intValue = intValue / 10;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
ResourceItem *item2 = sensor->item(RConfigMode);
if (item2 && item2->toString() == QLatin1String("heat"))
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_3;
}
else
{
dp = DP_IDENTIFIER_THERMOSTAT_HEATSETPOINT_4;
}
intValue = intValue * 2 / 10;
}
data.append(static_cast<qint8>((intValue >> 8) & 0xff));
data.append(static_cast<qint8>(intValue & 0xff));
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_VALUE , dp, data))
{
updated = true;
}
}
else
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0012, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigCoolSetpoint) // Signed integer
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0011, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigMode) // String
{
if (sensor->modelId() == QLatin1String("Cable outlet")) // Legrand cable outlet
{
static const std::array<KeyValMap, 6> RConfigModeLegrandValues = { { {QLatin1String("confort"), 0}, {QLatin1String("confort-1"), 1}, {QLatin1String("confort-2"), 2},
{QLatin1String("eco"), 3}, {QLatin1String("hors gel"), 4}, {QLatin1String("off"), 5} } };
const auto match = getMappedValue2(stringValue, RConfigModeLegrandValues);
if (!match.key.isEmpty())
{
if (addTaskControlModeCmd(task, 0x00, match.value))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 3> RConfigModeValuesTuya1 = { { {QLatin1String("auto"), {0x00}}, {QLatin1String("heat"), {0x01}}, {QLatin1String("off"), {0x02}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya1);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
quint8 dpIdentifier = DP_IDENTIFIER_THERMOSTAT_MODE_1;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_MODE_2;
}
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_ENUM, dpIdentifier, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
const std::array<KeyValMapTuyaSingle, 2> RConfigModeValuesTuya2 = { { {QLatin1String("off"), {0x00}}, {QLatin1String("heat"), {0x01}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya2);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x01, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 2> RConfigModeValuesTuya2 = { { {QLatin1String("off"), {0x00}}, {QLatin1String("heat"), {0x01}} } };
const auto match = getMappedValue2(stringValue, RConfigModeValuesTuya2);
if (!match.key.isEmpty())
{
if (match.key == QLatin1String("off"))
{
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x65 , QByteArray("\x00", 1)))
{
updated = true;
}
}
else
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x6c, data) &&
sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, 0x65, QByteArray("\x01", 1)))
{
updated = true;
}
}
}
}
else if (sensor->modelId().startsWith(QLatin1String("S1")) ||
sensor->modelId().startsWith(QLatin1String("S2")) ||
sensor->modelId().startsWith(QLatin1String("J1")))
{
if (addTaskUbisysConfigureSwitch(task))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
if (stringValue == QLatin1String("off"))
{
hostFlags |= 0x000020; // set enable off
hostFlags &= 0xffffeb; // clear boost, clear disable off
}
else if (stringValue == QLatin1String("heat"))
{
hostFlags |= 0x000014; // set boost, set disable off
}
else if (stringValue == QLatin1String("auto"))
{
hostFlags &= 0xfffffb; // clear boost
hostFlags |= 0x000010; // set disable off
}
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4008, deCONZ::Zcl24BitUint, hostFlags))
{
updated = true;
}
}
}
else
{
static const std::array<KeyValMap, 9> RConfigModeValues = { { {QLatin1String("off"), 0}, {QLatin1String("auto"), 1}, {QLatin1String("cool"), 3}, {QLatin1String("heat"), 4},
{QLatin1String("emergency heating"), 5}, {QLatin1String("precooling"), 6}, {QLatin1String("fan only"), 7},
{QLatin1String("dry"), 8}, {QLatin1String("sleep"), 9} } };
const auto match = getMappedValue2(stringValue, RConfigModeValues);
if (!match.key.isEmpty())
{
if (sensor->modelId() == QLatin1String("Super TR")) // Set device on/off state through mode via device specific attribute
{
if (match.value != 0x00 && match.value != 0x04) { }
else
{
bool data = match.value == 0x00 ? false : true;
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0406, deCONZ::ZclBoolean, data))
{
updated = true;
}
}
}
else if (sensor->modelId().startsWith(QLatin1String("SLR2")) ||
sensor->modelId() == QLatin1String("SLR1b"))
{
// Change automatically the Setpoint Hold
// Add a timer for Boost mode
if (match.value == 0x00) { attributeList.insert(0x0023, (quint32)0x00); }
else if (match.value == 0x04) { attributeList.insert(0x0023, (quint32)0x01); }
else if (match.value == 0x05)
{
attributeList.insert(0x0023, (quint32)0x01);
attributeList.insert(0x0026, (quint32)0x003C);
}
if (!attributeList.isEmpty())
{
if (addTaskThermostatWriteAttributeList(task, 0, attributeList))
{
updated = true;
}
}
}
else
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x001C, deCONZ::Zcl8BitEnum, uintValue))
{
updated = true;
}
}
}
else if (isClip)
{
updated = true;
}
}
}
else if (rid.suffix == RConfigPreset) // String
{
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
const std::array<KeyValMapTuyaSingle, 7> RConfigPresetValuesTuya = { { {QLatin1String("holiday"), {0x00}}, {QLatin1String("auto"), {0x01}}, {QLatin1String("manual"), {0x02}},
{QLatin1String("comfort"), {0x04}}, {QLatin1String("eco"), {0x05}}, {QLatin1String("boost"), {0x06}},
{QLatin1String("complex"), {0x07}} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya);
if (!match.key.isEmpty())
{
QByteArray data = QByteArray::fromRawData(match.value, 1);
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x04, data))
{
updated = true;
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
static const std::array<KeyValMap, 2> RConfigPresetValuesTuya2 = { { {QLatin1String("auto"), 0}, {QLatin1String("program"), 0} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya2);
if (!match.key.isEmpty())
{
if (match.key == QLatin1String("auto"))
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x02, QByteArray("\x01", 1)) &&
sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x03, QByteArray("\x00", 1)))
{
updated = true;
}
}
else if (match.key == QLatin1String("program"))
{
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x02, QByteArray("\x00", 1)) &&
sendTuyaRequest(task, TaskThermostat, DP_TYPE_ENUM, 0x03, QByteArray("\x01", 1)))
{
updated = true;
}
}
}
}
else if (R_GetProductId(sensor) == QLatin1String("NAS-AB02B0 Siren"))
{
const std::array<KeyValMap, 4> RConfigPresetValuesTuya3 = { { {QLatin1String("both"), 0}, {QLatin1String("humidity"), 0}, {QLatin1String("temperature"), 0},
{QLatin1String("off"), 0} } };
const auto match = getMappedValue2(stringValue, RConfigPresetValuesTuya3);
if (!match.key.isEmpty())
{
QByteArray data1;
QByteArray data2;
quint8 dpIdentifier1 = DP_IDENTIFIER_TEMPERATURE_ALARM;
quint8 dpIdentifier2 = DP_IDENTIFIER_HUMIDITY_ALARM;
if (match.key == QLatin1String("both"))
{
data1 = data2 = QByteArray("\x01", 1);
}
else if (match.key == QLatin1String("humidity"))
{
data1 = QByteArray("\x00", 1);
data2 = QByteArray("\x01", 1);
}
else if (match.key == QLatin1String("temperature"))
{
data1 = QByteArray("\x01", 1);
data2 = QByteArray("\x00", 1);
}
else if (match.key == QLatin1String("off"))
{
data1 = data2 = QByteArray("\x00", 1);
}
if (sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_BOOL, dpIdentifier1, data1) &&
sendTuyaRequest(task, TaskTuyaRequest, DP_TYPE_BOOL, dpIdentifier2, data2))
{
updated = true;
}
}
}
}
else if (rid.suffix == RConfigLocked) // Boolean
{
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV"))
{
QByteArray data = QByteArray("\x00", 1);
qint8 dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_1;
if (boolValue) { data = QByteArray("\x01", 1); }
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_2;
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD MOES TRV"))
{
dpIdentifier = DP_IDENTIFIER_THERMOSTAT_CHILDLOCK_3;
}
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_BOOL, dpIdentifier, data))
{
updated = true;
}
}
else if (sensor->modelId() == QLatin1String("Super TR"))
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0413, deCONZ::ZclBoolean, boolValue))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
if (boolValue) { hostFlags |= 0x000080; } // set locked
else { hostFlags &= 0xffff6f; } // clear locked, clear disable off
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4008, deCONZ::Zcl24BitUint, hostFlags))
{
updated = true;
}
}
}
else
{
uintValue = boolValue; // Use integer representation
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0001, deCONZ::Zcl8BitEnum, uintValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigDisplayFlipped) // Boolean
{
if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001"))
{
uintValue = boolValue;
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x4000, deCONZ::Zcl8BitEnum, uintValue, VENDOR_DANFOSS))
{
updated = true;
}
}
else if (sensor->modelId().startsWith(QLatin1String("SPZB"))) // Eurotronic Spirit
{
if (hostFlags == 0)
{
ResourceItem *item = sensor->item(RConfigHostFlags);
hostFlags = item->toNumber();
if (boolValue) { hostFlags |= 0x000002; } // set flipped
else { hostFlags &= 0xffffed; } // clear flipped, clear disable off
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_JENNIC, 0x4008, deCONZ::Zcl24BitUint, hostFlags))
{
updated = true;
}
}
}
}
else if (rid.suffix == RConfigMountingMode) // Boolean
{
uintValue = boolValue; // Use integer representation
if (addTaskThermostatUiConfigurationReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x4013, deCONZ::Zcl8BitEnum, uintValue, VENDOR_DANFOSS))
{
updated = true;
}
}
else if (rid.suffix == RConfigExternalTemperatureSensor) // Signed integer
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x4015, deCONZ::Zcl16BitInt, intValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigExternalWindowOpen) // Boolean
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, VENDOR_DANFOSS, 0x4003, deCONZ::ZclBoolean, boolValue))
{
updated = true;
}
}
else if (rid.suffix == RConfigSetValve) // Boolean
{
QByteArray data = QByteArray("\x00", 1);
if (boolValue)
{
data = QByteArray("\x01", 1);
}
if (sendTuyaRequest(task, TaskThermostat , DP_TYPE_BOOL, DP_IDENTIFIER_THERMOSTAT_VALVE , data))
{
updated = true;
}
}
else if (rid.suffix == RConfigTemperatureMeasurement) // String
{
if (sensor->modelId() == QLatin1String("Super TR"))
{
static const std::array<KeyValMap, 5> RConfigTemperatureMeasurementValues = { { {QLatin1String("air sensor"), 0}, {QLatin1String("floor sensor"), 1},
{QLatin1String("floor protection"), 3} } };
const auto match = getMappedValue2(stringValue, RConfigTemperatureMeasurementValues);
if (!match.key.isEmpty())
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x0403, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
}
else if (rid.suffix == RConfigWindowOpen) // Boolean
{
QByteArray data = QByteArray("\x00", 1); // Config on / off
if (boolValue) { data = QByteArray("\x01", 1); }
qint8 dpIdentifier = DP_IDENTIFIER_WINDOW_OPEN;
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
dpIdentifier = DP_IDENTIFIER_WINDOW_OPEN2;
}
if (sendTuyaRequest(task, TaskThermostat, DP_TYPE_BOOL, dpIdentifier, data))
{
updated = true;
}
}
else if (rid.suffix == RConfigSwingMode) // String
{
static const std::array<KeyValMap, 5> RConfigSwingModeValues = { { {QLatin1String("fully closed"), 1}, {QLatin1String("fully open"), 2}, {QLatin1String("quarter open"), 3},
{QLatin1String("half open"), 4}, {QLatin1String("three quarters open"), 5} } };
const auto match = getMappedValue2(stringValue, RConfigSwingModeValues);
if (!match.key.isEmpty())
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, 0x0045, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigFanMode) // String
{
static const std::array<KeyValMap, 7> RConfigFanModeValues = { { {QLatin1String("off"), 0}, {QLatin1String("low"), 1}, {QLatin1String("medium"), 2}, {QLatin1String("high"), 3},
{QLatin1String("on"), 4}, {QLatin1String("auto"), 5}, {QLatin1String("smart"), 6}} };
const auto match = getMappedValue2(stringValue, RConfigFanModeValues);
if (!match.key.isEmpty())
{
if (addTaskFanControlReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0000, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigControlSequence) // Unsigned integer
{
static const std::array<KeyValMapInt, 6> RConfigControlSequenceValues = { { {1, COOLING_ONLY}, {2, COOLING_WITH_REHEAT}, {3, HEATING_ONLY}, {4, HEATING_WITH_REHEAT},
{5, COOLING_AND_HEATING_4PIPES}, {6, COOLING_AND_HEATING_4PIPES_WITH_REHEAT} } };
const auto match = getMappedValue2(stringValue, RConfigControlSequenceValues);
if (match.key)
{
if (addTaskThermostatReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0, 0x001B, deCONZ::Zcl8BitEnum, match.value))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigPulseConfiguration) // Unsigned integer
{
if (uintValue <= UINT16_MAX &&
addTaskSimpleMeteringReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0300, deCONZ::Zcl16BitUint, uintValue, VENDOR_DEVELCO))
{
updated = true;
}
}
else if (rid.suffix == RConfigInterfaceMode) // Unsigned integer
{
quint16 data = 0xFFFF;
if (sensor->modelId().startsWith(QLatin1String("EMIZB-1")))
{
static const std::array<KeyValMapInt, 8> RConfigInterfaceModeValuesZHEMI = { { {1, PULSE_COUNTING_ELECTRICITY}, {2, PULSE_COUNTING_GAS}, {3, PULSE_COUNTING_WATER},
{4, KAMSTRUP_KMP}, {5, LINKY}, {6, DLMS_COSEM}, {7, DSMR_23}, {8, DSMR_40} } };
const auto match = getMappedValue2(uintValue, RConfigInterfaceModeValuesZHEMI);
if (match.key)
{
data = match.value;
}
}
else if (sensor->modelId().startsWith(QLatin1String("EMIZB-1")))
{
static const std::array<KeyValMapInt, 5> RConfigInterfaceModeValuesEMIZB = { { {1, NORWEGIAN_HAN}, {2, NORWEGIAN_HAN_EXTRA_LOAD}, {3, AIDON_METER},
{4, KAIFA_KAMSTRUP_METERS}, {5, AUTO_DETECT} } };
const auto match = getMappedValue2(uintValue, RConfigInterfaceModeValuesEMIZB);
if (match.key)
{
data = match.value;
}
}
if (data != 0xFFFF)
{
if (addTaskSimpleMeteringReadWriteAttribute(task, deCONZ::ZclWriteAttributesId, 0x0302, deCONZ::Zcl16BitEnum, data, VENDOR_DEVELCO))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigWindowCoveringType) // Unsigned integer
{
if (sensor->modelId().startsWith(QLatin1String("J1")))
{
if (addTaskWindowCoveringCalibrate(task, uintValue))
{
updated = true;
}
}
}
else if (rid.suffix == RConfigGroup) // String
{
checkSensorBindingsForClientClusters(sensor);
continue;
}
else if (QString(rid.suffix).startsWith("config/ubisys_j1_"))
{
uint16_t mfrCode = VENDOR_UBISYS;
uint16_t attrId;
uint8_t attrType = deCONZ::Zcl16BitUint;
if (rid.suffix == RConfigUbisysJ1Mode)
{
mfrCode = 0x0000;
attrId = 0x0017;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1WindowCoveringType)
{
attrId = 0x0000;
attrType = deCONZ::Zcl8BitEnum;
}
else if (rid.suffix == RConfigUbisysJ1ConfigurationAndStatus)
{
attrId = 0x0007;
attrType = deCONZ::Zcl8BitBitMap;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitLift)
{
attrId = 0x0010;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitLift)
{
attrId = 0x0011;
}
else if (rid.suffix == RConfigUbisysJ1InstalledOpenLimitTilt)
{
attrId = 0x0012;
}
else if (rid.suffix == RConfigUbisysJ1InstalledClosedLimitTilt)
{
attrId = 0x0013;
}
else if (rid.suffix == RConfigUbisysJ1TurnaroundGuardTime)
{
attrId = 0x1000;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps)
{
attrId = 0x1001;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps)
{
attrId = 0x1002;
}
else if (rid.suffix == RConfigUbisysJ1LiftToTiltTransitionSteps2)
{
attrId = 0x1003;
}
else if (rid.suffix == RConfigUbisysJ1TotalSteps2)
{
attrId = 0x1004;
}
else if (rid.suffix == RConfigUbisysJ1AdditionalSteps)
{
attrId = 0x1005;
attrType = deCONZ::Zcl8BitUint;
}
else if (rid.suffix == RConfigUbisysJ1InactivePowerThreshold)
{
attrId = 0x1006;
}
else if (rid.suffix == RConfigUbisysJ1StartupSteps)
{
attrId = 0x1007;
}
else
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (addTaskWindowCoveringSetAttr(task, mfrCode, attrId, attrType, uintValue))
{
updated = true;
}
}
if (invalidValue)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(map[pi.key()].toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (updated)
{
if (item->setValue(val))
{
if (item->lastChanged() == item->lastSet())
{
updated = true;
}
rspItemState[QString("/sensors/%1/config/%2").arg(id).arg(pi.key())] = val;
rspItem["success"] = rspItemState;
Event e(RSensors, rid.suffix, id, item);
enqueueEvent(e);
}
updated = false;
}
else
{
rsp.list.append(errorToMap(ERR_ACTION_ERROR, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QLatin1String("Could not set attribute")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else // Not available
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else // Not modifiable
{
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/config/%2").arg(id).arg(pi.key()),
QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (tholdUpdated)
{
ResourceItem *item = sensor->item(RStateLightLevel);
if (item)
{
quint16 lightlevel = item->toNumber();
item = sensor->item(RConfigTholdDark);
if (item)
{
quint16 tholddark = item->toNumber();
item = sensor->item(RConfigTholdOffset);
if (item)
{
quint16 tholdoffset = item->toNumber();
bool dark = lightlevel <= tholddark;
bool daylight = lightlevel >= tholddark + tholdoffset;
item = sensor->item(RStateDark);
if (!item)
{
item = sensor->addItem(DataTypeBool, RStateDark);
}
if (item && item->setValue(dark))
{
if (item->lastChanged() == item->lastSet())
{
Event e(RSensors, RStateDark, sensor->id(), item);
enqueueEvent(e);
}
}
item = sensor->item(RStateDaylight);
if (!item)
{
item = sensor->addItem(DataTypeBool, RStateDaylight);
}
if (item && item->setValue(daylight))
{
if (item->lastChanged() == item->lastSet())
{
Event e(RSensors, RStateDaylight, sensor->id(), item);
enqueueEvent(e);
}
}
}
}
}
}
if (offsetUpdated)
{
ResourceItem *item = sensor->item(RStateTemperature);
if (item)
{
qint16 temp = item->toNumber();
temp += offset;
if (item->setValue(temp))
{
Event e(RSensors, RStateTemperature, sensor->id(), item);
enqueueEvent(e);
}
}
item = sensor->item(RStateHumidity);
if (item)
{
quint16 humidity = item->toNumber();
qint16 _humidity = humidity + offset;
humidity = _humidity < 0 ? 0 : _humidity > 10000 ? 10000 : _humidity;
if (item->setValue(humidity))
{
Event e(RSensors, RStateHumidity, sensor->id(), item);
enqueueEvent(e);
}
}
}
if (pendingMask)
{
ResourceItem *item = sensor->item(RConfigPending);
if (item)
{
quint16 mask = item->toNumber();
mask |= pendingMask;
item->setValue(mask);
Event e(RSensors, RConfigPending, sensor->id(), item);
enqueueEvent(e);
}
}
rsp.list.append(rspItem);
updateSensorEtag(sensor);
if (updated)
{
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
processTasks();
return REQ_READY_SEND;
}
/*! POST, DELETE /api/<apikey>/sensors/<id>/config/schedule/Wbbb
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeThermostatSchedule(const ApiRequest &req, ApiResponse &rsp)
{
rsp.httpStatus = HttpStatusOk;
// Get the /sensors/id resource.
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
// Check that it has config/schedule.
ResourceItem *item = sensor->item(RConfigSchedule);
if (!item)
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/config/schedule").arg(id), QString("resource, /sensors/%1/config/schedule, not available").arg(id)));
return REQ_READY_SEND;
}
// Check valid weekday pattern
bool ok;
uint bbb = req.path[6].mid(1).toUInt(&ok);
if (req.path[6].left(1) != "W" || !ok || bbb < 1 || bbb > 127)
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("resource, /sensors/%1/config/schedule/%2, not available").arg(id).arg(req.path[6])));
return REQ_READY_SEND;
}
quint8 weekdays = bbb;
// Check body
QString transitions = QString("");
if (req.hdr.method() == "POST")
{
QVariant var = Json::parse(req.content, ok);
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
QVariantList list = var.toList();
// QString transitions = QString("");
if (!serialiseThermostatTransitions(list, &transitions))
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("body contains invalid list of transitions")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
if (req.sock)
{
userActivity();
}
bool ok2 = false;
// Queue task.
TaskItem task;
task.req.dstAddress() = sensor->address();
task.req.setTxOptions(deCONZ::ApsTxAcknowledgedTransmission);
task.req.setDstEndpoint(sensor->fingerPrint().endpoint);
task.req.setSrcEndpoint(getSrcEndpoint(sensor, task.req));
task.req.setDstAddressMode(deCONZ::ApsExtAddress);
if (R_GetProductId(sensor) == QLatin1String("Tuya_THD HY369 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD HY368 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD GS361A-H04 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Essentials TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD Smart radiator TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD NX-4911-675 TRV") ||
R_GetProductId(sensor) == QLatin1String("Tuya_THD SEA801-ZIGBEE TRV"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_2);
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD BTH-002 Thermostat"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_1);
}
else if (R_GetProductId(sensor) == QLatin1String("Tuya_THD WZB-TRVL TRV"))
{
ok2 = sendTuyaRequestThermostatSetWeeklySchedule(task, weekdays, transitions, DP_IDENTIFIER_THERMOSTAT_SCHEDULE_4);
}
else
{
ok2 = addTaskThermostatSetWeeklySchedule(task, weekdays, transitions);
}
if (!ok2)
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/config/schedule/%2").arg(id).arg(req.path[6]), QString("could not set schedule")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
QVariantMap rspItem;
QVariantMap rspItemState;
if (req.hdr.method() == "POST")
{
QVariantList l;
deserialiseThermostatTransitions(transitions, &l);
rspItemState[QString("/config/schedule/W%1").arg(weekdays)] = l;
rspItem["success"] = rspItemState;
}
else
{
rspItem["success"] = QString("/sensors/%1/config/schedule/W%2 deleted.").arg(id).arg(weekdays);
}
rsp.list.append(rspItem);
updateThermostatSchedule(sensor, weekdays, transitions);
processTasks();
return REQ_READY_SEND;
}
/*! PUT, PATCH /api/<apikey>/sensors/<id>/state
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::changeSensorState(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
bool ok;
bool updated = false;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
QVariantMap rspItem;
QVariantMap rspItemState;
rsp.httpStatus = HttpStatusOk;
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1/state").arg(id), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool isClip = sensor->type().startsWith(QLatin1String("CLIP"));
if (req.sock)
{
userActivity();
}
//check invalid parameter
QVariantMap::const_iterator pi = map.begin();
QVariantMap::const_iterator pend = map.end();
for (; pi != pend; ++pi)
{
ResourceItem *item = nullptr;
ResourceItemDescriptor rid;
if (getResourceItemDescriptor(QString("state/%1").arg(pi.key()), rid))
{
if (rid.suffix == RStateButtonEvent)
{
// allow modify physical switch buttonevent via api
}
else if (!isClip)
{
continue;
}
if (rid.suffix != RStateLux && rid.suffix != RStateDark && rid.suffix != RStateDaylight)
{
item = sensor->item(rid.suffix);
}
if (item)
{
QVariant val = map[pi.key()];
if (rid.suffix == RStateTemperature || rid.suffix == RStateHumidity)
{
ResourceItem *item2 = sensor->item(RConfigOffset);
if (item2 && item2->toNumber() != 0) {
val = val.toInt() + item2->toNumber();
if (rid.suffix == RStateHumidity)
{
val = val < 0 ? 0 : val > 10000 ? 10000 : val;
}
}
}
if (item->setValue(val))
{
rspItemState[QString("/sensors/%1/state/%2").arg(id).arg(pi.key())] = val;
rspItem["success"] = rspItemState;
if (rid.suffix == RStateButtonEvent || // always fire events for buttons
item->lastChanged() == item->lastSet())
{
updated = true;
Event e(RSensors, rid.suffix, id, item);
enqueueEvent(e);
}
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateLastUpdated, id));
if (rid.suffix == RStateLightLevel)
{
ResourceItem *item2 = 0;
quint16 measuredValue = val.toUInt();
quint16 tholddark = R_THOLDDARK_DEFAULT;
quint16 tholdoffset = R_THOLDOFFSET_DEFAULT;
item2 = sensor->item(RConfigTholdDark);
if (item2)
{
tholddark = item2->toNumber();
}
item2 = sensor->item(RConfigTholdOffset);
if (item2)
{
tholdoffset = item2->toNumber();
}
bool dark = measuredValue <= tholddark;
bool daylight = measuredValue >= tholddark + tholdoffset;
item2 = sensor->item(RStateDark);
if (!item2)
{
item2 = sensor->addItem(DataTypeBool, RStateDark);
}
if (item2->setValue(dark))
{
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateDark, id, item2);
enqueueEvent(e);
}
}
item2 = sensor->item(RStateDaylight);
if (!item2)
{
item2 = sensor->addItem(DataTypeBool, RStateDaylight);
}
if (item2->setValue(daylight))
{
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateDaylight, id, item2);
enqueueEvent(e);
}
}
item2 = sensor->item(RStateLux);
if (!item2)
{
item2 = sensor->addItem(DataTypeUInt32, RStateLux);
}
quint32 lux = 0;
if (measuredValue > 0 && measuredValue < 0xffff)
{
// valid values are 1 - 0xfffe
// 0, too low to measure
// 0xffff invalid value
// ZCL Attribute = 10.000 * log10(Illuminance (lx)) + 1
// lux = 10^((ZCL Attribute - 1)/10.000)
qreal exp = measuredValue - 1;
qreal l = qPow(10, exp / 10000.0f);
l += 0.5; // round value
lux = static_cast<quint32>(l);
}
item2->setValue(lux);
if (item2->lastChanged() == item2->lastSet())
{
Event e(RSensors, RStateLux, id, item2);
enqueueEvent(e);
}
}
else if (rid.suffix == RStatePresence)
{
ResourceItem *item2 = sensor->item(RConfigDuration);
if (item2 && item2->toNumber() > 0)
{
sensor->durationDue = QDateTime::currentDateTime().addSecs(item2->toNumber()).addMSecs(-500);
}
}
}
else // invalid
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/state/%2").arg(id).arg(pi.key()),
QString("invalid value, %1, for parameter %2").arg(val.toString()).arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
}
if (!item)
{
// not found
rsp.list.append(errorToMap(ERR_PARAMETER_NOT_AVAILABLE, QString("/sensors/%1/state/%2").arg(id).arg(pi.key()), QString("parameter, %1, not available").arg(pi.key())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
rsp.list.append(rspItem);
updateSensorEtag(sensor);
if (updated)
{
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_HUGE_SAVE_DELAY);
}
return REQ_READY_SEND;
}
/*! DELETE /api/<apikey>/sensors/<id>
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::deleteSensor(const ApiRequest &req, ApiResponse &rsp)
{
QString id = req.path[3];
Sensor *sensor = id.length() < MIN_UNIQUEID_LENGTH ? getSensorNodeForId(id) : getSensorNodeForUniqueId(id);
userActivity();
if (!sensor || (sensor->deletedState() == Sensor::StateDeleted))
{
rsp.httpStatus = HttpStatusNotFound;
rsp.list.append(errorToMap(ERR_RESOURCE_NOT_AVAILABLE, QString("/sensors/%1").arg(id), QString("resource, /sensors/%1, not available").arg(id)));
return REQ_READY_SEND;
}
bool ok;
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
if (!ok)
{
rsp.list.append(errorToMap(ERR_INVALID_JSON, QString("/sensors/%1").arg(id), QString("body contains invalid JSON")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
sensor->setDeletedState(Sensor::StateDeleted);
sensor->setNeedSaveDatabase(true);
Event e(RSensors, REventDeleted, sensor->id());
enqueueEvent(e);
bool hasReset = map.contains("reset");
if (hasReset)
{
if (map["reset"].type() == QVariant::Bool)
{
bool reset = map["reset"].toBool();
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QString("/sensors/%1/reset").arg(id)] = reset;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
if (reset)
{
sensor->setResetRetryCount(10);
}
}
else
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/sensors/%1/reset").arg(id), QString("invalid value, %1, for parameter, reset").arg(map["reset"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
}
else
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState["id"] = id;
rspItem["success"] = rspItemState;
rsp.list.append(rspItem);
rsp.httpStatus = HttpStatusOk;
}
{
Q_Q(DeRestPlugin);
q->nodeUpdated(sensor->address().ext(), QLatin1String("deleted"), QLatin1String(""));
}
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
updateSensorEtag(sensor);
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! POST /api/<apikey>/sensors
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::searchNewSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!isInNetwork())
{
rsp.list.append(errorToMap(ERR_NOT_CONNECTED, QLatin1String("/sensors"), QLatin1String("Not connected")));
rsp.httpStatus = HttpStatusServiceUnavailable;
return REQ_READY_SEND;
}
startSearchSensors();
{
QVariantMap rspItem;
QVariantMap rspItemState;
rspItemState[QLatin1String("/sensors")] = QLatin1String("Searching for new devices");
rspItemState[QLatin1String("/sensors/duration")] = (double)searchSensorsTimeout;
rspItem[QLatin1String("success")] = rspItemState;
rsp.list.append(rspItem);
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! GET /api/<apikey>/sensors/new
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::getNewSensors(const ApiRequest &req, ApiResponse &rsp)
{
Q_UNUSED(req);
if (!searchSensorsResult.isEmpty() &&
(searchSensorsState == SearchSensorsActive || searchSensorsState == SearchSensorsDone))
{
rsp.map = searchSensorsResult;
}
if (searchSensorsState == SearchSensorsActive)
{
rsp.map["lastscan"] = QLatin1String("active");
}
else if (searchSensorsState == SearchSensorsDone)
{
rsp.map["lastscan"] = lastSensorsScan;
}
else
{
rsp.map["lastscan"] = QLatin1String("none");
}
rsp.httpStatus = HttpStatusOk;
return REQ_READY_SEND;
}
/*! Put all sensor parameters in a map.
\return true - on success
false - on error
*/
bool DeRestPluginPrivate::sensorToMap(const Sensor *sensor, QVariantMap &map, const ApiRequest &req)
{
if (!sensor)
{
return false;
}
QVariantMap state;
const ResourceItem *iox = nullptr;
const ResourceItem *ioy = nullptr;
const ResourceItem *ioz = nullptr;
QVariantList orientation;
const ResourceItem *ix = nullptr;
const ResourceItem *iy = nullptr;
QVariantList xy;
QVariantMap config;
const ResourceItem *ilcs = nullptr;
const ResourceItem *ilca = nullptr;
const ResourceItem *ilct = nullptr;
QVariantMap lastchange;
for (int i = 0; i < sensor->itemCount(); i++)
{
const ResourceItem *item = sensor->itemForIndex(static_cast<size_t>(i));
DBG_Assert(item);
const ResourceItemDescriptor &rid = item->descriptor();
if (!item->isPublic())
{
continue;
}
if (rid.suffix == RConfigLat || rid.suffix == RConfigLong)
{
continue; // don't return due privacy reasons
}
if (rid.suffix == RConfigHostFlags)
{
continue; // hidden
}
if (rid.suffix == RConfigReachable &&
sensor->type().startsWith(QLatin1String("ZGP")))
{
continue; // don't provide reachable for green power devices
}
if (strncmp(rid.suffix, "config/", 7) == 0)
{
const char *key = item->descriptor().suffix + 7;
if (rid.suffix == RConfigPending)
{
QVariantList pending;
auto value = item->toNumber();
if (value & R_PENDING_DELAY)
{
pending.append("delay");
}
if (value & R_PENDING_LEDINDICATION)
{
pending.append("ledindication");
}
if (value & R_PENDING_SENSITIVITY)
{
pending.append("sensitivity");
}
if (value & R_PENDING_USERTEST)
{
pending.append("usertest");
}
if (value & R_PENDING_DEVICEMODE)
{
pending.append("devicemode");
}
config[key] = pending;
}
else if (rid.suffix == RConfigLastChangeSource)
{
ilcs = item;
}
else if (rid.suffix == RConfigLastChangeAmount)
{
ilca = item;
}
else if (rid.suffix == RConfigLastChangeTime)
{
ilct = item;
}
else if (rid.suffix == RConfigSchedule)
{
QVariantMap schedule;
deserialiseThermostatSchedule(item->toString(), &schedule);
config[key] = schedule;
}
else
{
config[key] = item->toVariant();
}
}
if (strncmp(rid.suffix, "state/", 6) == 0)
{
const char *key = item->descriptor().suffix + 6;
if (rid.suffix == RStateLastUpdated)
{
if (!item->lastSet().isValid() || item->lastSet().date().year() < 2000)
{
state[key] = QLatin1String("none");
}
else
{
state[key] = item->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ss.zzz");
}
}
else if (rid.suffix == RStateOrientationX)
{
iox = item;
}
else if (rid.suffix == RStateOrientationY)
{
ioy = item;
}
else if (rid.suffix == RStateOrientationZ)
{
ioz = item;
}
else if (rid.suffix == RStateX)
{
ix = item;
}
else if (rid.suffix == RStateY)
{
iy = item;
}
else
{
state[key] = item->toVariant();
}
}
}
if (iox && ioy && ioz)
{
orientation.append(iox->toNumber());
orientation.append(ioy->toNumber());
orientation.append(ioz->toNumber());
state["orientation"] = orientation;
}
if (ix && iy)
{
xy.append(round(ix->toNumber() / 6.5535) / 10000.0);
xy.append(round(iy->toNumber() / 6.5535) / 10000.0);
state["xy"] = xy;
}
if (ilcs && ilca && ilct)
{
lastchange["source"] = RConfigLastChangeSourceValues[ilcs->toNumber()];
lastchange["amount"] = ilca->toNumber();
lastchange["time"] = ilct->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ssZ");
config["lastchange"] = lastchange;
}
//sensor
map["name"] = sensor->name();
map["type"] = sensor->type();
if (sensor->type().startsWith(QLatin1String("Z"))) // ZigBee sensor
{
map["lastseen"] = sensor->lastRx().toUTC().toString("yyyy-MM-ddTHH:mmZ");
}
if (req.path.size() > 2 && req.path[2] == QLatin1String("devices"))
{
// don't add in sub device
}
else
{
if (!sensor->modelId().isEmpty())
{
map["modelid"] = sensor->modelId();
}
if (!sensor->manufacturer().isEmpty())
{
map["manufacturername"] = sensor->manufacturer();
}
if (!sensor->swVersion().isEmpty() && !sensor->type().startsWith(QLatin1String("ZGP")))
{
map["swversion"] = sensor->swVersion();
}
if (sensor->fingerPrint().endpoint != INVALID_ENDPOINT)
{
map["ep"] = sensor->fingerPrint().endpoint;
}
QString etag = sensor->etag;
etag.remove('"'); // no quotes allowed in string
map["etag"] = etag;
}
// whitelist, HueApp crashes on ZHAAlarm and ZHAPressure
if (req.mode == ApiModeHue)
{
if (!(sensor->type() == QLatin1String("Daylight") ||
sensor->type() == QLatin1String("CLIPGenericFlag") ||
sensor->type() == QLatin1String("CLIPGenericStatus") ||
sensor->type() == QLatin1String("CLIPSwitch") ||
sensor->type() == QLatin1String("CLIPOpenClose") ||
sensor->type() == QLatin1String("CLIPPresence") ||
sensor->type() == QLatin1String("CLIPTemperature") ||
sensor->type() == QLatin1String("CLIPHumidity") ||
sensor->type() == QLatin1String("CLIPLightlevel") ||
sensor->type() == QLatin1String("ZGPSwitch") ||
sensor->type() == QLatin1String("ZHASwitch") ||
sensor->type() == QLatin1String("ZHAOpenClose") ||
sensor->type() == QLatin1String("ZHAPresence") ||
sensor->type() == QLatin1String("ZHATemperature") ||
sensor->type() == QLatin1String("ZHAHumidity") ||
sensor->type() == QLatin1String("ZHALightLevel")))
{
return false;
}
// mimic Hue Dimmer Switch
if (sensor->modelId() == QLatin1String("TRADFRI wireless dimmer") ||
sensor->modelId() == QLatin1String("lumi.sensor_switch.aq2"))
{
map["manufacturername"] = "Philips";
map["modelid"] = "RWL021";
}
// mimic Hue motion sensor
else if (false)
{
map["manufacturername"] = "Philips";
map["modelid"] = "SML001";
}
}
if (req.mode != ApiModeNormal &&
sensor->manufacturer().startsWith(QLatin1String("Philips")) &&
sensor->type().startsWith(QLatin1String("ZHA")))
{
QString type = sensor->type();
type.replace(QLatin1String("ZHA"), QLatin1String("ZLL"));
map["type"] = type;
}
if (sensor->mode() != Sensor::ModeNone &&
sensor->type().endsWith(QLatin1String("Switch")))
{
map["mode"] = (double)sensor->mode();
}
const ResourceItem *item = sensor->item(RAttrUniqueId);
if (item)
{
map["uniqueid"] = item->toString();
}
map["state"] = state;
map["config"] = config;
return true;
}
void DeRestPluginPrivate::handleSensorEvent(const Event &e)
{
DBG_Assert(e.resource() == RSensors);
DBG_Assert(e.what() != nullptr);
Sensor *sensor = getSensorNodeForId(e.id());
if (!sensor)
{
return;
}
const QDateTime now = QDateTime::currentDateTime();
// speedup sensor state check
if ((e.what() == RStatePresence || e.what() == RStateButtonEvent) &&
sensor && sensor->durationDue.isValid())
{
sensorCheckFast = CHECK_SENSOR_FAST_ROUNDS;
}
// push sensor state updates through websocket
if (strncmp(e.what(), "state/", 6) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
if (item->descriptor().suffix == RStatePresence && item->toBool())
{
globalLastMotion = item->lastSet(); // remember
}
if (!(item->needPushSet() || item->needPushChange()))
{
DBG_Printf(DBG_INFO_L2, "discard sensor state push for %s: %s (already pushed)\n", qPrintable(e.id()), e.what());
webSocketServer->flush(); // force transmit send buffer
return; // already pushed
}
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap state;
ResourceItem *iox = nullptr;
ResourceItem *ioy = nullptr;
ResourceItem *ioz = nullptr;
ResourceItem *ix = nullptr;
ResourceItem *iy = nullptr;
for (int i = 0; i < sensor->itemCount(); i++)
{
item = sensor->itemForIndex(i);
const ResourceItemDescriptor &rid = item->descriptor();
if (strncmp(rid.suffix, "state/", 6) == 0)
{
const char *key = item->descriptor().suffix + 6;
if (rid.suffix == RStateOrientationX)
{
iox = item;
}
else if (rid.suffix == RStateOrientationY)
{
ioy = item;
}
else if (rid.suffix == RStateOrientationZ)
{
ioz = item;
}
else if (rid.suffix == RStateX)
{
ix = item;
}
else if (rid.suffix == RStateY)
{
iy = item;
}
else if (item->isPublic() && item->lastSet().isValid() && (gwWebSocketNotifyAll || rid.suffix == RStateButtonEvent || item->needPushChange()))
{
state[key] = item->toVariant();
item->clearNeedPush();
}
}
}
if (iox && iox->lastSet().isValid() && ioy && ioy->lastSet().isValid() && ioz && ioz->lastSet().isValid())
{
if (gwWebSocketNotifyAll || iox->needPushChange() || ioy->needPushChange() || ioz->needPushChange())
{
iox->clearNeedPush();
ioy->clearNeedPush();
ioz->clearNeedPush();
QVariantList orientation;
orientation.append(iox->toNumber());
orientation.append(ioy->toNumber());
orientation.append(ioz->toNumber());
state["orientation"] = orientation;
}
}
if (ix && ix->lastSet().isValid() && iy && iy->lastSet().isValid())
{
if (gwWebSocketNotifyAll || ix->needPushChange() || iy->needPushChange())
{
ix->clearNeedPush();
iy->clearNeedPush();
QVariantList xy;
xy.append(round(ix->toNumber() / 6.5535) / 10000.0);
xy.append(round(iy->toNumber() / 6.5535) / 10000.0);
state["xy"] = xy;
}
}
if (!state.isEmpty())
{
map["state"] = state;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
}
else if (strncmp(e.what(), "config/", 7) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
if (!(item->needPushSet() || item->needPushChange()))
{
DBG_Printf(DBG_INFO_L2, "discard sensor config push for %s (already pushed)\n", e.what());
return; // already pushed
}
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap config;
ResourceItem *ilcs = nullptr;
ResourceItem *ilca = nullptr;
ResourceItem *ilct = nullptr;
for (int i = 0; i < sensor->itemCount(); i++)
{
item = sensor->itemForIndex(i);
const ResourceItemDescriptor &rid = item->descriptor();
if (strncmp(rid.suffix, "config/", 7) == 0)
{
const char *key = item->descriptor().suffix + 7;
if (rid.suffix == RConfigHostFlags)
{
continue;
}
else if (rid.suffix == RConfigLastChangeSource)
{
ilcs = item;
}
else if (rid.suffix == RConfigLastChangeAmount)
{
ilca = item;
}
else if (rid.suffix == RConfigLastChangeTime)
{
ilct = item;
}
else if (item->isPublic() && item->lastSet().isValid() && (gwWebSocketNotifyAll || item->needPushChange()))
{
if (rid.suffix == RConfigSchedule)
{
QVariantMap schedule;
deserialiseThermostatSchedule(item->toString(), &schedule);
config[key] = schedule;
}
else if (rid.suffix == RConfigPending)
{
QVariantList pending;
auto value = item->toNumber();
if (value & R_PENDING_DELAY)
{
pending.append("delay");
}
if (value & R_PENDING_LEDINDICATION)
{
pending.append("ledindication");
}
if (value & R_PENDING_SENSITIVITY)
{
pending.append("sensitivity");
}
if (value & R_PENDING_USERTEST)
{
pending.append("usertest");
}
if (value & R_PENDING_DEVICEMODE)
{
pending.append("devicemode");
}
config[key] = pending;
}
else
{
config[key] = item->toVariant();
}
item->clearNeedPush();
}
}
}
if (ilcs && ilcs->lastSet().isValid() && ilca && ilca->lastSet().isValid() && ilct && ilct->lastSet().isValid())
{
if (gwWebSocketNotifyAll || ilcs->needPushChange() || ilca->needPushChange() || ilct->needPushChange())
{
ilcs->clearNeedPush();
ilca->clearNeedPush();
ilct->clearNeedPush();
QVariantMap lastchange;
lastchange["source"] = RConfigLastChangeSourceValues[ilcs->toNumber()];
lastchange["amount"] = ilca->toNumber();
lastchange["time"] = ilct->toVariant().toDateTime().toString("yyyy-MM-ddTHH:mm:ssZ");
config["lastchange"] = lastchange;
}
}
if (!config.isEmpty())
{
map["config"] = config;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
}
else if (strncmp(e.what(), "attr/", 5) == 0)
{
ResourceItem *item = sensor->item(e.what());
if (item && item->isPublic())
{
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("changed");
map["r"] = QLatin1String("sensors");
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
QVariantMap config;
// For now, don't collect top-level attributes into a single event.
const char *key = item->descriptor().suffix + 5;
map[key] = item->toVariant();
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
}
else if (e.what() == REventAdded)
{
checkSensorGroup(sensor);
checkSensorBindingsForAttributeReporting(sensor);
checkSensorBindingsForClientClusters(sensor);
pushSensorInfoToCore(sensor);
QVariantMap res;
res["name"] = sensor->name();
searchSensorsResult[sensor->id()] = res;
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("added");
map["r"] = QLatin1String("sensors");
QVariantMap smap;
QHttpRequestHeader hdr; // dummy
QStringList path; // dummy
ApiRequest req(hdr, path, nullptr, QLatin1String("")); // dummy
req.mode = ApiModeNormal;
sensorToMap(sensor, smap, req);
map["id"] = sensor->id();
map["uniqueid"] = sensor->uniqueId();
smap["id"] = sensor->id();
map["sensor"] = smap;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
else if (e.what() == REventDeleted)
{
deleteGroupsWithDeviceMembership(e.id());
QVariantMap map;
map["t"] = QLatin1String("event");
map["e"] = QLatin1String("deleted");
map["r"] = QLatin1String("sensors");
QVariantMap smap;
map["id"] = e.id();
map["uniqueid"] = sensor->uniqueId();
smap["id"] = e.id();
map["sensor"] = smap;
webSocketServer->broadcastTextMessage(Json::serialize(map));
}
else if (e.what() == REventValidGroup)
{
checkOldSensorGroups(sensor);
ResourceItem *item = sensor->item(RConfigGroup);
DBG_Assert(item != nullptr);
if (!item)
{
return;
}
QStringList gids = item->toString().split(',', QString::SkipEmptyParts);
for (int j = 0; j < gids.size(); j++) {
const QString gid = gids[j];
if (gid == "0")
{
continue;
}
Group *group = getGroupForId(gid);
if (group && group->state() != Group::StateNormal)
{
DBG_Printf(DBG_INFO, "reanimate group %s for sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
group->setState(Group::StateNormal);
group->setName(sensor->modelId() + QLatin1String(" ") + sensor->id());
updateGroupEtag(group);
queSaveDb(DB_GROUPS, DB_SHORT_SAVE_DELAY);
}
if (group && group->addDeviceMembership(sensor->id()))
{
DBG_Printf(DBG_INFO, "attach group %s to sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
queSaveDb(DB_GROUPS, DB_LONG_SAVE_DELAY);
updateGroupEtag(group);
}
if (!group) // create
{
DBG_Printf(DBG_INFO, "create group %s for sensor %s\n", qPrintable(gid), qPrintable(sensor->id()));
Group g;
g.setAddress(gid.toUInt());
g.setName(sensor->modelId() + QLatin1String(" ") + sensor->id());
g.addDeviceMembership(sensor->id());
ResourceItem *item2 = g.addItem(DataTypeString, RAttrUniqueId);
DBG_Assert(item2);
if (item2)
{
// FIXME: use the endpoint from which the group command was sent.
const QString uid = generateUniqueId(sensor->address().ext(), 0, 0);
item2->setValue(uid);
}
groups.push_back(g);
updateGroupEtag(&groups.back());
queSaveDb(DB_GROUPS, DB_SHORT_SAVE_DELAY);
checkSensorBindingsForClientClusters(sensor);
}
}
}
}
/*! Starts the search for new sensors.
*/
void DeRestPluginPrivate::startSearchSensors()
{
if (searchSensorsState == SearchSensorsIdle || searchSensorsState == SearchSensorsDone)
{
pollNodes.clear();
bindingQueue.clear();
sensors.reserve(sensors.size() + 10);
searchSensorsCandidates.clear();
searchSensorsResult.clear();
lastSensorsScan = QDateTime::currentDateTimeUtc().toString(QLatin1String("yyyy-MM-ddTHH:mm:ss"));
QTimer::singleShot(1000, this, SLOT(searchSensorsTimerFired()));
searchSensorGppPairCounter = 0;
searchSensorsState = SearchSensorsActive;
}
else
{
Q_ASSERT(searchSensorsState == SearchSensorsActive);
}
searchSensorsTimeout = gwNetworkOpenDuration;
gwPermitJoinResend = searchSensorsTimeout;
if (!resendPermitJoinTimer->isActive())
{
resendPermitJoinTimer->start(100);
}
}
/*! Handler for search sensors active state.
*/
void DeRestPluginPrivate::searchSensorsTimerFired()
{
if (gwPermitJoinResend == 0)
{
if (gwPermitJoinDuration == 0)
{
searchSensorsTimeout = 0; // done
}
}
if (searchSensorsTimeout > 0)
{
searchSensorsTimeout--;
QTimer::singleShot(1000, this, SLOT(searchSensorsTimerFired()));
}
if (searchSensorsTimeout == 0)
{
DBG_Printf(DBG_INFO, "Search sensors done\n");
fastProbeAddr = deCONZ::Address();
fastProbeIndications.clear();
searchSensorsState = SearchSensorsDone;
}
}
/*! Validate sensor states. */
void DeRestPluginPrivate::checkSensorStateTimerFired()
{
if (sensors.empty())
{
return;
}
if (sensorCheckIter >= sensors.size())
{
sensorCheckIter = 0;
sensorCheckFast = (sensorCheckFast > 0) ? sensorCheckFast - 1 : 0;
}
for (int i = 0; i < CHECK_SENSORS_MAX; i++)
{
if (sensorCheckIter >= sensors.size())
{
break;
}
Sensor *sensor = &sensors[sensorCheckIter];
sensorCheckIter++;
if (sensor->deletedState() != Sensor::StateNormal)
{
continue;
}
if (sensor->durationDue.isValid())
{
QDateTime now = QDateTime::currentDateTime();
if (sensor->modelId() == QLatin1String("TY0202")) // Lidl/SILVERCREST motion sensor
{
continue; // will be only reset via IAS Zone status
}
if (sensor->durationDue <= now)
{
// automatically set presence to false, if not triggered in config.duration
ResourceItem *item = sensor->item(RStatePresence);
if (item && item->toBool())
{
DBG_Printf(DBG_INFO, "sensor %s (%s): disable presence\n", qPrintable(sensor->id()), qPrintable(sensor->modelId()));
item->setValue(false);
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStatePresence, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
for (quint16 clusterId : sensor->fingerPrint().inClusters)
{
if (sensor->modelId().startsWith(QLatin1String("TRADFRI")))
{
clusterId = OCCUPANCY_SENSING_CLUSTER_ID; // workaround
}
if (clusterId == IAS_ZONE_CLUSTER_ID || clusterId == OCCUPANCY_SENSING_CLUSTER_ID)
{
pushZclValueDb(sensor->address().ext(), sensor->fingerPrint().endpoint, clusterId, 0x0000, 0);
break;
}
}
}
else if (!item && sensor->modelId() == QLatin1String("lumi.sensor_switch"))
{
// Xiaomi round button (WXKG01LM)
// generate artificial hold event
item = sensor->item(RStateButtonEvent);
if (item && item->toNumber() == (S_BUTTON_1 + S_BUTTON_ACTION_INITIAL_PRESS))
{
item->setValue(S_BUTTON_1 + S_BUTTON_ACTION_HOLD);
DBG_Printf(DBG_INFO, "[INFO] - Button %u Hold %s\n", item->toNumber(), qPrintable(sensor->modelId()));
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateButtonEvent, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
else if (sensor->modelId() == QLatin1String("FOHSWITCH"))
{
// Friends of Hue switch
// generate artificial hold event
item = sensor->item(RStateButtonEvent);
quint32 btn = item ? static_cast<quint32>(item->toNumber()) : 0;
const quint32 action = btn & 0x03;
if (btn >= S_BUTTON_1 && btn <= S_BUTTON_6 && action == S_BUTTON_ACTION_INITIAL_PRESS)
{
btn &= ~0x03;
item->setValue(btn + S_BUTTON_ACTION_HOLD);
DBG_Printf(DBG_INFO, "FoH switch button %d Hold %s\n", item->toNumber(), qPrintable(sensor->modelId()));
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateButtonEvent, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
else if (!item && sensor->modelId().startsWith(QLatin1String("lumi.vibration")) && sensor->type() == QLatin1String("ZHAVibration"))
{
item = sensor->item(RStateVibration);
if (item && item->toBool())
{
DBG_Printf(DBG_INFO, "sensor %s (%s): disable vibration\n", qPrintable(sensor->id()), qPrintable(sensor->modelId()));
item->setValue(false);
sensor->updateStateTimestamp();
enqueueEvent(Event(RSensors, RStateVibration, sensor->id(), item));
enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));
updateSensorEtag(sensor);
}
}
sensor->durationDue = QDateTime();
}
else
{
sensorCheckFast = CHECK_SENSOR_FAST_ROUNDS;
}
}
}
// adjust check speed if needed
int interval = (sensorCheckFast > 0) ? CHECK_SENSOR_FAST_INTERVAL
: CHECK_SENSOR_INTERVAL;
if (interval != checkSensorsTimer->interval())
{
DBG_Printf(DBG_INFO, "Set sensor check interval to %d milliseconds\n", interval);
checkSensorsTimer->setInterval(interval);
}
}
/*! Check insta mac address to model identifier.
*/
void DeRestPluginPrivate::checkInstaModelId(Sensor *sensor)
{
if (sensor && existDevicesWithVendorCodeForMacPrefix(sensor->address(), VENDOR_INSTA))
{
if (!sensor->modelId().endsWith(QLatin1String("_1")))
{ // extract model identifier from mac address 6th byte
const quint64 model = (sensor->address().ext() >> 16) & 0xff;
QString modelId;
if (model == 0x01) { modelId = QLatin1String("HS_4f_GJ_1"); }
else if (model == 0x02) { modelId = QLatin1String("WS_4f_J_1"); }
else if (model == 0x03) { modelId = QLatin1String("WS_3f_G_1"); }
if (!modelId.isEmpty() && sensor->modelId() != modelId)
{
sensor->setModelId(modelId);
sensor->setNeedSaveDatabase(true);
updateSensorEtag(sensor);
}
}
}
}
/*! Heuristic to detect the type and configuration of devices.
*/
void DeRestPluginPrivate::handleIndicationSearchSensors(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)
{
if (searchSensorsState != SearchSensorsActive)
{
return;
}
if ((ind.srcAddress().hasExt() && ind.srcAddress().ext() == fastProbeAddr.ext()) ||
(fastProbeAddr.hasExt() && ind.srcAddress().hasNwk() && ind.srcAddress().nwk() == fastProbeAddr.nwk()))
{
DBG_Printf(DBG_INFO, "FP indication 0x%04X / 0x%04X (0x%016llX / 0x%04X)\n", ind.profileId(), ind.clusterId(), ind.srcAddress().ext(), ind.srcAddress().nwk());
DBG_Printf(DBG_INFO, " ... (0x%016llX / 0x%04X)\n", fastProbeAddr.ext(), fastProbeAddr.nwk());
}
if (ind.profileId() == ZDP_PROFILE_ID && ind.clusterId() == ZDP_DEVICE_ANNCE_CLID)
{
QDataStream stream(ind.asdu());
stream.setByteOrder(QDataStream::LittleEndian);
quint8 seq;
quint16 nwk;
quint64 ext;
quint8 macCapabilities;
stream >> seq;
stream >> nwk;
stream >> ext;
stream >> macCapabilities;
DBG_Printf(DBG_INFO, "device announce 0x%016llX (0x%04X) mac capabilities 0x%02X\n", ext, nwk, macCapabilities);
// filter supported devices
// Busch-Jaeger
if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_BUSCH_JAEGER))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_UBISYS))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_SUNRICHER))
{
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_BOSCH))
{ // macCapabilities == 0
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_DEVELCO))
{ // macCapabilities == 0
}
else if (macCapabilities & deCONZ::MacDeviceIsFFD)
{
if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_LDS))
{ // Fix to allow Samsung SmartThings plug sensors to be created (7A-PL-Z-J3, modelId ZB-ONOFFPlug-D0005)
}
else if (existDevicesWithVendorCodeForMacPrefix(ext, VENDOR_JASCO))
{ // Fix to support GE mains powered switches
}
else
{
return;
}
}
else if (macCapabilities == 0)
{
return;
}
if (fastProbeAddr.hasExt())
{
return;
}
DBG_Printf(DBG_INFO, "set fast probe address to 0x%016llX (0x%04X)\n", ext, nwk);
fastProbeAddr.setExt(ext);
fastProbeAddr.setNwk(nwk);
if (!fastProbeTimer->isActive())
{
fastProbeTimer->start(900);
}
fastProbeIndications.clear();
fastProbeIndications.push_back(ind);
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (i->address.ext() == ext || i->address.nwk() == nwk)
{
i->waitIndicationClusterId = 0xffff;
i->timeout.invalidate();
i->address = deCONZ::Address(); // clear
}
}
SensorCandidate sc;
sc.waitIndicationClusterId = 0xffff;
sc.address.setExt(ext);
sc.address.setNwk(nwk);
sc.macCapabilities = macCapabilities;
searchSensorsCandidates.push_back(sc);
return;
}
else if (ind.profileId() == ZDP_PROFILE_ID)
{
if (ind.clusterId() == ZDP_MATCH_DESCRIPTOR_CLID)
{
return;
}
if (!fastProbeAddr.hasExt())
{
return;
}
if (ind.srcAddress().hasExt() && fastProbeAddr.ext() != ind.srcAddress().ext())
{
return;
}
else if (ind.srcAddress().hasNwk() && fastProbeAddr.nwk() != ind.srcAddress().nwk())
{
return;
}
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (i->address.ext() == fastProbeAddr.ext())
{
DBG_Printf(DBG_INFO, "ZDP indication search sensors 0x%016llX (0x%04X) cluster 0x%04X\n", ind.srcAddress().ext(), ind.srcAddress().nwk(), ind.clusterId());
if (ind.clusterId() == i->waitIndicationClusterId && i->timeout.isValid())
{
DBG_Printf(DBG_INFO, "ZDP indication search sensors 0x%016llX (0x%04X) clear timeout on cluster 0x%04X\n", ind.srcAddress().ext(), ind.srcAddress().nwk(), ind.clusterId());
i->timeout.invalidate();
i->waitIndicationClusterId = 0xffff;
}
if (ind.clusterId() & 0x8000)
{
fastProbeIndications.push_back(ind); // remember responses
}
fastProbeTimer->stop();
fastProbeTimer->start(5);
break;
}
}
return;
}
else if (ind.profileId() == ZLL_PROFILE_ID || ind.profileId() == HA_PROFILE_ID)
{
switch (ind.clusterId())
{
case ONOFF_CLUSTER_ID:
case SCENE_CLUSTER_ID:
case LEVEL_CLUSTER_ID:
case VENDOR_CLUSTER_ID:
if ((zclFrame.frameControl() & deCONZ::ZclFCClusterCommand) == 0)
{
return;
}
if (zclFrame.frameControl() & deCONZ::ZclFCDirectionServerToClient)
{
return;
}
break; // ok
case BASIC_CLUSTER_ID:
if (!zclFrame.isProfileWideCommand())
{
return;
}
if (zclFrame.commandId() != deCONZ::ZclReadAttributesResponseId && zclFrame.commandId() != deCONZ::ZclReportAttributesId)
{
return;
}
break; // ok
case IAS_ZONE_CLUSTER_ID:
break; // ok
default:
return;
}
}
else
{
return;
}
if (ind.dstAddressMode() != deCONZ::ApsGroupAddress && ind.dstAddressMode() != deCONZ::ApsNwkAddress)
{
return;
}
SensorCandidate *sc = nullptr;
{
std::vector<SensorCandidate>::iterator i = searchSensorsCandidates.begin();
std::vector<SensorCandidate>::iterator end = searchSensorsCandidates.end();
for (; i != end; ++i)
{
if (ind.srcAddress().hasExt() && i->address.ext() == ind.srcAddress().ext())
{
sc = &*i;
break;
}
if (ind.srcAddress().hasNwk() && i->address.nwk() == ind.srcAddress().nwk())
{
sc = &*i;
break;
}
}
}
if (sc && fastProbeAddr.hasExt() && sc->address.ext() == fastProbeAddr.ext())
{
if (zclFrame.manufacturerCode() == VENDOR_XIAOMI || zclFrame.manufacturerCode() == VENDOR_DSR)
{
DBG_Printf(DBG_INFO, "Remember Xiaomi special for 0x%016llX\n", ind.srcAddress().ext());
fastProbeIndications.push_back(ind); // remember Xiaomi special report
}
if (!fastProbeTimer->isActive())
{
fastProbeTimer->start(5);
}
if (ind.profileId() == ZLL_PROFILE_ID || ind.profileId() == HA_PROFILE_ID)
{
if (ind.clusterId() == sc->waitIndicationClusterId && sc->timeout.isValid())
{
DBG_Printf(DBG_INFO, "Clear fast probe timeout for cluster 0x%04X, 0x%016llX\n", ind.clusterId(), ind.srcAddress().ext());
sc->timeout.invalidate();
sc->waitIndicationClusterId = 0xffff;
}
}
}
quint8 macCapabilities = 0;
deCONZ::Address indAddress;
if (!sc)
{
Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());
if (sensor)
{
indAddress = sensor->address();
if (sensor->node())
{
macCapabilities = (int)sensor->node()->macCapabilities();
}
}
if (apsCtrl && (!sensor || (macCapabilities == 0)))
{
int i = 0;
const deCONZ::Node *node;
while (apsCtrl->getNode(i, &node) == 0)
{
/*if (node->macCapabilities() == 0)
{
// ignore
}
else*/ if (node->address().hasExt() && ind.srcAddress().hasExt() &&
ind.srcAddress().ext() == node->address().ext())
{
indAddress = node->address();
macCapabilities = node->macCapabilities();
break;
}
else if (node->address().hasNwk() && ind.srcAddress().hasNwk() &&
ind.srcAddress().nwk() == node->address().nwk())
{
indAddress = node->address();
macCapabilities = node->macCapabilities();
break;
}
i++;
}
}
}
// currently only end-devices are supported
if (!sc && (macCapabilities == 0 || (macCapabilities & deCONZ::MacDeviceIsFFD)))
{
return;
}
if (!sc && indAddress.hasExt() && indAddress.hasNwk())
{
SensorCandidate sc2;
sc2.address = indAddress;
sc2.macCapabilities = macCapabilities;
searchSensorsCandidates.push_back(sc2);
sc = &searchSensorsCandidates.back();
}
if (!sc) // we need a valid candidate from device announce or cache
{
return;
}
// check for dresden elektronik devices
if (existDevicesWithVendorCodeForMacPrefix(sc->address, VENDOR_DDEL))
{
if (sc->macCapabilities & deCONZ::MacDeviceIsFFD) // end-devices only
return;
if (ind.profileId() != HA_PROFILE_ID)
return;
SensorCommand cmd;
cmd.cluster = ind.clusterId();
cmd.endpoint = ind.srcEndpoint();
cmd.dstGroup = ind.dstAddress().group();
cmd.zclCommand = zclFrame.commandId();
cmd.zclCommandParameter = 0;
// filter
if (cmd.endpoint == 0x01 && cmd.cluster == ONOFF_CLUSTER_ID)
{
// on: Lighting and Scene Switch left button
DBG_Printf(DBG_INFO, "Lighting or Scene Switch left button\n");
}
else if (cmd.endpoint == 0x02 && cmd.cluster == ONOFF_CLUSTER_ID)
{
// on: Lighting Switch right button
DBG_Printf(DBG_INFO, "Lighting Switch right button\n");
}
else if (cmd.endpoint == 0x01 && cmd.cluster == SCENE_CLUSTER_ID && cmd.zclCommand == 0x05
&& zclFrame.payload().size() >= 3 && zclFrame.payload().at(2) == 0x04)
{
// recall scene: Scene Switch
cmd.zclCommandParameter = zclFrame.payload()[2]; // sceneId
DBG_Printf(DBG_INFO, "Scene Switch scene %u\n", cmd.zclCommandParameter);
}
else
{
return;
}
bool found = false;
for (size_t i = 0; i < sc->rxCommands.size(); i++)
{
if (sc->rxCommands[i] == cmd)
{
found = true;
break;
}
}
if (!found)
{
sc->rxCommands.push_back(cmd);
}
bool isLightingSwitch = false;
bool isSceneSwitch = false;
quint16 group1 = 0;
quint16 group2 = 0;
for (size_t i = 0; i < sc->rxCommands.size(); i++)
{
const SensorCommand &c = sc->rxCommands[i];
if (c.cluster == SCENE_CLUSTER_ID && c.zclCommandParameter == 0x04 && c.endpoint == 0x01)
{
group1 = c.dstGroup;
isSceneSwitch = true;
DBG_Printf(DBG_INFO, "Scene Switch group1 0x%04X\n", group1);
break;
}
else if (c.cluster == ONOFF_CLUSTER_ID && c.endpoint == 0x01)
{
group1 = c.dstGroup;
}
else if (c.cluster == ONOFF_CLUSTER_ID && c.endpoint == 0x02)
{
group2 = c.dstGroup;
}
if (!isSceneSwitch && group1 != 0 && group2 != 0)
{
if (group1 > group2)
{
std::swap(group1, group2); // reorder
}
isLightingSwitch = true;
DBG_Printf(DBG_INFO, "Lighting Switch group1 0x%04X, group2 0x%04X\n", group1, group2);
break;
}
}
Sensor *s1 = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x01);
Sensor *s2 = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), 0x02);
if (isSceneSwitch || isLightingSwitch)
{
Sensor sensorNode;
SensorFingerprint &fp = sensorNode.fingerPrint();
fp.endpoint = 0x01;
fp.deviceId = DEV_ID_ZLL_COLOR_CONTROLLER;
fp.profileId = HA_PROFILE_ID;
fp.inClusters.push_back(BASIC_CLUSTER_ID);
fp.inClusters.push_back(COMMISSIONING_CLUSTER_ID);
fp.outClusters.push_back(ONOFF_CLUSTER_ID);
fp.outClusters.push_back(LEVEL_CLUSTER_ID);
fp.outClusters.push_back(SCENE_CLUSTER_ID);
sensorNode.setNode(0);
sensorNode.address() = sc->address;
sensorNode.setType("ZHASwitch");
sensorNode.fingerPrint() = fp;
sensorNode.setUniqueId(generateUniqueId(sensorNode.address().ext(), sensorNode.fingerPrint().endpoint, COMMISSIONING_CLUSTER_ID));
sensorNode.setManufacturer(QLatin1String("dresden elektronik"));
ResourceItem *item;
item = sensorNode.item(RConfigOn);
item->setValue(true);
item = sensorNode.item(RConfigReachable);
item->setValue(true);
sensorNode.addItem(DataTypeInt32, RStateButtonEvent);
sensorNode.updateStateTimestamp();
sensorNode.setNeedSaveDatabase(true);
updateSensorEtag(&sensorNode);
bool update = false;
if (!s1 && isSceneSwitch && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeScenes);
sensorNode.setModelId(QLatin1String("Scene Switch"));
sensorNode.setName(QString("Scene Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensors.push_back(sensorNode);
s1 = &sensors.back();
updateSensorEtag(s1);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
else if (isLightingSwitch)
{
if (!s1 && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeTwoGroups);
sensorNode.setModelId(QLatin1String("Lighting Switch"));
sensorNode.setName(QString("Lighting Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensors.push_back(sensorNode);
s1 = &sensors.back();
updateSensorEtag(s1);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
if (!s2 && searchSensorsState == SearchSensorsActive)
{
openDb();
sensorNode.setId(QString::number(getFreeSensorId()));
closeDb();
sensorNode.setMode(Sensor::ModeTwoGroups);
sensorNode.setName(QString("Lighting Switch %1").arg(sensorNode.id()));
sensorNode.setNeedSaveDatabase(true);
sensorNode.fingerPrint().endpoint = 0x02;
sensorNode.setUniqueId(generateUniqueId(sensorNode.address().ext(), sensorNode.fingerPrint().endpoint, COMMISSIONING_CLUSTER_ID));
sensors.push_back(sensorNode);
s2 = &sensors.back();
updateSensorEtag(s2);
update = true;
Event e(RSensors, REventAdded, sensorNode.id());
enqueueEvent(e);
}
}
// check updated data
if (s1 && s1->modelId().isEmpty())
{
if (isSceneSwitch) { s1->setModelId(QLatin1String("Scene Switch")); }
else if (isLightingSwitch) { s1->setModelId(QLatin1String("Lighting Switch")); }
s1->setNeedSaveDatabase(true);
update = true;
}
if (s2 && s2->modelId().isEmpty())
{
if (isLightingSwitch) { s2->setModelId(QLatin1String("Lighting Switch")); }
s2->setNeedSaveDatabase(true);
update = true;
}
if (s1 && s1->manufacturer().isEmpty())
{
s1->setManufacturer(QLatin1String("dresden elektronik"));
s1->setNeedSaveDatabase(true);
update = true;
}
if (s2 && s2->manufacturer().isEmpty())
{
s2->setManufacturer(QLatin1String("dresden elektronik"));
s2->setNeedSaveDatabase(true);
update = true;
}
// create or update first group
Group *g = (s1 && group1 != 0) ? getGroupForId(group1) : 0;
if (!g && s1 && group1 != 0)
{
// delete older groups of this switch permanently
deleteOldGroupOfSwitch(s1, group1);
//create new switch group
Group group;
group.setAddress(group1);
group.addDeviceMembership(s1->id());
group.setName(QString("%1").arg(s1->name()));
updateGroupEtag(&group);
groups.push_back(group);
update = true;
}
else if (g && s1)
{
if (g->state() == Group::StateDeleted)
{
g->setState(Group::StateNormal);
}
// check for changed device memberships
if (!g->m_deviceMemberships.empty())
{
if (isLightingSwitch || isSceneSwitch) // only support one device member per group
{
if (g->m_deviceMemberships.size() > 1 || g->m_deviceMemberships.front() != s1->id())
{
g->m_deviceMemberships.clear();
}
}
}
if (g->addDeviceMembership(s1->id()))
{
updateGroupEtag(g);
update = true;
}
}
// create or update second group (if needed)
g = (s2 && group2 != 0) ? getGroupForId(group2) : 0;
if (!g && s2 && group2 != 0)
{
// delete older groups of this switch permanently
deleteOldGroupOfSwitch(s2, group2);
//create new switch group
Group group;
group.setAddress(group2);
group.addDeviceMembership(s2->id());
group.setName(QString("%1").arg(s2->name()));
updateGroupEtag(&group);
groups.push_back(group);
}
else if (g && s2)
{
if (g->state() == Group::StateDeleted)
{
g->setState(Group::StateNormal);
}
// check for changed device memberships
if (!g->m_deviceMemberships.empty())
{
if (isLightingSwitch || isSceneSwitch) // only support one device member per group
{
if (g->m_deviceMemberships.size() > 1 || g->m_deviceMemberships.front() != s2->id())
{
g->m_deviceMemberships.clear();
}
}
}
if (g->addDeviceMembership(s2->id()))
{
updateGroupEtag(g);
update = true;
}
}
if (update)
{
queSaveDb(DB_GROUPS | DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
}
}
else if (existDevicesWithVendorCodeForMacPrefix(sc->address, VENDOR_IKEA))
{
if (sc->macCapabilities & deCONZ::MacDeviceIsFFD) // end-devices only
return;
if (ind.profileId() != HA_PROFILE_ID)
return;
// filter for remote control toggle command (large button)
if (ind.srcEndpoint() == 0x01 && ind.clusterId() == SCENE_CLUSTER_ID && zclFrame.manufacturerCode() == VENDOR_IKEA &&
zclFrame.commandId() == 0x07 && zclFrame.payload().at(0) == 0x02)
{
// TODO move following legacy cleanup code in Phoscon App / switch editor
DBG_Printf(DBG_INFO, "ikea remote setup button\n");
Sensor *s = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());
if (!s)
{
return;
}
std::vector<Rule>::iterator ri = rules.begin();
std::vector<Rule>::iterator rend = rules.end();
QString sensorAddress(QLatin1String("/sensors/"));
sensorAddress.append(s->id());
bool changed = false;
for (; ri != rend; ++ri)
{
if (ri->state() != Rule::StateNormal)
{
continue;
}
std::vector<RuleCondition>::const_iterator ci = ri->conditions().begin();
std::vector<RuleCondition>::const_iterator cend = ri->conditions().end();
for (; ci != cend; ++ci)
{
if (ci->address().startsWith(sensorAddress))
{
if (ri->name().startsWith(QLatin1String("default-ct")) && ri->owner() == QLatin1String("deCONZ"))
{
DBG_Printf(DBG_INFO, "ikea remote delete legacy rule %s\n", qPrintable(ri->name()));
ri->setState(Rule::StateDeleted);
changed = true;
}
}
}
}
if (changed)
{
indexRulesTriggers();
queSaveDb(DB_RULES, DB_SHORT_SAVE_DELAY);
}
}
}
} |
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <google/dense_hash_set>
#include <locale>
#include <list>
#include <iostream>
#include <string>
#include <re2/re2.h>
#include "smart_git.h"
#include "timer.h"
using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;
#define CHUNK_SIZE (1 << 20)
struct search_file {
string path;
const char *ref;
git_oid oid;
};
struct chunk_file {
search_file *file;
int left;
int right;
};
#define CHUNK_MAGIC 0xC407FADE
struct chunk {
int size;
unsigned magic;
vector<chunk_file> files;
char data[0];
chunk()
: size(0), magic(CHUNK_MAGIC), files() {
}
chunk_file &get_chunk_file(search_file *sf, const char *p) {
if (files.empty() || files.back().file != sf) {
int off = p - data;
files.push_back(chunk_file());
chunk_file &cf = files.back();
cf.file = sf;
cf.left = cf.right = off;
}
return files.back();
}
};
#define CHUNK_SPACE (CHUNK_SIZE - (sizeof(chunk)))
chunk *alloc_chunk() {
void *p;
if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
return NULL;
return new(p) chunk;
};
class chunk_allocator {
public:
chunk_allocator() : current_() {
new_chunk();
}
char *alloc(size_t len) {
assert(len < CHUNK_SPACE);
if ((current_->size + len) > CHUNK_SPACE)
new_chunk();
char *out = current_->data + current_->size;
current_->size += len;
return out;
}
list<chunk*>::iterator begin () {
return chunks_.begin();
}
typename list<chunk*>::iterator end () {
return chunks_.end();
}
chunk *current_chunk() {
return current_;
}
protected:
void new_chunk() {
current_ = alloc_chunk();
chunks_.push_back(current_);
}
list<chunk*> chunks_;
chunk *current_;
};
/*
* We special-case data() == NULL to provide an "empty" element for
* dense_hash_set.
*
* StringPiece::operator== will consider a zero-length string equal to a
* zero-length string with a NULL data().
*/
struct eqstr {
bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
if (lhs.data() == NULL && rhs.data() == NULL)
return true;
if (lhs.data() == NULL || rhs.data() == NULL)
return false;
return lhs == rhs;
}
};
struct hashstr {
locale loc;
size_t operator()(const StringPiece &str) const {
const collate<char> &coll = use_facet<collate<char> >(loc);
return coll.hash(str.data(), str.data() + str.size());
}
};
const StringPiece empty_string(NULL, 0);
typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;
class code_counter {
public:
code_counter(git_repository *repo)
: repo_(repo), stats_()
{
lines_.set_empty_key(empty_string);
}
void walk_ref(const char *ref) {
smart_object<git_commit> commit;
smart_object<git_tree> tree;
resolve_ref(commit, ref);
git_commit_tree(tree, commit);
walk_tree(ref, "", tree);
}
void dump_stats() {
printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
}
bool match(RE2& pat) {
list<chunk*>::iterator it;
StringPiece match;
int matches = 0;
for (it = alloc_.begin(); it != alloc_.end(); it++) {
StringPiece str((*it)->data, (*it)->size);
int pos = 0;
while (pos < str.size()) {
if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
break;
assert(memchr(match.data(), '\n', match.size()) == NULL);
StringPiece line = find_line(str, match);
printf("%.*s\n", line.size(), line.data());
print_files(line.data());
pos = line.size() + line.data() - str.data();
if (++matches == 10)
return true;
}
}
return matches > 0;
}
protected:
void print_files (const char *p) {
chunk *c = find_chunk(p);
int off = p - c->data;
for(vector<chunk_file>::iterator it = c->files.begin();
it != c->files.end(); it++) {
if (off >= it->left && off < it->right) {
printf(" (%s:%s)\n", it->file->ref, it->file->path.c_str());
}
}
}
StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
const char *start, *end;
assert(match.data() >= chunk.data());
assert(match.data() < chunk.data() + chunk.size());
assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
start = static_cast<const char*>
(memrchr(chunk.data(), '\n', match.data() - chunk.data()));
if (start == NULL)
start = chunk.data();
else
start++;
end = static_cast<const char*>
(memchr(match.data() + match.size(), '\n',
chunk.size() - (match.data() - chunk.data()) - match.size()));
if (end == NULL)
end = chunk.data() + chunk.size();
return StringPiece(start, end - start);
}
void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
string path;
int entries = git_tree_entrycount(tree);
int i;
for (i = 0; i < entries; i++) {
const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
path = pfx + "/" + git_tree_entry_name(ent);
smart_object<git_object> obj;
git_tree_entry_2object(obj, repo_, ent);
if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
walk_tree(ref, path, obj);
} else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
update_stats(ref, path, obj);
}
}
}
chunk* find_chunk(const char *p) {
chunk *out = reinterpret_cast<chunk*>
(reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
assert(out->magic == CHUNK_MAGIC);
return out;
}
void update_stats(const char *ref, const string& path, git_blob *blob) {
size_t len = git_blob_rawsize(blob);
const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
const char *end = p + len;
const char *f;
string_hash::iterator it;
search_file *sf = new search_file;
sf->path = path;
sf->ref = ref;
git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
chunk *c;
const char *line;
while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
it = lines_.find(StringPiece(p, f - p));
if (it == lines_.end()) {
stats_.dedup_bytes += (f - p) + 1;
stats_.dedup_lines ++;
// Include the trailing '\n' in the chunk buffer
char *alloc = alloc_.alloc(f - p + 1);
memcpy(alloc, p, f - p + 1);
lines_.insert(StringPiece(alloc, f - p));
c = alloc_.current_chunk();
line = alloc;
} else {
line = it->data();
c = find_chunk(line);
}
chunk_file &cf = c->get_chunk_file(sf, line);
cf.left = min(static_cast<long>(cf.left), p - c->data);
cf.right = max(static_cast<long>(cf.right), f - c->data);
p = f + 1;
stats_.lines++;
}
stats_.bytes += len;
}
void resolve_ref(smart_object<git_commit> &out, const char *refname) {
git_reference *ref;
const git_oid *oid;
git_oid tmp;
smart_object<git_object> obj;
if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
} else {
git_reference_lookup(&ref, repo_, refname);
git_reference_resolve(&ref, ref);
oid = git_reference_oid(ref);
git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
}
if (git_object_type(obj) == GIT_OBJ_TAG) {
git_tag_target(out, obj);
} else {
out = obj.release();
}
}
git_repository *repo_;
string_hash lines_;
struct {
unsigned long bytes, dedup_bytes;
unsigned long lines, dedup_lines;
} stats_;
chunk_allocator alloc_;
};
int main(int argc, char **argv) {
git_repository *repo;
git_repository_open(&repo, ".git");
code_counter counter(repo);
for (int i = 1; i < argc; i++) {
timer tm;
struct timeval elapsed;
printf("Walking %s...", argv[i]);
fflush(stdout);
counter.walk_ref(argv[i]);
elapsed = tm.elapsed();
printf(" done in %d.%06ds\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
counter.dump_stats();
RE2::Options opts;
opts.set_never_nl(true);
opts.set_one_line(false);
opts.set_posix_syntax(true);
while (true) {
printf("regex> ");
string line;
getline(cin, line);
if (cin.eof())
break;
RE2 re(line, opts);
if (re.ok()) {
timer tm;
struct timeval elapsed;
if (!counter.match(re)) {
printf("no match\n");
}
elapsed = tm.elapsed();
printf("Match completed in %d.%06ds.\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
}
return 0;
}
Fix the tracking of 'left' and 'right' indices in chunk_file.
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <google/dense_hash_set>
#include <locale>
#include <list>
#include <iostream>
#include <string>
#include <re2/re2.h>
#include "smart_git.h"
#include "timer.h"
using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;
#define CHUNK_SIZE (1 << 20)
struct search_file {
string path;
const char *ref;
git_oid oid;
};
struct chunk_file {
search_file *file;
unsigned int left;
unsigned int right;
};
#define CHUNK_MAGIC 0xC407FADE
struct chunk {
int size;
unsigned magic;
vector<chunk_file> files;
char data[0];
chunk()
: size(0), magic(CHUNK_MAGIC), files() {
}
chunk_file &get_chunk_file(search_file *sf, const char *p) {
if (files.empty() || files.back().file != sf) {
int off = p - data;
files.push_back(chunk_file());
chunk_file &cf = files.back();
cf.file = sf;
cf.left = cf.right = off;
}
return files.back();
}
};
#define CHUNK_SPACE (CHUNK_SIZE - (sizeof(chunk)))
chunk *alloc_chunk() {
void *p;
if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
return NULL;
return new(p) chunk;
};
class chunk_allocator {
public:
chunk_allocator() : current_() {
new_chunk();
}
char *alloc(size_t len) {
assert(len < CHUNK_SPACE);
if ((current_->size + len) > CHUNK_SPACE)
new_chunk();
char *out = current_->data + current_->size;
current_->size += len;
return out;
}
list<chunk*>::iterator begin () {
return chunks_.begin();
}
typename list<chunk*>::iterator end () {
return chunks_.end();
}
chunk *current_chunk() {
return current_;
}
protected:
void new_chunk() {
current_ = alloc_chunk();
chunks_.push_back(current_);
}
list<chunk*> chunks_;
chunk *current_;
};
/*
* We special-case data() == NULL to provide an "empty" element for
* dense_hash_set.
*
* StringPiece::operator== will consider a zero-length string equal to a
* zero-length string with a NULL data().
*/
struct eqstr {
bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
if (lhs.data() == NULL && rhs.data() == NULL)
return true;
if (lhs.data() == NULL || rhs.data() == NULL)
return false;
return lhs == rhs;
}
};
struct hashstr {
locale loc;
size_t operator()(const StringPiece &str) const {
const collate<char> &coll = use_facet<collate<char> >(loc);
return coll.hash(str.data(), str.data() + str.size());
}
};
const StringPiece empty_string(NULL, 0);
typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;
class code_counter {
public:
code_counter(git_repository *repo)
: repo_(repo), stats_()
{
lines_.set_empty_key(empty_string);
}
void walk_ref(const char *ref) {
smart_object<git_commit> commit;
smart_object<git_tree> tree;
resolve_ref(commit, ref);
git_commit_tree(tree, commit);
walk_tree(ref, "", tree);
}
void dump_stats() {
printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
}
bool match(RE2& pat) {
list<chunk*>::iterator it;
StringPiece match;
int matches = 0;
for (it = alloc_.begin(); it != alloc_.end(); it++) {
StringPiece str((*it)->data, (*it)->size);
int pos = 0;
while (pos < str.size()) {
if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
break;
assert(memchr(match.data(), '\n', match.size()) == NULL);
StringPiece line = find_line(str, match);
printf("%.*s\n", line.size(), line.data());
print_files(line.data());
pos = line.size() + line.data() - str.data();
if (++matches == 10)
return true;
}
}
return matches > 0;
}
protected:
void print_files (const char *p) {
chunk *c = find_chunk(p);
int off = p - c->data;
for(vector<chunk_file>::iterator it = c->files.begin();
it != c->files.end(); it++) {
if (off >= it->left && off < it->right) {
printf(" (%s:%s)\n", it->file->ref, it->file->path.c_str());
}
}
}
StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
const char *start, *end;
assert(match.data() >= chunk.data());
assert(match.data() < chunk.data() + chunk.size());
assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
start = static_cast<const char*>
(memrchr(chunk.data(), '\n', match.data() - chunk.data()));
if (start == NULL)
start = chunk.data();
else
start++;
end = static_cast<const char*>
(memchr(match.data() + match.size(), '\n',
chunk.size() - (match.data() - chunk.data()) - match.size()));
if (end == NULL)
end = chunk.data() + chunk.size();
return StringPiece(start, end - start);
}
void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
string path;
int entries = git_tree_entrycount(tree);
int i;
for (i = 0; i < entries; i++) {
const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
path = pfx + "/" + git_tree_entry_name(ent);
smart_object<git_object> obj;
git_tree_entry_2object(obj, repo_, ent);
if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
walk_tree(ref, path, obj);
} else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
update_stats(ref, path, obj);
}
}
}
chunk* find_chunk(const char *p) {
chunk *out = reinterpret_cast<chunk*>
(reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
assert(out->magic == CHUNK_MAGIC);
return out;
}
void update_stats(const char *ref, const string& path, git_blob *blob) {
size_t len = git_blob_rawsize(blob);
const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
const char *end = p + len;
const char *f;
string_hash::iterator it;
search_file *sf = new search_file;
sf->path = path;
sf->ref = ref;
git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
chunk *c;
const char *line;
while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
it = lines_.find(StringPiece(p, f - p));
if (it == lines_.end()) {
stats_.dedup_bytes += (f - p) + 1;
stats_.dedup_lines ++;
// Include the trailing '\n' in the chunk buffer
char *alloc = alloc_.alloc(f - p + 1);
memcpy(alloc, p, f - p + 1);
lines_.insert(StringPiece(alloc, f - p));
c = alloc_.current_chunk();
line = alloc;
} else {
line = it->data();
c = find_chunk(line);
}
chunk_file &cf = c->get_chunk_file(sf, line);
cf.left = min(static_cast<long>(cf.left), p - blob_data);
cf.right = max(static_cast<long>(cf.right), f - blob_data);
assert(cf.left < CHUNK_SPACE);
assert(cf.right < CHUNK_SPACE);
p = f + 1;
stats_.lines++;
}
stats_.bytes += len;
}
void resolve_ref(smart_object<git_commit> &out, const char *refname) {
git_reference *ref;
const git_oid *oid;
git_oid tmp;
smart_object<git_object> obj;
if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
} else {
git_reference_lookup(&ref, repo_, refname);
git_reference_resolve(&ref, ref);
oid = git_reference_oid(ref);
git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
}
if (git_object_type(obj) == GIT_OBJ_TAG) {
git_tag_target(out, obj);
} else {
out = obj.release();
}
}
git_repository *repo_;
string_hash lines_;
struct {
unsigned long bytes, dedup_bytes;
unsigned long lines, dedup_lines;
} stats_;
chunk_allocator alloc_;
};
int main(int argc, char **argv) {
git_repository *repo;
git_repository_open(&repo, ".git");
code_counter counter(repo);
for (int i = 1; i < argc; i++) {
timer tm;
struct timeval elapsed;
printf("Walking %s...", argv[i]);
fflush(stdout);
counter.walk_ref(argv[i]);
elapsed = tm.elapsed();
printf(" done in %d.%06ds\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
counter.dump_stats();
RE2::Options opts;
opts.set_never_nl(true);
opts.set_one_line(false);
opts.set_posix_syntax(true);
while (true) {
printf("regex> ");
string line;
getline(cin, line);
if (cin.eof())
break;
RE2 re(line, opts);
if (re.ok()) {
timer tm;
struct timeval elapsed;
if (!counter.match(re)) {
printf("no match\n");
}
elapsed = tm.elapsed();
printf("Match completed in %d.%06ds.\n",
(int)elapsed.tv_sec, (int)elapsed.tv_usec);
}
}
return 0;
}
|
/*
* Startup Self Tests
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/selftest.h>
#include <botan/filters.h>
#include <botan/def_eng.h>
#include <botan/stl_util.h>
namespace Botan {
namespace {
/*
* Perform a Known Answer Test
*/
bool test_filter_kat(Filter* filter,
const std::string& input,
const std::string& output)
{
Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
pipe.process_msg(input);
return (output == pipe.read_all_as_string());
}
}
/*
* Run a set of KATs
*/
std::map<std::string, bool>
algorithm_kat(const SCAN_Name& algo_name,
const std::map<std::string, std::string>& vars,
Algorithm_Factory& af)
{
const std::string& algo = algo_name.algo_name_and_args();
std::vector<std::string> providers = af.providers_of(algo);
std::map<std::string, bool> all_results;
if(providers.empty()) // no providers, nothing to do
return all_results;
const std::string input = search_map(vars, std::string("input"));
const std::string output = search_map(vars, std::string("output"));
const std::string key = search_map(vars, std::string("key"));
const std::string iv = search_map(vars, std::string("iv"));
for(u32bit i = 0; i != providers.size(); ++i)
{
const std::string provider = providers[i];
if(const HashFunction* proto =
af.prototype_hash_function(algo, provider))
{
Filter* filt = new Hash_Filter(proto->clone());
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const MessageAuthenticationCode* proto =
af.prototype_mac(algo, provider))
{
Keyed_Filter* filt = new MAC_Filter(proto->clone(), key);
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const StreamCipher* proto =
af.prototype_stream_cipher(algo, provider))
{
Keyed_Filter* filt = new StreamCipher_Filter(proto->clone());
filt->set_key(key);
filt->set_iv(iv);
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const BlockCipher* proto =
af.prototype_block_cipher(algo, provider))
{
Keyed_Filter* enc = get_cipher_mode(proto, ENCRYPTION,
algo_name.cipher_mode(),
algo_name.cipher_mode_pad());
Keyed_Filter* dec = get_cipher_mode(proto, DECRYPTION,
algo_name.cipher_mode(),
algo_name.cipher_mode_pad());
if(!enc || !dec)
{
delete enc;
delete dec;
continue;
}
enc->set_key(key);
enc->set_iv(iv);
dec->set_key(key);
dec->set_iv(iv);
bool enc_ok = test_filter_kat(enc, input, output);
bool dec_ok = test_filter_kat(dec, output, input);
all_results[provider] = enc_ok && dec_ok;
}
}
return all_results;
}
namespace {
void do_kat(const std::string& in, const std::string& out,
const std::string& algo_name, Filter* filter)
{
if(!test_filter_kat(filter, in, out))
throw Self_Test_Failure(algo_name + " startup test");
}
void verify_results(const std::string& algo,
const std::map<std::string, bool>& results)
{
for(std::map<std::string, bool>::const_iterator i = results.begin();
i != results.end(); ++i)
{
if(!i->second)
throw Self_Test_Failure(algo + " self-test failed, provider "+
i->first);
}
}
void hash_test(Algorithm_Factory& af,
const std::string& name,
const std::string& in,
const std::string& out)
{
std::map<std::string, std::string> vars;
vars["input"] = in;
vars["output"] = out;
verify_results(name, algorithm_kat(name, vars, af));
}
void mac_test(Algorithm_Factory& af,
const std::string& name,
const std::string& in,
const std::string& out,
const std::string& key)
{
std::map<std::string, std::string> vars;
vars["input"] = in;
vars["output"] = out;
vars["key"] = key;
verify_results(name, algorithm_kat(name, vars, af));
}
/*
* Perform a KAT for a cipher
*/
void cipher_kat(Algorithm_Factory& af,
const std::string& algo,
const std::string& key_str,
const std::string& iv_str,
const std::string& in,
const std::string& ecb_out,
const std::string& cbc_out,
const std::string& cfb_out,
const std::string& ofb_out,
const std::string& ctr_out)
{
SymmetricKey key(key_str);
InitializationVector iv(iv_str);
std::map<std::string, std::string> vars;
vars["key"] = key_str;
vars["iv"] = iv_str;
vars["input"] = in;
std::map<std::string, bool> results;
vars["output"] = ecb_out;
verify_results(algo + "/ECB", algorithm_kat(algo + "/ECB", vars, af));
vars["output"] = cbc_out;
verify_results(algo + "/CBC",
algorithm_kat(algo + "/CBC/NoPadding", vars, af));
vars["output"] = cfb_out;
verify_results(algo + "/CFB", algorithm_kat(algo + "/CFB", vars, af));
vars["output"] = ofb_out;
verify_results(algo + "/OFB", algorithm_kat(algo + "/OFB", vars, af));
vars["output"] = ctr_out;
verify_results(algo + "/CTR", algorithm_kat(algo + "/CTR-BE", vars, af));
}
}
/*
* Perform Self Tests
*/
bool passes_self_tests(Algorithm_Factory& af)
{
try
{
cipher_kat(af, "DES",
"0123456789ABCDEF", "1234567890ABCDEF",
"4E6F77206973207468652074696D6520666F7220616C6C20",
"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
"F3096249C7F46E51A69E839B1A92F78403467133898EA622",
"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");
cipher_kat(af, "TripleDES",
"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
"C141B5FCCD28DC8A",
"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");
cipher_kat(af, "AES-128",
"2B7E151628AED2A6ABF7158809CF4F3C",
"000102030405060708090A0B0C0D0E0F",
"6BC1BEE22E409F96E93D7E117393172A"
"AE2D8A571E03AC9C9EB76FAC45AF8E51",
"3AD77BB40D7A3660A89ECAF32466EF97"
"F5D3D58503B9699DE785895A96FDBAAF",
"7649ABAC8119B246CEE98E9B12E9197D"
"5086CB9B507219EE95DB113A917678B2",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"C8A64537A0B3A93FCDE3CDAD9F1CE58B",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"7789508D16918F03F53C52DAC54ED825",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"010C041999E03F36448624483E582D0E");
hash_test(af, "SHA-1",
"", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
hash_test(af, "SHA-1",
"616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
hash_test(af, "SHA-1",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
mac_test(af, "HMAC(SHA-1)",
"4869205468657265",
"B617318655057264E28BC0B6FB378C8EF146BE00",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
hash_test(af, "SHA-256",
"",
"E3B0C44298FC1C149AFBF4C8996FB924"
"27AE41E4649B934CA495991B7852B855");
hash_test(af, "SHA-256",
"616263",
"BA7816BF8F01CFEA414140DE5DAE2223"
"B00361A396177A9CB410FF61F20015AD");
hash_test(af, "SHA-256",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"248D6A61D20638B8E5C026930C3E6039"
"A33CE45964FF2167F6ECEDD419DB06C1");
mac_test(af, "HMAC(SHA-256)",
"4869205468657265",
"198A607EB44BFBC69903A0F1CF2BBDC5"
"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
}
catch(Self_Test_Failure)
{
return false;
}
return true;
}
}
Remove a dead function
/*
* Startup Self Tests
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/selftest.h>
#include <botan/filters.h>
#include <botan/def_eng.h>
#include <botan/stl_util.h>
namespace Botan {
namespace {
/*
* Perform a Known Answer Test
*/
bool test_filter_kat(Filter* filter,
const std::string& input,
const std::string& output)
{
Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
pipe.process_msg(input);
return (output == pipe.read_all_as_string());
}
}
/*
* Run a set of KATs
*/
std::map<std::string, bool>
algorithm_kat(const SCAN_Name& algo_name,
const std::map<std::string, std::string>& vars,
Algorithm_Factory& af)
{
const std::string& algo = algo_name.algo_name_and_args();
std::vector<std::string> providers = af.providers_of(algo);
std::map<std::string, bool> all_results;
if(providers.empty()) // no providers, nothing to do
return all_results;
const std::string input = search_map(vars, std::string("input"));
const std::string output = search_map(vars, std::string("output"));
const std::string key = search_map(vars, std::string("key"));
const std::string iv = search_map(vars, std::string("iv"));
for(u32bit i = 0; i != providers.size(); ++i)
{
const std::string provider = providers[i];
if(const HashFunction* proto =
af.prototype_hash_function(algo, provider))
{
Filter* filt = new Hash_Filter(proto->clone());
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const MessageAuthenticationCode* proto =
af.prototype_mac(algo, provider))
{
Keyed_Filter* filt = new MAC_Filter(proto->clone(), key);
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const StreamCipher* proto =
af.prototype_stream_cipher(algo, provider))
{
Keyed_Filter* filt = new StreamCipher_Filter(proto->clone());
filt->set_key(key);
filt->set_iv(iv);
all_results[provider] = test_filter_kat(filt, input, output);
}
else if(const BlockCipher* proto =
af.prototype_block_cipher(algo, provider))
{
Keyed_Filter* enc = get_cipher_mode(proto, ENCRYPTION,
algo_name.cipher_mode(),
algo_name.cipher_mode_pad());
Keyed_Filter* dec = get_cipher_mode(proto, DECRYPTION,
algo_name.cipher_mode(),
algo_name.cipher_mode_pad());
if(!enc || !dec)
{
delete enc;
delete dec;
continue;
}
enc->set_key(key);
enc->set_iv(iv);
dec->set_key(key);
dec->set_iv(iv);
bool enc_ok = test_filter_kat(enc, input, output);
bool dec_ok = test_filter_kat(dec, output, input);
all_results[provider] = enc_ok && dec_ok;
}
}
return all_results;
}
namespace {
void verify_results(const std::string& algo,
const std::map<std::string, bool>& results)
{
for(std::map<std::string, bool>::const_iterator i = results.begin();
i != results.end(); ++i)
{
if(!i->second)
throw Self_Test_Failure(algo + " self-test failed, provider "+
i->first);
}
}
void hash_test(Algorithm_Factory& af,
const std::string& name,
const std::string& in,
const std::string& out)
{
std::map<std::string, std::string> vars;
vars["input"] = in;
vars["output"] = out;
verify_results(name, algorithm_kat(name, vars, af));
}
void mac_test(Algorithm_Factory& af,
const std::string& name,
const std::string& in,
const std::string& out,
const std::string& key)
{
std::map<std::string, std::string> vars;
vars["input"] = in;
vars["output"] = out;
vars["key"] = key;
verify_results(name, algorithm_kat(name, vars, af));
}
/*
* Perform a KAT for a cipher
*/
void cipher_kat(Algorithm_Factory& af,
const std::string& algo,
const std::string& key_str,
const std::string& iv_str,
const std::string& in,
const std::string& ecb_out,
const std::string& cbc_out,
const std::string& cfb_out,
const std::string& ofb_out,
const std::string& ctr_out)
{
SymmetricKey key(key_str);
InitializationVector iv(iv_str);
std::map<std::string, std::string> vars;
vars["key"] = key_str;
vars["iv"] = iv_str;
vars["input"] = in;
std::map<std::string, bool> results;
vars["output"] = ecb_out;
verify_results(algo + "/ECB", algorithm_kat(algo + "/ECB", vars, af));
vars["output"] = cbc_out;
verify_results(algo + "/CBC",
algorithm_kat(algo + "/CBC/NoPadding", vars, af));
vars["output"] = cfb_out;
verify_results(algo + "/CFB", algorithm_kat(algo + "/CFB", vars, af));
vars["output"] = ofb_out;
verify_results(algo + "/OFB", algorithm_kat(algo + "/OFB", vars, af));
vars["output"] = ctr_out;
verify_results(algo + "/CTR", algorithm_kat(algo + "/CTR-BE", vars, af));
}
}
/*
* Perform Self Tests
*/
bool passes_self_tests(Algorithm_Factory& af)
{
try
{
cipher_kat(af, "DES",
"0123456789ABCDEF", "1234567890ABCDEF",
"4E6F77206973207468652074696D6520666F7220616C6C20",
"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
"F3096249C7F46E51A69E839B1A92F78403467133898EA622",
"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");
cipher_kat(af, "TripleDES",
"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
"C141B5FCCD28DC8A",
"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");
cipher_kat(af, "AES-128",
"2B7E151628AED2A6ABF7158809CF4F3C",
"000102030405060708090A0B0C0D0E0F",
"6BC1BEE22E409F96E93D7E117393172A"
"AE2D8A571E03AC9C9EB76FAC45AF8E51",
"3AD77BB40D7A3660A89ECAF32466EF97"
"F5D3D58503B9699DE785895A96FDBAAF",
"7649ABAC8119B246CEE98E9B12E9197D"
"5086CB9B507219EE95DB113A917678B2",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"C8A64537A0B3A93FCDE3CDAD9F1CE58B",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"7789508D16918F03F53C52DAC54ED825",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"010C041999E03F36448624483E582D0E");
hash_test(af, "SHA-1",
"", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
hash_test(af, "SHA-1",
"616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
hash_test(af, "SHA-1",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
mac_test(af, "HMAC(SHA-1)",
"4869205468657265",
"B617318655057264E28BC0B6FB378C8EF146BE00",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
hash_test(af, "SHA-256",
"",
"E3B0C44298FC1C149AFBF4C8996FB924"
"27AE41E4649B934CA495991B7852B855");
hash_test(af, "SHA-256",
"616263",
"BA7816BF8F01CFEA414140DE5DAE2223"
"B00361A396177A9CB410FF61F20015AD");
hash_test(af, "SHA-256",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"248D6A61D20638B8E5C026930C3E6039"
"A33CE45964FF2167F6ECEDD419DB06C1");
mac_test(af, "HMAC(SHA-256)",
"4869205468657265",
"198A607EB44BFBC69903A0F1CF2BBDC5"
"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
}
catch(Self_Test_Failure)
{
return false;
}
return true;
}
}
|
// 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/macros.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
namespace extensions {
// An InProcessBrowserTest for testing the ExtensionToolbarModel.
// TODO(erikkay) It's unfortunate that this needs to be an in-proc browser test.
// It would be nice to refactor things so that ExtensionService could run
// without so much of the browser in place.
class ExtensionToolbarModelTest : public ExtensionBrowserTest,
public ExtensionToolbarModel::Observer {
public:
virtual void SetUp() {
inserted_count_ = 0;
removed_count_ = 0;
moved_count_ = 0;
highlight_mode_count_ = 0;
ExtensionBrowserTest::SetUp();
}
virtual void SetUpOnMainThread() OVERRIDE {
model_ = ExtensionToolbarModel::Get(browser()->profile());
model_->AddObserver(this);
}
virtual void CleanUpOnMainThread() OVERRIDE {
model_->RemoveObserver(this);
}
virtual void BrowserActionAdded(const Extension* extension,
int index) OVERRIDE {
inserted_count_++;
}
virtual void BrowserActionRemoved(const Extension* extension) OVERRIDE {
removed_count_++;
}
virtual void BrowserActionMoved(const Extension* extension,
int index) OVERRIDE {
moved_count_++;
}
virtual void HighlightModeChanged(bool is_highlighting) OVERRIDE {
// Add one if highlighting, subtract one if not.
highlight_mode_count_ += is_highlighting ? 1 : -1;
}
const Extension* ExtensionAt(int index) {
const ExtensionList& toolbar_items = model_->toolbar_items();
for (ExtensionList::const_iterator i = toolbar_items.begin();
i < toolbar_items.end(); ++i) {
if (index-- == 0)
return i->get();
}
return NULL;
}
protected:
ExtensionToolbarModel* model_;
int inserted_count_;
int removed_count_;
int moved_count_;
int highlight_mode_count_;
};
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, Basic) {
// Load an extension with no browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none")));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, inserted_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
ASSERT_EQ(NULL, ExtensionAt(0));
// Load an extension with a browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
// We should now find our extension in the model.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension = ExtensionAt(0);
ASSERT_TRUE(NULL != extension);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extension->name().c_str());
// Should be a no-op, but still fires the events.
model_->MoveBrowserAction(extension, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension2 = ExtensionAt(0);
EXPECT_EQ(extension, extension2);
UnloadExtension(extension->id());
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
EXPECT_EQ(NULL, ExtensionAt(0));
}
#if defined(OS_MACOSX)
// Flaky on Mac 10.8 Blink canary bots: http://crbug.com/166580
#define MAYBE_ReorderAndReinsert DISABLED_ReorderAndReinsert
#else
#define MAYBE_ReorderAndReinsert ReorderAndReinsert
#endif
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, MAYBE_ReorderAndReinsert) {
// Load an extension with a browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
// First extension loaded.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extensionA = ExtensionAt(0);
ASSERT_TRUE(NULL != extensionA);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
// Load another extension with a browser action.
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
// Second extension loaded.
EXPECT_EQ(2, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
const Extension* extensionB = ExtensionAt(1);
ASSERT_TRUE(NULL != extensionB);
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
// Load yet another extension with a browser action.
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
// Third extension loaded.
EXPECT_EQ(3, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
const Extension* extensionC = ExtensionAt(2);
ASSERT_TRUE(NULL != extensionC);
EXPECT_STREQ("A page action which removes a popup.",
extensionC->name().c_str());
// Order is now A, B, C. Let's put C first.
model_->MoveBrowserAction(extensionC, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(extensionB, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, A, B. Let's put A last.
model_->MoveBrowserAction(extensionA, 2);
EXPECT_EQ(2, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionB, ExtensionAt(1));
EXPECT_EQ(extensionA, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, B, A. Let's remove B.
std::string idB = extensionB->id();
UnloadExtension(idB);
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Load extension B again.
ASSERT_TRUE(LoadExtension(extension_b_path));
// Extension B loaded again.
EXPECT_EQ(4, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list. We should get the same
// extension again, otherwise the order has changed.
ASSERT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
// Unload B again.
UnloadExtension(idB);
EXPECT_EQ(2, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now C, A. Flip it.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(3, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Move A to the location it already occupies.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(4, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now A, C. Remove C.
std::string idC = extensionC->id();
UnloadExtension(idC);
EXPECT_EQ(3, removed_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(NULL, ExtensionAt(1));
// Load extension C again.
ASSERT_TRUE(LoadExtension(extension_c_path));
// Extension C loaded again.
EXPECT_EQ(5, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list (at the very end).
ASSERT_STREQ(idC.c_str(), ExtensionAt(1)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, UnloadAndDisableMultiple) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
// Verify we got the three we asked for and that they are ordered as: A, B, C.
const Extension* extensionA = ExtensionAt(0);
const Extension* extensionB = ExtensionAt(1);
const Extension* extensionC = ExtensionAt(2);
std::string idA = extensionA->id();
std::string idB = extensionB->id();
std::string idC = extensionC->id();
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
EXPECT_STREQ("A page action which removes a popup.",
extensionC->name().c_str());
// Unload B, then C, then A.
UnloadExtension(idB);
UnloadExtension(idC);
UnloadExtension(idA);
// Load C, then A, then B.
ASSERT_TRUE(LoadExtension(extension_c_path));
ASSERT_TRUE(LoadExtension(extension_a_path));
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(0, moved_count_);
extensionA = ExtensionAt(0);
extensionB = ExtensionAt(1);
extensionC = ExtensionAt(2);
// Make sure we get the order we started with (A, B, C).
EXPECT_STREQ(idA.c_str(), extensionA->id().c_str());
EXPECT_STREQ(idB.c_str(), extensionB->id().c_str());
EXPECT_STREQ(idC.c_str(), extensionC->id().c_str());
// Put C in the middle and A to the end.
model_->MoveBrowserAction(extensionC, 1);
model_->MoveBrowserAction(extensionA, 2);
// Make sure we get this order (C, B, A).
EXPECT_STREQ(idC.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
EXPECT_STREQ(idA.c_str(), ExtensionAt(2)->id().c_str());
// Disable B, then C, then A.
DisableExtension(idB);
DisableExtension(idC);
DisableExtension(idA);
// Enable C, then A, then B.
EnableExtension(idA);
EnableExtension(idB);
EnableExtension(idC);
// Make sure we get the order we started with.
EXPECT_STREQ(idC.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
EXPECT_STREQ(idA.c_str(), ExtensionAt(2)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, Uninstall) {
// Load two extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
// Verify we got what we came for.
const Extension* extensionA = ExtensionAt(0);
const Extension* extensionB = ExtensionAt(1);
std::string idA = extensionA->id();
std::string idB = extensionB->id();
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
// Order is now A, B. Make B first.
model_->MoveBrowserAction(extensionB, 0);
// Order is now B, A. Uninstall Extension B.
UninstallExtension(idB);
// List contains only A now. Validate that.
EXPECT_STREQ(idA.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_EQ(1u, model_->toolbar_items().size());
// Load Extension B again.
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(2u, model_->toolbar_items().size());
// Make sure Extension B is _not_ first (should have been forgotten at
// uninstall time).
EXPECT_STREQ(idA.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, ReorderOnPrefChange) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Change value of toolbar preference.
ExtensionIdList new_order;
new_order.push_back(id_c);
new_order.push_back(id_b);
ExtensionPrefs::Get(browser()->profile())->SetToolbarOrder(new_order);
// Verify order is changed.
EXPECT_EQ(id_c, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_a, ExtensionAt(2)->id());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, HighlightMode) {
EXPECT_FALSE(model_->HighlightExtensions(ExtensionIdList()));
EXPECT_EQ(0, highlight_mode_count_);
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Highlight one extension.
ExtensionIdList extension_ids;
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Stop highlighting.
model_->StopHighlighting();
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
// Verify that the extensions are back to normal.
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
// Call stop highlighting a second time (shouldn't be notified).
model_->StopHighlighting();
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
// Highlight all extensions.
extension_ids.clear();
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
extension_ids.push_back(id_c);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
// Highlight only extension b (shrink the highlight list).
extension_ids.clear();
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(2, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Highlight extensions a and b (grow the highlight list).
extension_ids.clear();
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(3, highlight_mode_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
// Highlight no extensions (empty the highlight list).
extension_ids.clear();
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(2, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, HighlightModeRemove) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Highlight two of the extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
// Disable one of them - only one should remain highlighted.
DisableExtension(id_a);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Uninstall the remaining highlighted extension. This should result in
// highlight mode exiting.
UninstallExtension(id_b);
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// Test that removing an unhighlighted extension still works.
// Reinstall extension b, and then highlight extension c.
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(id_b, ExtensionAt(1)->id());
extension_ids.clear();
extension_ids.push_back(id_c);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// Uninstalling b should not have visible impact.
UninstallExtension(id_b);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// When we stop, only extension c should remain.
model_->StopHighlighting();
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, HighlightModeAdd) {
// Load two extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
// Highlight one of the extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(id_a);
model_->HighlightExtensions(extension_ids);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
// Adding the new extension should have no visible effect.
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
const Extension* extension_c = LoadExtension(extension_c_path);
ASSERT_TRUE(extension_c);
std::string id_c = extension_c->id();
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
// When we stop highlighting, we should see the new extension show up.
model_->StopHighlighting();
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
}
} // namespace extensions
Disable the ExtensionToolbarModelTest.HighlightModeRemove test on mac.
From the logs:
Retrying 1 test (retry #1)
[0401/112720:ERROR:kill_posix.cc(191)] Unable to terminate process group 7136: No such process
[ RUN ] ExtensionToolbarModelTest.HighlightModeRemove
[852/852] ExtensionToolbarModelTest.HighlightModeRemove (2093 ms)
Retrying 1 test (retry #2)
[0401/112723:ERROR:kill_posix.cc(191)] Unable to terminate process group 7140: No such process
[ RUN ] ExtensionToolbarModelTest.HighlightModeRemove
[853/853] ExtensionToolbarModelTest.HighlightModeRemove (2356 ms)
Retrying 1 test (retry #3)
[0401/112725:ERROR:kill_posix.cc(191)] Unable to terminate process group 7146: No such process
[ RUN ] ExtensionToolbarModelTest.HighlightModeRemove
[854/854] ExtensionToolbarModelTest.HighlightModeRemove (2094 ms)
1 test failed:
ExtensionToolbarModelTest.HighlightModeRemove
NOTRY=true
R=rlarocque@chromium.org
TBR=kalman@chromium.org
BUG=358752
Review URL: https://codereview.chromium.org/221193003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@260930 0039d316-1c4b-4281-b951-d872f2087c98
// 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/macros.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
namespace extensions {
// An InProcessBrowserTest for testing the ExtensionToolbarModel.
// TODO(erikkay) It's unfortunate that this needs to be an in-proc browser test.
// It would be nice to refactor things so that ExtensionService could run
// without so much of the browser in place.
class ExtensionToolbarModelTest : public ExtensionBrowserTest,
public ExtensionToolbarModel::Observer {
public:
virtual void SetUp() {
inserted_count_ = 0;
removed_count_ = 0;
moved_count_ = 0;
highlight_mode_count_ = 0;
ExtensionBrowserTest::SetUp();
}
virtual void SetUpOnMainThread() OVERRIDE {
model_ = ExtensionToolbarModel::Get(browser()->profile());
model_->AddObserver(this);
}
virtual void CleanUpOnMainThread() OVERRIDE {
model_->RemoveObserver(this);
}
virtual void BrowserActionAdded(const Extension* extension,
int index) OVERRIDE {
inserted_count_++;
}
virtual void BrowserActionRemoved(const Extension* extension) OVERRIDE {
removed_count_++;
}
virtual void BrowserActionMoved(const Extension* extension,
int index) OVERRIDE {
moved_count_++;
}
virtual void HighlightModeChanged(bool is_highlighting) OVERRIDE {
// Add one if highlighting, subtract one if not.
highlight_mode_count_ += is_highlighting ? 1 : -1;
}
const Extension* ExtensionAt(int index) {
const ExtensionList& toolbar_items = model_->toolbar_items();
for (ExtensionList::const_iterator i = toolbar_items.begin();
i < toolbar_items.end(); ++i) {
if (index-- == 0)
return i->get();
}
return NULL;
}
protected:
ExtensionToolbarModel* model_;
int inserted_count_;
int removed_count_;
int moved_count_;
int highlight_mode_count_;
};
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, Basic) {
// Load an extension with no browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none")));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, inserted_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
ASSERT_EQ(NULL, ExtensionAt(0));
// Load an extension with a browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
// We should now find our extension in the model.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension = ExtensionAt(0);
ASSERT_TRUE(NULL != extension);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extension->name().c_str());
// Should be a no-op, but still fires the events.
model_->MoveBrowserAction(extension, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension2 = ExtensionAt(0);
EXPECT_EQ(extension, extension2);
UnloadExtension(extension->id());
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
EXPECT_EQ(NULL, ExtensionAt(0));
}
#if defined(OS_MACOSX)
// Flaky on Mac 10.8 Blink canary bots: http://crbug.com/166580
#define MAYBE_ReorderAndReinsert DISABLED_ReorderAndReinsert
#else
#define MAYBE_ReorderAndReinsert ReorderAndReinsert
#endif
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, MAYBE_ReorderAndReinsert) {
// Load an extension with a browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
// First extension loaded.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extensionA = ExtensionAt(0);
ASSERT_TRUE(NULL != extensionA);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
// Load another extension with a browser action.
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
// Second extension loaded.
EXPECT_EQ(2, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
const Extension* extensionB = ExtensionAt(1);
ASSERT_TRUE(NULL != extensionB);
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
// Load yet another extension with a browser action.
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
// Third extension loaded.
EXPECT_EQ(3, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
const Extension* extensionC = ExtensionAt(2);
ASSERT_TRUE(NULL != extensionC);
EXPECT_STREQ("A page action which removes a popup.",
extensionC->name().c_str());
// Order is now A, B, C. Let's put C first.
model_->MoveBrowserAction(extensionC, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(extensionB, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, A, B. Let's put A last.
model_->MoveBrowserAction(extensionA, 2);
EXPECT_EQ(2, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionB, ExtensionAt(1));
EXPECT_EQ(extensionA, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, B, A. Let's remove B.
std::string idB = extensionB->id();
UnloadExtension(idB);
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Load extension B again.
ASSERT_TRUE(LoadExtension(extension_b_path));
// Extension B loaded again.
EXPECT_EQ(4, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list. We should get the same
// extension again, otherwise the order has changed.
ASSERT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
// Unload B again.
UnloadExtension(idB);
EXPECT_EQ(2, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now C, A. Flip it.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(3, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Move A to the location it already occupies.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(4, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now A, C. Remove C.
std::string idC = extensionC->id();
UnloadExtension(idC);
EXPECT_EQ(3, removed_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(NULL, ExtensionAt(1));
// Load extension C again.
ASSERT_TRUE(LoadExtension(extension_c_path));
// Extension C loaded again.
EXPECT_EQ(5, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list (at the very end).
ASSERT_STREQ(idC.c_str(), ExtensionAt(1)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, UnloadAndDisableMultiple) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
// Verify we got the three we asked for and that they are ordered as: A, B, C.
const Extension* extensionA = ExtensionAt(0);
const Extension* extensionB = ExtensionAt(1);
const Extension* extensionC = ExtensionAt(2);
std::string idA = extensionA->id();
std::string idB = extensionB->id();
std::string idC = extensionC->id();
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
EXPECT_STREQ("A page action which removes a popup.",
extensionC->name().c_str());
// Unload B, then C, then A.
UnloadExtension(idB);
UnloadExtension(idC);
UnloadExtension(idA);
// Load C, then A, then B.
ASSERT_TRUE(LoadExtension(extension_c_path));
ASSERT_TRUE(LoadExtension(extension_a_path));
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(0, moved_count_);
extensionA = ExtensionAt(0);
extensionB = ExtensionAt(1);
extensionC = ExtensionAt(2);
// Make sure we get the order we started with (A, B, C).
EXPECT_STREQ(idA.c_str(), extensionA->id().c_str());
EXPECT_STREQ(idB.c_str(), extensionB->id().c_str());
EXPECT_STREQ(idC.c_str(), extensionC->id().c_str());
// Put C in the middle and A to the end.
model_->MoveBrowserAction(extensionC, 1);
model_->MoveBrowserAction(extensionA, 2);
// Make sure we get this order (C, B, A).
EXPECT_STREQ(idC.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
EXPECT_STREQ(idA.c_str(), ExtensionAt(2)->id().c_str());
// Disable B, then C, then A.
DisableExtension(idB);
DisableExtension(idC);
DisableExtension(idA);
// Enable C, then A, then B.
EnableExtension(idA);
EnableExtension(idB);
EnableExtension(idC);
// Make sure we get the order we started with.
EXPECT_STREQ(idC.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
EXPECT_STREQ(idA.c_str(), ExtensionAt(2)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, Uninstall) {
// Load two extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
// Verify we got what we came for.
const Extension* extensionA = ExtensionAt(0);
const Extension* extensionB = ExtensionAt(1);
std::string idA = extensionA->id();
std::string idB = extensionB->id();
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
// Order is now A, B. Make B first.
model_->MoveBrowserAction(extensionB, 0);
// Order is now B, A. Uninstall Extension B.
UninstallExtension(idB);
// List contains only A now. Validate that.
EXPECT_STREQ(idA.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_EQ(1u, model_->toolbar_items().size());
// Load Extension B again.
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(2u, model_->toolbar_items().size());
// Make sure Extension B is _not_ first (should have been forgotten at
// uninstall time).
EXPECT_STREQ(idA.c_str(), ExtensionAt(0)->id().c_str());
EXPECT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, ReorderOnPrefChange) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Change value of toolbar preference.
ExtensionIdList new_order;
new_order.push_back(id_c);
new_order.push_back(id_b);
ExtensionPrefs::Get(browser()->profile())->SetToolbarOrder(new_order);
// Verify order is changed.
EXPECT_EQ(id_c, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_a, ExtensionAt(2)->id());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, HighlightMode) {
EXPECT_FALSE(model_->HighlightExtensions(ExtensionIdList()));
EXPECT_EQ(0, highlight_mode_count_);
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Highlight one extension.
ExtensionIdList extension_ids;
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Stop highlighting.
model_->StopHighlighting();
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
// Verify that the extensions are back to normal.
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
// Call stop highlighting a second time (shouldn't be notified).
model_->StopHighlighting();
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
// Highlight all extensions.
extension_ids.clear();
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
extension_ids.push_back(id_c);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
// Highlight only extension b (shrink the highlight list).
extension_ids.clear();
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(2, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Highlight extensions a and b (grow the highlight list).
extension_ids.clear();
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(3, highlight_mode_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
// Highlight no extensions (empty the highlight list).
extension_ids.clear();
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(2, highlight_mode_count_);
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
}
#if defined(OS_MACOSX)
// Flaky on Mac bots: http://crbug.com/358752
#define MAYBE_HighlightModeRemove DISABLED_HighlightModeRemove
#else
#define MAYBE_HighlightModeRemove HighlightModeRemove
#endif
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, MAYBE_HighlightModeRemove) {
// Load three extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
std::string id_c = ExtensionAt(2)->id();
// Highlight two of the extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(id_a);
extension_ids.push_back(id_b);
model_->HighlightExtensions(extension_ids);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
// Disable one of them - only one should remain highlighted.
DisableExtension(id_a);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_b, ExtensionAt(0)->id());
// Uninstall the remaining highlighted extension. This should result in
// highlight mode exiting.
UninstallExtension(id_b);
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// Test that removing an unhighlighted extension still works.
// Reinstall extension b, and then highlight extension c.
ASSERT_TRUE(LoadExtension(extension_b_path));
EXPECT_EQ(id_b, ExtensionAt(1)->id());
extension_ids.clear();
extension_ids.push_back(id_c);
model_->HighlightExtensions(extension_ids);
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// Uninstalling b should not have visible impact.
UninstallExtension(id_b);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
// When we stop, only extension c should remain.
model_->StopHighlighting();
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(0, highlight_mode_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_c, ExtensionAt(0)->id());
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, HighlightModeAdd) {
// Load two extensions with browser action.
base::FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
base::FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
std::string id_a = ExtensionAt(0)->id();
std::string id_b = ExtensionAt(1)->id();
// Highlight one of the extensions.
ExtensionIdList extension_ids;
extension_ids.push_back(id_a);
model_->HighlightExtensions(extension_ids);
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
// Adding the new extension should have no visible effect.
base::FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
const Extension* extension_c = LoadExtension(extension_c_path);
ASSERT_TRUE(extension_c);
std::string id_c = extension_c->id();
EXPECT_TRUE(model_->is_highlighting());
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
// When we stop highlighting, we should see the new extension show up.
model_->StopHighlighting();
EXPECT_FALSE(model_->is_highlighting());
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(id_a, ExtensionAt(0)->id());
EXPECT_EQ(id_b, ExtensionAt(1)->id());
EXPECT_EQ(id_c, ExtensionAt(2)->id());
}
} // namespace extensions
|
#include "Halide.h"
#include <stdio.h>
#include "test/common/gpu_object_lifetime_tracker.h"
using namespace Halide;
Internal::GpuObjectLifetimeTracker tracker;
void halide_print(void *user_context, const char *str) {
printf("%s", str);
tracker.record_gpu_debug(str);
}
int main(int argc, char **argv) {
Internal::JITHandlers handlers;
handlers.custom_print = halide_print;
Internal::JITSharedRuntime::set_default_handlers(handlers);
Target target = get_jit_target_from_environment();
// We need debug output to record object creation.
target.set_feature(Target::Debug);
{
Halide::Buffer<float> buf(100, 100);
{
// Make a shallow copy of the original buf, and trigger a gpu copy of it.
Halide::Buffer<float> copy = buf;
Func f;
Var x, y;
f(x, y) = copy(x, y);
if (target.has_gpu_feature()) {
f.gpu_tile(x, y, 8, 8);
} else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
f.hexagon();
}
f.set_custom_print(halide_print);
f.realize(50, 50, target);
// The copy now has a non-zero dev field, but the original
// buf is unaware of that fact. It should get cleaned up
// here.
assert(copy.has_device_allocation());
}
Halide::Internal::JITSharedRuntime::release_all();
assert(!buf.has_device_allocation());
// At this point, the device allocation should have been cleaned up, even though the original buffer still lives.
if (tracker.validate_gpu_object_lifetime(true /* allow_globals */,
true /* allow_none */,
1 /* max_globals */)) {
return -1;
}
}
printf("Success!\n");
return 0;
}
Fix faulty assert
Former-commit-id: 4848b91ff8779284ea9c1ffcdffcfc5b4438919e
#include "Halide.h"
#include <stdio.h>
#include "test/common/gpu_object_lifetime_tracker.h"
using namespace Halide;
Internal::GpuObjectLifetimeTracker tracker;
void halide_print(void *user_context, const char *str) {
printf("%s", str);
tracker.record_gpu_debug(str);
}
int main(int argc, char **argv) {
Internal::JITHandlers handlers;
handlers.custom_print = halide_print;
Internal::JITSharedRuntime::set_default_handlers(handlers);
Target target = get_jit_target_from_environment();
// We need debug output to record object creation.
target.set_feature(Target::Debug);
{
Halide::Buffer<float> buf(100, 100);
{
// Make a shallow copy of the original buf, and trigger a gpu copy of it.
Halide::Buffer<float> copy = buf;
Func f;
Var x, y;
f(x, y) = copy(x, y);
if (target.has_gpu_feature()) {
f.gpu_tile(x, y, 8, 8);
} else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
f.hexagon();
}
f.set_custom_print(halide_print);
f.realize(50, 50, target);
// The copy now has a non-zero dev field, but the original
// buf is unaware of that fact. It should get cleaned up
// here.
if (target.has_gpu_feature()) {
assert(copy.has_device_allocation());
}
}
Halide::Internal::JITSharedRuntime::release_all();
assert(!buf.has_device_allocation());
// At this point, the device allocation should have been cleaned up, even though the original buffer still lives.
if (tracker.validate_gpu_object_lifetime(true /* allow_globals */,
true /* allow_none */,
1 /* max_globals */)) {
return -1;
}
}
printf("Success!\n");
return 0;
}
|
#include <Halide.h>
#include <stdio.h>
#include <math.h>
using namespace Halide;
// A version of pow that tracks usage so we can check how many times it was called.
#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
int call_count;
extern "C" DLLEXPORT float my_powf(float x, float y) {
call_count++;
return powf(x, y);
}
HalideExtern_2(float, my_powf, float, float);
int main(int argc, char **argv) {
// Brighten some tiles of an image, where that region is given by
// a lower-res bitmap.
ImageParam bitmap(Bool(), 2);
ImageParam image(Float(32), 2);
const int tile_size = 16;
Var x("x"), y("y"), xi("xi"), yi("yi"), t("t");
// Brighten the image
Func brighter("brighter");
brighter(x, y) = my_powf(image(x, y), 0.8f);
// Select either the brighter or the input depending on the bitmap
Func output("output");
output(x, y) = select(bitmap(x/tile_size, y/tile_size), brighter(x, y), image(x, y));
// Compute the output in tiles of the appropriate size
output.tile(x, y, xi, yi, tile_size, tile_size);
// Vectorize within tiles, parallelize across tiles.
output.vectorize(xi, 4).fuse(x, y, t).parallel(t);
// Compute brighter per output tile
brighter.compute_at(output, t);
// Assert that the output is a whole number of tiles. Otherwise
// the tiles in the schedule don't match up to the tiles in the
// algorithm, and you can't safely skip any work.
output.bound(x, 0, (image.extent(0)/tile_size)*tile_size);
output.bound(y, 0, (image.extent(1)/tile_size)*tile_size);
output.compile_jit();
Image<bool> bitmap_buf(10, 10);
bitmap_buf(5, 5) = 1;
bitmap.set(bitmap_buf);
Image<float> image_buf = lambda(x, y, (sin(x+y)+1)/2).realize(10 * tile_size, 10 * tile_size);
image.set(image_buf);
call_count = 0;
Image<float> result = output.realize(10 * tile_size, 10 * tile_size);
// Check the right number of calls to powf occurred
if (call_count != tile_size*tile_size) {
printf("call_count = %d instead of %d\n", call_count, tile_size * tile_size);
return -1;
}
// Check the output is correct
for (int y = 0; y < result.height(); y++) {
for (int x = 0; x < result.width(); x++) {
bool active = bitmap_buf(x/tile_size, y/tile_size);
float correct = active ? my_powf(image_buf(x, y), 0.8f) : image_buf(x, y);
if (fabs(correct - result(x, y)) > 0.001f) {
printf("result(%d, %d) = %f instead of %f\n",
x, y, result(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
Fix race condition in process_some_tiles
#include <Halide.h>
#include <stdio.h>
#include <math.h>
using namespace Halide;
// A version of pow that tracks usage so we can check how many times it was called.
#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
int call_count;
extern "C" DLLEXPORT float my_powf(float x, float y) {
call_count++;
return powf(x, y);
}
HalideExtern_2(float, my_powf, float, float);
int main(int argc, char **argv) {
// Brighten some tiles of an image, where that region is given by
// a lower-res bitmap.
ImageParam bitmap(Bool(), 2);
ImageParam image(Float(32), 2);
const int tile_size = 16;
Var x("x"), y("y"), xi("xi"), yi("yi"), t("t");
// Brighten the image
Func brighter("brighter");
brighter(x, y) = my_powf(image(x, y), 0.8f);
// Select either the brighter or the input depending on the bitmap
Func output("output");
output(x, y) = select(bitmap(x/tile_size, y/tile_size), brighter(x, y), image(x, y));
// Compute the output in tiles of the appropriate size
output.tile(x, y, xi, yi, tile_size, tile_size);
// Vectorize within tiles. We would also parallelize across tiles,
// but that introduces a race condition in the call_count.
output.vectorize(xi, 4).fuse(x, y, t);
// Compute brighter per output tile
brighter.compute_at(output, t);
// Assert that the output is a whole number of tiles. Otherwise
// the tiles in the schedule don't match up to the tiles in the
// algorithm, and you can't safely skip any work.
output.bound(x, 0, (image.extent(0)/tile_size)*tile_size);
output.bound(y, 0, (image.extent(1)/tile_size)*tile_size);
output.compile_jit();
Image<bool> bitmap_buf(10, 10);
bitmap_buf(5, 5) = 1;
bitmap.set(bitmap_buf);
Image<float> image_buf = lambda(x, y, (sin(x+y)+1)/2).realize(10 * tile_size, 10 * tile_size);
image.set(image_buf);
call_count = 0;
Image<float> result = output.realize(10 * tile_size, 10 * tile_size);
// Check the right number of calls to powf occurred
if (call_count != tile_size*tile_size) {
printf("call_count = %d instead of %d\n", call_count, tile_size * tile_size);
return -1;
}
// Check the output is correct
for (int y = 0; y < result.height(); y++) {
for (int x = 0; x < result.width(); x++) {
bool active = bitmap_buf(x/tile_size, y/tile_size);
float correct = active ? my_powf(image_buf(x, y), 0.8f) : image_buf(x, y);
if (fabs(correct - result(x, y)) > 0.001f) {
printf("result(%d, %d) = %f instead of %f\n",
x, y, result(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
|
#include "stdafx.h"
#include "ThreadManager.h"
#include "Ini.h"
#include "SceneThread.h"
#include "SceneManager.h"
#include "Config.h"
ThreadManager* g_pThreadManager = NULL ;
ThreadManager::ThreadManager()
{
__ENTER_FUNCTION
m_pThreadPool = new ThreadPool ;
Assert( m_pThreadPool ) ;
m_pServerThread = new ServerThread ;
Assert( m_pServerThread ) ;
m_nThreads = 0 ;
__LEAVE_FUNCTION
}
ThreadManager::~ThreadManager()
{
__ENTER_FUNCTION
SAFE_DELETE( m_pThreadPool) ;
SAFE_DELETE( m_pServerThread ) ;
__LEAVE_FUNCTION
}
BOOL ThreadManager::Init( UINT MaxSceneCount )
{
__ENTER_FUNCTION
BOOL ret = FALSE ;
//根据配置文件读取需要使用的场景,为每个场景分配一个线程;
//读取场景数量
UINT count = MaxSceneCount ;
Assert( MAX_SCENE >= count ) ;
UINT uMaxThreadCount = 0 ;
UINT i ;
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
if ( ( ID_t )uMaxThreadCount < g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex )
{
uMaxThreadCount = g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ;
}
}
SceneThread* pSceneThread = NULL ;
for ( i = 0; i <= uMaxThreadCount; i++ )
{
pSceneThread = new SceneThread ;
Assert( pSceneThread ) ;
ret = m_pThreadPool->AddThread( i, pSceneThread ) ;
Assert( ret ) ;
m_nThreads ++ ;
}
/** //my debug output
for ( i = 0; i <= uMaxThreadCount; i++ )
{
Thread** m_pThread = m_pThreadPool->GetThread();
SceneThread* pSceneThread1 = (SceneThread*)( m_pThread[ i ] );
LERR( "FILE: %s, LINE: %d, pSceneThread1: %d, index: %d", __FILE__, __LINE__, pSceneThread1, i );
}
**/
MySleep( 3600 );
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
SceneThread* pSceneThread = ( SceneThread* )( m_pThreadPool->GetThreadByIndex( g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ) ) ;
if ( NULL == pSceneThread )
{
AssertEx( FALSE, "没有创建所需的线程" ) ;
}
else
{
Scene* pScene = g_pSceneManager->GetScene( SceneID ) ;
pSceneThread->AddScene( pScene );
}
}
if ( m_pServerThread->IsActive() )
{
m_nThreads ++ ;
}
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Start()
{
__ENTER_FUNCTION
BOOL ret ;
m_pServerThread->start() ;
MySleep( 500 ) ;
ret = m_pThreadPool->Start( ) ;
return ret ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Stop()
{
__ENTER_FUNCTION
if ( m_pServerThread )
{
m_pServerThread->stop() ;
}
return m_pThreadPool->Stop() ;
__LEAVE_FUNCTION
return FALSE ;
}
fix bug
#include "stdafx.h"
#include "ThreadManager.h"
#include "Ini.h"
#include "SceneThread.h"
#include "SceneManager.h"
#include "Config.h"
ThreadManager* g_pThreadManager = NULL ;
ThreadManager::ThreadManager()
{
__ENTER_FUNCTION
m_pThreadPool = new ThreadPool ;
Assert( m_pThreadPool ) ;
m_pServerThread = new ServerThread ;
Assert( m_pServerThread ) ;
m_nThreads = 0 ;
__LEAVE_FUNCTION
}
ThreadManager::~ThreadManager()
{
__ENTER_FUNCTION
SAFE_DELETE( m_pThreadPool) ;
SAFE_DELETE( m_pServerThread ) ;
__LEAVE_FUNCTION
}
BOOL ThreadManager::Init( UINT MaxSceneCount )
{
__ENTER_FUNCTION
BOOL ret = FALSE ;
//根据配置文件读取需要使用的场景,为每个场景分配一个线程;
//读取场景数量
UINT count = MaxSceneCount ;
Assert( MAX_SCENE >= count ) ;
UINT uMaxThreadCount = 0 ;
UINT i ;
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
if ( ( ID_t )uMaxThreadCount < g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex )
{
uMaxThreadCount = g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ;
}
}
SceneThread* pSceneThread = NULL ;
for ( i = 0; i <= uMaxThreadCount; i++ )
{
pSceneThread = new SceneThread ;
Assert( pSceneThread ) ;
ret = m_pThreadPool->AddThread( i, pSceneThread ) ;
Assert( ret ) ;
m_nThreads ++ ;
}
/** //my debug output
for ( i = 0 ; i <= uMaxThreadCount ; i++ )
{
Thread** m_pThread = m_pThreadPool->GetThread() ;
SceneThread* pSceneThread1 = (SceneThread*)( m_pThread[ i ] ) ;
LERR( "FILE: %s, LINE: %d, pSceneThread1: %d, index: %d", __FILE__, __LINE__, pSceneThread1, i ) ;
}
**/
MySleep( 3600 ) ;
for ( i = 0; i < count; i++ )
{
//读取场景
SceneID_t SceneID = ( SceneID_t )( g_Config.m_SceneInfo.m_pScene[i].m_SceneID ) ;
Assert( MAX_SCENE > SceneID ) ;
UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
if ( ServerID != g_Config.m_ConfigInfo.m_ServerID )
{//不是当前服务器的程序运行的场景
continue ;
}
if ( 0 == g_Config.m_SceneInfo.m_pScene[i].m_IsActive )
{//不是激活的场景
continue ;
}
SceneThread* pSceneThread = ( SceneThread* )( m_pThreadPool->GetThreadByIndex( g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ) ) ;
if ( NULL == pSceneThread )
{
AssertEx( FALSE, "没有创建所需的线程" ) ;
}
else
{
Scene* pScene = g_pSceneManager->GetScene( SceneID ) ;
pSceneThread->AddScene( pScene ) ;
}
}
if ( m_pServerThread->IsActive() )
{
m_nThreads ++ ;
}
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Start()
{
__ENTER_FUNCTION
BOOL ret ;
m_pServerThread->start() ;
MySleep( 500 ) ;
ret = m_pThreadPool->Start() ;
return ret ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL ThreadManager::Stop()
{
__ENTER_FUNCTION
if ( m_pServerThread )
{
m_pServerThread->stop() ;
}
return m_pThreadPool->Stop() ;
__LEAVE_FUNCTION
return FALSE ;
}
|
#ifndef COFFEE_MILL_REWEIGHT_WHAM_HPP
#define COFFEE_MILL_REWEIGHT_WHAM_HPP
#include "Histogram.hpp"
#include "ProbabilityDensity.hpp"
#include "PotentialFunction.hpp"
#include "ReactionCoordinate.hpp"
#include <mill/util/logger.hpp>
#include <vector>
#include <cmath>
namespace mill
{
class WHAMSolver
{
public:
WHAMSolver(const double kBT, const double tolerance,
const std::size_t max_iteration)
: kBT_(kBT), beta_(1.0 / kBT), tolerance_(tolerance), max_iteration_(max_iteration)
{}
ProbabilityDensity operator()(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins = 100)
{
return this->reconstruct(this->solve_f(trajs), trajs, bins);
}
private:
double relative_diff(const double lhs, const double rhs) const noexcept
{
return (lhs - rhs) / ((lhs + rhs) * 0.5);
}
std::vector<double> solve_f(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs);
ProbabilityDensity reconstruct(const std::vector<double>& fs,
const std::vector<std::pair<std::vector<double>,
std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins);
private:
double kBT_, beta_, tolerance_;
std::size_t max_iteration_;
};
inline std::vector<double> WHAMSolver::solve_f(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs)
{
const auto nwin = trajs.size();
std::vector<double> expfs_prev(nwin, 1.0);
// (l, i) -> l * nwin + i
std::vector<std::vector<double>> cache_expW(nwin * nwin);
for(std::size_t l = 0; l < nwin; ++l)
{
if(not trajs.at(l).second)
{
log::fatal("traj ", l, " does not have potential function");
}
const auto& Vl = *(trajs.at(l).second);
for(std::size_t i = 0; i < nwin; ++i)
{
const auto& traj_i = trajs.at(i).first;
std::vector<double> expWs_i(traj_i.size());
for(std::size_t j=0; j < traj_i.size(); ++j)
{
expWs_i.at(j) = std::exp(-beta_ * Vl(traj_i.at(j)));
}
cache_expW.at(l * nwin + i) = expWs_i;
}
}
log::info("expW cached");
for(std::size_t iteration = 0; iteration < max_iteration_; ++iteration)
{
std::vector<double> expfs(trajs.size(), 0.0);
for(std::size_t l = 0; l < nwin; ++l)
{
auto& expf = expfs.at(l);
for(std::size_t i = 0; i < nwin; ++i)
{
const auto& expW = cache_expW.at(l * nwin + i);
const auto& traj_i = trajs.at(i).first;
for(std::size_t j = 0; j < traj_i.size(); ++j)
{
const double numer = expW.at(j);
double denom = 0.0;
for(std::size_t k = 0; k < nwin; ++k)
{
denom += trajs.at(k).first.size() *
cache_expW.at(k * nwin + i).at(j) *
expfs_prev.at(k);
}
expf += numer / denom;
}
}
}
for(auto& expf : expfs)
{
expf = 1.0 / expf;
}
double max_relative_diff = 0.0;
for(std::size_t i=0; i<expfs.size(); ++i)
{
max_relative_diff = std::max(max_relative_diff,
relative_diff(expfs.at(i), expfs_prev.at(i)));
}
log::info(iteration, "-th iteration: diff = ", max_relative_diff);
if(max_relative_diff < tolerance_)
{
log::info("parameter converged: ", expfs);
return expfs;
}
expfs_prev = expfs;
}
log::fatal("WHAM does not converge after ", max_iteration_, " iteration.");
}
inline ProbabilityDensity WHAMSolver::reconstruct(const std::vector<double>& expfs,
const std::vector<std::pair<std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins)
{
double start = std::numeric_limits<double>::max();
double stop = -std::numeric_limits<double>::max();
for(const auto& [traj, rc] : trajs)
{
for(const auto& x : traj)
{
start = std::min(start, x);
stop = std::max(stop, x);
}
}
const double dx = (stop - start) / (bins - 1);
start -= dx * 0.5;
stop += dx * 0.5;
log::info("WHAM: range = [", start, ", ", stop, ") dx = ", dx);
Histogram<double, double> unbiased(bins, start, stop);
for(const auto& [traj, rc] : trajs)
{
for(const auto& x: traj)
{
double denom = 0.0;
for(std::size_t i=0; i<trajs.size(); ++i)
{
denom += trajs.at(i).first.size() * expfs.at(i) *
std::exp(-1.0 * this->beta_ * (*trajs.at(i).second)(x));
}
unbiased.at(x) += 1.0 / denom;
}
}
return ProbabilityDensity(unbiased);
}
} // mill
#endif// COFFEE_MILL_MATH_HISTOGRAM_HPP
:rotating_light: remove structural binding
#ifndef COFFEE_MILL_REWEIGHT_WHAM_HPP
#define COFFEE_MILL_REWEIGHT_WHAM_HPP
#include "Histogram.hpp"
#include "ProbabilityDensity.hpp"
#include "PotentialFunction.hpp"
#include "ReactionCoordinate.hpp"
#include <mill/util/logger.hpp>
#include <vector>
#include <cmath>
namespace mill
{
class WHAMSolver
{
public:
WHAMSolver(const double kBT, const double tolerance,
const std::size_t max_iteration)
: kBT_(kBT), beta_(1.0 / kBT), tolerance_(tolerance), max_iteration_(max_iteration)
{}
ProbabilityDensity operator()(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins = 100)
{
return this->reconstruct(this->solve_f(trajs), trajs, bins);
}
private:
double relative_diff(const double lhs, const double rhs) const noexcept
{
return (lhs - rhs) / ((lhs + rhs) * 0.5);
}
std::vector<double> solve_f(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs);
ProbabilityDensity reconstruct(const std::vector<double>& fs,
const std::vector<std::pair<std::vector<double>,
std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins);
private:
double kBT_, beta_, tolerance_;
std::size_t max_iteration_;
};
inline std::vector<double> WHAMSolver::solve_f(const std::vector<std::pair<
std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs)
{
const auto nwin = trajs.size();
std::vector<double> expfs_prev(nwin, 1.0);
// (l, i) -> l * nwin + i
std::vector<std::vector<double>> cache_expW(nwin * nwin);
for(std::size_t l = 0; l < nwin; ++l)
{
if(not trajs.at(l).second)
{
log::fatal("traj ", l, " does not have potential function");
}
const auto& Vl = *(trajs.at(l).second);
for(std::size_t i = 0; i < nwin; ++i)
{
const auto& traj_i = trajs.at(i).first;
std::vector<double> expWs_i(traj_i.size());
for(std::size_t j=0; j < traj_i.size(); ++j)
{
expWs_i.at(j) = std::exp(-beta_ * Vl(traj_i.at(j)));
}
cache_expW.at(l * nwin + i) = expWs_i;
}
}
log::info("expW cached");
for(std::size_t iteration = 0; iteration < max_iteration_; ++iteration)
{
std::vector<double> expfs(trajs.size(), 0.0);
for(std::size_t l = 0; l < nwin; ++l)
{
auto& expf = expfs.at(l);
for(std::size_t i = 0; i < nwin; ++i)
{
const auto& expW = cache_expW.at(l * nwin + i);
const auto& traj_i = trajs.at(i).first;
for(std::size_t j = 0; j < traj_i.size(); ++j)
{
const double numer = expW.at(j);
double denom = 0.0;
for(std::size_t k = 0; k < nwin; ++k)
{
denom += trajs.at(k).first.size() *
cache_expW.at(k * nwin + i).at(j) *
expfs_prev.at(k);
}
expf += numer / denom;
}
}
}
for(auto& expf : expfs)
{
expf = 1.0 / expf;
}
double max_relative_diff = 0.0;
for(std::size_t i=0; i<expfs.size(); ++i)
{
max_relative_diff = std::max(max_relative_diff,
relative_diff(expfs.at(i), expfs_prev.at(i)));
}
log::info(iteration, "-th iteration: diff = ", max_relative_diff);
if(max_relative_diff < tolerance_)
{
log::info("parameter converged: ", expfs);
return expfs;
}
expfs_prev = expfs;
}
log::fatal("WHAM does not converge after ", max_iteration_, " iteration.");
}
inline ProbabilityDensity WHAMSolver::reconstruct(const std::vector<double>& expfs,
const std::vector<std::pair<std::vector<double>, std::unique_ptr<PotentialFunction>>>& trajs,
const std::size_t bins)
{
double start = std::numeric_limits<double>::max();
double stop = -std::numeric_limits<double>::max();
for(const auto& traj_rc : trajs)
{
for(const auto& x : traj_rc.first)
{
start = std::min(start, x);
stop = std::max(stop, x);
}
}
const double dx = (stop - start) / (bins - 1);
start -= dx * 0.5;
stop += dx * 0.5;
log::info("WHAM: range = [", start, ", ", stop, ") dx = ", dx);
Histogram<double, double> unbiased(bins, start, stop);
for(const auto& traj_rc : trajs)
{
for(const auto& x: traj_rc.first)
{
double denom = 0.0;
for(std::size_t i=0; i<trajs.size(); ++i)
{
denom += trajs.at(i).first.size() * expfs.at(i) *
std::exp(-1.0 * this->beta_ * (*trajs.at(i).second)(x));
}
unbiased.at(x) += 1.0 / denom;
}
}
return ProbabilityDensity(unbiased);
}
} // mill
#endif// COFFEE_MILL_MATH_HISTOGRAM_HPP
|
/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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 "feature_extractor.hpp"
#include <iostream>
#include "../../string_util.hpp"
namespace resembla {
const char FeatureExtractor::FEATURE_DELIMITER = '&';
const char FeatureExtractor::KEYVALUE_DELIMITER = '=';
FeatureExtractor::FeatureExtractor(const std::string base_similarity_key):
base_similarity_key(base_similarity_key)
{}
void FeatureExtractor::append(Feature::key_type key, std::shared_ptr<Function> func)
{
functions[key] = func;
}
FeatureExtractor::output_type FeatureExtractor::operator()(const std::string& raw_text, const std::string& raw_features) const
{
#ifdef DEBUG
std::cerr << "load features from saved data: text=" << raw_text << ", features=" << raw_features << std::endl;
#else
(void)raw_text;
#endif
output_type features;
for(const auto& f: split(raw_features, FEATURE_DELIMITER)){
auto kv = split(f, KEYVALUE_DELIMITER);
if(kv.size() == 2){
#ifdef DEBUG
std::cerr << "load feature: key=" << kv[0] << ", value=" << kv[1] << std::endl;
#endif
features[kv[0]] = kv[1];
}
}
return features;
}
FeatureExtractor::output_type FeatureExtractor::operator()(
const resembla::ResemblaResponse& data, const output_type& given_features) const
{
#ifdef DEBUG
std::cerr << "extract features" << std::endl;
#endif
output_type features(given_features);
features[base_similarity_key] = Feature::toText(data.score);
for(const auto& i: functions){
auto k = features.find(i.first);
if(k == std::end(features)){
#ifdef DEBUG
std::cerr << "extract feature: " << i.first << std::endl;
#endif
features[i.first] = (*i.second)(data.text);
}
else{
#ifdef DEBUG
std::cerr << "skip already computed feature: " << i.first << std::endl;
#endif
}
}
return features;
}
FeatureExtractor::output_type FeatureExtractor::operator()(const string_type& text) const
{
#ifdef DEBUG
std::cerr << "extract features from text" << std::endl;
#endif
output_type features;
for(const auto& i: functions){
#ifdef DEBUG
std::cerr << "extract feature: " << i.first << std::endl;
#endif
features[i.first] = (*i.second)(text);
}
return features;
}
}
add todo
/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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 "feature_extractor.hpp"
#include <iostream>
#include "../../string_util.hpp"
namespace resembla {
const char FeatureExtractor::FEATURE_DELIMITER = '&';
const char FeatureExtractor::KEYVALUE_DELIMITER = '=';
FeatureExtractor::FeatureExtractor(const std::string base_similarity_key):
base_similarity_key(base_similarity_key)
{}
void FeatureExtractor::append(Feature::key_type key, std::shared_ptr<Function> func)
{
functions[key] = func;
}
FeatureExtractor::output_type FeatureExtractor::operator()(const std::string& raw_text, const std::string& raw_features) const
{
#ifdef DEBUG
std::cerr << "load features from saved data: text=" << raw_text << ", features=" << raw_features << std::endl;
#else
(void)raw_text;
#endif
output_type features;
for(const auto& f: split(raw_features, FEATURE_DELIMITER)){
auto kv = split(f, KEYVALUE_DELIMITER);
if(kv.size() == 2){
#ifdef DEBUG
std::cerr << "load feature: key=" << kv[0] << ", value=" << kv[1] << std::endl;
#endif
features[kv[0]] = kv[1];
}
}
return features;
}
FeatureExtractor::output_type FeatureExtractor::operator()(
const resembla::ResemblaResponse& data, const output_type& given_features) const
{
#ifdef DEBUG
std::cerr << "extract features" << std::endl;
#endif
output_type features(given_features);
// TODO: remove this code. FeatureExtractor should accept multiple base similarities
features[base_similarity_key] = Feature::toText(data.score);
for(const auto& i: functions){
auto k = features.find(i.first);
if(k == std::end(features)){
#ifdef DEBUG
std::cerr << "extract feature: " << i.first << std::endl;
#endif
features[i.first] = (*i.second)(data.text);
}
else{
#ifdef DEBUG
std::cerr << "skip already computed feature: " << i.first << std::endl;
#endif
}
}
return features;
}
FeatureExtractor::output_type FeatureExtractor::operator()(const string_type& text) const
{
#ifdef DEBUG
std::cerr << "extract features from text" << std::endl;
#endif
output_type features;
for(const auto& i: functions){
#ifdef DEBUG
std::cerr << "extract feature: " << i.first << std::endl;
#endif
features[i.first] = (*i.second)(text);
}
return features;
}
}
|
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "http_client.h"
#include "config.h" // for XAPIAND_CLUSTERING, XAPIAND_CHAISCRIPT, XAPIAND_DATABASE_WAL
#include <cassert> // for assert
#include <errno.h> // for errno
#include <exception> // for std::exception
#include <functional> // for std::function
#include <regex> // for std::regex, std::regex_constants
#include <signal.h> // for SIGTERM
#include <sysexits.h> // for EX_SOFTWARE
#include <syslog.h> // for LOG_WARNING, LOG_ERR, LOG...
#include <utility> // for std::move
#ifdef USE_ICU
#include <unicode/uvernum.h>
#endif
#ifdef XAPIAND_CHAISCRIPT
#include "chaiscript/chaiscript_defines.hpp" // for chaiscript::Build_Info
#endif
#include "cppcodec/base64_rfc4648.hpp" // for cppcodec::base64_rfc4648
#include "database/handler.h" // for DatabaseHandler, DocIndexer
#include "database/utils.h" // for query_field_t
#include "database/pool.h" // for DatabasePool
#include "database/schema.h" // for Schema
#include "endpoint.h" // for Endpoints, Endpoint
#include "epoch.hh" // for epoch::now
#include "error.hh" // for error:name, error::description
#include "ev/ev++.h" // for async, io, loop_ref (ptr ...
#include "exception.h" // for Exception, SerialisationE...
#include "field_parser.h" // for FieldParser, FieldParserError
#include "hashes.hh" // for hhl
#include "http_utils.h" // for catch_http_errors
#include "io.hh" // for close, write, unlink
#include "log.h" // for L_CALL, L_ERR, LOG_DEBUG
#include "logger.h" // for Logging
#include "manager.h" // for XapiandManager
#include "metrics.h" // for Metrics::metrics
#include "mime_types.hh" // for mime_type
#include "msgpack.h" // for MsgPack, msgpack::object
#include "aggregations/aggregations.h" // for AggregationMatchSpy
#include "node.h" // for Node::local_node, Node::leader_node
#include "opts.h" // for opts::*
#include "package.h" // for Package::*
#include "phf.hh" // for phf::*
#include "rapidjson/document.h" // for Document
#include "reserved/aggregations.h" // for RESERVED_AGGS_*
#include "reserved/fields.h" // for RESERVED_*
#include "reserved/query_dsl.h" // for RESERVED_QUERYDSL_*
#include "reserved/schema.h" // for RESERVED_VERSION
#include "response.h" // for RESPONSE_*
#include "serialise.h" // for Serialise::boolean
#include "strings.hh" // for strings::from_delta
#include "system.hh" // for check_compiler, check_OS, check_architecture
#include "xapian.h" // for Xapian::major_version, Xapian::minor_version
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_CONN
// #define L_CONN L_GREEN
// #undef L_HTTP
// #define L_HTTP L_RED
// #undef L_HTTP_WIRE
// #define L_HTTP_WIRE L_ORANGE
// #undef L_HTTP_PROTO
// #define L_HTTP_PROTO L_TEAL
#define QUERY_FIELD_PRIMARY (1 << 0)
#define QUERY_FIELD_WRITABLE (1 << 1)
#define QUERY_FIELD_COMMIT (1 << 2)
#define QUERY_FIELD_SEARCH (1 << 3)
#define QUERY_FIELD_ID (1 << 4)
#define QUERY_FIELD_TIME (1 << 5)
#define QUERY_FIELD_PERIOD (1 << 6)
#define QUERY_FIELD_VOLATILE (1 << 7)
#define DEFAULT_INDENTATION 2
static const std::regex header_params_re(R"(\s*;\s*([a-z]+)=(\d+(?:\.\d+)?))", std::regex::optimize);
static const std::regex header_accept_re(R"(([-a-z+]+|\*)/([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::regex header_accept_encoding_re(R"(([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::string eol("\r\n");
// Available commands
#define METHODS_OPTIONS() \
OPTION(DELETE, "delete") \
OPTION(GET, "get") \
OPTION(HEAD, "head") \
OPTION(POST, "post") \
OPTION(PUT, "put") \
OPTION(CONNECT, "connect") \
OPTION(OPTIONS, "options") \
OPTION(TRACE, "trace") \
OPTION(PATCH, "patch") \
OPTION(PURGE, "purge") \
OPTION(LINK, "link") \
OPTION(UNLINK, "unlink") \
OPTION(CHECK, "check") \
OPTION(CLOSE, "close") \
OPTION(COMMIT, "commit") \
OPTION(COPY, "copy") \
OPTION(COUNT, "count") \
OPTION(DUMP, "dump") \
OPTION(FLUSH, "flush") \
OPTION(INFO, "info") \
OPTION(LOCK, "lock") \
OPTION(MERGE, "merge") \
OPTION(MOVE, "move") \
OPTION(OPEN, "open") \
OPTION(QUIT, "quit") \
OPTION(RESTORE, "restore") \
OPTION(SEARCH, "search") \
OPTION(STORE, "store") \
OPTION(UNLOCK, "unlock") \
OPTION(UPDATE, "update")
constexpr static auto http_methods = phf::make_phf({
#define OPTION(name, str) hhl(str),
METHODS_OPTIONS()
#undef OPTION
});
bool is_range(std::string_view str) {
try {
FieldParser fieldparser(str);
fieldparser.parse();
return fieldparser.is_range();
} catch (const FieldParserError&) {
return false;
}
}
bool can_preview(const ct_type_t& ct_type) {
#define CONTENT_TYPE_OPTIONS() \
OPTION("application/eps") \
OPTION("application/pdf") \
OPTION("application/postscript") \
OPTION("application/x-bzpdf") \
OPTION("application/x-eps") \
OPTION("application/x-gzpdf") \
OPTION("application/x-pdf") \
OPTION("application/x-photoshop") \
OPTION("application/photoshop") \
OPTION("application/psd")
constexpr static auto _ = phf::make_phf({
#define OPTION(ct) hhl(ct),
CONTENT_TYPE_OPTIONS()
#undef OPTION
});
switch (_.fhhl(ct_type.to_string())) {
#define OPTION(ct) case _.fhhl(ct):
CONTENT_TYPE_OPTIONS()
#undef OPTION
return true;
default:
return ct_type.first == "image";
}
}
/*
* _ _ _ _
* | | | | |_| |_ _ __
* | |_| | __| __| '_ \
* | _ | |_| |_| |_) |
* |_| |_|\__|\__| .__/
* |_|
*/
HttpClient::HttpClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: BaseClient<HttpClient>(std::move(parent_), ev_loop_, ev_flags_),
new_request(std::make_shared<Request>(this))
{
++XapiandManager::http_clients();
Metrics::metrics()
.xapiand_http_connections
.Increment();
// Initialize new_request->begins as soon as possible (for correctly timing disconnecting clients)
new_request->begins = std::chrono::steady_clock::now();
L_CONN("New Http Client, {} client(s) of a total of {} connected.", XapiandManager::http_clients().load(), XapiandManager::total_clients().load());
}
HttpClient::~HttpClient() noexcept
{
try {
if (XapiandManager::http_clients().fetch_sub(1) == 0) {
L_CRIT("Inconsistency in number of http clients");
sig_exit(-EX_SOFTWARE);
}
if (is_shutting_down() && !is_idle()) {
L_INFO("HTTP client killed!");
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
std::string
HttpClient::http_response(Request& request, enum http_status status, int mode, const std::string& body, const std::string& location, const std::string& ct_type, const std::string& ct_encoding, size_t content_length) {
L_CALL("HttpClient::http_response()");
std::string head;
std::string headers;
std::string head_sep;
std::string headers_sep;
std::string response_body;
if ((mode & HTTP_STATUS_RESPONSE) != 0) {
assert(request.response.status == static_cast<http_status>(0));
request.response.status = status;
auto http_major = request.parser.http_major;
auto http_minor = request.parser.http_minor;
if (http_major == 0 && http_minor == 0) {
http_major = 1;
}
head += strings::format("HTTP/{}.{} {} ", http_major, http_minor, status);
head += http_status_str(status);
head_sep += eol;
if ((mode & HTTP_HEADER_RESPONSE) == 0) {
headers_sep += eol;
}
}
assert(request.response.status != static_cast<http_status>(0));
if ((mode & HTTP_HEADER_RESPONSE) != 0) {
headers += "Server: " + Package::STRING + eol;
// if (!endpoints.empty()) {
// headers += "Database: " + endpoints.to_string() + eol;
// }
request.ends = std::chrono::steady_clock::now();
if (request.human) {
headers += strings::format("Response-Time: {}", strings::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count())) + eol;
if (request.ready >= request.processing) {
headers += strings::format("Operation-Time: {}", strings::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count())) + eol;
}
} else {
headers += strings::format("Response-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count() / 1e9) + eol;
if (request.ready >= request.processing) {
headers += strings::format("Operation-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count() / 1e9) + eol;
}
}
if ((mode & HTTP_OPTIONS_RESPONSE) != 0) {
headers += "Allow: GET, POST, PUT, PATCH, UPDATE, STORE, DELETE, HEAD, OPTIONS" + eol;
}
if (!location.empty()) {
headers += "Location: " + location + eol;
}
if ((mode & HTTP_CONTENT_TYPE_RESPONSE) != 0 && !ct_type.empty()) {
headers += "Content-Type: " + ct_type + eol;
}
if ((mode & HTTP_CONTENT_ENCODING_RESPONSE) != 0 && !ct_encoding.empty()) {
headers += "Content-Encoding: " + ct_encoding + eol;
}
if ((mode & HTTP_CONTENT_LENGTH_RESPONSE) != 0) {
headers += strings::format("Content-Length: {}", content_length) + eol;
} else {
headers += strings::format("Content-Length: {}", body.size()) + eol;
}
headers_sep += eol;
}
if ((mode & HTTP_BODY_RESPONSE) != 0) {
response_body += body;
}
auto this_response_size = response_body.size();
request.response.size += this_response_size;
if (Logging::log_level >= LOG_DEBUG) {
request.response.head += head;
request.response.headers += headers;
}
return head + head_sep + headers + headers_sep + response_body;
}
template <typename Func>
int
HttpClient::handled_errors(Request& request, Func&& func)
{
L_CALL("HttpClient::handled_errors()");
auto http_errors = catch_http_errors(std::forward<Func>(func));
if (http_errors.error_code != HTTP_STATUS_OK) {
if (request.response.status != static_cast<http_status>(0)) {
// There was an error, but request already had written stuff...
// disconnect client!
detach();
} else if (request.comments) {
write_http_response(request, http_errors.error_code, MsgPack({
{ RESPONSE_xSTATUS, static_cast<unsigned>(http_errors.error_code) },
{ RESPONSE_xMESSAGE, strings::split(http_errors.error, '\n') }
}));
} else {
write_http_response(request, http_errors.error_code);
}
request.atom_ending = true;
}
return http_errors.ret;
}
size_t
HttpClient::pending_requests() const
{
std::lock_guard<std::mutex> lk(runner_mutex);
auto requests_size = requests.size();
if (requests_size && requests.front()->response.status != static_cast<http_status>(0)) {
--requests_size;
}
return requests_size;
}
bool
HttpClient::is_idle() const
{
L_CALL("HttpClient::is_idle() {{is_waiting:{}, is_running:{}, write_queue_empty:{}, pending_requests:{}}}", is_waiting(), is_running(), write_queue.empty(), pending_requests());
return !is_waiting() && !is_running() && write_queue.empty() && !pending_requests();
}
void
HttpClient::destroy_impl()
{
L_CALL("HttpClient::destroy_impl()");
BaseClient<HttpClient>::destroy_impl();
// HttpClient could be using indexer (which would block)
// if destroying is received, finish indexer:
std::unique_lock<std::mutex> lk(runner_mutex);
if (!requests.empty()) {
auto& request = *requests.front();
if (request.indexer) {
request.indexer->finish();
}
}
}
ssize_t
HttpClient::on_read(const char* buf, ssize_t received)
{
L_CALL("HttpClient::on_read(<buf>, {})", received);
if (received <= 0) {
std::string reason;
if (received < 0) {
reason = strings::format("{} ({}): {}", error::name(errno), errno, error::description(errno));
if (errno != ENOTCONN && errno != ECONNRESET && errno != ESPIPE) {
L_NOTICE("HTTP client connection closed unexpectedly after {}: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
} else {
reason = "EOF";
}
auto state = HTTP_PARSER_STATE(&new_request->parser);
if (state != s_start_req) {
L_NOTICE("HTTP client closed unexpectedly after {}: Not in final HTTP state ({}): {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), state, reason);
close();
return received;
}
if (is_waiting()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There was still a request in progress: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
if (!write_queue.empty()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There is still pending data: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
if (pending_requests()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There are still pending requests: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
// HTTP client normally closed connection.
close();
return received;
}
L_HTTP_WIRE("HttpClient::on_read: {} bytes", received);
ssize_t parsed = http_parser_execute(&new_request->parser, &parser_settings, buf, received);
if (parsed != received) {
enum http_status error_code = HTTP_STATUS_BAD_REQUEST;
http_errno err = HTTP_PARSER_ERRNO(&new_request->parser);
if (err == HPE_INVALID_METHOD) {
if (new_request->response.status == static_cast<http_status>(0)) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
end_http_request(*new_request);
}
} else {
std::string message(http_errno_description(err));
L_DEBUG("HTTP parser error: {}", HTTP_PARSER_ERRNO(&new_request->parser) != HPE_OK ? message : "incomplete request");
if (new_request->response.status == static_cast<http_status>(0)) {
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, strings::split(message, '\n') }
}));
} else {
write_http_response(*new_request, error_code);
}
end_http_request(*new_request);
}
}
detach();
}
return received;
}
void
HttpClient::on_read_file(const char* /*buf*/, ssize_t received)
{
L_CALL("HttpClient::on_read_file(<buf>, {})", received);
L_ERR("Not Implemented: HttpClient::on_read_file: {} bytes", received);
}
void
HttpClient::on_read_file_done()
{
L_CALL("HttpClient::on_read_file_done()");
L_ERR("Not Implemented: HttpClient::on_read_file_done");
}
// HTTP parser callbacks.
const http_parser_settings HttpClient::parser_settings = {
HttpClient::message_begin_cb,
HttpClient::url_cb,
HttpClient::status_cb,
HttpClient::header_field_cb,
HttpClient::header_value_cb,
HttpClient::headers_complete_cb,
HttpClient::body_cb,
HttpClient::message_complete_cb,
HttpClient::chunk_header_cb,
HttpClient::chunk_complete_cb,
};
inline std::string readable_http_parser_flags(http_parser* parser) {
std::vector<std::string> values;
if ((parser->flags & F_CHUNKED) == F_CHUNKED) values.push_back("F_CHUNKED");
if ((parser->flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) values.push_back("F_CONNECTION_KEEP_ALIVE");
if ((parser->flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) values.push_back("F_CONNECTION_CLOSE");
if ((parser->flags & F_CONNECTION_UPGRADE) == F_CONNECTION_UPGRADE) values.push_back("F_CONNECTION_UPGRADE");
if ((parser->flags & F_TRAILING) == F_TRAILING) values.push_back("F_TRAILING");
if ((parser->flags & F_UPGRADE) == F_UPGRADE) values.push_back("F_UPGRADE");
if ((parser->flags & F_SKIPBODY) == F_SKIPBODY) values.push_back("F_SKIPBODY");
if ((parser->flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) values.push_back("F_CONTENTLENGTH");
return strings::join(values, "|");
}
int
HttpClient::message_begin_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_begin(parser);
});
}
int
HttpClient::url_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_url(parser, at, length);
});
}
int
HttpClient::status_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_status(parser, at, length);
});
}
int
HttpClient::header_field_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_field(parser, at, length);
});
}
int
HttpClient::header_value_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_value(parser, at, length);
});
}
int
HttpClient::headers_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_headers_complete(parser);
});
}
int
HttpClient::body_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_body(parser, at, length);
});
}
int
HttpClient::message_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_complete(parser);
});
}
int
HttpClient::chunk_header_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_header(parser);
});
}
int
HttpClient::chunk_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_complete(parser);
});
}
int
HttpClient::on_message_begin([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_begin(<parser>)");
L_HTTP_PROTO("on_message_begin {{state:{}, header_state:{}}}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)));
waiting = true;
new_request->begins = std::chrono::steady_clock::now();
L_TIMED_VAR(new_request->log, 10s,
"Request taking too long...",
"Request took too long!");
return 0;
}
int
HttpClient::on_url(http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_url(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_url {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->method = HTTP_PARSER_METHOD(parser);
new_request->path.append(at, length);
return 0;
}
int
HttpClient::on_status([[maybe_unused]] http_parser* parser, [[maybe_unused]] const char* at, [[maybe_unused]] size_t length)
{
L_CALL("HttpClient::on_status(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_status {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
return 0;
}
int
HttpClient::on_header_field([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_field(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_field {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->_header_name = std::string(at, length);
return 0;
}
int
HttpClient::on_header_value([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_value(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_value {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
auto _header_value = std::string_view(at, length);
if (Logging::log_level >= LOG_DEBUG) {
new_request->headers.append(new_request->_header_name);
new_request->headers.append(": ");
new_request->headers.append(_header_value);
new_request->headers.append(eol);
}
constexpr static auto _ = phf::make_phf({
hhl("expect"),
hhl("100-continue"),
hhl("content-type"),
hhl("accept"),
hhl("accept-encoding"),
hhl("http-method-override"),
hhl("x-http-method-override"),
});
switch (_.fhhl(new_request->_header_name)) {
case _.fhhl("expect"):
case _.fhhl("100-continue"):
// Respond with HTTP/1.1 100 Continue
new_request->expect_100 = true;
break;
case _.fhhl("content-type"):
new_request->ct_type = ct_type_t(_header_value);
break;
case _.fhhl("accept"): {
static AcceptLRU accept_sets;
auto value = strings::lower(_header_value);
auto lookup = accept_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
int indent = -1;
double q = 1.0;
if (next->length(3) != 0) {
auto param = next->str(3);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
} else if (next_param->str(1) == "indent") {
indent = strict_stoi(next_param->str(2));
if (indent < 0) { indent = 0;
} else if (indent > 16) { indent = 16; }
}
++next_param;
}
}
lookup.second.emplace(i, q, ct_type_t(next->str(1), next->str(2)), indent);
++next;
++i;
}
accept_sets.emplace(value, lookup.second);
}
new_request->accept_set = std::move(lookup.second);
break;
}
case _.fhhl("accept-encoding"): {
static AcceptEncodingLRU accept_encoding_sets;
auto value = strings::lower(_header_value);
auto lookup = accept_encoding_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_encoding_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
double q = 1.0;
if (next->length(2) != 0) {
auto param = next->str(2);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
}
++next_param;
}
} else {
}
lookup.second.emplace(i, q, next->str(1));
++next;
++i;
}
accept_encoding_sets.emplace(value, lookup.second);
}
new_request->accept_encoding_set = std::move(lookup.second);
break;
}
case _.fhhl("x-http-method-override"):
case _.fhhl("http-method-override"): {
switch (http_methods.fhhl(_header_value)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "{} header must use the POST method", repr(new_request->_header_name)); \
} \
new_request->method = HTTP_##name; \
break;
METHODS_OPTIONS()
#undef OPTION
default:
parser->http_errno = HPE_INVALID_METHOD;
break;
}
break;
}
}
return 0;
}
int
HttpClient::on_headers_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_headers_complete(<parser>)");
L_HTTP_PROTO("on_headers_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
// Prepare the request view
if (int err = prepare()) {
end_http_request(*new_request);
return err;
}
if likely(!closed && !new_request->atom_ending) {
if likely(new_request->view) {
if (new_request->mode != Request::Mode::FULL) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || new_request != requests.front()) {
requests.push_back(new_request); // Enqueue streamed request
}
}
}
}
return 0;
}
int
HttpClient::on_body([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_body(<parser>, <at>, {})", length);
L_HTTP_PROTO("on_body {{state:{}, header_state:{}, flags:[{}]}}: {}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser),
repr(at, length));
new_request->size += length;
if likely(!closed && !new_request->atom_ending) {
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || new_request->view) {
signal_pending = new_request->append(at, length);
}
if (new_request->view) {
if (signal_pending) {
new_request->pending.signal();
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
}
}
return 0;
}
int
HttpClient::on_message_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_complete(<parser>)");
L_HTTP_PROTO("on_message_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
if (Logging::log_level > LOG_DEBUG) {
log_request(*new_request);
}
if likely(!closed && !new_request->atom_ending) {
new_request->atom_ending = true;
std::shared_ptr<Request> request = std::make_shared<Request>(this);
std::swap(new_request, request);
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || request->view) {
request->append(nullptr, 0); // flush pending stuff
signal_pending = true; // always signal pending
}
if (request->view) {
if (signal_pending) {
request->pending.signal(); // always signal, so view continues ending
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || request != requests.front()) {
requests.push_back(std::move(request)); // Enqueue request
}
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
} else {
end_http_request(*request);
}
}
waiting = false;
return 0;
}
int
HttpClient::on_chunk_header([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_header(<parser>)");
L_HTTP_PROTO("on_chunk_header {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::on_chunk_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_complete(<parser>)");
L_HTTP_PROTO("on_chunk_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::prepare()
{
L_CALL("HttpClient::prepare()");
L_TIMED_VAR(request.log, 1s,
"Response taking too long: {}",
"Response took too long: {}",
request.head());
new_request->received = std::chrono::steady_clock::now();
if (new_request->parser.http_major == 0 || (new_request->parser.http_major == 1 && new_request->parser.http_minor == 0)) {
new_request->closing = true;
}
if ((new_request->parser.flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) {
new_request->closing = false;
}
if ((new_request->parser.flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) {
new_request->closing = true;
}
if (new_request->accept_set.empty()) {
if (!new_request->ct_type.empty()) {
new_request->accept_set.emplace(0, 1.0, new_request->ct_type, 0);
}
new_request->accept_set.emplace(1, 1.0, any_type, 0);
}
new_request->type_encoding = resolve_encoding(*new_request);
if (new_request->type_encoding == Encoding::unknown) {
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response encoding gzip, deflate or identity not provided in the Accept-Encoding header" }) } }
}));
} else {
write_http_response(*new_request, error_code);
}
return 1;
}
url_resolve(*new_request);
auto id = new_request->path_parser.get_id();
auto has_pth = new_request->path_parser.has_pth();
auto cmd = new_request->path_parser.get_cmd();
if (!cmd.empty()) {
auto mapping = cmd;
mapping.remove_prefix(1);
switch (http_methods.fhhl(mapping)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "HTTP Mappings must use GET or POST method"); \
} \
new_request->method = HTTP_##name; \
cmd = ""; \
break;
METHODS_OPTIONS()
#undef OPTION
}
}
switch (new_request->method) {
case HTTP_SEARCH:
if (id.empty()) {
new_request->view = &HttpClient::search_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COUNT:
if (id.empty()) {
new_request->view = &HttpClient::count_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_INFO:
if (id.empty()) {
new_request->view = &HttpClient::info_view;
} else {
new_request->view = &HttpClient::info_view;
}
break;
case HTTP_HEAD:
if (id.empty()) {
new_request->view = &HttpClient::database_exists_view;
} else {
new_request->view = &HttpClient::document_exists_view;
}
break;
case HTTP_GET:
if (!cmd.empty() && id.empty()) {
if (!has_pth && cmd == ":metrics") {
new_request->view = &HttpClient::metrics_view;
} else {
new_request->view = &HttpClient::retrieve_metadata_view;
}
} else if (!id.empty()) {
if (is_range(id)) {
new_request->view = &HttpClient::search_view;
} else {
new_request->view = &HttpClient::retrieve_document_view;
}
} else {
new_request->view = &HttpClient::retrieve_database_view;
}
break;
case HTTP_POST:
if (!cmd.empty() && id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else if (!id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_PUT:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::write_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::write_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_PATCH:
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::update_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_STORE:
if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DELETE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::delete_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::delete_document_view;
} else if (has_pth) {
new_request->view = &HttpClient::delete_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COMMIT:
if (id.empty()) {
new_request->view = &HttpClient::commit_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DUMP:
if (id.empty()) {
new_request->view = &HttpClient::dump_database_view;
} else {
new_request->view = &HttpClient::dump_document_view;
}
break;
case HTTP_RESTORE:
if (id.empty()) {
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) {
if (new_request->ct_type == ndjson_type || new_request->ct_type == x_ndjson_type) {
new_request->mode = Request::Mode::STREAM_NDJSON;
} else if (new_request->ct_type == msgpack_type || new_request->ct_type == x_msgpack_type) {
new_request->mode = Request::Mode::STREAM_MSGPACK;
}
}
new_request->view = &HttpClient::restore_database_view;
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_CHECK:
if (id.empty()) {
new_request->view = &HttpClient::check_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_FLUSH:
if (opts.admin_commands && id.empty() && !has_pth) {
// Flush both databases and clients by default (unless one is specified)
new_request->query_parser.rewind();
int flush_databases = new_request->query_parser.next("databases");
new_request->query_parser.rewind();
int flush_clients = new_request->query_parser.next("clients");
if (flush_databases != -1 || flush_clients == -1) {
XapiandManager::database_pool()->cleanup(true);
}
if (flush_clients != -1 || flush_databases == -1) {
XapiandManager::manager()->shutdown(0, 0);
}
write_http_response(*new_request, HTTP_STATUS_OK);
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_OPTIONS:
write(http_response(*new_request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_OPTIONS_RESPONSE | HTTP_BODY_RESPONSE));
break;
case HTTP_QUIT:
if (opts.admin_commands && !has_pth && id.empty()) {
XapiandManager::try_shutdown(true);
write_http_response(*new_request, HTTP_STATUS_OK);
destroy();
detach();
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
#if XAPIAND_DATABASE_WAL
case HTTP_WAL:
if (id.empty()) {
new_request->view = &HttpClient::wal_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
#endif
default: {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
new_request->parser.http_errno = HPE_INVALID_METHOD;
return 1;
}
}
if (!new_request->view && Logging::log_level < LOG_DEBUG) {
return 1;
}
if (new_request->expect_100) {
// Return "100 Continue" if client sent "Expect: 100-continue"
write(http_response(*new_request, HTTP_STATUS_CONTINUE, HTTP_STATUS_RESPONSE));
// Go back to unknown response state:
new_request->response.head.clear();
new_request->response.status = static_cast<http_status>(0);
}
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH && new_request->parser.content_length) {
if (new_request->mode == Request::Mode::STREAM_MSGPACK) {
new_request->unpacker.reserve_buffer(new_request->parser.content_length);
} else {
new_request->raw.reserve(new_request->parser.content_length);
}
}
return 0;
}
void
HttpClient::process(Request& request)
{
L_CALL("HttpClient::process()");
L_OBJ_BEGIN("HttpClient::process:BEGIN");
L_OBJ_END("HttpClient::process:END");
handled_errors(request, [&]{
(this->*request.view)(request);
return 0;
});
}
void
HttpClient::operator()()
{
L_CALL("HttpClient::operator()()");
L_CONN("Start running in worker...");
std::unique_lock<std::mutex> lk(runner_mutex);
while (!requests.empty() && !closed) {
Request& request = *requests.front();
if (request.atom_ended) {
requests.pop_front();
continue;
}
request.ending = request.atom_ending.load();
lk.unlock();
// wait for the request to be ready
if (!request.ending && !request.wait()) {
lk.lock();
continue;
}
try {
assert(request.view);
process(request);
request.begining = false;
} catch (...) {
request.begining = false;
end_http_request(request);
lk.lock();
requests.pop_front();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: HTTP client ended with an unhandled exception");
detach();
throw;
}
if (request.ending) {
end_http_request(request);
auto closing = request.closing;
lk.lock();
requests.pop_front();
if (closing) {
running = false;
L_CONN("Running in worker ended after request closing.");
lk.unlock();
destroy();
detach();
return;
}
} else {
lk.lock();
}
}
running = false;
L_CONN("Running in replication worker ended. {{requests_empty:{}, closed:{}, is_shutting_down:{}}}", requests.empty(), closed.load(), is_shutting_down());
lk.unlock();
if (is_shutting_down() && is_idle()) {
detach();
return;
}
redetach(); // try re-detaching if already flagged as detaching
}
MsgPack
HttpClient::node_obj()
{
L_CALL("HttpClient::node_obj()");
endpoints.clear();
auto leader_node = Node::leader_node();
endpoints.add(Endpoint{".xapiand/nodes", leader_node});
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
auto local_node = Node::local_node();
auto document = db_handler.get_document(local_node->lower_name());
auto obj = document.get_obj();
#ifdef XAPIAND_CLUSTERING
auto nodes = MsgPack::ARRAY();
for (auto& node : Node::nodes()) {
if (node->idx) {
auto node_obj = MsgPack::MAP();
node_obj["idx"] = node->idx;
node_obj["name"] = node->name();
if (Node::is_active(node)) {
node_obj["host"] = node->host();
node_obj["http_port"] = node->http_port;
node_obj["remote_port"] = node->remote_port;
node_obj["replication_port"] = node->replication_port;
node_obj["active"] = true;
} else {
node_obj["active"] = false;
}
nodes.push_back(node_obj);
}
}
#endif
obj.update(MsgPack({
#ifdef XAPIAND_CLUSTERING
{ "cluster_name", opts.cluster_name },
#endif
{ "server", {
{ "name", Package::NAME },
{ "url", Package::URL },
{ "issues", Package::BUGREPORT },
{ "version", Package::VERSION },
{ "revision", Package::REVISION },
{ "hash", Package::HASH },
{ "compiler", check_compiler() },
{ "os", check_OS() },
{ "arch", check_architecture() },
} },
{ "versions", {
{ "Xapiand", Package::REVISION.empty() ? Package::VERSION : strings::format("{}_{}", Package::VERSION, Package::REVISION) },
{ "Xapian", strings::format("{}.{}.{}", Xapian::major_version(), Xapian::minor_version(), Xapian::revision()) },
#ifdef XAPIAND_CHAISCRIPT
{ "ChaiScript", strings::format("{}.{}", chaiscript::Build_Info::version_major(), chaiscript::Build_Info::version_minor()) },
#endif
#ifdef USE_ICU
{ "ICU", strings::format("{}.{}", U_ICU_VERSION_MAJOR_NUM, U_ICU_VERSION_MINOR_NUM) },
#endif
} },
{ "options", {
{ "verbosity", opts.verbosity },
{ "processors", opts.processors },
{ "limits", {
// { "max_clients", opts.max_clients },
{ "max_database_readers", opts.max_database_readers },
} },
{ "cache", {
{ "database_pool_size", opts.database_pool_size },
{ "schema_pool_size", opts.schema_pool_size },
{ "scripts_cache_size", opts.scripts_cache_size },
#ifdef XAPIAND_CLUSTERING
{ "resolver_cache_size", opts.resolver_cache_size },
#endif
} },
{ "thread_pools", {
{ "num_shards", opts.num_shards },
{ "num_replicas", opts.num_replicas },
{ "num_http_servers", opts.num_http_servers },
{ "num_http_clients", opts.num_http_clients },
#ifdef XAPIAND_CLUSTERING
{ "num_remote_servers", opts.num_remote_servers },
{ "num_remote_clients", opts.num_remote_clients },
{ "num_replication_servers", opts.num_replication_servers },
{ "num_replication_clients", opts.num_replication_clients },
#endif
{ "num_async_wal_writers", opts.num_async_wal_writers },
{ "num_doc_matchers", opts.num_doc_matchers },
{ "num_doc_preparers", opts.num_doc_preparers },
{ "num_doc_indexers", opts.num_doc_indexers },
{ "num_committers", opts.num_committers },
{ "num_fsynchers", opts.num_fsynchers },
#ifdef XAPIAND_CLUSTERING
{ "num_replicators", opts.num_replicators },
{ "num_discoverers", opts.num_discoverers },
#endif
} },
} },
#ifdef XAPIAND_CLUSTERING
{ "nodes", nodes },
#endif
}));
return obj;
}
void
HttpClient::metrics_view(Request& request)
{
L_CALL("HttpClient::metrics_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
auto server_info = XapiandManager::server_metrics();
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE | HTTP_BODY_RESPONSE, server_info, "", "text/plain", "", server_info.size()));
}
void
HttpClient::document_exists_view(Request& request)
{
L_CALL("HttpClient::document_exists_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
db_handler.get_document(request.path_parser.get_id()).validate();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
void
HttpClient::delete_document_view(Request& request)
{
L_CALL("HttpClient::delete_document_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
std::string document_id(request.path_parser.get_id());
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.delete_document(document_id, query_field.commit);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_NO_CONTENT);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Deletion took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "delete"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_document_view(Request& request)
{
L_CALL("HttpClient::write_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
auto indexed = db_handler.index(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
request.ready = std::chrono::steady_clock::now();
std::string location;
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (request.echo) {
auto it = response_obj.find(ID_FIELD_NAME);
if (document_id.empty()) {
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, document_id_obj.as_str());
response_obj[ID_FIELD_NAME] = std::move(document_id_obj);
} else {
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, it.value().as_str());
}
} else {
if (it == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj, location);
} else {
if (document_id.empty()) {
auto it = response_obj.find(ID_FIELD_NAME);
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, document_id_obj.as_str());
} else {
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, it.value().as_str());
}
}
write_http_response(request, document_id.empty() ? HTTP_STATUS_CREATED : HTTP_STATUS_NO_CONTENT, MsgPack(), location);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Indexing took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "index"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_document_view(Request& request)
{
L_CALL("HttpClient::update_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
assert(!document_id.empty());
request.processing = std::chrono::steady_clock::now();
std::string operation;
DataType indexed;
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (request.method == HTTP_PATCH) {
operation = "patch";
indexed = db_handler.patch(document_id, query_field.version, decoded_body, query_field.commit);
} else if (request.method == HTTP_STORE) {
operation = "store";
indexed = db_handler.update(document_id, query_field.version, true, decoded_body, query_field.commit, request.ct_type == json_type || request.ct_type == x_json_type || request.ct_type == yaml_type || request.ct_type == x_yaml_type || request.ct_type == msgpack_type || request.ct_type == x_msgpack_type || request.ct_type.empty() ? mime_type(selector) : request.ct_type);
} else {
operation = "update";
indexed = db_handler.update(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
}
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (response_obj.find(ID_FIELD_NAME) == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", operation},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_metadata_view(Request& request)
{
L_CALL("HttpClient::retrieve_metadata_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
MsgPack response_obj;
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
assert(!key.empty());
key.remove_prefix(1);
if (key.empty()) {
response_obj = MsgPack::MAP();
for (auto& _key : db_handler.get_metadata_keys()) {
auto metadata = db_handler.get_metadata(_key);
if (!metadata.empty()) {
response_obj[_key] = MsgPack::unserialise(metadata);
}
}
} else {
auto metadata = db_handler.get_metadata(key);
if (metadata.empty()) {
throw Xapian::DocNotFoundError("Metadata not found");
} else {
response_obj = MsgPack::unserialise(metadata);
}
}
request.ready = std::chrono::steady_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Get metadata took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "get_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_metadata_view(Request& request)
{
L_CALL("HttpClient::write_metadata_view()");
auto& decoded_body = request.decoded_body();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
assert(!key.empty());
key.remove_prefix(1);
if (key.empty() || key == "schema" || key == "wal" || key == "nodes" || key == "metrics") {
THROW(ClientError, "Metadata {} is read-only", repr(request.path_parser.get_cmd()));
}
db_handler.set_metadata(key, decoded_body.serialise());
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
write_http_response(request, HTTP_STATUS_OK, selector.empty() ? decoded_body : decoded_body.select(selector));
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Set metadata took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "set_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_metadata_view(Request& request)
{
L_CALL("HttpClient::update_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::delete_metadata_view(Request& request)
{
L_CALL("HttpClient::delete_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::info_view(Request& request)
{
L_CALL("HttpClient::info_view()");
MsgPack response_obj;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Info about a specific document was requested
if (request.path_parser.off_id != nullptr) {
auto id = request.path_parser.get_id();
request.query_parser.rewind();
bool raw = request.query_parser.next("raw") != -1;
response_obj = db_handler.get_document_info(id, raw, request.human);
} else {
response_obj = db_handler.get_database_info();
}
request.ready = std::chrono::steady_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Info took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "info"}
})
.Observe(took / 1e9);
}
void
HttpClient::database_exists_view(Request& request)
{
L_CALL("HttpClient::database_exists_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN);
db_handler.reopen(); // Ensure it can be opened.
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
MsgPack
HttpClient::retrieve_database(const query_field_t& query_field, bool is_root)
{
L_CALL("HttpClient::retrieve_database()");
MsgPack schema;
MsgPack settings;
auto obj = MsgPack::MAP();
// Get active schema
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrieve full schema
schema = db_handler.get_schema()->get_full(true);
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Get index settings (from .xapiand/indices)
auto id = std::string(endpoints.size() == 1 ? endpoints[0].path : unsharded_path(endpoints[0].path).first);
endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{".xapiand/indices"},
false,
query_field.primary);
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
auto did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
settings = document.get_obj();
// Remove schema, ID and version from document:
auto it_e = settings.end();
auto it = settings.find(SCHEMA_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(ID_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(RESERVED_VERSION);
if (it != it_e) {
settings.erase(it);
}
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Add node information for '/':
if (is_root) {
obj.update(node_obj());
}
if (!settings.empty()) {
obj[RESERVED_SETTINGS].update(settings);
}
if (!schema.empty()) {
obj[RESERVED_SCHEMA].update(schema);
}
return obj;
}
void
HttpClient::retrieve_database_view(Request& request)
{
L_CALL("HttpClient::retrieve_database_view()");
assert(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving database took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve_database"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE DATABASE");
}
void
HttpClient::update_database_view(Request& request)
{
L_CALL("HttpClient::update_database_view()");
assert(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (decoded_body.is_map()) {
auto schema_it = decoded_body.find(RESERVED_SCHEMA);
if (schema_it != decoded_body.end()) {
auto& schema = schema_it.value();
db_handler.write_schema(schema, false);
}
}
db_handler.reopen(); // Ensure touch.
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating database took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "update_database"},
})
.Observe(took / 1e9);
}
void
HttpClient::delete_database_view(Request& request)
{
L_CALL("HttpClient::delete_database_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::commit_database_view(Request& request)
{
L_CALL("HttpClient::commit_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.commit(); // Ensure touch.
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Commit took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "commit"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_document_view(Request& request)
{
L_CALL("HttpClient::dump_document_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto document_id = request.path_parser.get_id();
assert(!document_id.empty());
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto obj = db_handler.dump_document(document_id);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_database_view(Request& request)
{
L_CALL("HttpClient::dump_database_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto ct_type = resolve_ct_type(request, MSGPACK_CONTENT_TYPE);
if (ct_type.empty()) {
auto dump_ct_type = resolve_ct_type(request, ct_type_t("application/octet-stream"));
if (dump_ct_type.empty()) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type application/octet-stream not provided in the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED SEARCH");
return;
}
char path[] = "/tmp/xapian_dump.XXXXXX";
int file_descriptor = io::mkstemp(path);
try {
db_handler.dump_documents(file_descriptor);
} catch (...) {
io::close(file_descriptor);
io::unlink(path);
throw;
}
request.ready = std::chrono::steady_clock::now();
size_t content_length = io::lseek(file_descriptor, 0, SEEK_CUR);
io::close(file_descriptor);
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE, "", "", dump_ct_type.to_string(), "", content_length));
write_file(path, true);
return;
}
auto docs = db_handler.dump_documents();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, docs);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::restore_database_view(Request& request)
{
L_CALL("HttpClient::restore_database_view()");
if (request.mode == Request::Mode::STREAM_MSGPACK || request.mode == Request::Mode::STREAM_NDJSON) {
MsgPack obj;
while (request.next_object(obj)) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments, query_field.commit);
}
request.indexer->prepare(std::move(obj));
}
} else {
auto& docs = request.decoded_body();
if (!docs.is_array()) {
THROW(ClientError, "Invalid request body");
}
for (auto& obj : docs) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments, query_field.commit);
}
request.indexer->prepare(std::move(obj));
}
}
if (request.ending) {
if (request.indexer) {
request.indexer->wait();
}
request.ready = std::chrono::steady_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
MsgPack response_obj = {
// { RESPONSE_ENDPOINT, endpoints.to_string() },
{ RESPONSE_PROCESSED, request.indexer ? request.indexer->processed() : 0 },
{ RESPONSE_INDEXED, request.indexer ? request.indexer->indexed() : 0 },
{ RESPONSE_TOTAL, request.indexer ? request.indexer->total() : 0 },
{ RESPONSE_ITEMS, request.indexer ? request.indexer->results() : MsgPack::ARRAY() },
};
if (request.human) {
response_obj[RESPONSE_TOOK] = strings::from_delta(took);
} else {
response_obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
L_TIME("Restore took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "restore"},
})
.Observe(took / 1e9);
}
}
#if XAPIAND_DATABASE_WAL
void
HttpClient::wal_view(Request& request)
{
L_CALL("HttpClient::wal_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler{endpoints};
request.query_parser.rewind();
bool unserialised = request.query_parser.next("raw") == -1;
auto obj = db_handler.repr_wal(0, std::numeric_limits<Xapian::rev>::max(), unserialised);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("WAL took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "wal"},
})
.Observe(took / 1e9);
}
#endif
void
HttpClient::check_database_view(Request& request)
{
L_CALL("HttpClient::check_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler{endpoints};
auto status = db_handler.check();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, status);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Database check took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "db_check"},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_document_view(Request& request)
{
L_CALL("HttpClient::retrieve_document_view()");
auto id = request.path_parser.get_id();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_ID);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
Xapian::docid did;
did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const Data data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto accepted = data.get_accepted(request.accept_set, mime_type(selector));
if (accepted.first == nullptr) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type not accepted by the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED RETRIEVE");
return;
}
auto& locator = *accepted.first;
if (locator.ct_type.empty()) {
// Locator doesn't have a content type, serialize and return as document
auto obj = MsgPack::unserialise(locator.data());
// Detailed info about the document:
if (obj.find(ID_FIELD_NAME) == obj.end()) {
obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
obj[RESPONSE_xSHARD] = shard_num + 1;
// obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
// Locator has content type, return as a blob (an image for instance)
auto ct_type = locator.ct_type;
request.response.blob = locator.data();
#ifdef XAPIAND_DATA_STORAGE
if (locator.type == Locator::Type::stored || locator.type == Locator::Type::compressed_stored) {
if (request.response.blob.empty()) {
auto stored = db_handler.storage_get_stored(locator, did);
request.response.blob = unserialise_string_at(STORED_BLOB, stored);
}
}
#endif
request.ready = std::chrono::steady_clock::now();
request.response.ct_type = ct_type;
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, request.response.blob, false, true, true);
if (!encoded.empty() && encoded.size() <= request.response.blob.size()) {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, encoded, "", ct_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string()));
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE");
}
void
HttpClient::search_view(Request& request)
{
L_CALL("HttpClient::search_view()");
std::string selector_string_holder;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
MSet mset;
MsgPack aggregations;
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
if (!decoded_body.is_map()) {
THROW(ClientError, "Invalid request body");
}
AggregationMatchSpy aggs(decoded_body, db_handler.get_schema());
if (decoded_body.find(RESERVED_QUERYDSL_SELECTOR) != decoded_body.end()) {
auto selector_obj = decoded_body.at(RESERVED_QUERYDSL_SELECTOR);
if (selector_obj.is_string()) {
selector_string_holder = selector_obj.as_str();
selector = selector_string_holder;
} else {
THROW(ClientError, "The {} must be a string", RESERVED_QUERYDSL_SELECTOR);
}
}
mset = db_handler.get_mset(query_field, &decoded_body, &aggs);
aggregations = aggs.get_aggregation().at(RESERVED_AGGS_AGGREGATIONS);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
obj[RESPONSE_COUNT] = mset.size();
if (aggregations) {
obj[RESPONSE_AGGREGATIONS] = aggregations;
}
obj[RESPONSE_HITS] = MsgPack::ARRAY();
auto& hits = obj[RESPONSE_HITS];
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto did = *m;
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const auto data = Data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto hit_obj = MsgPack::MAP();
auto main_locator = data.get("");
if (main_locator != nullptr) {
auto locator_data = main_locator->data();
if (!locator_data.empty()) {
hit_obj = MsgPack::unserialise(locator_data);
}
}
// Detailed info about the document:
if (hit_obj.find(ID_FIELD_NAME) == hit_obj.end()) {
hit_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
hit_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
hit_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
hit_obj[RESPONSE_xSHARD] = shard_num + 1;
// hit_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
hit_obj[RESPONSE_xRANK] = m.get_rank();
hit_obj[RESPONSE_xWEIGHT] = m.get_weight();
hit_obj[RESPONSE_xPERCENT] = m.get_percent();
}
if (!selector.empty()) {
hit_obj = hit_obj.select(selector);
}
hits.append(hit_obj);
}
request.ready = std::chrono::steady_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Searching took {}", strings::from_delta(took));
if (request.human) {
obj[RESPONSE_TOOK] = strings::from_delta(took);
} else {
obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, obj);
if (aggregations) {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "aggregation"},
})
.Observe(took / 1e9);
} else {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "search"},
})
.Observe(took / 1e9);
}
L_SEARCH("FINISH SEARCH");
}
void
HttpClient::count_view(Request& request)
{
L_CALL("HttpClient::count_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
MSet mset{};
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
if (!decoded_body.is_map()) {
THROW(ClientError, "Invalid request body");
}
mset = db_handler.get_mset(query_field, &decoded_body, nullptr);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
}
void
HttpClient::write_status_response(Request& request, enum http_status status, const std::string& message)
{
L_CALL("HttpClient::write_status_response()");
if (request.comments) {
write_http_response(request, status, MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, message.empty() ? MsgPack({ http_status_str(status) }) : strings::split(message, '\n') }
}));
} else {
write_http_response(request, status);
}
}
void
HttpClient::url_resolve(Request& request)
{
L_CALL("HttpClient::url_resolve(request)");
struct http_parser_url u;
std::string b = repr(request.path, true, 0);
L_HTTP("URL: {}", b);
if (http_parser_parse_url(request.path.data(), request.path.size(), 0, &u) != 0) {
L_HTTP_PROTO("Parsing not done");
THROW(ClientError, "Invalid HTTP");
}
L_HTTP_PROTO("HTTP parsing done!");
if ((u.field_set & (1 << UF_PATH )) != 0) {
if (request.path_parser.init(std::string_view(request.path.data() + u.field_data[3].off, u.field_data[3].len)) >= PathParser::State::END) {
THROW(ClientError, "Invalid path");
}
}
if ((u.field_set & (1 << UF_QUERY)) != 0) {
if (request.query_parser.init(std::string_view(b.data() + u.field_data[4].off, u.field_data[4].len)) < 0) {
THROW(ClientError, "Invalid query");
}
}
bool pretty = !opts.no_pretty && (opts.pretty || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("pretty") != -1) {
if (request.query_parser.len != 0u) {
try {
pretty = Serialise::boolean(request.query_parser.get()) == "t";
request.indented = pretty ? DEFAULT_INDENTATION : -1;
} catch (const Exception&) { }
} else {
if (request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
} else {
if (pretty && request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
request.query_parser.rewind();
if (request.query_parser.next("human") != -1) {
if (request.query_parser.len != 0u) {
try {
request.human = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.human = true;
}
} else {
request.human = pretty;
}
bool echo = !opts.no_echo && (opts.echo || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("echo") != -1) {
if (request.query_parser.len != 0u) {
try {
request.echo = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.echo = true;
}
} else {
request.echo = echo;
}
bool comments = !opts.no_comments && (opts.comments || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("comments") != -1) {
if (request.query_parser.len != 0u) {
try {
request.comments = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.comments = true;
}
} else {
request.comments = comments;
}
}
size_t
HttpClient::resolve_index_endpoints(Request& request, const query_field_t& query_field, const MsgPack* settings)
{
L_CALL("HttpClient::resolve_index_endpoints(<request>, <query_field>, <settings>)");
auto paths = expand_paths(request);
endpoints.clear();
for (const auto& path : paths) {
auto index_endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{path},
query_field.writable,
query_field.primary,
settings);
if (index_endpoints.empty()) {
throw Xapian::NetworkError("Endpoint node not available");
}
for (auto& endpoint : index_endpoints) {
endpoints.add(endpoint);
}
}
L_HTTP("Endpoint: -> {}", endpoints.to_string());
return paths.size();
}
std::vector<std::string>
HttpClient::expand_paths(Request& request)
{
L_CALL("HttpClient::expand_paths(<request>)");
std::vector<std::string> paths;
request.path_parser.rewind();
PathParser::State state;
while ((state = request.path_parser.next()) < PathParser::State::END) {
std::string index_path;
auto pth = request.path_parser.get_pth();
if (strings::startswith(pth, '/')) {
pth.remove_prefix(1);
}
index_path.append(pth);
#ifdef XAPIAND_CLUSTERING
MSet mset;
if (strings::endswith(index_path, '*')) {
index_path.pop_back();
auto stripped_index_path = index_path;
if (strings::endswith(stripped_index_path, '/')) {
stripped_index_path.pop_back();
}
Endpoints index_endpoints;
for (auto& node : Node::nodes()) {
if (node->idx) {
index_endpoints.add(Endpoint{strings::format(".xapiand/nodes/{}", node->lower_name())});
}
}
DatabaseHandler db_handler;
db_handler.reset(index_endpoints);
if (stripped_index_path.empty()) {
mset = db_handler.get_all_mset("", 0, 100);
} else {
auto query = Xapian::Query(Xapian::Query::OP_AND_NOT,
Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(prefixed(stripped_index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path + "/.", DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR)))
);
mset = db_handler.get_mset(query, 0, 100);
}
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto document = db_handler.get_document(*m);
index_path = document.get_value(DB_SLOT_ID);
paths.push_back(std::move(index_path));
}
} else {
#endif
paths.push_back(std::move(index_path));
#ifdef XAPIAND_CLUSTERING
}
#endif
}
return paths;
}
query_field_t
HttpClient::query_field_maker(Request& request, int flags)
{
L_CALL("HttpClient::query_field_maker(<request>, <flags>)");
query_field_t query_field;
if ((flags & QUERY_FIELD_WRITABLE) != 0) {
query_field.writable = true;
}
if ((flags & QUERY_FIELD_PRIMARY) != 0) {
query_field.primary = true;
}
if ((flags & QUERY_FIELD_COMMIT) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("commit") != -1) {
query_field.commit = true;
if (request.query_parser.len != 0u) {
try {
query_field.commit = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("version") != -1) {
query_field.version = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_VOLATILE) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("volatile") != -1) {
query_field.primary = true;
if (request.query_parser.len != 0u) {
try {
query_field.primary = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
}
if (((flags & QUERY_FIELD_ID) != 0) || ((flags & QUERY_FIELD_SEARCH) != 0)) {
request.query_parser.rewind();
if (request.query_parser.next("offset") != -1) {
query_field.offset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("check_at_least") != -1) {
query_field.check_at_least = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("limit") != -1) {
query_field.limit = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_SEARCH) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("spelling") != -1) {
query_field.spelling = true;
if (request.query_parser.len != 0u) {
try {
query_field.spelling = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("synonyms") != -1) {
query_field.synonyms = true;
if (request.query_parser.len != 0u) {
try {
query_field.synonyms = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
while (request.query_parser.next("query") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("q") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("sort") != -1) {
query_field.sort.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("metric") != -1) {
query_field.metric = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("icase") != -1) {
query_field.icase = Serialise::boolean(request.query_parser.get()) == "t";
}
request.query_parser.rewind();
if (request.query_parser.next("collapse_max") != -1) {
query_field.collapse_max = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("collapse") != -1) {
query_field.collapse = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy") != -1) {
query_field.is_fuzzy = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_fuzzy = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_fuzzy) {
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_rset") != -1) {
query_field.fuzzy.n_rset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_eset") != -1) {
query_field.fuzzy.n_eset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_term") != -1) {
query_field.fuzzy.n_term = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.field") != -1) {
query_field.fuzzy.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.type") != -1) {
query_field.fuzzy.type.emplace_back(request.query_parser.get());
}
}
request.query_parser.rewind();
if (request.query_parser.next("nearest") != -1) {
query_field.is_nearest = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_nearest = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_nearest) {
query_field.nearest.n_rset = 5;
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_rset") != -1) {
query_field.nearest.n_rset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_eset") != -1) {
query_field.nearest.n_eset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_term") != -1) {
query_field.nearest.n_term = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.field") != -1) {
query_field.nearest.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.type") != -1) {
query_field.nearest.type.emplace_back(request.query_parser.get());
}
}
}
if ((flags & QUERY_FIELD_TIME) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("time") != -1) {
query_field.time = request.query_parser.get();
} else {
query_field.time = "1h";
}
}
if ((flags & QUERY_FIELD_PERIOD) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("period") != -1) {
query_field.period = request.query_parser.get();
} else {
query_field.period = "1m";
}
}
request.query_parser.rewind();
if (request.query_parser.next("selector") != -1) {
query_field.selector = request.query_parser.get();
}
return query_field;
}
void
HttpClient::log_request(Request& request)
{
L_CALL("HttpClient::log_request()");
std::string request_prefix = " 🌎 ";
int priority = LOG_DEBUG;
if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
priority = LOG_INFO;
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
priority = LOG_NOTICE;
}
auto request_text = request.to_text(true);
L(priority, NO_COLOR, "{}{}", request_prefix, strings::indent(request_text, ' ', 4, false));
}
void
HttpClient::log_response(Response& response)
{
L_CALL("HttpClient::log_response()");
std::string response_prefix = " 💊 ";
int priority = LOG_DEBUG;
if ((int)response.status >= 300 && (int)response.status <= 399) {
response_prefix = " 💫 ";
} else if ((int)response.status == 404) {
response_prefix = " 🕸 ";
} else if ((int)response.status >= 400 && (int)response.status <= 499) {
response_prefix = " 💥 ";
priority = LOG_INFO;
} else if ((int)response.status >= 500 && (int)response.status <= 599) {
response_prefix = " 🔥 ";
priority = LOG_NOTICE;
}
auto response_text = response.to_text(true);
L(priority, NO_COLOR, "{}{}", response_prefix, strings::indent(response_text, ' ', 4, false));
}
void
HttpClient::end_http_request(Request& request)
{
L_CALL("HttpClient::end_http_request()");
request.ends = std::chrono::steady_clock::now();
request.atom_ending = true;
request.atom_ended = true;
waiting = false;
if (request.indexer) {
request.indexer->finish();
request.indexer.reset();
}
if (request.log) {
request.log->clear();
request.log.reset();
}
if (request.parser.http_errno != 0u) {
L(LOG_ERR, LIGHT_RED, "HTTP parsing error ({}): {}", http_errno_name(HTTP_PARSER_ERRNO(&request.parser)), http_errno_description(HTTP_PARSER_ERRNO(&request.parser)));
} else {
static constexpr auto fmt_defaut = RED + "\"{}\" {} {} {}";
auto fmt = fmt_defaut.c_str();
int priority = LOG_DEBUG;
if ((int)request.response.status >= 200 && (int)request.response.status <= 299) {
static constexpr auto fmt_2xx = LIGHT_GREY + "\"{}\" {} {} {}";
fmt = fmt_2xx.c_str();
} else if ((int)request.response.status >= 300 && (int)request.response.status <= 399) {
static constexpr auto fmt_3xx = STEEL_BLUE + "\"{}\" {} {} {}";
fmt = fmt_3xx.c_str();
} else if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
static constexpr auto fmt_4xx = SADDLE_BROWN + "\"{}\" {} {} {}";
fmt = fmt_4xx.c_str();
if ((int)request.response.status != 404) {
priority = LOG_INFO;
}
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
static constexpr auto fmt_5xx = LIGHT_PURPLE + "\"{}\" {} {} {}";
fmt = fmt_5xx.c_str();
priority = LOG_NOTICE;
}
if (Logging::log_level > LOG_DEBUG) {
log_response(request.response);
} else if (Logging::log_level == LOG_DEBUG) {
if ((int)request.response.status >= 400 && (int)request.response.status != 404) {
log_request(request);
log_response(request.response);
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count();
Metrics::metrics()
.xapiand_http_requests_summary
.Add({
{"method", http_method_str(request.method)},
{"status", strings::format("{}", request.response.status)},
})
.Observe(took / 1e9);
L(priority, NO_COLOR, fmt, request.head(), (int)request.response.status, strings::from_bytes(request.response.size), strings::from_delta(request.begins, request.ends));
}
L_TIME("Full request took {}, response took {}", strings::from_delta(request.begins, request.ends), strings::from_delta(request.received, request.ends));
auto sent = total_sent_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_sent_bytes
.Increment(sent);
auto received = total_received_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_received_bytes
.Increment(received);
}
ct_type_t
HttpClient::resolve_ct_type(Request& request, ct_type_t ct_type)
{
L_CALL("HttpClient::resolve_ct_type({})", repr(ct_type.to_string()));
if (
ct_type == json_type || ct_type == x_json_type ||
ct_type == yaml_type || ct_type == x_yaml_type ||
ct_type == msgpack_type || ct_type == x_msgpack_type
) {
if (is_acceptable_type(get_acceptable_type(request, json_type), json_type) != nullptr) {
ct_type = json_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_json_type), json_type) != nullptr) {
ct_type = x_json_type;
} else if (is_acceptable_type(get_acceptable_type(request, yaml_type), yaml_type) != nullptr) {
ct_type = yaml_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_yaml_type), yaml_type) != nullptr) {
ct_type = x_yaml_type;
} else if (is_acceptable_type(get_acceptable_type(request, msgpack_type), msgpack_type) != nullptr) {
ct_type = msgpack_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_msgpack_type), x_msgpack_type) != nullptr) {
ct_type = x_msgpack_type;
}
}
std::vector<ct_type_t> ct_types;
if (
ct_type == json_type || ct_type == x_json_type ||
ct_type == yaml_type || ct_type == x_yaml_type ||
ct_type == msgpack_type || ct_type == x_msgpack_type
) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(std::move(ct_type));
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
const auto accepted_ct_type = is_acceptable_type(accepted_type, ct_types);
if (accepted_ct_type == nullptr) {
return no_type;
}
return *accepted_ct_type;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const ct_type_t& ct_type)
{
L_CALL("HttpClient::is_acceptable_type({}, {})", repr(ct_type_pattern.to_string()), repr(ct_type.to_string()));
bool type_ok = false, subtype_ok = false;
if (ct_type_pattern.first == "*") {
type_ok = true;
} else {
type_ok = ct_type_pattern.first == ct_type.first;
}
if (ct_type_pattern.second == "*") {
subtype_ok = true;
} else {
subtype_ok = ct_type_pattern.second == ct_type.second;
}
if (type_ok && subtype_ok) {
return &ct_type;
}
return nullptr;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const std::vector<ct_type_t>& ct_types)
{
L_CALL("HttpClient::is_acceptable_type(({}, <ct_types>)", repr(ct_type_pattern.to_string()));
for (auto& ct_type : ct_types) {
if (is_acceptable_type(ct_type_pattern, ct_type) != nullptr) {
return &ct_type;
}
}
return nullptr;
}
template <typename T>
const ct_type_t&
HttpClient::get_acceptable_type(Request& request, const T& ct)
{
L_CALL("HttpClient::get_acceptable_type()");
if (request.accept_set.empty()) {
return no_type;
}
for (const auto& accept : request.accept_set) {
if (is_acceptable_type(accept.ct_type, ct)) {
return accept.ct_type;
}
}
const auto& accept = *request.accept_set.begin();
auto indent = accept.indent;
if (indent != -1) {
request.indented = indent;
}
return accept.ct_type;
}
std::pair<std::string, std::string>
HttpClient::serialize_response(const MsgPack& obj, const ct_type_t& ct_type, int indent, bool serialize_error)
{
L_CALL("HttpClient::serialize_response({}, {}, {}, {})", repr(obj.to_string(), true, '\'', 200), repr(ct_type.to_string()), indent, serialize_error);
if (ct_type == no_type) {
return std::make_pair("", "");
}
if (is_acceptable_type(ct_type, json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), x_json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, yaml_type) != nullptr) {
return std::make_pair(obj.to_string(indent), yaml_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_yaml_type) != nullptr) {
return std::make_pair(obj.to_string(indent), x_yaml_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), x_msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, html_type) != nullptr) {
std::function<std::string(const msgpack::object&)> html_serialize = serialize_error ? msgpack_to_html_error : msgpack_to_html;
return std::make_pair(obj.external(html_serialize), html_type.to_string() + "; charset=utf-8");
}
/*if (is_acceptable_type(ct_type, text_type)) {
error:
{{ ERROR_CODE }} - {{ MESSAGE }}
obj:
{{ key1 }}: {{ val1 }}
{{ key2 }}: {{ val2 }}
...
array:
{{ val1 }}, {{ val2 }}, ...
}*/
THROW(SerialisationError, "Type is not serializable");
}
void
HttpClient::write_http_response(Request& request, enum http_status status, const MsgPack& obj, const std::string& location)
{
L_CALL("HttpClient::write_http_response()");
if (obj.is_undefined()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE, "", location));
return;
}
std::vector<ct_type_t> ct_types;
if (
request.ct_type == json_type || request.ct_type == x_json_type ||
request.ct_type == yaml_type || request.ct_type == x_yaml_type ||
request.ct_type == msgpack_type || request.ct_type == x_msgpack_type ||
request.ct_type.empty()
) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(request.ct_type);
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
try {
auto result = serialize_response(obj, accepted_type, request.indented, (int)status >= 400);
if (Logging::log_level >= LOG_DEBUG && request.response.size <= 1024 * 10) {
if (is_acceptable_type(accepted_type, json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, yaml_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_yaml_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, html_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, text_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (!obj.empty()) {
request.response.text.append("...");
}
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, result.first, false, true, true);
if (!encoded.empty() && encoded.size() <= result.first.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, result.second, readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, result.first, location, result.second, readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, result.first, location, result.second));
}
} catch (const SerialisationError& exc) {
status = HTTP_STATUS_NOT_ACCEPTABLE;
std::string response_str;
if (request.comments) {
MsgPack response_err = MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type " + accepted_type.to_string() + " " + exc.what() }) } }
});
response_str = response_err.to_string(request.indented);
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, response_str, false, true, true);
if (!encoded.empty() && encoded.size() <= response_str.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, accepted_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, response_str, location, accepted_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, response_str, location, accepted_type.to_string()));
}
return;
}
}
Encoding
HttpClient::resolve_encoding(Request& request)
{
L_CALL("HttpClient::resolve_encoding()");
if (request.accept_encoding_set.empty()) {
return Encoding::none;
}
constexpr static auto _ = phf::make_phf({
hhl("gzip"),
hhl("deflate"),
hhl("identity"),
hhl("*"),
});
for (const auto& encoding : request.accept_encoding_set) {
switch (_.fhhl(encoding.encoding)) {
case _.fhhl("gzip"):
return Encoding::gzip;
case _.fhhl("deflate"):
return Encoding::deflate;
case _.fhhl("identity"):
return Encoding::identity;
case _.fhhl("*"):
return Encoding::identity;
default:
continue;
}
}
return Encoding::unknown;
}
std::string
HttpClient::readable_encoding(Encoding e)
{
L_CALL("Request::readable_encoding()");
switch (e) {
case Encoding::none:
return "none";
case Encoding::gzip:
return "gzip";
case Encoding::deflate:
return "deflate";
case Encoding::identity:
return "identity";
default:
return "Encoding:UNKNOWN";
}
}
std::string
HttpClient::encoding_http_response(Response& response, Encoding e, const std::string& response_obj, bool chunk, bool start, bool end)
{
L_CALL("HttpClient::encoding_http_response({})", repr(response_obj));
bool gzip = false;
switch (e) {
case Encoding::gzip:
gzip = true;
[[fallthrough]];
case Encoding::deflate: {
if (chunk) {
if (start) {
response.encoding_compressor.reset(nullptr, 0, gzip);
response.encoding_compressor.begin();
}
if (end) {
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size(), DeflateCompressData::FINISH_COMPRESS);
return ret;
}
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size());
return ret;
}
response.encoding_compressor.reset(response_obj.data(), response_obj.size(), gzip);
response.it_compressor = response.encoding_compressor.begin();
std::string encoding_respose;
while (response.it_compressor) {
encoding_respose.append(*response.it_compressor);
++response.it_compressor;
}
return encoding_respose;
}
case Encoding::identity:
return response_obj;
default:
return std::string();
}
}
std::string
HttpClient::__repr__() const
{
return strings::format(STEEL_BLUE + "<HttpClient {{cnt:{}, sock:{}}}{}{}{}{}{}{}{}{}>",
use_count(),
sock,
is_runner() ? " " + DARK_STEEL_BLUE + "(runner)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(worker)" + STEEL_BLUE,
is_running_loop() ? " " + DARK_STEEL_BLUE + "(running loop)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(stopped loop)" + STEEL_BLUE,
is_detaching() ? " " + ORANGE + "(detaching)" + STEEL_BLUE : "",
is_idle() ? " " + DARK_STEEL_BLUE + "(idle)" + STEEL_BLUE : "",
is_waiting() ? " " + LIGHT_STEEL_BLUE + "(waiting)" + STEEL_BLUE : "",
is_running() ? " " + DARK_ORANGE + "(running)" + STEEL_BLUE : "",
is_shutting_down() ? " " + ORANGE + "(shutting down)" + STEEL_BLUE : "",
is_closed() ? " " + ORANGE + "(closed)" + STEEL_BLUE : "");
}
Request::Request(HttpClient* client)
: mode{Mode::FULL},
view{nullptr},
type_encoding{Encoding::none},
begining{true},
ending{false},
atom_ending{false},
atom_ended{false},
raw_peek{0},
raw_offset{0},
size{0},
echo{false},
human{false},
comments{true},
indented{-1},
expect_100{false},
closing{false},
begins{std::chrono::steady_clock::now()}
{
parser.data = client;
http_parser_init(&parser, HTTP_REQUEST);
}
Request::~Request() noexcept
{
try {
if (indexer) {
indexer->finish();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
try {
if (log) {
log->clear();
log.reset();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
MsgPack
Request::decode(std::string_view body)
{
L_CALL("Request::decode({})", repr(body));
std::string ct_type_str = ct_type.to_string();
if (ct_type_str.empty()) {
ct_type_str = JSON_CONTENT_TYPE;
}
MsgPack decoded;
rapidjson::Document rdoc;
constexpr static auto _ = phf::make_phf({
hhl(JSON_CONTENT_TYPE),
hhl(X_JSON_CONTENT_TYPE),
hhl(YAML_CONTENT_TYPE),
hhl(X_YAML_CONTENT_TYPE),
hhl(MSGPACK_CONTENT_TYPE),
hhl(X_MSGPACK_CONTENT_TYPE),
hhl(NDJSON_CONTENT_TYPE),
hhl(X_NDJSON_CONTENT_TYPE),
hhl(FORM_URLENCODED_CONTENT_TYPE),
hhl(X_FORM_URLENCODED_CONTENT_TYPE),
});
switch (_.fhhl(ct_type_str)) {
case _.fhhl(NDJSON_CONTENT_TYPE):
case _.fhhl(X_NDJSON_CONTENT_TYPE):
decoded = MsgPack::ARRAY();
for (auto json : Split<std::string_view>(body, '\n')) {
json_load(rdoc, json);
decoded.append(rdoc);
}
ct_type = json_type;
return decoded;
case _.fhhl(JSON_CONTENT_TYPE):
case _.fhhl(X_JSON_CONTENT_TYPE):
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
return decoded;
case _.fhhl(YAML_CONTENT_TYPE):
case _.fhhl(X_YAML_CONTENT_TYPE):
yaml_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = yaml_type;
return decoded;
case _.fhhl(MSGPACK_CONTENT_TYPE):
case _.fhhl(X_MSGPACK_CONTENT_TYPE):
decoded = MsgPack::unserialise(body);
ct_type = msgpack_type;
return decoded;
case _.fhhl(FORM_URLENCODED_CONTENT_TYPE):
case _.fhhl(X_FORM_URLENCODED_CONTENT_TYPE):
try {
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
} catch (const std::exception&) {
decoded = MsgPack(body);
ct_type = msgpack_type;
}
return decoded;
default:
decoded = MsgPack(body);
return decoded;
}
}
MsgPack&
Request::decoded_body()
{
L_CALL("Request::decoded_body()");
if (_decoded_body.is_undefined()) {
if (!raw.empty()) {
_decoded_body = decode(raw);
}
}
return _decoded_body;
}
bool
Request::append(const char* at, size_t length)
{
L_CALL("Request::append(<at>, <length>)");
bool signal_pending = false;
switch (mode) {
case Mode::FULL:
raw.append(std::string_view(at, length));
break;
case Mode::STREAM:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
raw.append(std::string_view(at, length));
signal_pending = true;
break;
case Mode::STREAM_NDJSON:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
raw.append(std::string_view(at, length));
auto new_raw_offset = raw.find_first_of('\n', raw_peek);
while (new_raw_offset != std::string::npos) {
auto json = std::string_view(raw).substr(raw_offset, new_raw_offset - raw_offset);
raw_offset = raw_peek = new_raw_offset + 1;
new_raw_offset = raw.find_first_of('\n', raw_peek);
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
}
if (!length) {
auto json = std::string_view(raw).substr(raw_offset);
raw_offset = raw_peek = raw.size();
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
break;
case Mode::STREAM_MSGPACK:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
unpacker.reserve_buffer(length);
memcpy(unpacker.buffer(), at, length);
unpacker.buffer_consumed(length);
try {
msgpack::object_handle result;
while (unpacker.next(result)) {
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(result.get());
}
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
break;
}
return signal_pending;
}
bool
Request::wait()
{
if (mode != Request::Mode::FULL) {
// Wait for a pending raw body for one second (1000000us) and flush
// pending signals before processing the request, otherwise retry
// checking for empty/ended requests or closed connections.
if (!pending.wait(1000000)) {
return false;
}
while (pending.tryWaitMany(std::numeric_limits<ssize_t>::max())) { }
}
return true;
}
bool
Request::next(std::string_view& str_view)
{
L_CALL("Request::next(<&str_view>)");
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
assert(mode == Mode::STREAM);
if (raw_offset == raw.size()) {
return false;
}
str_view = std::string_view(raw).substr(raw_offset);
raw_offset = raw.size();
return true;
}
bool
Request::next_object(MsgPack& obj)
{
L_CALL("Request::next_object(<&obj>)");
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
assert(mode == Mode::STREAM_MSGPACK || mode == Mode::STREAM_NDJSON);
std::lock_guard<std::mutex> lk(objects_mtx);
if (objects.empty()) {
return false;
}
obj = std::move(objects.front());
objects.pop_front();
return true;
}
std::string
Request::head()
{
L_CALL("Request::head()");
auto parser_method = HTTP_PARSER_METHOD(&parser);
if (parser_method != method) {
return strings::format("{} <- {} {} HTTP/{}.{}",
http_method_str(method),
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
return strings::format("{} {} HTTP/{}.{}",
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
std::string
Request::to_text(bool decode)
{
L_CALL("Request::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto request_headers_color = no_col.c_str();
auto request_head_color = no_col.c_str();
auto request_text_color = no_col.c_str();
switch (method) {
case HTTP_OPTIONS: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_INFO: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_HEAD: {
// rgb(144, 18, 254)
static constexpr auto _request_headers_color = rgba(100, 64, 131, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(100, 64, 131);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(100, 64, 131);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_GET: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_SEARCH: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COUNT: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_POST: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DUMP: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_RESTORE: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_OPEN: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_CLOSE: {
// rgb(227, 32, 40)
static constexpr auto _request_headers_color = rgba(101, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(101, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(101, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PATCH: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_STORE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PUT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COMMIT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DELETE: {
// rgb(246, 64, 68)
static constexpr auto _request_headers_color = rgba(151, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(151, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(151, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
default:
break;
};
auto request_text = request_head_color + head() + "\n" + request_headers_color + headers + request_text_color;
if (!raw.empty()) {
if (!decode) {
if (raw.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
} else {
request_text += "<body " + repr(raw, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(raw);
request_text += strings::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
request_text += b64_data;
request_text += '\a';
} else {
if (raw.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
} else {
auto& decoded = decoded_body();
if (
ct_type == json_type ||
ct_type == x_json_type ||
ct_type == yaml_type ||
ct_type == x_yaml_type ||
ct_type == msgpack_type ||
ct_type == x_msgpack_type
) {
request_text += decoded.to_string(DEFAULT_INDENTATION);
} else {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
}
}
}
} else if (!text.empty()) {
if (!decode) {
if (text.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(text.size()) + ">";
} else {
request_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (text.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(text.size()) + ">";
} else {
request_text += text;
}
} else if (size) {
request_text += "<body " + strings::from_bytes(size) + ">";
}
return request_text;
}
Response::Response()
: status{static_cast<http_status>(0)},
size{0}
{
}
std::string
Response::to_text(bool decode)
{
L_CALL("Response::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto response_headers_color = no_col.c_str();
auto response_head_color = no_col.c_str();
auto response_text_color = no_col.c_str();
if ((int)status >= 200 && (int)status <= 299) {
static constexpr auto _response_headers_color = rgba(68, 136, 68, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 68);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 68);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 300 && (int)status <= 399) {
static constexpr auto _response_headers_color = rgba(68, 136, 120, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 120);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 120);
response_text_color = _response_text_color.c_str();
} else if ((int)status == 404) {
static constexpr auto _response_headers_color = rgba(116, 100, 77, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(116, 100, 77);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(116, 100, 77);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 400 && (int)status <= 499) {
static constexpr auto _response_headers_color = rgba(183, 70, 17, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(183, 70, 17);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(183, 70, 17);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 500 && (int)status <= 599) {
static constexpr auto _response_headers_color = rgba(190, 30, 10, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(190, 30, 10);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(190, 30, 10);
response_text_color = _response_text_color.c_str();
}
auto response_text = response_head_color + head + "\n" + response_headers_color + headers + response_text_color;
if (!blob.empty()) {
if (!decode) {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + repr(blob, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(blob);
response_text += strings::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
response_text += b64_data;
response_text += '\a';
} else {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
}
}
} else if (!text.empty()) {
if (!decode) {
if (size > 1024 * 10) {
response_text += "<body " + strings::from_bytes(size) + ">";
} else {
response_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (size > 1024 * 10) {
response_text += "<body " + strings::from_bytes(size) + ">";
} else {
response_text += text;
}
} else if (size) {
response_text += "<body " + strings::from_bytes(size) + ">";
}
return response_text;
}
Exceptions: Move Xapian related exceptions out of exceptions.h
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "http_client.h"
#include "config.h" // for XAPIAND_CLUSTERING, XAPIAND_CHAISCRIPT, XAPIAND_DATABASE_WAL
#include <cassert> // for assert
#include <errno.h> // for errno
#include <exception> // for std::exception
#include <functional> // for std::function
#include <regex> // for std::regex, std::regex_constants
#include <signal.h> // for SIGTERM
#include <sysexits.h> // for EX_SOFTWARE
#include <syslog.h> // for LOG_WARNING, LOG_ERR, LOG...
#include <utility> // for std::move
#ifdef USE_ICU
#include <unicode/uvernum.h>
#endif
#ifdef XAPIAND_CHAISCRIPT
#include "chaiscript/chaiscript_defines.hpp" // for chaiscript::Build_Info
#endif
#include "cppcodec/base64_rfc4648.hpp" // for cppcodec::base64_rfc4648
#include "database/handler.h" // for DatabaseHandler, DocIndexer
#include "database/utils.h" // for query_field_t
#include "database/pool.h" // for DatabasePool
#include "database/schema.h" // for Schema
#include "endpoint.h" // for Endpoints, Endpoint
#include "epoch.hh" // for epoch::now
#include "error.hh" // for error:name, error::description
#include "ev/ev++.h" // for async, io, loop_ref (ptr ...
#include "exception_xapian.h" // for Exception, SerialisationError
#include "field_parser.h" // for FieldParser, FieldParserError
#include "hashes.hh" // for hhl
#include "http_utils.h" // for catch_http_errors
#include "io.hh" // for close, write, unlink
#include "log.h" // for L_CALL, L_ERR, LOG_DEBUG
#include "logger.h" // for Logging
#include "manager.h" // for XapiandManager
#include "metrics.h" // for Metrics::metrics
#include "mime_types.hh" // for mime_type
#include "msgpack.h" // for MsgPack, msgpack::object
#include "aggregations/aggregations.h" // for AggregationMatchSpy
#include "node.h" // for Node::local_node, Node::leader_node
#include "opts.h" // for opts::*
#include "package.h" // for Package::*
#include "phf.hh" // for phf::*
#include "rapidjson/document.h" // for Document
#include "reserved/aggregations.h" // for RESERVED_AGGS_*
#include "reserved/fields.h" // for RESERVED_*
#include "reserved/query_dsl.h" // for RESERVED_QUERYDSL_*
#include "reserved/schema.h" // for RESERVED_VERSION
#include "response.h" // for RESPONSE_*
#include "serialise.h" // for Serialise::boolean
#include "strings.hh" // for strings::from_delta
#include "system.hh" // for check_compiler, check_OS, check_architecture
#include "xapian.h" // for Xapian::major_version, Xapian::minor_version
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_CONN
// #define L_CONN L_GREEN
// #undef L_HTTP
// #define L_HTTP L_RED
// #undef L_HTTP_WIRE
// #define L_HTTP_WIRE L_ORANGE
// #undef L_HTTP_PROTO
// #define L_HTTP_PROTO L_TEAL
#define QUERY_FIELD_PRIMARY (1 << 0)
#define QUERY_FIELD_WRITABLE (1 << 1)
#define QUERY_FIELD_COMMIT (1 << 2)
#define QUERY_FIELD_SEARCH (1 << 3)
#define QUERY_FIELD_ID (1 << 4)
#define QUERY_FIELD_TIME (1 << 5)
#define QUERY_FIELD_PERIOD (1 << 6)
#define QUERY_FIELD_VOLATILE (1 << 7)
#define DEFAULT_INDENTATION 2
static const std::regex header_params_re(R"(\s*;\s*([a-z]+)=(\d+(?:\.\d+)?))", std::regex::optimize);
static const std::regex header_accept_re(R"(([-a-z+]+|\*)/([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::regex header_accept_encoding_re(R"(([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::string eol("\r\n");
// Available commands
#define METHODS_OPTIONS() \
OPTION(DELETE, "delete") \
OPTION(GET, "get") \
OPTION(HEAD, "head") \
OPTION(POST, "post") \
OPTION(PUT, "put") \
OPTION(CONNECT, "connect") \
OPTION(OPTIONS, "options") \
OPTION(TRACE, "trace") \
OPTION(PATCH, "patch") \
OPTION(PURGE, "purge") \
OPTION(LINK, "link") \
OPTION(UNLINK, "unlink") \
OPTION(CHECK, "check") \
OPTION(CLOSE, "close") \
OPTION(COMMIT, "commit") \
OPTION(COPY, "copy") \
OPTION(COUNT, "count") \
OPTION(DUMP, "dump") \
OPTION(FLUSH, "flush") \
OPTION(INFO, "info") \
OPTION(LOCK, "lock") \
OPTION(MERGE, "merge") \
OPTION(MOVE, "move") \
OPTION(OPEN, "open") \
OPTION(QUIT, "quit") \
OPTION(RESTORE, "restore") \
OPTION(SEARCH, "search") \
OPTION(STORE, "store") \
OPTION(UNLOCK, "unlock") \
OPTION(UPDATE, "update")
constexpr static auto http_methods = phf::make_phf({
#define OPTION(name, str) hhl(str),
METHODS_OPTIONS()
#undef OPTION
});
bool is_range(std::string_view str) {
try {
FieldParser fieldparser(str);
fieldparser.parse();
return fieldparser.is_range();
} catch (const FieldParserError&) {
return false;
}
}
bool can_preview(const ct_type_t& ct_type) {
#define CONTENT_TYPE_OPTIONS() \
OPTION("application/eps") \
OPTION("application/pdf") \
OPTION("application/postscript") \
OPTION("application/x-bzpdf") \
OPTION("application/x-eps") \
OPTION("application/x-gzpdf") \
OPTION("application/x-pdf") \
OPTION("application/x-photoshop") \
OPTION("application/photoshop") \
OPTION("application/psd")
constexpr static auto _ = phf::make_phf({
#define OPTION(ct) hhl(ct),
CONTENT_TYPE_OPTIONS()
#undef OPTION
});
switch (_.fhhl(ct_type.to_string())) {
#define OPTION(ct) case _.fhhl(ct):
CONTENT_TYPE_OPTIONS()
#undef OPTION
return true;
default:
return ct_type.first == "image";
}
}
/*
* _ _ _ _
* | | | | |_| |_ _ __
* | |_| | __| __| '_ \
* | _ | |_| |_| |_) |
* |_| |_|\__|\__| .__/
* |_|
*/
HttpClient::HttpClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: BaseClient<HttpClient>(std::move(parent_), ev_loop_, ev_flags_),
new_request(std::make_shared<Request>(this))
{
++XapiandManager::http_clients();
Metrics::metrics()
.xapiand_http_connections
.Increment();
// Initialize new_request->begins as soon as possible (for correctly timing disconnecting clients)
new_request->begins = std::chrono::steady_clock::now();
L_CONN("New Http Client, {} client(s) of a total of {} connected.", XapiandManager::http_clients().load(), XapiandManager::total_clients().load());
}
HttpClient::~HttpClient() noexcept
{
try {
if (XapiandManager::http_clients().fetch_sub(1) == 0) {
L_CRIT("Inconsistency in number of http clients");
sig_exit(-EX_SOFTWARE);
}
if (is_shutting_down() && !is_idle()) {
L_INFO("HTTP client killed!");
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
std::string
HttpClient::http_response(Request& request, enum http_status status, int mode, const std::string& body, const std::string& location, const std::string& ct_type, const std::string& ct_encoding, size_t content_length) {
L_CALL("HttpClient::http_response()");
std::string head;
std::string headers;
std::string head_sep;
std::string headers_sep;
std::string response_body;
if ((mode & HTTP_STATUS_RESPONSE) != 0) {
assert(request.response.status == static_cast<http_status>(0));
request.response.status = status;
auto http_major = request.parser.http_major;
auto http_minor = request.parser.http_minor;
if (http_major == 0 && http_minor == 0) {
http_major = 1;
}
head += strings::format("HTTP/{}.{} {} ", http_major, http_minor, status);
head += http_status_str(status);
head_sep += eol;
if ((mode & HTTP_HEADER_RESPONSE) == 0) {
headers_sep += eol;
}
}
assert(request.response.status != static_cast<http_status>(0));
if ((mode & HTTP_HEADER_RESPONSE) != 0) {
headers += "Server: " + Package::STRING + eol;
// if (!endpoints.empty()) {
// headers += "Database: " + endpoints.to_string() + eol;
// }
request.ends = std::chrono::steady_clock::now();
if (request.human) {
headers += strings::format("Response-Time: {}", strings::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count())) + eol;
if (request.ready >= request.processing) {
headers += strings::format("Operation-Time: {}", strings::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count())) + eol;
}
} else {
headers += strings::format("Response-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count() / 1e9) + eol;
if (request.ready >= request.processing) {
headers += strings::format("Operation-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count() / 1e9) + eol;
}
}
if ((mode & HTTP_OPTIONS_RESPONSE) != 0) {
headers += "Allow: GET, POST, PUT, PATCH, UPDATE, STORE, DELETE, HEAD, OPTIONS" + eol;
}
if (!location.empty()) {
headers += "Location: " + location + eol;
}
if ((mode & HTTP_CONTENT_TYPE_RESPONSE) != 0 && !ct_type.empty()) {
headers += "Content-Type: " + ct_type + eol;
}
if ((mode & HTTP_CONTENT_ENCODING_RESPONSE) != 0 && !ct_encoding.empty()) {
headers += "Content-Encoding: " + ct_encoding + eol;
}
if ((mode & HTTP_CONTENT_LENGTH_RESPONSE) != 0) {
headers += strings::format("Content-Length: {}", content_length) + eol;
} else {
headers += strings::format("Content-Length: {}", body.size()) + eol;
}
headers_sep += eol;
}
if ((mode & HTTP_BODY_RESPONSE) != 0) {
response_body += body;
}
auto this_response_size = response_body.size();
request.response.size += this_response_size;
if (Logging::log_level >= LOG_DEBUG) {
request.response.head += head;
request.response.headers += headers;
}
return head + head_sep + headers + headers_sep + response_body;
}
template <typename Func>
int
HttpClient::handled_errors(Request& request, Func&& func)
{
L_CALL("HttpClient::handled_errors()");
auto http_errors = catch_http_errors(std::forward<Func>(func));
if (http_errors.error_code != HTTP_STATUS_OK) {
if (request.response.status != static_cast<http_status>(0)) {
// There was an error, but request already had written stuff...
// disconnect client!
detach();
} else if (request.comments) {
write_http_response(request, http_errors.error_code, MsgPack({
{ RESPONSE_xSTATUS, static_cast<unsigned>(http_errors.error_code) },
{ RESPONSE_xMESSAGE, strings::split(http_errors.error, '\n') }
}));
} else {
write_http_response(request, http_errors.error_code);
}
request.atom_ending = true;
}
return http_errors.ret;
}
size_t
HttpClient::pending_requests() const
{
std::lock_guard<std::mutex> lk(runner_mutex);
auto requests_size = requests.size();
if (requests_size && requests.front()->response.status != static_cast<http_status>(0)) {
--requests_size;
}
return requests_size;
}
bool
HttpClient::is_idle() const
{
L_CALL("HttpClient::is_idle() {{is_waiting:{}, is_running:{}, write_queue_empty:{}, pending_requests:{}}}", is_waiting(), is_running(), write_queue.empty(), pending_requests());
return !is_waiting() && !is_running() && write_queue.empty() && !pending_requests();
}
void
HttpClient::destroy_impl()
{
L_CALL("HttpClient::destroy_impl()");
BaseClient<HttpClient>::destroy_impl();
// HttpClient could be using indexer (which would block)
// if destroying is received, finish indexer:
std::unique_lock<std::mutex> lk(runner_mutex);
if (!requests.empty()) {
auto& request = *requests.front();
if (request.indexer) {
request.indexer->finish();
}
}
}
ssize_t
HttpClient::on_read(const char* buf, ssize_t received)
{
L_CALL("HttpClient::on_read(<buf>, {})", received);
if (received <= 0) {
std::string reason;
if (received < 0) {
reason = strings::format("{} ({}): {}", error::name(errno), errno, error::description(errno));
if (errno != ENOTCONN && errno != ECONNRESET && errno != ESPIPE) {
L_NOTICE("HTTP client connection closed unexpectedly after {}: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
} else {
reason = "EOF";
}
auto state = HTTP_PARSER_STATE(&new_request->parser);
if (state != s_start_req) {
L_NOTICE("HTTP client closed unexpectedly after {}: Not in final HTTP state ({}): {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), state, reason);
close();
return received;
}
if (is_waiting()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There was still a request in progress: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
if (!write_queue.empty()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There is still pending data: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
if (pending_requests()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There are still pending requests: {}", strings::from_delta(new_request->begins, std::chrono::steady_clock::now()), reason);
close();
return received;
}
// HTTP client normally closed connection.
close();
return received;
}
L_HTTP_WIRE("HttpClient::on_read: {} bytes", received);
ssize_t parsed = http_parser_execute(&new_request->parser, &parser_settings, buf, received);
if (parsed != received) {
enum http_status error_code = HTTP_STATUS_BAD_REQUEST;
http_errno err = HTTP_PARSER_ERRNO(&new_request->parser);
if (err == HPE_INVALID_METHOD) {
if (new_request->response.status == static_cast<http_status>(0)) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
end_http_request(*new_request);
}
} else {
std::string message(http_errno_description(err));
L_DEBUG("HTTP parser error: {}", HTTP_PARSER_ERRNO(&new_request->parser) != HPE_OK ? message : "incomplete request");
if (new_request->response.status == static_cast<http_status>(0)) {
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, strings::split(message, '\n') }
}));
} else {
write_http_response(*new_request, error_code);
}
end_http_request(*new_request);
}
}
detach();
}
return received;
}
void
HttpClient::on_read_file(const char* /*buf*/, ssize_t received)
{
L_CALL("HttpClient::on_read_file(<buf>, {})", received);
L_ERR("Not Implemented: HttpClient::on_read_file: {} bytes", received);
}
void
HttpClient::on_read_file_done()
{
L_CALL("HttpClient::on_read_file_done()");
L_ERR("Not Implemented: HttpClient::on_read_file_done");
}
// HTTP parser callbacks.
const http_parser_settings HttpClient::parser_settings = {
HttpClient::message_begin_cb,
HttpClient::url_cb,
HttpClient::status_cb,
HttpClient::header_field_cb,
HttpClient::header_value_cb,
HttpClient::headers_complete_cb,
HttpClient::body_cb,
HttpClient::message_complete_cb,
HttpClient::chunk_header_cb,
HttpClient::chunk_complete_cb,
};
inline std::string readable_http_parser_flags(http_parser* parser) {
std::vector<std::string> values;
if ((parser->flags & F_CHUNKED) == F_CHUNKED) values.push_back("F_CHUNKED");
if ((parser->flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) values.push_back("F_CONNECTION_KEEP_ALIVE");
if ((parser->flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) values.push_back("F_CONNECTION_CLOSE");
if ((parser->flags & F_CONNECTION_UPGRADE) == F_CONNECTION_UPGRADE) values.push_back("F_CONNECTION_UPGRADE");
if ((parser->flags & F_TRAILING) == F_TRAILING) values.push_back("F_TRAILING");
if ((parser->flags & F_UPGRADE) == F_UPGRADE) values.push_back("F_UPGRADE");
if ((parser->flags & F_SKIPBODY) == F_SKIPBODY) values.push_back("F_SKIPBODY");
if ((parser->flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) values.push_back("F_CONTENTLENGTH");
return strings::join(values, "|");
}
int
HttpClient::message_begin_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_begin(parser);
});
}
int
HttpClient::url_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_url(parser, at, length);
});
}
int
HttpClient::status_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_status(parser, at, length);
});
}
int
HttpClient::header_field_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_field(parser, at, length);
});
}
int
HttpClient::header_value_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_value(parser, at, length);
});
}
int
HttpClient::headers_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_headers_complete(parser);
});
}
int
HttpClient::body_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_body(parser, at, length);
});
}
int
HttpClient::message_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_complete(parser);
});
}
int
HttpClient::chunk_header_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_header(parser);
});
}
int
HttpClient::chunk_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_complete(parser);
});
}
int
HttpClient::on_message_begin([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_begin(<parser>)");
L_HTTP_PROTO("on_message_begin {{state:{}, header_state:{}}}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)));
waiting = true;
new_request->begins = std::chrono::steady_clock::now();
L_TIMED_VAR(new_request->log, 10s,
"Request taking too long...",
"Request took too long!");
return 0;
}
int
HttpClient::on_url(http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_url(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_url {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->method = HTTP_PARSER_METHOD(parser);
new_request->path.append(at, length);
return 0;
}
int
HttpClient::on_status([[maybe_unused]] http_parser* parser, [[maybe_unused]] const char* at, [[maybe_unused]] size_t length)
{
L_CALL("HttpClient::on_status(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_status {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
return 0;
}
int
HttpClient::on_header_field([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_field(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_field {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->_header_name = std::string(at, length);
return 0;
}
int
HttpClient::on_header_value([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_value(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_value {{state:{}, header_state:{}}}: {}", enum_name(HTTP_PARSER_STATE(parser)), enum_name(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
auto _header_value = std::string_view(at, length);
if (Logging::log_level >= LOG_DEBUG) {
new_request->headers.append(new_request->_header_name);
new_request->headers.append(": ");
new_request->headers.append(_header_value);
new_request->headers.append(eol);
}
constexpr static auto _ = phf::make_phf({
hhl("expect"),
hhl("100-continue"),
hhl("content-type"),
hhl("accept"),
hhl("accept-encoding"),
hhl("http-method-override"),
hhl("x-http-method-override"),
});
switch (_.fhhl(new_request->_header_name)) {
case _.fhhl("expect"):
case _.fhhl("100-continue"):
// Respond with HTTP/1.1 100 Continue
new_request->expect_100 = true;
break;
case _.fhhl("content-type"):
new_request->ct_type = ct_type_t(_header_value);
break;
case _.fhhl("accept"): {
static AcceptLRU accept_sets;
auto value = strings::lower(_header_value);
auto lookup = accept_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
int indent = -1;
double q = 1.0;
if (next->length(3) != 0) {
auto param = next->str(3);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
} else if (next_param->str(1) == "indent") {
indent = strict_stoi(next_param->str(2));
if (indent < 0) { indent = 0;
} else if (indent > 16) { indent = 16; }
}
++next_param;
}
}
lookup.second.emplace(i, q, ct_type_t(next->str(1), next->str(2)), indent);
++next;
++i;
}
accept_sets.emplace(value, lookup.second);
}
new_request->accept_set = std::move(lookup.second);
break;
}
case _.fhhl("accept-encoding"): {
static AcceptEncodingLRU accept_encoding_sets;
auto value = strings::lower(_header_value);
auto lookup = accept_encoding_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_encoding_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
double q = 1.0;
if (next->length(2) != 0) {
auto param = next->str(2);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
}
++next_param;
}
} else {
}
lookup.second.emplace(i, q, next->str(1));
++next;
++i;
}
accept_encoding_sets.emplace(value, lookup.second);
}
new_request->accept_encoding_set = std::move(lookup.second);
break;
}
case _.fhhl("x-http-method-override"):
case _.fhhl("http-method-override"): {
switch (http_methods.fhhl(_header_value)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "{} header must use the POST method", repr(new_request->_header_name)); \
} \
new_request->method = HTTP_##name; \
break;
METHODS_OPTIONS()
#undef OPTION
default:
parser->http_errno = HPE_INVALID_METHOD;
break;
}
break;
}
}
return 0;
}
int
HttpClient::on_headers_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_headers_complete(<parser>)");
L_HTTP_PROTO("on_headers_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
// Prepare the request view
if (int err = prepare()) {
end_http_request(*new_request);
return err;
}
if likely(!closed && !new_request->atom_ending) {
if likely(new_request->view) {
if (new_request->mode != Request::Mode::FULL) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || new_request != requests.front()) {
requests.push_back(new_request); // Enqueue streamed request
}
}
}
}
return 0;
}
int
HttpClient::on_body([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_body(<parser>, <at>, {})", length);
L_HTTP_PROTO("on_body {{state:{}, header_state:{}, flags:[{}]}}: {}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser),
repr(at, length));
new_request->size += length;
if likely(!closed && !new_request->atom_ending) {
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || new_request->view) {
signal_pending = new_request->append(at, length);
}
if (new_request->view) {
if (signal_pending) {
new_request->pending.signal();
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
}
}
return 0;
}
int
HttpClient::on_message_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_complete(<parser>)");
L_HTTP_PROTO("on_message_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
if (Logging::log_level > LOG_DEBUG) {
log_request(*new_request);
}
if likely(!closed && !new_request->atom_ending) {
new_request->atom_ending = true;
std::shared_ptr<Request> request = std::make_shared<Request>(this);
std::swap(new_request, request);
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || request->view) {
request->append(nullptr, 0); // flush pending stuff
signal_pending = true; // always signal pending
}
if (request->view) {
if (signal_pending) {
request->pending.signal(); // always signal, so view continues ending
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || request != requests.front()) {
requests.push_back(std::move(request)); // Enqueue request
}
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
} else {
end_http_request(*request);
}
}
waiting = false;
return 0;
}
int
HttpClient::on_chunk_header([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_header(<parser>)");
L_HTTP_PROTO("on_chunk_header {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::on_chunk_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_complete(<parser>)");
L_HTTP_PROTO("on_chunk_complete {{state:{}, header_state:{}, flags:[{}]}}",
enum_name(HTTP_PARSER_STATE(parser)),
enum_name(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::prepare()
{
L_CALL("HttpClient::prepare()");
L_TIMED_VAR(request.log, 1s,
"Response taking too long: {}",
"Response took too long: {}",
request.head());
new_request->received = std::chrono::steady_clock::now();
if (new_request->parser.http_major == 0 || (new_request->parser.http_major == 1 && new_request->parser.http_minor == 0)) {
new_request->closing = true;
}
if ((new_request->parser.flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) {
new_request->closing = false;
}
if ((new_request->parser.flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) {
new_request->closing = true;
}
if (new_request->accept_set.empty()) {
if (!new_request->ct_type.empty()) {
new_request->accept_set.emplace(0, 1.0, new_request->ct_type, 0);
}
new_request->accept_set.emplace(1, 1.0, any_type, 0);
}
new_request->type_encoding = resolve_encoding(*new_request);
if (new_request->type_encoding == Encoding::unknown) {
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response encoding gzip, deflate or identity not provided in the Accept-Encoding header" }) } }
}));
} else {
write_http_response(*new_request, error_code);
}
return 1;
}
url_resolve(*new_request);
auto id = new_request->path_parser.get_id();
auto has_pth = new_request->path_parser.has_pth();
auto cmd = new_request->path_parser.get_cmd();
if (!cmd.empty()) {
auto mapping = cmd;
mapping.remove_prefix(1);
switch (http_methods.fhhl(mapping)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "HTTP Mappings must use GET or POST method"); \
} \
new_request->method = HTTP_##name; \
cmd = ""; \
break;
METHODS_OPTIONS()
#undef OPTION
}
}
switch (new_request->method) {
case HTTP_SEARCH:
if (id.empty()) {
new_request->view = &HttpClient::search_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COUNT:
if (id.empty()) {
new_request->view = &HttpClient::count_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_INFO:
if (id.empty()) {
new_request->view = &HttpClient::info_view;
} else {
new_request->view = &HttpClient::info_view;
}
break;
case HTTP_HEAD:
if (id.empty()) {
new_request->view = &HttpClient::database_exists_view;
} else {
new_request->view = &HttpClient::document_exists_view;
}
break;
case HTTP_GET:
if (!cmd.empty() && id.empty()) {
if (!has_pth && cmd == ":metrics") {
new_request->view = &HttpClient::metrics_view;
} else {
new_request->view = &HttpClient::retrieve_metadata_view;
}
} else if (!id.empty()) {
if (is_range(id)) {
new_request->view = &HttpClient::search_view;
} else {
new_request->view = &HttpClient::retrieve_document_view;
}
} else {
new_request->view = &HttpClient::retrieve_database_view;
}
break;
case HTTP_POST:
if (!cmd.empty() && id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else if (!id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_PUT:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::write_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::write_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_PATCH:
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::update_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_STORE:
if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DELETE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::delete_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::delete_document_view;
} else if (has_pth) {
new_request->view = &HttpClient::delete_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COMMIT:
if (id.empty()) {
new_request->view = &HttpClient::commit_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DUMP:
if (id.empty()) {
new_request->view = &HttpClient::dump_database_view;
} else {
new_request->view = &HttpClient::dump_document_view;
}
break;
case HTTP_RESTORE:
if (id.empty()) {
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) {
if (new_request->ct_type == ndjson_type || new_request->ct_type == x_ndjson_type) {
new_request->mode = Request::Mode::STREAM_NDJSON;
} else if (new_request->ct_type == msgpack_type || new_request->ct_type == x_msgpack_type) {
new_request->mode = Request::Mode::STREAM_MSGPACK;
}
}
new_request->view = &HttpClient::restore_database_view;
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_CHECK:
if (id.empty()) {
new_request->view = &HttpClient::check_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_FLUSH:
if (opts.admin_commands && id.empty() && !has_pth) {
// Flush both databases and clients by default (unless one is specified)
new_request->query_parser.rewind();
int flush_databases = new_request->query_parser.next("databases");
new_request->query_parser.rewind();
int flush_clients = new_request->query_parser.next("clients");
if (flush_databases != -1 || flush_clients == -1) {
XapiandManager::database_pool()->cleanup(true);
}
if (flush_clients != -1 || flush_databases == -1) {
XapiandManager::manager()->shutdown(0, 0);
}
write_http_response(*new_request, HTTP_STATUS_OK);
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_OPTIONS:
write(http_response(*new_request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_OPTIONS_RESPONSE | HTTP_BODY_RESPONSE));
break;
case HTTP_QUIT:
if (opts.admin_commands && !has_pth && id.empty()) {
XapiandManager::try_shutdown(true);
write_http_response(*new_request, HTTP_STATUS_OK);
destroy();
detach();
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
#if XAPIAND_DATABASE_WAL
case HTTP_WAL:
if (id.empty()) {
new_request->view = &HttpClient::wal_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
#endif
default: {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
new_request->parser.http_errno = HPE_INVALID_METHOD;
return 1;
}
}
if (!new_request->view && Logging::log_level < LOG_DEBUG) {
return 1;
}
if (new_request->expect_100) {
// Return "100 Continue" if client sent "Expect: 100-continue"
write(http_response(*new_request, HTTP_STATUS_CONTINUE, HTTP_STATUS_RESPONSE));
// Go back to unknown response state:
new_request->response.head.clear();
new_request->response.status = static_cast<http_status>(0);
}
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH && new_request->parser.content_length) {
if (new_request->mode == Request::Mode::STREAM_MSGPACK) {
new_request->unpacker.reserve_buffer(new_request->parser.content_length);
} else {
new_request->raw.reserve(new_request->parser.content_length);
}
}
return 0;
}
void
HttpClient::process(Request& request)
{
L_CALL("HttpClient::process()");
L_OBJ_BEGIN("HttpClient::process:BEGIN");
L_OBJ_END("HttpClient::process:END");
handled_errors(request, [&]{
(this->*request.view)(request);
return 0;
});
}
void
HttpClient::operator()()
{
L_CALL("HttpClient::operator()()");
L_CONN("Start running in worker...");
std::unique_lock<std::mutex> lk(runner_mutex);
while (!requests.empty() && !closed) {
Request& request = *requests.front();
if (request.atom_ended) {
requests.pop_front();
continue;
}
request.ending = request.atom_ending.load();
lk.unlock();
// wait for the request to be ready
if (!request.ending && !request.wait()) {
lk.lock();
continue;
}
try {
assert(request.view);
process(request);
request.begining = false;
} catch (...) {
request.begining = false;
end_http_request(request);
lk.lock();
requests.pop_front();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: HTTP client ended with an unhandled exception");
detach();
throw;
}
if (request.ending) {
end_http_request(request);
auto closing = request.closing;
lk.lock();
requests.pop_front();
if (closing) {
running = false;
L_CONN("Running in worker ended after request closing.");
lk.unlock();
destroy();
detach();
return;
}
} else {
lk.lock();
}
}
running = false;
L_CONN("Running in replication worker ended. {{requests_empty:{}, closed:{}, is_shutting_down:{}}}", requests.empty(), closed.load(), is_shutting_down());
lk.unlock();
if (is_shutting_down() && is_idle()) {
detach();
return;
}
redetach(); // try re-detaching if already flagged as detaching
}
MsgPack
HttpClient::node_obj()
{
L_CALL("HttpClient::node_obj()");
endpoints.clear();
auto leader_node = Node::leader_node();
endpoints.add(Endpoint{".xapiand/nodes", leader_node});
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
auto local_node = Node::local_node();
auto document = db_handler.get_document(local_node->lower_name());
auto obj = document.get_obj();
#ifdef XAPIAND_CLUSTERING
auto nodes = MsgPack::ARRAY();
for (auto& node : Node::nodes()) {
if (node->idx) {
auto node_obj = MsgPack::MAP();
node_obj["idx"] = node->idx;
node_obj["name"] = node->name();
if (Node::is_active(node)) {
node_obj["host"] = node->host();
node_obj["http_port"] = node->http_port;
node_obj["remote_port"] = node->remote_port;
node_obj["replication_port"] = node->replication_port;
node_obj["active"] = true;
} else {
node_obj["active"] = false;
}
nodes.push_back(node_obj);
}
}
#endif
obj.update(MsgPack({
#ifdef XAPIAND_CLUSTERING
{ "cluster_name", opts.cluster_name },
#endif
{ "server", {
{ "name", Package::NAME },
{ "url", Package::URL },
{ "issues", Package::BUGREPORT },
{ "version", Package::VERSION },
{ "revision", Package::REVISION },
{ "hash", Package::HASH },
{ "compiler", check_compiler() },
{ "os", check_OS() },
{ "arch", check_architecture() },
} },
{ "versions", {
{ "Xapiand", Package::REVISION.empty() ? Package::VERSION : strings::format("{}_{}", Package::VERSION, Package::REVISION) },
{ "Xapian", strings::format("{}.{}.{}", Xapian::major_version(), Xapian::minor_version(), Xapian::revision()) },
#ifdef XAPIAND_CHAISCRIPT
{ "ChaiScript", strings::format("{}.{}", chaiscript::Build_Info::version_major(), chaiscript::Build_Info::version_minor()) },
#endif
#ifdef USE_ICU
{ "ICU", strings::format("{}.{}", U_ICU_VERSION_MAJOR_NUM, U_ICU_VERSION_MINOR_NUM) },
#endif
} },
{ "options", {
{ "verbosity", opts.verbosity },
{ "processors", opts.processors },
{ "limits", {
// { "max_clients", opts.max_clients },
{ "max_database_readers", opts.max_database_readers },
} },
{ "cache", {
{ "database_pool_size", opts.database_pool_size },
{ "schema_pool_size", opts.schema_pool_size },
{ "scripts_cache_size", opts.scripts_cache_size },
#ifdef XAPIAND_CLUSTERING
{ "resolver_cache_size", opts.resolver_cache_size },
#endif
} },
{ "thread_pools", {
{ "num_shards", opts.num_shards },
{ "num_replicas", opts.num_replicas },
{ "num_http_servers", opts.num_http_servers },
{ "num_http_clients", opts.num_http_clients },
#ifdef XAPIAND_CLUSTERING
{ "num_remote_servers", opts.num_remote_servers },
{ "num_remote_clients", opts.num_remote_clients },
{ "num_replication_servers", opts.num_replication_servers },
{ "num_replication_clients", opts.num_replication_clients },
#endif
{ "num_async_wal_writers", opts.num_async_wal_writers },
{ "num_doc_matchers", opts.num_doc_matchers },
{ "num_doc_preparers", opts.num_doc_preparers },
{ "num_doc_indexers", opts.num_doc_indexers },
{ "num_committers", opts.num_committers },
{ "num_fsynchers", opts.num_fsynchers },
#ifdef XAPIAND_CLUSTERING
{ "num_replicators", opts.num_replicators },
{ "num_discoverers", opts.num_discoverers },
#endif
} },
} },
#ifdef XAPIAND_CLUSTERING
{ "nodes", nodes },
#endif
}));
return obj;
}
void
HttpClient::metrics_view(Request& request)
{
L_CALL("HttpClient::metrics_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
auto server_info = XapiandManager::server_metrics();
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE | HTTP_BODY_RESPONSE, server_info, "", "text/plain", "", server_info.size()));
}
void
HttpClient::document_exists_view(Request& request)
{
L_CALL("HttpClient::document_exists_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
db_handler.get_document(request.path_parser.get_id()).validate();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
void
HttpClient::delete_document_view(Request& request)
{
L_CALL("HttpClient::delete_document_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
std::string document_id(request.path_parser.get_id());
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.delete_document(document_id, query_field.commit);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_NO_CONTENT);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Deletion took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "delete"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_document_view(Request& request)
{
L_CALL("HttpClient::write_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
auto indexed = db_handler.index(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
request.ready = std::chrono::steady_clock::now();
std::string location;
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (request.echo) {
auto it = response_obj.find(ID_FIELD_NAME);
if (document_id.empty()) {
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, document_id_obj.as_str());
response_obj[ID_FIELD_NAME] = std::move(document_id_obj);
} else {
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, it.value().as_str());
}
} else {
if (it == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj, location);
} else {
if (document_id.empty()) {
auto it = response_obj.find(ID_FIELD_NAME);
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, document_id_obj.as_str());
} else {
location = strings::format("/{}/{}", unsharded_path(endpoints[0].path).first, it.value().as_str());
}
}
write_http_response(request, document_id.empty() ? HTTP_STATUS_CREATED : HTTP_STATUS_NO_CONTENT, MsgPack(), location);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Indexing took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "index"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_document_view(Request& request)
{
L_CALL("HttpClient::update_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
assert(!document_id.empty());
request.processing = std::chrono::steady_clock::now();
std::string operation;
DataType indexed;
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (request.method == HTTP_PATCH) {
operation = "patch";
indexed = db_handler.patch(document_id, query_field.version, decoded_body, query_field.commit);
} else if (request.method == HTTP_STORE) {
operation = "store";
indexed = db_handler.update(document_id, query_field.version, true, decoded_body, query_field.commit, request.ct_type == json_type || request.ct_type == x_json_type || request.ct_type == yaml_type || request.ct_type == x_yaml_type || request.ct_type == msgpack_type || request.ct_type == x_msgpack_type || request.ct_type.empty() ? mime_type(selector) : request.ct_type);
} else {
operation = "update";
indexed = db_handler.update(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
}
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (response_obj.find(ID_FIELD_NAME) == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", operation},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_metadata_view(Request& request)
{
L_CALL("HttpClient::retrieve_metadata_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
MsgPack response_obj;
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
assert(!key.empty());
key.remove_prefix(1);
if (key.empty()) {
response_obj = MsgPack::MAP();
for (auto& _key : db_handler.get_metadata_keys()) {
auto metadata = db_handler.get_metadata(_key);
if (!metadata.empty()) {
response_obj[_key] = MsgPack::unserialise(metadata);
}
}
} else {
auto metadata = db_handler.get_metadata(key);
if (metadata.empty()) {
throw Xapian::DocNotFoundError("Metadata not found");
} else {
response_obj = MsgPack::unserialise(metadata);
}
}
request.ready = std::chrono::steady_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Get metadata took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "get_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_metadata_view(Request& request)
{
L_CALL("HttpClient::write_metadata_view()");
auto& decoded_body = request.decoded_body();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
assert(!key.empty());
key.remove_prefix(1);
if (key.empty() || key == "schema" || key == "wal" || key == "nodes" || key == "metrics") {
THROW(ClientError, "Metadata {} is read-only", repr(request.path_parser.get_cmd()));
}
db_handler.set_metadata(key, decoded_body.serialise());
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
write_http_response(request, HTTP_STATUS_OK, selector.empty() ? decoded_body : decoded_body.select(selector));
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Set metadata took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "set_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_metadata_view(Request& request)
{
L_CALL("HttpClient::update_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::delete_metadata_view(Request& request)
{
L_CALL("HttpClient::delete_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::info_view(Request& request)
{
L_CALL("HttpClient::info_view()");
MsgPack response_obj;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Info about a specific document was requested
if (request.path_parser.off_id != nullptr) {
auto id = request.path_parser.get_id();
request.query_parser.rewind();
bool raw = request.query_parser.next("raw") != -1;
response_obj = db_handler.get_document_info(id, raw, request.human);
} else {
response_obj = db_handler.get_database_info();
}
request.ready = std::chrono::steady_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Info took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "info"}
})
.Observe(took / 1e9);
}
void
HttpClient::database_exists_view(Request& request)
{
L_CALL("HttpClient::database_exists_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN);
db_handler.reopen(); // Ensure it can be opened.
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
MsgPack
HttpClient::retrieve_database(const query_field_t& query_field, bool is_root)
{
L_CALL("HttpClient::retrieve_database()");
MsgPack schema;
MsgPack settings;
auto obj = MsgPack::MAP();
// Get active schema
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrieve full schema
schema = db_handler.get_schema()->get_full(true);
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Get index settings (from .xapiand/indices)
auto id = std::string(endpoints.size() == 1 ? endpoints[0].path : unsharded_path(endpoints[0].path).first);
endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{".xapiand/indices"},
false,
query_field.primary);
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
auto did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
settings = document.get_obj();
// Remove schema, ID and version from document:
auto it_e = settings.end();
auto it = settings.find(SCHEMA_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(ID_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(RESERVED_VERSION);
if (it != it_e) {
settings.erase(it);
}
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Add node information for '/':
if (is_root) {
obj.update(node_obj());
}
if (!settings.empty()) {
obj[RESERVED_SETTINGS].update(settings);
}
if (!schema.empty()) {
obj[RESERVED_SCHEMA].update(schema);
}
return obj;
}
void
HttpClient::retrieve_database_view(Request& request)
{
L_CALL("HttpClient::retrieve_database_view()");
assert(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving database took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve_database"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE DATABASE");
}
void
HttpClient::update_database_view(Request& request)
{
L_CALL("HttpClient::update_database_view()");
assert(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (decoded_body.is_map()) {
auto schema_it = decoded_body.find(RESERVED_SCHEMA);
if (schema_it != decoded_body.end()) {
auto& schema = schema_it.value();
db_handler.write_schema(schema, false);
}
}
db_handler.reopen(); // Ensure touch.
request.ready = std::chrono::steady_clock::now();
if (request.echo) {
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating database took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "update_database"},
})
.Observe(took / 1e9);
}
void
HttpClient::delete_database_view(Request& request)
{
L_CALL("HttpClient::delete_database_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::commit_database_view(Request& request)
{
L_CALL("HttpClient::commit_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.commit(); // Ensure touch.
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Commit took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "commit"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_document_view(Request& request)
{
L_CALL("HttpClient::dump_document_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto document_id = request.path_parser.get_id();
assert(!document_id.empty());
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto obj = db_handler.dump_document(document_id);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_database_view(Request& request)
{
L_CALL("HttpClient::dump_database_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto ct_type = resolve_ct_type(request, MSGPACK_CONTENT_TYPE);
if (ct_type.empty()) {
auto dump_ct_type = resolve_ct_type(request, ct_type_t("application/octet-stream"));
if (dump_ct_type.empty()) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type application/octet-stream not provided in the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED SEARCH");
return;
}
char path[] = "/tmp/xapian_dump.XXXXXX";
int file_descriptor = io::mkstemp(path);
try {
db_handler.dump_documents(file_descriptor);
} catch (...) {
io::close(file_descriptor);
io::unlink(path);
throw;
}
request.ready = std::chrono::steady_clock::now();
size_t content_length = io::lseek(file_descriptor, 0, SEEK_CUR);
io::close(file_descriptor);
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE, "", "", dump_ct_type.to_string(), "", content_length));
write_file(path, true);
return;
}
auto docs = db_handler.dump_documents();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, docs);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::restore_database_view(Request& request)
{
L_CALL("HttpClient::restore_database_view()");
if (request.mode == Request::Mode::STREAM_MSGPACK || request.mode == Request::Mode::STREAM_NDJSON) {
MsgPack obj;
while (request.next_object(obj)) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments, query_field.commit);
}
request.indexer->prepare(std::move(obj));
}
} else {
auto& docs = request.decoded_body();
if (!docs.is_array()) {
THROW(ClientError, "Invalid request body");
}
for (auto& obj : docs) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments, query_field.commit);
}
request.indexer->prepare(std::move(obj));
}
}
if (request.ending) {
if (request.indexer) {
request.indexer->wait();
}
request.ready = std::chrono::steady_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
MsgPack response_obj = {
// { RESPONSE_ENDPOINT, endpoints.to_string() },
{ RESPONSE_PROCESSED, request.indexer ? request.indexer->processed() : 0 },
{ RESPONSE_INDEXED, request.indexer ? request.indexer->indexed() : 0 },
{ RESPONSE_TOTAL, request.indexer ? request.indexer->total() : 0 },
{ RESPONSE_ITEMS, request.indexer ? request.indexer->results() : MsgPack::ARRAY() },
};
if (request.human) {
response_obj[RESPONSE_TOOK] = strings::from_delta(took);
} else {
response_obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
L_TIME("Restore took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "restore"},
})
.Observe(took / 1e9);
}
}
#if XAPIAND_DATABASE_WAL
void
HttpClient::wal_view(Request& request)
{
L_CALL("HttpClient::wal_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler{endpoints};
request.query_parser.rewind();
bool unserialised = request.query_parser.next("raw") == -1;
auto obj = db_handler.repr_wal(0, std::numeric_limits<Xapian::rev>::max(), unserialised);
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("WAL took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "wal"},
})
.Observe(took / 1e9);
}
#endif
void
HttpClient::check_database_view(Request& request)
{
L_CALL("HttpClient::check_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::steady_clock::now();
DatabaseHandler db_handler{endpoints};
auto status = db_handler.check();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, status);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Database check took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "db_check"},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_document_view(Request& request)
{
L_CALL("HttpClient::retrieve_document_view()");
auto id = request.path_parser.get_id();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_ID);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
Xapian::docid did;
did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const Data data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto accepted = data.get_accepted(request.accept_set, mime_type(selector));
if (accepted.first == nullptr) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type not accepted by the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED RETRIEVE");
return;
}
auto& locator = *accepted.first;
if (locator.ct_type.empty()) {
// Locator doesn't have a content type, serialize and return as document
auto obj = MsgPack::unserialise(locator.data());
// Detailed info about the document:
if (obj.find(ID_FIELD_NAME) == obj.end()) {
obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
obj[RESPONSE_xSHARD] = shard_num + 1;
// obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
// Locator has content type, return as a blob (an image for instance)
auto ct_type = locator.ct_type;
request.response.blob = locator.data();
#ifdef XAPIAND_DATA_STORAGE
if (locator.type == Locator::Type::stored || locator.type == Locator::Type::compressed_stored) {
if (request.response.blob.empty()) {
auto stored = db_handler.storage_get_stored(locator, did);
request.response.blob = unserialise_string_at(STORED_BLOB, stored);
}
}
#endif
request.ready = std::chrono::steady_clock::now();
request.response.ct_type = ct_type;
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, request.response.blob, false, true, true);
if (!encoded.empty() && encoded.size() <= request.response.blob.size()) {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, encoded, "", ct_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string()));
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving took {}", strings::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE");
}
void
HttpClient::search_view(Request& request)
{
L_CALL("HttpClient::search_view()");
std::string selector_string_holder;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
MSet mset;
MsgPack aggregations;
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
if (!decoded_body.is_map()) {
THROW(ClientError, "Invalid request body");
}
AggregationMatchSpy aggs(decoded_body, db_handler.get_schema());
if (decoded_body.find(RESERVED_QUERYDSL_SELECTOR) != decoded_body.end()) {
auto selector_obj = decoded_body.at(RESERVED_QUERYDSL_SELECTOR);
if (selector_obj.is_string()) {
selector_string_holder = selector_obj.as_str();
selector = selector_string_holder;
} else {
THROW(ClientError, "The {} must be a string", RESERVED_QUERYDSL_SELECTOR);
}
}
mset = db_handler.get_mset(query_field, &decoded_body, &aggs);
aggregations = aggs.get_aggregation().at(RESERVED_AGGS_AGGREGATIONS);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
obj[RESPONSE_COUNT] = mset.size();
if (aggregations) {
obj[RESPONSE_AGGREGATIONS] = aggregations;
}
obj[RESPONSE_HITS] = MsgPack::ARRAY();
auto& hits = obj[RESPONSE_HITS];
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto did = *m;
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const auto data = Data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto hit_obj = MsgPack::MAP();
auto main_locator = data.get("");
if (main_locator != nullptr) {
auto locator_data = main_locator->data();
if (!locator_data.empty()) {
hit_obj = MsgPack::unserialise(locator_data);
}
}
// Detailed info about the document:
if (hit_obj.find(ID_FIELD_NAME) == hit_obj.end()) {
hit_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
hit_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
hit_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
hit_obj[RESPONSE_xSHARD] = shard_num + 1;
// hit_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
hit_obj[RESPONSE_xRANK] = m.get_rank();
hit_obj[RESPONSE_xWEIGHT] = m.get_weight();
hit_obj[RESPONSE_xPERCENT] = m.get_percent();
}
if (!selector.empty()) {
hit_obj = hit_obj.select(selector);
}
hits.append(hit_obj);
}
request.ready = std::chrono::steady_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Searching took {}", strings::from_delta(took));
if (request.human) {
obj[RESPONSE_TOOK] = strings::from_delta(took);
} else {
obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, obj);
if (aggregations) {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "aggregation"},
})
.Observe(took / 1e9);
} else {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "search"},
})
.Observe(took / 1e9);
}
L_SEARCH("FINISH SEARCH");
}
void
HttpClient::count_view(Request& request)
{
L_CALL("HttpClient::count_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
MSet mset{};
request.processing = std::chrono::steady_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
if (!decoded_body.is_map()) {
THROW(ClientError, "Invalid request body");
}
mset = db_handler.get_mset(query_field, &decoded_body, nullptr);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
request.ready = std::chrono::steady_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
}
void
HttpClient::write_status_response(Request& request, enum http_status status, const std::string& message)
{
L_CALL("HttpClient::write_status_response()");
if (request.comments) {
write_http_response(request, status, MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, message.empty() ? MsgPack({ http_status_str(status) }) : strings::split(message, '\n') }
}));
} else {
write_http_response(request, status);
}
}
void
HttpClient::url_resolve(Request& request)
{
L_CALL("HttpClient::url_resolve(request)");
struct http_parser_url u;
std::string b = repr(request.path, true, 0);
L_HTTP("URL: {}", b);
if (http_parser_parse_url(request.path.data(), request.path.size(), 0, &u) != 0) {
L_HTTP_PROTO("Parsing not done");
THROW(ClientError, "Invalid HTTP");
}
L_HTTP_PROTO("HTTP parsing done!");
if ((u.field_set & (1 << UF_PATH )) != 0) {
if (request.path_parser.init(std::string_view(request.path.data() + u.field_data[3].off, u.field_data[3].len)) >= PathParser::State::END) {
THROW(ClientError, "Invalid path");
}
}
if ((u.field_set & (1 << UF_QUERY)) != 0) {
if (request.query_parser.init(std::string_view(b.data() + u.field_data[4].off, u.field_data[4].len)) < 0) {
THROW(ClientError, "Invalid query");
}
}
bool pretty = !opts.no_pretty && (opts.pretty || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("pretty") != -1) {
if (request.query_parser.len != 0u) {
try {
pretty = Serialise::boolean(request.query_parser.get()) == "t";
request.indented = pretty ? DEFAULT_INDENTATION : -1;
} catch (const Exception&) { }
} else {
if (request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
} else {
if (pretty && request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
request.query_parser.rewind();
if (request.query_parser.next("human") != -1) {
if (request.query_parser.len != 0u) {
try {
request.human = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.human = true;
}
} else {
request.human = pretty;
}
bool echo = !opts.no_echo && (opts.echo || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("echo") != -1) {
if (request.query_parser.len != 0u) {
try {
request.echo = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.echo = true;
}
} else {
request.echo = echo;
}
bool comments = !opts.no_comments && (opts.comments || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("comments") != -1) {
if (request.query_parser.len != 0u) {
try {
request.comments = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.comments = true;
}
} else {
request.comments = comments;
}
}
size_t
HttpClient::resolve_index_endpoints(Request& request, const query_field_t& query_field, const MsgPack* settings)
{
L_CALL("HttpClient::resolve_index_endpoints(<request>, <query_field>, <settings>)");
auto paths = expand_paths(request);
endpoints.clear();
for (const auto& path : paths) {
auto index_endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{path},
query_field.writable,
query_field.primary,
settings);
if (index_endpoints.empty()) {
throw Xapian::NetworkError("Endpoint node not available");
}
for (auto& endpoint : index_endpoints) {
endpoints.add(endpoint);
}
}
L_HTTP("Endpoint: -> {}", endpoints.to_string());
return paths.size();
}
std::vector<std::string>
HttpClient::expand_paths(Request& request)
{
L_CALL("HttpClient::expand_paths(<request>)");
std::vector<std::string> paths;
request.path_parser.rewind();
PathParser::State state;
while ((state = request.path_parser.next()) < PathParser::State::END) {
std::string index_path;
auto pth = request.path_parser.get_pth();
if (strings::startswith(pth, '/')) {
pth.remove_prefix(1);
}
index_path.append(pth);
#ifdef XAPIAND_CLUSTERING
MSet mset;
if (strings::endswith(index_path, '*')) {
index_path.pop_back();
auto stripped_index_path = index_path;
if (strings::endswith(stripped_index_path, '/')) {
stripped_index_path.pop_back();
}
Endpoints index_endpoints;
for (auto& node : Node::nodes()) {
if (node->idx) {
index_endpoints.add(Endpoint{strings::format(".xapiand/nodes/{}", node->lower_name())});
}
}
DatabaseHandler db_handler;
db_handler.reset(index_endpoints);
if (stripped_index_path.empty()) {
mset = db_handler.get_all_mset("", 0, 100);
} else {
auto query = Xapian::Query(Xapian::Query::OP_AND_NOT,
Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(prefixed(stripped_index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path + "/.", DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR)))
);
mset = db_handler.get_mset(query, 0, 100);
}
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto document = db_handler.get_document(*m);
index_path = document.get_value(DB_SLOT_ID);
paths.push_back(std::move(index_path));
}
} else {
#endif
paths.push_back(std::move(index_path));
#ifdef XAPIAND_CLUSTERING
}
#endif
}
return paths;
}
query_field_t
HttpClient::query_field_maker(Request& request, int flags)
{
L_CALL("HttpClient::query_field_maker(<request>, <flags>)");
query_field_t query_field;
if ((flags & QUERY_FIELD_WRITABLE) != 0) {
query_field.writable = true;
}
if ((flags & QUERY_FIELD_PRIMARY) != 0) {
query_field.primary = true;
}
if ((flags & QUERY_FIELD_COMMIT) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("commit") != -1) {
query_field.commit = true;
if (request.query_parser.len != 0u) {
try {
query_field.commit = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("version") != -1) {
query_field.version = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_VOLATILE) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("volatile") != -1) {
query_field.primary = true;
if (request.query_parser.len != 0u) {
try {
query_field.primary = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
}
if (((flags & QUERY_FIELD_ID) != 0) || ((flags & QUERY_FIELD_SEARCH) != 0)) {
request.query_parser.rewind();
if (request.query_parser.next("offset") != -1) {
query_field.offset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("check_at_least") != -1) {
query_field.check_at_least = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("limit") != -1) {
query_field.limit = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_SEARCH) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("spelling") != -1) {
query_field.spelling = true;
if (request.query_parser.len != 0u) {
try {
query_field.spelling = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("synonyms") != -1) {
query_field.synonyms = true;
if (request.query_parser.len != 0u) {
try {
query_field.synonyms = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
while (request.query_parser.next("query") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("q") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("sort") != -1) {
query_field.sort.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("metric") != -1) {
query_field.metric = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("icase") != -1) {
query_field.icase = Serialise::boolean(request.query_parser.get()) == "t";
}
request.query_parser.rewind();
if (request.query_parser.next("collapse_max") != -1) {
query_field.collapse_max = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("collapse") != -1) {
query_field.collapse = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy") != -1) {
query_field.is_fuzzy = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_fuzzy = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_fuzzy) {
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_rset") != -1) {
query_field.fuzzy.n_rset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_eset") != -1) {
query_field.fuzzy.n_eset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_term") != -1) {
query_field.fuzzy.n_term = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.field") != -1) {
query_field.fuzzy.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.type") != -1) {
query_field.fuzzy.type.emplace_back(request.query_parser.get());
}
}
request.query_parser.rewind();
if (request.query_parser.next("nearest") != -1) {
query_field.is_nearest = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_nearest = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_nearest) {
query_field.nearest.n_rset = 5;
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_rset") != -1) {
query_field.nearest.n_rset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_eset") != -1) {
query_field.nearest.n_eset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_term") != -1) {
query_field.nearest.n_term = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.field") != -1) {
query_field.nearest.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.type") != -1) {
query_field.nearest.type.emplace_back(request.query_parser.get());
}
}
}
if ((flags & QUERY_FIELD_TIME) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("time") != -1) {
query_field.time = request.query_parser.get();
} else {
query_field.time = "1h";
}
}
if ((flags & QUERY_FIELD_PERIOD) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("period") != -1) {
query_field.period = request.query_parser.get();
} else {
query_field.period = "1m";
}
}
request.query_parser.rewind();
if (request.query_parser.next("selector") != -1) {
query_field.selector = request.query_parser.get();
}
return query_field;
}
void
HttpClient::log_request(Request& request)
{
L_CALL("HttpClient::log_request()");
std::string request_prefix = " 🌎 ";
int priority = LOG_DEBUG;
if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
priority = LOG_INFO;
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
priority = LOG_NOTICE;
}
auto request_text = request.to_text(true);
L(priority, NO_COLOR, "{}{}", request_prefix, strings::indent(request_text, ' ', 4, false));
}
void
HttpClient::log_response(Response& response)
{
L_CALL("HttpClient::log_response()");
std::string response_prefix = " 💊 ";
int priority = LOG_DEBUG;
if ((int)response.status >= 300 && (int)response.status <= 399) {
response_prefix = " 💫 ";
} else if ((int)response.status == 404) {
response_prefix = " 🕸 ";
} else if ((int)response.status >= 400 && (int)response.status <= 499) {
response_prefix = " 💥 ";
priority = LOG_INFO;
} else if ((int)response.status >= 500 && (int)response.status <= 599) {
response_prefix = " 🔥 ";
priority = LOG_NOTICE;
}
auto response_text = response.to_text(true);
L(priority, NO_COLOR, "{}{}", response_prefix, strings::indent(response_text, ' ', 4, false));
}
void
HttpClient::end_http_request(Request& request)
{
L_CALL("HttpClient::end_http_request()");
request.ends = std::chrono::steady_clock::now();
request.atom_ending = true;
request.atom_ended = true;
waiting = false;
if (request.indexer) {
request.indexer->finish();
request.indexer.reset();
}
if (request.log) {
request.log->clear();
request.log.reset();
}
if (request.parser.http_errno != 0u) {
L(LOG_ERR, LIGHT_RED, "HTTP parsing error ({}): {}", http_errno_name(HTTP_PARSER_ERRNO(&request.parser)), http_errno_description(HTTP_PARSER_ERRNO(&request.parser)));
} else {
static constexpr auto fmt_defaut = RED + "\"{}\" {} {} {}";
auto fmt = fmt_defaut.c_str();
int priority = LOG_DEBUG;
if ((int)request.response.status >= 200 && (int)request.response.status <= 299) {
static constexpr auto fmt_2xx = LIGHT_GREY + "\"{}\" {} {} {}";
fmt = fmt_2xx.c_str();
} else if ((int)request.response.status >= 300 && (int)request.response.status <= 399) {
static constexpr auto fmt_3xx = STEEL_BLUE + "\"{}\" {} {} {}";
fmt = fmt_3xx.c_str();
} else if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
static constexpr auto fmt_4xx = SADDLE_BROWN + "\"{}\" {} {} {}";
fmt = fmt_4xx.c_str();
if ((int)request.response.status != 404) {
priority = LOG_INFO;
}
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
static constexpr auto fmt_5xx = LIGHT_PURPLE + "\"{}\" {} {} {}";
fmt = fmt_5xx.c_str();
priority = LOG_NOTICE;
}
if (Logging::log_level > LOG_DEBUG) {
log_response(request.response);
} else if (Logging::log_level == LOG_DEBUG) {
if ((int)request.response.status >= 400 && (int)request.response.status != 404) {
log_request(request);
log_response(request.response);
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count();
Metrics::metrics()
.xapiand_http_requests_summary
.Add({
{"method", http_method_str(request.method)},
{"status", strings::format("{}", request.response.status)},
})
.Observe(took / 1e9);
L(priority, NO_COLOR, fmt, request.head(), (int)request.response.status, strings::from_bytes(request.response.size), strings::from_delta(request.begins, request.ends));
}
L_TIME("Full request took {}, response took {}", strings::from_delta(request.begins, request.ends), strings::from_delta(request.received, request.ends));
auto sent = total_sent_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_sent_bytes
.Increment(sent);
auto received = total_received_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_received_bytes
.Increment(received);
}
ct_type_t
HttpClient::resolve_ct_type(Request& request, ct_type_t ct_type)
{
L_CALL("HttpClient::resolve_ct_type({})", repr(ct_type.to_string()));
if (
ct_type == json_type || ct_type == x_json_type ||
ct_type == yaml_type || ct_type == x_yaml_type ||
ct_type == msgpack_type || ct_type == x_msgpack_type
) {
if (is_acceptable_type(get_acceptable_type(request, json_type), json_type) != nullptr) {
ct_type = json_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_json_type), json_type) != nullptr) {
ct_type = x_json_type;
} else if (is_acceptable_type(get_acceptable_type(request, yaml_type), yaml_type) != nullptr) {
ct_type = yaml_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_yaml_type), yaml_type) != nullptr) {
ct_type = x_yaml_type;
} else if (is_acceptable_type(get_acceptable_type(request, msgpack_type), msgpack_type) != nullptr) {
ct_type = msgpack_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_msgpack_type), x_msgpack_type) != nullptr) {
ct_type = x_msgpack_type;
}
}
std::vector<ct_type_t> ct_types;
if (
ct_type == json_type || ct_type == x_json_type ||
ct_type == yaml_type || ct_type == x_yaml_type ||
ct_type == msgpack_type || ct_type == x_msgpack_type
) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(std::move(ct_type));
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
const auto accepted_ct_type = is_acceptable_type(accepted_type, ct_types);
if (accepted_ct_type == nullptr) {
return no_type;
}
return *accepted_ct_type;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const ct_type_t& ct_type)
{
L_CALL("HttpClient::is_acceptable_type({}, {})", repr(ct_type_pattern.to_string()), repr(ct_type.to_string()));
bool type_ok = false, subtype_ok = false;
if (ct_type_pattern.first == "*") {
type_ok = true;
} else {
type_ok = ct_type_pattern.first == ct_type.first;
}
if (ct_type_pattern.second == "*") {
subtype_ok = true;
} else {
subtype_ok = ct_type_pattern.second == ct_type.second;
}
if (type_ok && subtype_ok) {
return &ct_type;
}
return nullptr;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const std::vector<ct_type_t>& ct_types)
{
L_CALL("HttpClient::is_acceptable_type(({}, <ct_types>)", repr(ct_type_pattern.to_string()));
for (auto& ct_type : ct_types) {
if (is_acceptable_type(ct_type_pattern, ct_type) != nullptr) {
return &ct_type;
}
}
return nullptr;
}
template <typename T>
const ct_type_t&
HttpClient::get_acceptable_type(Request& request, const T& ct)
{
L_CALL("HttpClient::get_acceptable_type()");
if (request.accept_set.empty()) {
return no_type;
}
for (const auto& accept : request.accept_set) {
if (is_acceptable_type(accept.ct_type, ct)) {
return accept.ct_type;
}
}
const auto& accept = *request.accept_set.begin();
auto indent = accept.indent;
if (indent != -1) {
request.indented = indent;
}
return accept.ct_type;
}
std::pair<std::string, std::string>
HttpClient::serialize_response(const MsgPack& obj, const ct_type_t& ct_type, int indent, bool serialize_error)
{
L_CALL("HttpClient::serialize_response({}, {}, {}, {})", repr(obj.to_string(), true, '\'', 200), repr(ct_type.to_string()), indent, serialize_error);
if (ct_type == no_type) {
return std::make_pair("", "");
}
if (is_acceptable_type(ct_type, json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), x_json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, yaml_type) != nullptr) {
return std::make_pair(obj.to_string(indent), yaml_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_yaml_type) != nullptr) {
return std::make_pair(obj.to_string(indent), x_yaml_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), x_msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, html_type) != nullptr) {
std::function<std::string(const msgpack::object&)> html_serialize = serialize_error ? msgpack_to_html_error : msgpack_to_html;
return std::make_pair(obj.external(html_serialize), html_type.to_string() + "; charset=utf-8");
}
/*if (is_acceptable_type(ct_type, text_type)) {
error:
{{ ERROR_CODE }} - {{ MESSAGE }}
obj:
{{ key1 }}: {{ val1 }}
{{ key2 }}: {{ val2 }}
...
array:
{{ val1 }}, {{ val2 }}, ...
}*/
THROW(SerialisationError, "Type is not serializable");
}
void
HttpClient::write_http_response(Request& request, enum http_status status, const MsgPack& obj, const std::string& location)
{
L_CALL("HttpClient::write_http_response()");
if (obj.is_undefined()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE, "", location));
return;
}
std::vector<ct_type_t> ct_types;
if (
request.ct_type == json_type || request.ct_type == x_json_type ||
request.ct_type == yaml_type || request.ct_type == x_yaml_type ||
request.ct_type == msgpack_type || request.ct_type == x_msgpack_type ||
request.ct_type.empty()
) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(request.ct_type);
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
try {
auto result = serialize_response(obj, accepted_type, request.indented, (int)status >= 400);
if (Logging::log_level >= LOG_DEBUG && request.response.size <= 1024 * 10) {
if (is_acceptable_type(accepted_type, json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, yaml_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_yaml_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, html_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, text_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (!obj.empty()) {
request.response.text.append("...");
}
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, result.first, false, true, true);
if (!encoded.empty() && encoded.size() <= result.first.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, result.second, readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, result.first, location, result.second, readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, result.first, location, result.second));
}
} catch (const SerialisationError& exc) {
status = HTTP_STATUS_NOT_ACCEPTABLE;
std::string response_str;
if (request.comments) {
MsgPack response_err = MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type " + accepted_type.to_string() + " " + exc.what() }) } }
});
response_str = response_err.to_string(request.indented);
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, response_str, false, true, true);
if (!encoded.empty() && encoded.size() <= response_str.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, accepted_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, response_str, location, accepted_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, response_str, location, accepted_type.to_string()));
}
return;
}
}
Encoding
HttpClient::resolve_encoding(Request& request)
{
L_CALL("HttpClient::resolve_encoding()");
if (request.accept_encoding_set.empty()) {
return Encoding::none;
}
constexpr static auto _ = phf::make_phf({
hhl("gzip"),
hhl("deflate"),
hhl("identity"),
hhl("*"),
});
for (const auto& encoding : request.accept_encoding_set) {
switch (_.fhhl(encoding.encoding)) {
case _.fhhl("gzip"):
return Encoding::gzip;
case _.fhhl("deflate"):
return Encoding::deflate;
case _.fhhl("identity"):
return Encoding::identity;
case _.fhhl("*"):
return Encoding::identity;
default:
continue;
}
}
return Encoding::unknown;
}
std::string
HttpClient::readable_encoding(Encoding e)
{
L_CALL("Request::readable_encoding()");
switch (e) {
case Encoding::none:
return "none";
case Encoding::gzip:
return "gzip";
case Encoding::deflate:
return "deflate";
case Encoding::identity:
return "identity";
default:
return "Encoding:UNKNOWN";
}
}
std::string
HttpClient::encoding_http_response(Response& response, Encoding e, const std::string& response_obj, bool chunk, bool start, bool end)
{
L_CALL("HttpClient::encoding_http_response({})", repr(response_obj));
bool gzip = false;
switch (e) {
case Encoding::gzip:
gzip = true;
[[fallthrough]];
case Encoding::deflate: {
if (chunk) {
if (start) {
response.encoding_compressor.reset(nullptr, 0, gzip);
response.encoding_compressor.begin();
}
if (end) {
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size(), DeflateCompressData::FINISH_COMPRESS);
return ret;
}
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size());
return ret;
}
response.encoding_compressor.reset(response_obj.data(), response_obj.size(), gzip);
response.it_compressor = response.encoding_compressor.begin();
std::string encoding_respose;
while (response.it_compressor) {
encoding_respose.append(*response.it_compressor);
++response.it_compressor;
}
return encoding_respose;
}
case Encoding::identity:
return response_obj;
default:
return std::string();
}
}
std::string
HttpClient::__repr__() const
{
return strings::format(STEEL_BLUE + "<HttpClient {{cnt:{}, sock:{}}}{}{}{}{}{}{}{}{}>",
use_count(),
sock,
is_runner() ? " " + DARK_STEEL_BLUE + "(runner)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(worker)" + STEEL_BLUE,
is_running_loop() ? " " + DARK_STEEL_BLUE + "(running loop)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(stopped loop)" + STEEL_BLUE,
is_detaching() ? " " + ORANGE + "(detaching)" + STEEL_BLUE : "",
is_idle() ? " " + DARK_STEEL_BLUE + "(idle)" + STEEL_BLUE : "",
is_waiting() ? " " + LIGHT_STEEL_BLUE + "(waiting)" + STEEL_BLUE : "",
is_running() ? " " + DARK_ORANGE + "(running)" + STEEL_BLUE : "",
is_shutting_down() ? " " + ORANGE + "(shutting down)" + STEEL_BLUE : "",
is_closed() ? " " + ORANGE + "(closed)" + STEEL_BLUE : "");
}
Request::Request(HttpClient* client)
: mode{Mode::FULL},
view{nullptr},
type_encoding{Encoding::none},
begining{true},
ending{false},
atom_ending{false},
atom_ended{false},
raw_peek{0},
raw_offset{0},
size{0},
echo{false},
human{false},
comments{true},
indented{-1},
expect_100{false},
closing{false},
begins{std::chrono::steady_clock::now()}
{
parser.data = client;
http_parser_init(&parser, HTTP_REQUEST);
}
Request::~Request() noexcept
{
try {
if (indexer) {
indexer->finish();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
try {
if (log) {
log->clear();
log.reset();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
MsgPack
Request::decode(std::string_view body)
{
L_CALL("Request::decode({})", repr(body));
std::string ct_type_str = ct_type.to_string();
if (ct_type_str.empty()) {
ct_type_str = JSON_CONTENT_TYPE;
}
MsgPack decoded;
rapidjson::Document rdoc;
constexpr static auto _ = phf::make_phf({
hhl(JSON_CONTENT_TYPE),
hhl(X_JSON_CONTENT_TYPE),
hhl(YAML_CONTENT_TYPE),
hhl(X_YAML_CONTENT_TYPE),
hhl(MSGPACK_CONTENT_TYPE),
hhl(X_MSGPACK_CONTENT_TYPE),
hhl(NDJSON_CONTENT_TYPE),
hhl(X_NDJSON_CONTENT_TYPE),
hhl(FORM_URLENCODED_CONTENT_TYPE),
hhl(X_FORM_URLENCODED_CONTENT_TYPE),
});
switch (_.fhhl(ct_type_str)) {
case _.fhhl(NDJSON_CONTENT_TYPE):
case _.fhhl(X_NDJSON_CONTENT_TYPE):
decoded = MsgPack::ARRAY();
for (auto json : Split<std::string_view>(body, '\n')) {
json_load(rdoc, json);
decoded.append(rdoc);
}
ct_type = json_type;
return decoded;
case _.fhhl(JSON_CONTENT_TYPE):
case _.fhhl(X_JSON_CONTENT_TYPE):
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
return decoded;
case _.fhhl(YAML_CONTENT_TYPE):
case _.fhhl(X_YAML_CONTENT_TYPE):
yaml_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = yaml_type;
return decoded;
case _.fhhl(MSGPACK_CONTENT_TYPE):
case _.fhhl(X_MSGPACK_CONTENT_TYPE):
decoded = MsgPack::unserialise(body);
ct_type = msgpack_type;
return decoded;
case _.fhhl(FORM_URLENCODED_CONTENT_TYPE):
case _.fhhl(X_FORM_URLENCODED_CONTENT_TYPE):
try {
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
} catch (const std::exception&) {
decoded = MsgPack(body);
ct_type = msgpack_type;
}
return decoded;
default:
decoded = MsgPack(body);
return decoded;
}
}
MsgPack&
Request::decoded_body()
{
L_CALL("Request::decoded_body()");
if (_decoded_body.is_undefined()) {
if (!raw.empty()) {
_decoded_body = decode(raw);
}
}
return _decoded_body;
}
bool
Request::append(const char* at, size_t length)
{
L_CALL("Request::append(<at>, <length>)");
bool signal_pending = false;
switch (mode) {
case Mode::FULL:
raw.append(std::string_view(at, length));
break;
case Mode::STREAM:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
raw.append(std::string_view(at, length));
signal_pending = true;
break;
case Mode::STREAM_NDJSON:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
raw.append(std::string_view(at, length));
auto new_raw_offset = raw.find_first_of('\n', raw_peek);
while (new_raw_offset != std::string::npos) {
auto json = std::string_view(raw).substr(raw_offset, new_raw_offset - raw_offset);
raw_offset = raw_peek = new_raw_offset + 1;
new_raw_offset = raw.find_first_of('\n', raw_peek);
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
}
if (!length) {
auto json = std::string_view(raw).substr(raw_offset);
raw_offset = raw_peek = raw.size();
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
break;
case Mode::STREAM_MSGPACK:
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
unpacker.reserve_buffer(length);
memcpy(unpacker.buffer(), at, length);
unpacker.buffer_consumed(length);
try {
msgpack::object_handle result;
while (unpacker.next(result)) {
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(result.get());
}
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
break;
}
return signal_pending;
}
bool
Request::wait()
{
if (mode != Request::Mode::FULL) {
// Wait for a pending raw body for one second (1000000us) and flush
// pending signals before processing the request, otherwise retry
// checking for empty/ended requests or closed connections.
if (!pending.wait(1000000)) {
return false;
}
while (pending.tryWaitMany(std::numeric_limits<ssize_t>::max())) { }
}
return true;
}
bool
Request::next(std::string_view& str_view)
{
L_CALL("Request::next(<&str_view>)");
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
assert(mode == Mode::STREAM);
if (raw_offset == raw.size()) {
return false;
}
str_view = std::string_view(raw).substr(raw_offset);
raw_offset = raw.size();
return true;
}
bool
Request::next_object(MsgPack& obj)
{
L_CALL("Request::next_object(<&obj>)");
assert((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
assert(mode == Mode::STREAM_MSGPACK || mode == Mode::STREAM_NDJSON);
std::lock_guard<std::mutex> lk(objects_mtx);
if (objects.empty()) {
return false;
}
obj = std::move(objects.front());
objects.pop_front();
return true;
}
std::string
Request::head()
{
L_CALL("Request::head()");
auto parser_method = HTTP_PARSER_METHOD(&parser);
if (parser_method != method) {
return strings::format("{} <- {} {} HTTP/{}.{}",
http_method_str(method),
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
return strings::format("{} {} HTTP/{}.{}",
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
std::string
Request::to_text(bool decode)
{
L_CALL("Request::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto request_headers_color = no_col.c_str();
auto request_head_color = no_col.c_str();
auto request_text_color = no_col.c_str();
switch (method) {
case HTTP_OPTIONS: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_INFO: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_HEAD: {
// rgb(144, 18, 254)
static constexpr auto _request_headers_color = rgba(100, 64, 131, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(100, 64, 131);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(100, 64, 131);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_GET: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_SEARCH: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COUNT: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_POST: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DUMP: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_RESTORE: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_OPEN: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_CLOSE: {
// rgb(227, 32, 40)
static constexpr auto _request_headers_color = rgba(101, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(101, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(101, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PATCH: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_STORE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PUT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COMMIT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DELETE: {
// rgb(246, 64, 68)
static constexpr auto _request_headers_color = rgba(151, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(151, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(151, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
default:
break;
};
auto request_text = request_head_color + head() + "\n" + request_headers_color + headers + request_text_color;
if (!raw.empty()) {
if (!decode) {
if (raw.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
} else {
request_text += "<body " + repr(raw, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(raw);
request_text += strings::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
request_text += b64_data;
request_text += '\a';
} else {
if (raw.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
} else {
auto& decoded = decoded_body();
if (
ct_type == json_type ||
ct_type == x_json_type ||
ct_type == yaml_type ||
ct_type == x_yaml_type ||
ct_type == msgpack_type ||
ct_type == x_msgpack_type
) {
request_text += decoded.to_string(DEFAULT_INDENTATION);
} else {
request_text += "<body " + strings::from_bytes(raw.size()) + ">";
}
}
}
} else if (!text.empty()) {
if (!decode) {
if (text.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(text.size()) + ">";
} else {
request_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (text.size() > 1024 * 10) {
request_text += "<body " + strings::from_bytes(text.size()) + ">";
} else {
request_text += text;
}
} else if (size) {
request_text += "<body " + strings::from_bytes(size) + ">";
}
return request_text;
}
Response::Response()
: status{static_cast<http_status>(0)},
size{0}
{
}
std::string
Response::to_text(bool decode)
{
L_CALL("Response::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto response_headers_color = no_col.c_str();
auto response_head_color = no_col.c_str();
auto response_text_color = no_col.c_str();
if ((int)status >= 200 && (int)status <= 299) {
static constexpr auto _response_headers_color = rgba(68, 136, 68, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 68);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 68);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 300 && (int)status <= 399) {
static constexpr auto _response_headers_color = rgba(68, 136, 120, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 120);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 120);
response_text_color = _response_text_color.c_str();
} else if ((int)status == 404) {
static constexpr auto _response_headers_color = rgba(116, 100, 77, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(116, 100, 77);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(116, 100, 77);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 400 && (int)status <= 499) {
static constexpr auto _response_headers_color = rgba(183, 70, 17, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(183, 70, 17);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(183, 70, 17);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 500 && (int)status <= 599) {
static constexpr auto _response_headers_color = rgba(190, 30, 10, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(190, 30, 10);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(190, 30, 10);
response_text_color = _response_text_color.c_str();
}
auto response_text = response_head_color + head + "\n" + response_headers_color + headers + response_text_color;
if (!blob.empty()) {
if (!decode) {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + repr(blob, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(blob);
response_text += strings::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
response_text += b64_data;
response_text += '\a';
} else {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + strings::from_bytes(blob.size()) + ">";
}
}
} else if (!text.empty()) {
if (!decode) {
if (size > 1024 * 10) {
response_text += "<body " + strings::from_bytes(size) + ">";
} else {
response_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (size > 1024 * 10) {
response_text += "<body " + strings::from_bytes(size) + ">";
} else {
response_text += text;
}
} else if (size) {
response_text += "<body " + strings::from_bytes(size) + ">";
}
return response_text;
}
|
#include "sdlwrap.hpp"
namespace rs {
void Window::SetStdGLAttributes(int major, int minor, int depth) {
SetGLAttributes(SDL_GL_CONTEXT_MAJOR_VERSION, major,
SDL_GL_CONTEXT_MINOR_VERSION, minor,
SDL_GL_DOUBLEBUFFER, 1,
SDL_GL_DEPTH_SIZE, depth);
}
SPWindow Window::Create(const std::string& title, int w, int h, uint32_t flag) {
return Create(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flag|SDL_WINDOW_OPENGL);
}
SPWindow Window::Create(const std::string& title, int x, int y, int w, int h, uint32_t flag) {
return SPWindow(new Window(SDLEC_P(Trap, SDL_CreateWindow, title.c_str(), x, y, w, h, flag|SDL_WINDOW_OPENGL)));
}
Window::Window(SDL_Window* w): _window(w) {
_checkState();
}
Window::~Window() {
SDLEC_P(Warn, SDL_DestroyWindow, _window);
}
void Window::_checkState() {
uint32_t f = getSDLFlag();
if(f & SDL_WINDOW_SHOWN)
_stat = Stat::Hidden;
else if(f & SDL_WINDOW_FULLSCREEN)
_stat = Stat::Fullscreen;
else if(f & SDL_WINDOW_MINIMIZED)
_stat = Stat::Minimized;
else if(f & SDL_WINDOW_MAXIMIZED)
_stat = Stat::Maximized;
else
_stat = Stat::Shown;
}
void Window::setFullscreen(bool bFull) {
SDLEC_P(Warn, SDL_SetWindowFullscreen, _window, bFull ? SDL_WINDOW_FULLSCREEN : 0);
_checkState();
}
void Window::setGrab(bool bGrab) {
SDLEC_P(Warn, SDL_SetWindowGrab, _window, bGrab ? SDL_TRUE : SDL_FALSE);
}
void Window::setMaximumSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowMaximumSize, _window, w, h);
}
void Window::setMinimumSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowMinimumSize, _window, w, h);
}
void Window::setSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowSize, _window, w, h);
}
void Window::show(bool bShow) {
if(bShow)
SDLEC_P(Warn, SDL_ShowWindow, _window);
else
SDLEC_P(Warn, SDL_HideWindow, _window);
_checkState();
}
void Window::setTitle(const std::string& title) {
SDLEC_P(Warn, SDL_SetWindowTitle, _window, title.c_str());
}
void Window::maximize() {
SDLEC_P(Warn, SDL_MaximizeWindow, _window);
_checkState();
}
void Window::minimize() {
SDLEC_P(Warn, SDL_MinimizeWindow, _window);
_checkState();
}
void Window::restore() {
SDLEC_P(Warn, SDL_RestoreWindow, _window);
_checkState();
}
void Window::setPosition(int x, int y) {
SDLEC_P(Warn, SDL_SetWindowPosition, _window, x, y);
}
void Window::raise() {
SDLEC_P(Warn, SDL_RaiseWindow, _window);
_checkState();
}
uint32_t Window::getID() const {
return SDLEC_P(Warn, SDL_GetWindowID, _window);
}
Window::Stat Window::getState() const {
return _stat;
}
bool Window::isGrabbed() const {
return SDLEC_P(Warn, SDL_GetWindowGrab, _window) == SDL_TRUE;
}
bool Window::isResizable() const {
return getSDLFlag() & SDL_WINDOW_RESIZABLE;
}
bool Window::hasInputFocus() const {
return getSDLFlag() & SDL_WINDOW_INPUT_FOCUS;
}
bool Window::hasMouseFocus() const {
return getSDLFlag() & SDL_WINDOW_MOUSE_FOCUS;
}
namespace {
spn::Size GetSize(void (*func)(SDL_Window*,int*,int*), SDL_Window* wd) {
int w,h;
SDLEC_P(Warn, func, wd, &w, &h);
return spn::Size(w,h);
}
}
spn::Size Window::getSize() const {
return GetSize(SDL_GetWindowSize, _window);
}
spn::Size Window::getMaximumSize() const {
return GetSize(SDL_GetWindowMaximumSize, _window);
}
spn::Size Window::getMinimumSize() const {
return GetSize(SDL_GetWindowMinimumSize, _window);
}
uint32_t Window::getSDLFlag() const {
return SDLEC_P(Warn, SDL_GetWindowFlags, _window);
}
SDL_Window* Window::getWindow() const {
return _window;
}
void Window::EnableScreenSaver(bool bEnable) {
if(bEnable)
SDLEC_P(Warn, SDL_EnableScreenSaver);
else
SDLEC_P(Warn, SDL_DisableScreenSaver);
}
}
sdlw_window: 初期化位置をSDL_WINDOWPOS_UNDEFINEDにするとwindows環境で妙な位置にセットされるので固定
#include "sdlwrap.hpp"
namespace rs {
void Window::SetStdGLAttributes(int major, int minor, int depth) {
SetGLAttributes(SDL_GL_CONTEXT_MAJOR_VERSION, major,
SDL_GL_CONTEXT_MINOR_VERSION, minor,
SDL_GL_DOUBLEBUFFER, 1,
SDL_GL_DEPTH_SIZE, depth);
}
SPWindow Window::Create(const std::string& title, int w, int h, uint32_t flag) {
return Create(title, 128, 128, w, h, flag|SDL_WINDOW_OPENGL);
}
SPWindow Window::Create(const std::string& title, int x, int y, int w, int h, uint32_t flag) {
return SPWindow(new Window(SDLEC_P(Warn, SDL_CreateWindow, title.c_str(), x, y, w, h, flag|SDL_WINDOW_OPENGL)));
}
Window::Window(SDL_Window* w): _window(w) {
_checkState();
}
Window::~Window() {
SDLEC_P(Warn, SDL_DestroyWindow, _window);
}
void Window::_checkState() {
uint32_t f = getSDLFlag();
if(f & SDL_WINDOW_SHOWN)
_stat = Stat::Hidden;
else if(f & SDL_WINDOW_FULLSCREEN)
_stat = Stat::Fullscreen;
else if(f & SDL_WINDOW_MINIMIZED)
_stat = Stat::Minimized;
else if(f & SDL_WINDOW_MAXIMIZED)
_stat = Stat::Maximized;
else
_stat = Stat::Shown;
}
void Window::setFullscreen(bool bFull) {
SDLEC_P(Warn, SDL_SetWindowFullscreen, _window, bFull ? SDL_WINDOW_FULLSCREEN : 0);
_checkState();
}
void Window::setGrab(bool bGrab) {
SDLEC_P(Warn, SDL_SetWindowGrab, _window, bGrab ? SDL_TRUE : SDL_FALSE);
}
void Window::setMaximumSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowMaximumSize, _window, w, h);
}
void Window::setMinimumSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowMinimumSize, _window, w, h);
}
void Window::setSize(int w, int h) {
SDLEC_P(Warn, SDL_SetWindowSize, _window, w, h);
}
void Window::show(bool bShow) {
if(bShow)
SDLEC_P(Warn, SDL_ShowWindow, _window);
else
SDLEC_P(Warn, SDL_HideWindow, _window);
_checkState();
}
void Window::setTitle(const std::string& title) {
SDLEC_P(Warn, SDL_SetWindowTitle, _window, title.c_str());
}
void Window::maximize() {
SDLEC_P(Warn, SDL_MaximizeWindow, _window);
_checkState();
}
void Window::minimize() {
SDLEC_P(Warn, SDL_MinimizeWindow, _window);
_checkState();
}
void Window::restore() {
SDLEC_P(Warn, SDL_RestoreWindow, _window);
_checkState();
}
void Window::setPosition(int x, int y) {
SDLEC_P(Warn, SDL_SetWindowPosition, _window, x, y);
}
void Window::raise() {
SDLEC_P(Warn, SDL_RaiseWindow, _window);
_checkState();
}
uint32_t Window::getID() const {
return SDLEC_P(Warn, SDL_GetWindowID, _window);
}
Window::Stat Window::getState() const {
return _stat;
}
bool Window::isGrabbed() const {
return SDLEC_P(Warn, SDL_GetWindowGrab, _window) == SDL_TRUE;
}
bool Window::isResizable() const {
return getSDLFlag() & SDL_WINDOW_RESIZABLE;
}
bool Window::hasInputFocus() const {
return getSDLFlag() & SDL_WINDOW_INPUT_FOCUS;
}
bool Window::hasMouseFocus() const {
return getSDLFlag() & SDL_WINDOW_MOUSE_FOCUS;
}
namespace {
spn::Size GetSize(void (*func)(SDL_Window*,int*,int*), SDL_Window* wd) {
int w,h;
SDLEC_P(Warn, func, wd, &w, &h);
return spn::Size(w,h);
}
}
spn::Size Window::getSize() const {
return GetSize(SDL_GetWindowSize, _window);
}
spn::Size Window::getMaximumSize() const {
return GetSize(SDL_GetWindowMaximumSize, _window);
}
spn::Size Window::getMinimumSize() const {
return GetSize(SDL_GetWindowMinimumSize, _window);
}
uint32_t Window::getSDLFlag() const {
return SDLEC_P(Warn, SDL_GetWindowFlags, _window);
}
SDL_Window* Window::getWindow() const {
return _window;
}
void Window::EnableScreenSaver(bool bEnable) {
if(bEnable)
SDLEC_P(Warn, SDL_EnableScreenSaver);
else
SDLEC_P(Warn, SDL_DisableScreenSaver);
}
}
|
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "http_client.h"
#include "config.h" // for XAPIAND_CLUSTERING, XAPIAND_CHAISCRIPT, XAPIAND_DATABASE_WAL
#include <errno.h> // for errno
#include <exception> // for std::exception
#include <functional> // for std::function
#include <regex> // for std::regex, std::regex_constants
#include <signal.h> // for SIGTERM
#include <sysexits.h> // for EX_SOFTWARE
#include <syslog.h> // for LOG_WARNING, LOG_ERR, LOG...
#include <utility> // for std::move
#ifdef XAPIAND_CHAISCRIPT
#include "chaiscript/chaiscript_defines.hpp" // for chaiscript::Build_Info
#endif
#include "cppcodec/base64_rfc4648.hpp" // for cppcodec::base64_rfc4648
#include "database/handler.h" // for DatabaseHandler
#include "database/utils.h" // for query_field_t
#include "database/pool.h" // for DatabasePool
#include "database/schema.h" // for Schema
#include "endpoint.h" // for Endpoints, Endpoint
#include "epoch.hh" // for epoch::now
#include "error.hh" // for error:name, error::description
#include "ev/ev++.h" // for async, io, loop_ref (ptr ...
#include "exception.h" // for Exception, SerialisationE...
#include "field_parser.h" // for FieldParser, FieldParserError
#include "hashes.hh" // for hhl
#include "http_utils.h" // for catch_http_errors
#include "io.hh" // for close, write, unlink
#include "log.h" // for L_CALL, L_ERR, LOG_DEBUG
#include "logger.h" // for Logging
#include "manager.h" // for XapiandManager
#include "metrics.h" // for Metrics::metrics
#include "mime_types.hh" // for mime_type
#include "msgpack.h" // for MsgPack, msgpack::object
#include "aggregations/aggregations.h" // for AggregationMatchSpy
#include "node.h" // for Node::local_node, Node::leader_node
#include "opts.h" // for opts::*
#include "package.h" // for Package::*
#include "phf.hh" // for phf::*
#include "rapidjson/document.h" // for Document
#include "reserved/aggregations.h" // for RESERVED_AGGS_*
#include "reserved/fields.h" // for RESERVED_*
#include "reserved/query_dsl.h" // for RESERVED_QUERYDSL_*
#include "reserved/schema.h" // for RESERVED_VERSION
#include "response.h" // for RESPONSE_*
#include "serialise.h" // for Serialise::boolean
#include "string.hh" // for string::from_delta
#include "xapian.h" // for Xapian::major_version, Xapian::minor_version
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_CONN
// #define L_CONN L_GREEN
// #undef L_HTTP
// #define L_HTTP L_RED
// #undef L_HTTP_WIRE
// #define L_HTTP_WIRE L_ORANGE
// #undef L_HTTP_PROTO
// #define L_HTTP_PROTO L_TEAL
#define QUERY_FIELD_PRIMARY (1 << 0)
#define QUERY_FIELD_WRITABLE (1 << 1)
#define QUERY_FIELD_COMMIT (1 << 2)
#define QUERY_FIELD_SEARCH (1 << 3)
#define QUERY_FIELD_ID (1 << 4)
#define QUERY_FIELD_TIME (1 << 5)
#define QUERY_FIELD_PERIOD (1 << 6)
#define QUERY_FIELD_VOLATILE (1 << 7)
#define DEFAULT_INDENTATION 2
static const std::regex header_params_re(R"(\s*;\s*([a-z]+)=(\d+(?:\.\d+)?))", std::regex::optimize);
static const std::regex header_accept_re(R"(([-a-z+]+|\*)/([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::regex header_accept_encoding_re(R"(([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::string eol("\r\n");
// Available commands
#define METHODS_OPTIONS() \
OPTION(DELETE, "delete") \
OPTION(GET, "get") \
OPTION(HEAD, "head") \
OPTION(POST, "post") \
OPTION(PUT, "put") \
OPTION(CONNECT, "connect") \
OPTION(OPTIONS, "options") \
OPTION(TRACE, "trace") \
OPTION(PATCH, "patch") \
OPTION(PURGE, "purge") \
OPTION(LINK, "link") \
OPTION(UNLINK, "unlink") \
OPTION(CHECK, "check") \
OPTION(CLOSE, "close") \
OPTION(COMMIT, "commit") \
OPTION(COPY, "copy") \
OPTION(COUNT, "count") \
OPTION(DUMP, "dump") \
OPTION(FLUSH, "flush") \
OPTION(INFO, "info") \
OPTION(LOCK, "lock") \
OPTION(MERGE, "merge") \
OPTION(MOVE, "move") \
OPTION(OPEN, "open") \
OPTION(QUIT, "quit") \
OPTION(RESTORE, "restore") \
OPTION(SEARCH, "search") \
OPTION(STORE, "store") \
OPTION(UNLOCK, "unlock") \
OPTION(UPDATE, "update")
constexpr static auto http_methods = phf::make_phf({
#define OPTION(name, str) hhl(str),
METHODS_OPTIONS()
#undef OPTION
});
bool is_range(std::string_view str) {
try {
FieldParser fieldparser(str);
fieldparser.parse();
return fieldparser.is_range();
} catch (const FieldParserError&) {
return false;
}
}
const std::string& HttpParserStateNames(int type) {
static const std::string _[] = {
"s_none",
"s_dead",
"s_start_req_or_res",
"s_res_or_resp_H",
"s_start_res",
"s_res_H",
"s_res_HT",
"s_res_HTT",
"s_res_HTTP",
"s_res_first_http_major",
"s_res_http_major",
"s_res_first_http_minor",
"s_res_http_minor",
"s_res_first_status_code",
"s_res_status_code",
"s_res_status_start",
"s_res_status",
"s_res_line_almost_done",
"s_start_req",
"s_req_method",
"s_req_spaces_before_url",
"s_req_schema",
"s_req_schema_slash",
"s_req_schema_slash_slash",
"s_req_server_start",
"s_req_server",
"s_req_server_with_at",
"s_req_path",
"s_req_query_string_start",
"s_req_query_string",
"s_req_fragment_start",
"s_req_fragment",
"s_req_http_start",
"s_req_http_H",
"s_req_http_HT",
"s_req_http_HTT",
"s_req_http_HTTP",
"s_req_first_http_major",
"s_req_http_major",
"s_req_first_http_minor",
"s_req_http_minor",
"s_req_line_almost_done",
"s_header_field_start",
"s_header_field",
"s_header_value_discard_ws",
"s_header_value_discard_ws_almost_done",
"s_header_value_discard_lws",
"s_header_value_start",
"s_header_value",
"s_header_value_lws",
"s_header_almost_done",
"s_chunk_size_start",
"s_chunk_size",
"s_chunk_parameters",
"s_chunk_size_almost_done",
"s_headers_almost_done",
"s_headers_done",
"s_chunk_data",
"s_chunk_data_almost_done",
"s_chunk_data_done",
"s_body_identity",
"s_body_identity_eof",
"s_message_done",
};
auto idx = static_cast<size_t>(type);
if (idx >= 0 && idx < sizeof(_) / sizeof(_[0])) {
return _[idx];
}
static const std::string UNKNOWN = "UNKNOWN";
return UNKNOWN;
}
const std::string& HttpParserHeaderStateNames(int type) {
static const std::string _[] = {
"h_general",
"h_C",
"h_CO",
"h_CON",
"h_matching_connection",
"h_matching_proxy_connection",
"h_matching_content_length",
"h_matching_transfer_encoding",
"h_matching_upgrade",
"h_connection",
"h_content_length",
"h_transfer_encoding",
"h_upgrade",
"h_matching_transfer_encoding_chunked",
"h_matching_connection_token_start",
"h_matching_connection_keep_alive",
"h_matching_connection_close",
"h_matching_connection_upgrade",
"h_matching_connection_token",
"h_transfer_encoding_chunked",
"h_connection_keep_alive",
"h_connection_close",
"h_connection_upgrade",
};
auto idx = static_cast<size_t>(type);
if (idx >= 0 && idx < sizeof(_) / sizeof(_[0])) {
return _[idx];
}
static const std::string UNKNOWN = "UNKNOWN";
return UNKNOWN;
}
bool can_preview(const ct_type_t& ct_type) {
#define CONTENT_TYPE_OPTIONS() \
OPTION("application/eps") \
OPTION("application/pdf") \
OPTION("application/postscript") \
OPTION("application/x-bzpdf") \
OPTION("application/x-eps") \
OPTION("application/x-gzpdf") \
OPTION("application/x-pdf") \
OPTION("application/x-photoshop") \
OPTION("application/photoshop") \
OPTION("application/psd")
constexpr static auto _ = phf::make_phf({
#define OPTION(ct) hhl(ct),
CONTENT_TYPE_OPTIONS()
#undef OPTION
});
switch (_.fhhl(ct_type.to_string())) {
#define OPTION(ct) case _.fhhl(ct):
CONTENT_TYPE_OPTIONS()
#undef OPTION
return true;
default:
return ct_type.first == "image";
}
}
std::string
HttpClient::http_response(Request& request, enum http_status status, int mode, const std::string& body, const std::string& location, const std::string& ct_type, const std::string& ct_encoding, size_t content_length) {
L_CALL("HttpClient::http_response()");
std::string head;
std::string headers;
std::string head_sep;
std::string headers_sep;
std::string response_body;
if ((mode & HTTP_STATUS_RESPONSE) != 0) {
ASSERT(request.response.status == static_cast<http_status>(0));
request.response.status = status;
auto http_major = request.parser.http_major;
auto http_minor = request.parser.http_minor;
if (http_major == 0 && http_minor == 0) {
http_major = 1;
}
head += string::format("HTTP/{}.{} {} ", http_major, http_minor, status);
head += http_status_str(status);
head_sep += eol;
if ((mode & HTTP_HEADER_RESPONSE) == 0) {
headers_sep += eol;
}
}
ASSERT(request.response.status != static_cast<http_status>(0));
if ((mode & HTTP_HEADER_RESPONSE) != 0) {
headers += "Server: " + Package::STRING + eol;
// if (!endpoints.empty()) {
// headers += "Database: " + endpoints.to_string() + eol;
// }
request.ends = std::chrono::system_clock::now();
if (request.human) {
headers += string::format("Response-Time: {}", string::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count())) + eol;
if (request.ready >= request.processing) {
headers += string::format("Operation-Time: {}", string::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count())) + eol;
}
} else {
headers += string::format("Response-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count() / 1e9) + eol;
if (request.ready >= request.processing) {
headers += string::format("Operation-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count() / 1e9) + eol;
}
}
if ((mode & HTTP_OPTIONS_RESPONSE) != 0) {
headers += "Allow: GET, POST, PUT, PATCH, UPDATE, STORE, DELETE, HEAD, OPTIONS" + eol;
}
if (!location.empty()) {
headers += "Location: " + location + eol;
}
if ((mode & HTTP_CONTENT_TYPE_RESPONSE) != 0 && !ct_type.empty()) {
headers += "Content-Type: " + ct_type + eol;
}
if ((mode & HTTP_CONTENT_ENCODING_RESPONSE) != 0 && !ct_encoding.empty()) {
headers += "Content-Encoding: " + ct_encoding + eol;
}
if ((mode & HTTP_CONTENT_LENGTH_RESPONSE) != 0) {
headers += string::format("Content-Length: {}", content_length) + eol;
} else {
headers += string::format("Content-Length: {}", body.size()) + eol;
}
headers_sep += eol;
}
if ((mode & HTTP_BODY_RESPONSE) != 0) {
response_body += body;
}
auto this_response_size = response_body.size();
request.response.size += this_response_size;
if (Logging::log_level >= LOG_DEBUG) {
request.response.head += head;
request.response.headers += headers;
}
return head + head_sep + headers + headers_sep + response_body;
}
HttpClient::HttpClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: MetaBaseClient<HttpClient>(std::move(parent_), ev_loop_, ev_flags_),
new_request(std::make_shared<Request>(this))
{
++XapiandManager::http_clients();
Metrics::metrics()
.xapiand_http_connections
.Increment();
// Initialize new_request->begins as soon as possible (for correctly timing disconnecting clients)
new_request->begins = std::chrono::system_clock::now();
L_CONN("New Http Client, {} client(s) of a total of {} connected.", XapiandManager::http_clients().load(), XapiandManager::total_clients().load());
}
HttpClient::~HttpClient() noexcept
{
try {
if (XapiandManager::http_clients().fetch_sub(1) == 0) {
L_CRIT("Inconsistency in number of http clients");
sig_exit(-EX_SOFTWARE);
}
if (is_shutting_down() && !is_idle()) {
L_INFO("HTTP client killed!");
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
template <typename Func>
int
HttpClient::handled_errors(Request& request, Func&& func)
{
L_CALL("HttpClient::handled_errors()");
auto http_errors = catch_http_errors(std::forward<Func>(func));
if (http_errors.error_code != HTTP_STATUS_OK) {
if (request.response.status != static_cast<http_status>(0)) {
// There was an error, but request already had written stuff...
// disconnect client!
detach();
} else if (request.comments) {
write_http_response(request, http_errors.error_code, MsgPack({
{ RESPONSE_xSTATUS, static_cast<unsigned>(http_errors.error_code) },
{ RESPONSE_xMESSAGE, string::split(http_errors.error, '\n') }
}));
} else {
write_http_response(request, http_errors.error_code);
}
request.atom_ending = true;
}
return http_errors.ret;
}
size_t
HttpClient::pending_requests() const
{
std::lock_guard<std::mutex> lk(runner_mutex);
auto requests_size = requests.size();
if (requests_size && requests.front()->response.status != static_cast<http_status>(0)) {
--requests_size;
}
return requests_size;
}
bool
HttpClient::is_idle() const
{
L_CALL("RemoteProtocolClient::is_idle() {{is_waiting:{}, is_running:{}, write_queue_empty:{}, pending_requests:{}}}", is_waiting(), is_running(), write_queue.empty(), pending_requests());
return !is_waiting() && !is_running() && write_queue.empty() && !pending_requests();
}
ssize_t
HttpClient::on_read(const char* buf, ssize_t received)
{
L_CALL("HttpClient::on_read(<buf>, {})", received);
unsigned init_state = new_request->parser.state;
if (received <= 0) {
close();
if (received < 0) {
L_NOTICE("HTTP client connection closed unexpectedly after {} {{sock:{}}}: {} ({}): {}", string::from_delta(new_request->begins, std::chrono::system_clock::now()), sock, error::name(errno), errno, error::description(errno));
return received;
}
if (init_state != 18) {
L_NOTICE("HTTP client closed unexpectedly after {}: Not in final HTTP state ({})", string::from_delta(new_request->begins, std::chrono::system_clock::now()), init_state);
return received;
}
if (is_waiting()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There was still a request in progress", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
if (!write_queue.empty()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There is still pending data", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
if (pending_requests()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There are still pending requests", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
// HTTP client normally closed connection.
return received;
}
L_HTTP_WIRE("HttpClient::on_read: {} bytes", received);
ssize_t parsed = http_parser_execute(&new_request->parser, &http_parser_settings, buf, received);
if (parsed != received) {
enum http_status error_code = HTTP_STATUS_BAD_REQUEST;
http_errno err = HTTP_PARSER_ERRNO(&new_request->parser);
if (err == HPE_INVALID_METHOD) {
if (new_request->response.status == static_cast<http_status>(0)) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
end_http_request(*new_request);
}
} else {
std::string message(http_errno_description(err));
L_DEBUG("HTTP parser error: {}", HTTP_PARSER_ERRNO(&new_request->parser) != HPE_OK ? message : "incomplete request");
if (new_request->response.status == static_cast<http_status>(0)) {
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, string::split(message, '\n') }
}));
} else {
write_http_response(*new_request, error_code);
}
end_http_request(*new_request);
}
}
detach();
}
return received;
}
void
HttpClient::on_read_file(const char* /*buf*/, ssize_t received)
{
L_CALL("HttpClient::on_read_file(<buf>, {})", received);
L_ERR("Not Implemented: HttpClient::on_read_file: {} bytes", received);
}
void
HttpClient::on_read_file_done()
{
L_CALL("HttpClient::on_read_file_done()");
L_ERR("Not Implemented: HttpClient::on_read_file_done");
}
// HTTP parser callbacks.
const http_parser_settings HttpClient::http_parser_settings = {
HttpClient::message_begin_cb,
HttpClient::url_cb,
HttpClient::status_cb,
HttpClient::header_field_cb,
HttpClient::header_value_cb,
HttpClient::headers_complete_cb,
HttpClient::body_cb,
HttpClient::message_complete_cb,
HttpClient::chunk_header_cb,
HttpClient::chunk_complete_cb,
};
inline std::string readable_http_parser_flags(http_parser* parser) {
std::vector<std::string> values;
if ((parser->flags & F_CHUNKED) == F_CHUNKED) values.push_back("F_CHUNKED");
if ((parser->flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) values.push_back("F_CONNECTION_KEEP_ALIVE");
if ((parser->flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) values.push_back("F_CONNECTION_CLOSE");
if ((parser->flags & F_CONNECTION_UPGRADE) == F_CONNECTION_UPGRADE) values.push_back("F_CONNECTION_UPGRADE");
if ((parser->flags & F_TRAILING) == F_TRAILING) values.push_back("F_TRAILING");
if ((parser->flags & F_UPGRADE) == F_UPGRADE) values.push_back("F_UPGRADE");
if ((parser->flags & F_SKIPBODY) == F_SKIPBODY) values.push_back("F_SKIPBODY");
if ((parser->flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) values.push_back("F_CONTENTLENGTH");
return string::join(values, "|");
}
int
HttpClient::message_begin_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_begin(parser);
});
}
int
HttpClient::url_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_url(parser, at, length);
});
}
int
HttpClient::status_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_status(parser, at, length);
});
}
int
HttpClient::header_field_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_field(parser, at, length);
});
}
int
HttpClient::header_value_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_value(parser, at, length);
});
}
int
HttpClient::headers_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_headers_complete(parser);
});
}
int
HttpClient::body_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_body(parser, at, length);
});
}
int
HttpClient::message_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_complete(parser);
});
}
int
HttpClient::chunk_header_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_header(parser);
});
}
int
HttpClient::chunk_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_complete(parser);
});
}
int
HttpClient::on_message_begin([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_begin(<parser>)");
L_HTTP_PROTO("on_message_begin {{state:{}, header_state:{}}}", HttpParserStateNames(parser->state), HttpParserHeaderStateNames(parser->header_state));
waiting = true;
new_request->begins = std::chrono::system_clock::now();
L_TIMED_VAR(new_request->log, 10s,
"Request taking too long...",
"Request took too long!");
return 0;
}
int
HttpClient::on_url(http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_url(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_url {{state:{}, header_state:{}}}: {}", HttpParserStateNames(parser->state), HttpParserHeaderStateNames(parser->header_state), repr(at, length));
new_request->method = HTTP_PARSER_METHOD(parser);
new_request->path.append(at, length);
return 0;
}
int
HttpClient::on_status([[maybe_unused]] http_parser* parser, [[maybe_unused]] const char* at, [[maybe_unused]] size_t length)
{
L_CALL("HttpClient::on_status(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_status {{state:{}, header_state:{}}}: {}", HttpParserStateNames(parser->state), HttpParserHeaderStateNames(parser->header_state), repr(at, length));
return 0;
}
int
HttpClient::on_header_field([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_field(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_field {{state:{}, header_state:{}}}: {}", HttpParserStateNames(parser->state), HttpParserHeaderStateNames(parser->header_state), repr(at, length));
new_request->_header_name = std::string(at, length);
return 0;
}
int
HttpClient::on_header_value([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_value(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_value {{state:{}, header_state:{}}}: {}", HttpParserStateNames(parser->state), HttpParserHeaderStateNames(parser->header_state), repr(at, length));
auto _header_value = std::string_view(at, length);
if (Logging::log_level >= LOG_DEBUG) {
new_request->headers.append(new_request->_header_name);
new_request->headers.append(": ");
new_request->headers.append(_header_value);
new_request->headers.append(eol);
}
constexpr static auto _ = phf::make_phf({
hhl("expect"),
hhl("100-continue"),
hhl("content-type"),
hhl("accept"),
hhl("accept-encoding"),
hhl("http-method-override"),
hhl("x-http-method-override"),
});
switch (_.fhhl(new_request->_header_name)) {
case _.fhhl("expect"):
case _.fhhl("100-continue"):
// Respond with HTTP/1.1 100 Continue
new_request->expect_100 = true;
break;
case _.fhhl("content-type"):
new_request->ct_type = ct_type_t(_header_value);
break;
case _.fhhl("accept"): {
static AcceptLRU accept_sets;
auto value = string::lower(_header_value);
auto lookup = accept_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
int indent = -1;
double q = 1.0;
if (next->length(3) != 0) {
auto param = next->str(3);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
} else if (next_param->str(1) == "indent") {
indent = strict_stoi(next_param->str(2));
if (indent < 0) { indent = 0;
} else if (indent > 16) { indent = 16; }
}
++next_param;
}
}
lookup.second.emplace(i, q, ct_type_t(next->str(1), next->str(2)), indent);
++next;
++i;
}
accept_sets.emplace(value, lookup.second);
}
new_request->accept_set = std::move(lookup.second);
break;
}
case _.fhhl("accept-encoding"): {
static AcceptEncodingLRU accept_encoding_sets;
auto value = string::lower(_header_value);
auto lookup = accept_encoding_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_encoding_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
double q = 1.0;
if (next->length(2) != 0) {
auto param = next->str(2);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
}
++next_param;
}
} else {
}
lookup.second.emplace(i, q, next->str(1));
++next;
++i;
}
accept_encoding_sets.emplace(value, lookup.second);
}
new_request->accept_encoding_set = std::move(lookup.second);
break;
}
case _.fhhl("x-http-method-override"):
case _.fhhl("http-method-override"): {
switch (http_methods.fhhl(_header_value)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "{} header must use the POST method", repr(new_request->_header_name)); \
} \
new_request->method = HTTP_##name; \
break;
METHODS_OPTIONS()
#undef OPTION
default:
parser->http_errno = HPE_INVALID_METHOD;
break;
}
break;
}
}
return 0;
}
int
HttpClient::on_headers_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_headers_complete(<parser>)");
L_HTTP_PROTO("on_headers_complete {{state:{}, header_state:{}, flags:[{}]}}",
HttpParserStateNames(parser->state),
HttpParserHeaderStateNames(parser->header_state),
readable_http_parser_flags(parser));
// Prepare the request view
if (int err = prepare()) {
end_http_request(*new_request);
return err;
}
if likely(!closed && !new_request->atom_ending) {
if likely(new_request->view) {
if (new_request->mode != Request::Mode::FULL) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || new_request != requests.front()) {
requests.push_back(new_request); // Enqueue streamed request
}
}
}
}
return 0;
}
int
HttpClient::on_body([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_body(<parser>, <at>, {})", length);
L_HTTP_PROTO("on_body {{state:{}, header_state:{}, flags:[{}]}}: {}",
HttpParserStateNames(parser->state),
HttpParserHeaderStateNames(parser->header_state),
readable_http_parser_flags(parser),
repr(at, length));
new_request->size += length;
if likely(!closed && !new_request->atom_ending) {
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || new_request->view) {
signal_pending = new_request->append(at, length);
}
if (new_request->view) {
if (signal_pending) {
new_request->pending.signal();
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
}
}
return 0;
}
int
HttpClient::on_message_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_complete(<parser>)");
L_HTTP_PROTO("on_message_complete {{state:{}, header_state:{}, flags:[{}]}}",
HttpParserStateNames(parser->state),
HttpParserHeaderStateNames(parser->header_state),
readable_http_parser_flags(parser));
if (Logging::log_level > LOG_DEBUG) {
log_request(*new_request);
}
if likely(!closed && !new_request->atom_ending) {
new_request->atom_ending = true;
std::shared_ptr<Request> request = std::make_shared<Request>(this);
std::swap(new_request, request);
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || request->view) {
request->append(nullptr, 0); // flush pending stuff
signal_pending = true; // always signal pending
}
if (request->view) {
if (signal_pending) {
request->pending.signal(); // always signal, so view continues ending
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || request != requests.front()) {
requests.push_back(std::move(request)); // Enqueue request
}
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
} else {
end_http_request(*request);
}
}
waiting = false;
return 0;
}
int
HttpClient::on_chunk_header([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_header(<parser>)");
L_HTTP_PROTO("on_chunk_header {{state:{}, header_state:{}, flags:[{}]}}",
HttpParserStateNames(parser->state),
HttpParserHeaderStateNames(parser->header_state),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::on_chunk_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_complete(<parser>)");
L_HTTP_PROTO("on_chunk_complete {{state:{}, header_state:{}, flags:[{}]}}",
HttpParserStateNames(parser->state),
HttpParserHeaderStateNames(parser->header_state),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::prepare()
{
L_CALL("HttpClient::prepare()");
L_TIMED_VAR(request.log, 1s,
"Response taking too long: {}",
"Response took too long: {}",
request.head());
new_request->received = std::chrono::system_clock::now();
if (new_request->parser.http_major == 0 || (new_request->parser.http_major == 1 && new_request->parser.http_minor == 0)) {
new_request->closing = true;
}
if ((new_request->parser.flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) {
new_request->closing = false;
}
if ((new_request->parser.flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) {
new_request->closing = true;
}
if (new_request->accept_set.empty()) {
if (!new_request->ct_type.empty()) {
new_request->accept_set.emplace(0, 1.0, new_request->ct_type, 0);
}
new_request->accept_set.emplace(1, 1.0, any_type, 0);
}
new_request->type_encoding = resolve_encoding(*new_request);
if (new_request->type_encoding == Encoding::unknown) {
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response encoding gzip, deflate or identity not provided in the Accept-Encoding header" }) } }
}));
} else {
write_http_response(*new_request, error_code);
}
return 1;
}
url_resolve(*new_request);
auto id = new_request->path_parser.get_id();
auto has_pth = new_request->path_parser.has_pth();
auto cmd = new_request->path_parser.get_cmd();
if (!cmd.empty()) {
auto mapping = cmd;
mapping.remove_prefix(1);
switch (http_methods.fhhl(mapping)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "HTTP Mappings must use GET or POST method"); \
} \
new_request->method = HTTP_##name; \
cmd = ""; \
break;
METHODS_OPTIONS()
#undef OPTION
}
}
switch (new_request->method) {
case HTTP_SEARCH:
if (id.empty()) {
new_request->view = &HttpClient::search_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COUNT:
if (id.empty()) {
new_request->view = &HttpClient::count_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_INFO:
if (id.empty()) {
new_request->view = &HttpClient::info_view;
} else {
new_request->view = &HttpClient::info_view;
}
break;
case HTTP_HEAD:
if (id.empty()) {
new_request->view = &HttpClient::database_exists_view;
} else {
new_request->view = &HttpClient::document_exists_view;
}
break;
case HTTP_GET:
if (!cmd.empty() && id.empty()) {
if (!has_pth && cmd == ":metrics") {
new_request->view = &HttpClient::metrics_view;
#if XAPIAND_DATABASE_WAL
} else if (cmd == ":wal") {
new_request->view = &HttpClient::wal_view;
#endif
#if XAPIAND_CLUSTERING
} else if (!has_pth && cmd == ":nodes") {
new_request->view = &HttpClient::nodes_view;
#endif
} else {
new_request->view = &HttpClient::retrieve_metadata_view;
}
} else if (!id.empty()) {
if (is_range(id)) {
new_request->view = &HttpClient::search_view;
} else {
new_request->view = &HttpClient::retrieve_document_view;
}
} else {
new_request->view = &HttpClient::retrieve_database_view;
}
break;
case HTTP_POST:
if (!cmd.empty() && id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else if (!id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_PUT:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::write_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::write_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_PATCH:
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::update_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_STORE:
if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DELETE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::delete_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::delete_document_view;
} else if (has_pth) {
new_request->view = &HttpClient::delete_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COMMIT:
if (id.empty()) {
new_request->view = &HttpClient::commit_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DUMP:
if (id.empty()) {
new_request->view = &HttpClient::dump_database_view;
} else {
new_request->view = &HttpClient::dump_document_view;
}
break;
case HTTP_RESTORE:
if (id.empty()) {
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) {
if (new_request->ct_type == ndjson_type || new_request->ct_type == x_ndjson_type) {
new_request->mode = Request::Mode::STREAM_NDJSON;
} else if (new_request->ct_type == msgpack_type || new_request->ct_type == x_msgpack_type) {
new_request->mode = Request::Mode::STREAM_MSGPACK;
}
}
new_request->view = &HttpClient::restore_database_view;
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_CHECK:
if (id.empty()) {
new_request->view = &HttpClient::check_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_FLUSH:
if (opts.admin_commands && id.empty() && !has_pth) {
// Flush both databases and clients by default (unless one is specified)
new_request->query_parser.rewind();
int flush_databases = new_request->query_parser.next("databases");
new_request->query_parser.rewind();
int flush_clients = new_request->query_parser.next("clients");
if (flush_databases != -1 || flush_clients == -1) {
XapiandManager::database_pool()->cleanup(true);
}
if (flush_clients != -1 || flush_databases == -1) {
XapiandManager::manager()->shutdown(0, 0);
}
write_http_response(*new_request, HTTP_STATUS_OK);
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_OPTIONS:
write(http_response(*new_request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_OPTIONS_RESPONSE | HTTP_BODY_RESPONSE));
break;
case HTTP_QUIT:
if (opts.admin_commands && !has_pth && id.empty()) {
XapiandManager::try_shutdown(true);
write_http_response(*new_request, HTTP_STATUS_OK);
shutdown();
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
default: {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
new_request->parser.http_errno = HPE_INVALID_METHOD;
return 1;
}
}
if (!new_request->view && Logging::log_level < LOG_DEBUG) {
return 1;
}
if (new_request->expect_100) {
// Return "100 Continue" if client sent "Expect: 100-continue"
write(http_response(*new_request, HTTP_STATUS_CONTINUE, HTTP_STATUS_RESPONSE));
// Go back to unknown response state:
new_request->response.head.clear();
new_request->response.status = static_cast<http_status>(0);
}
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH && new_request->parser.content_length) {
if (new_request->mode == Request::Mode::STREAM_MSGPACK) {
new_request->unpacker.reserve_buffer(new_request->parser.content_length);
} else {
new_request->raw.reserve(new_request->parser.content_length);
}
}
return 0;
}
void
HttpClient::process(Request& request)
{
L_CALL("HttpClient::process()");
L_OBJ_BEGIN("HttpClient::process:BEGIN");
L_OBJ_END("HttpClient::process:END");
handled_errors(request, [&]{
(this->*request.view)(request);
return 0;
});
}
void
HttpClient::operator()()
{
L_CALL("HttpClient::operator()()");
L_CONN("Start running in worker...");
std::unique_lock<std::mutex> lk(runner_mutex);
while (!requests.empty() && !closed) {
Request& request = *requests.front();
if (request.atom_ended) {
requests.pop_front();
continue;
}
request.ending = request.atom_ending.load();
lk.unlock();
// wait for the request to be ready
if (!request.ending && !request.wait()) {
lk.lock();
continue;
}
try {
ASSERT(request.view);
process(request);
request.begining = false;
} catch (...) {
request.begining = false;
end_http_request(request);
lk.lock();
requests.pop_front();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: HTTP client ended with an unhandled exception");
detach();
throw;
}
if (request.ending) {
end_http_request(request);
auto closing = request.closing;
lk.lock();
requests.pop_front();
if (closing) {
running = false;
L_CONN("Running in worker ended after request closing.");
lk.unlock();
shutdown();
return;
}
} else {
lk.lock();
}
}
running = false;
L_CONN("Running in replication worker ended. {{requests_empty:{}, closed:{}, is_shutting_down:{}}}", requests.empty(), closed.load(), is_shutting_down());
lk.unlock();
if (is_shutting_down()) {
shutdown();
return;
}
redetach(); // try re-detaching if already flagged as detaching
}
MsgPack
HttpClient::node_obj()
{
L_CALL("HttpClient::node_obj()");
endpoints.clear();
auto leader_node = Node::leader_node();
endpoints.add(Endpoint{".xapiand", leader_node});
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
auto local_node = Node::local_node();
auto document = db_handler.get_document(local_node->lower_name());
auto obj = document.get_obj();
obj.update(MsgPack({
#ifdef XAPIAND_CLUSTERING
{ RESPONSE_CLUSTER_NAME, opts.cluster_name },
#endif
{ RESPONSE_SERVER, Package::STRING },
{ RESPONSE_URL, Package::BUGREPORT },
{ RESPONSE_VERSIONS, {
{ "Xapiand", Package::REVISION.empty() ? Package::VERSION : string::format("{}_{}", Package::VERSION, Package::REVISION) },
{ "Xapian", string::format("{}.{}.{}", Xapian::major_version(), Xapian::minor_version(), Xapian::revision()) },
#ifdef XAPIAND_CHAISCRIPT
{ "ChaiScript", string::format("{}.{}", chaiscript::Build_Info::version_major(), chaiscript::Build_Info::version_minor()) },
#endif
} },
{ "options", {
{ "verbosity", opts.verbosity },
{ "processors", opts.processors },
{ "limits", {
// { "max_clients", opts.max_clients },
{ "max_database_readers", opts.max_database_readers },
} },
{ "cache", {
{ "database_pool_size", opts.database_pool_size },
{ "schema_pool_size", opts.schema_pool_size },
{ "scripts_cache_size", opts.scripts_cache_size },
#ifdef XAPIAND_CLUSTERING
{ "resolver_cache_size", opts.resolver_cache_size },
#endif
} },
{ "thread_pools", {
{ "num_shards", opts.num_shards },
{ "num_replicas", opts.num_replicas },
{ "num_http_servers", opts.num_http_servers },
{ "num_http_clients", opts.num_http_clients },
#ifdef XAPIAND_CLUSTERING
{ "num_remote_servers", opts.num_remote_servers },
{ "num_remote_clients", opts.num_remote_clients },
{ "num_replication_servers", opts.num_replication_servers },
{ "num_replication_clients", opts.num_replication_clients },
#endif
{ "num_async_wal_writers", opts.num_async_wal_writers },
{ "num_doc_preparers", opts.num_doc_preparers },
{ "num_doc_indexers", opts.num_doc_indexers },
{ "num_committers", opts.num_committers },
{ "num_fsynchers", opts.num_fsynchers },
#ifdef XAPIAND_CLUSTERING
{ "num_replicators", opts.num_replicators },
{ "num_discoverers", opts.num_discoverers },
#endif
} },
} },
}));
return obj;
}
void
HttpClient::metrics_view(Request& request)
{
L_CALL("HttpClient::metrics_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
auto server_info = XapiandManager::server_metrics();
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE | HTTP_BODY_RESPONSE, server_info, "", "text/plain", "", server_info.size()));
}
void
HttpClient::document_exists_view(Request& request)
{
L_CALL("HttpClient::document_exists_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
db_handler.get_document(request.path_parser.get_id()).validate();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
void
HttpClient::delete_document_view(Request& request)
{
L_CALL("HttpClient::delete_document_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
std::string document_id(request.path_parser.get_id());
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.delete_document(document_id, query_field.commit);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_NO_CONTENT);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Deletion took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "delete"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_document_view(Request& request)
{
L_CALL("HttpClient::write_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
auto indexed = db_handler.index(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
request.ready = std::chrono::system_clock::now();
std::string location;
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (request.echo) {
auto it = response_obj.find(ID_FIELD_NAME);
if (document_id.empty()) {
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), document_id_obj.as_str());
response_obj[ID_FIELD_NAME] = std::move(document_id_obj);
} else {
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), it.value().as_str());
}
} else {
if (it == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj, location);
} else {
if (document_id.empty()) {
auto it = response_obj.find(ID_FIELD_NAME);
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), document_id_obj.as_str());
} else {
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), it.value().as_str());
}
}
write_http_response(request, document_id.empty() ? HTTP_STATUS_CREATED : HTTP_STATUS_NO_CONTENT, MsgPack(), location);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Indexing took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "index"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_document_view(Request& request)
{
L_CALL("HttpClient::update_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
ASSERT(!document_id.empty());
request.processing = std::chrono::system_clock::now();
std::string operation;
DataType indexed;
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (request.method == HTTP_PATCH) {
operation = "patch";
indexed = db_handler.patch(document_id, query_field.version, decoded_body, query_field.commit);
} else if (request.method == HTTP_STORE) {
operation = "store";
indexed = db_handler.update(document_id, query_field.version, true, decoded_body, query_field.commit, request.ct_type == json_type || request.ct_type == msgpack_type || request.ct_type.empty() ? mime_type(selector) : request.ct_type);
} else {
operation = "update";
indexed = db_handler.update(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
}
request.ready = std::chrono::system_clock::now();
if (request.echo) {
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (response_obj.find(ID_FIELD_NAME) == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", operation},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_metadata_view(Request& request)
{
L_CALL("HttpClient::retrieve_metadata_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
MsgPack response_obj;
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
ASSERT(!key.empty());
key.remove_prefix(1);
if (key.empty()) {
response_obj = MsgPack::MAP();
for (auto& _key : db_handler.get_metadata_keys()) {
auto metadata = db_handler.get_metadata(_key);
if (!metadata.empty()) {
response_obj[_key] = MsgPack::unserialise(metadata);
}
}
} else {
auto metadata = db_handler.get_metadata(key);
if (metadata.empty()) {
throw Xapian::DocNotFoundError("Metadata not found");
} else {
response_obj = MsgPack::unserialise(metadata);
}
}
request.ready = std::chrono::system_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Get metadata took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "get_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_metadata_view(Request& request)
{
L_CALL("HttpClient::write_metadata_view()");
auto& decoded_body = request.decoded_body();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
ASSERT(!key.empty());
key.remove_prefix(1);
if (key.empty() || key == "schema" || key == "wal" || key == "nodes" || key == "metrics") {
THROW(ClientError, "Metadata {} is read-only", repr(request.path_parser.get_cmd()));
}
db_handler.set_metadata(key, decoded_body.serialise());
request.ready = std::chrono::system_clock::now();
if (request.echo) {
write_http_response(request, HTTP_STATUS_OK, selector.empty() ? decoded_body : decoded_body.select(selector));
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Set metadata took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "set_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_metadata_view(Request& request)
{
L_CALL("HttpClient::update_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::delete_metadata_view(Request& request)
{
L_CALL("HttpClient::delete_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::info_view(Request& request)
{
L_CALL("HttpClient::info_view()");
MsgPack response_obj;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Info about a specific document was requested
if (request.path_parser.off_id != nullptr) {
auto id = request.path_parser.get_id();
request.query_parser.rewind();
bool raw = request.query_parser.next("raw") != -1;
response_obj = db_handler.get_document_info(id, raw, request.human);
} else {
response_obj = db_handler.get_database_info();
}
request.ready = std::chrono::system_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Info took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "info"}
})
.Observe(took / 1e9);
}
void
HttpClient::nodes_view(Request& request)
{
L_CALL("HttpClient::nodes_view()");
auto nodes = MsgPack::ARRAY();
#ifdef XAPIAND_CLUSTERING
for (auto& node : Node::nodes()) {
if (node->idx) {
auto obj = MsgPack::MAP();
obj["idx"] = node->idx;
obj["name"] = node->name();
if (Node::is_active(node)) {
obj["host"] = node->host();
obj["http_port"] = node->http_port;
obj["remote_port"] = node->remote_port;
obj["replication_port"] = node->replication_port;
obj["active"] = true;
} else {
obj["active"] = false;
}
nodes.push_back(obj);
}
}
#endif
write_http_response(request, HTTP_STATUS_OK, {
{ RESPONSE_CLUSTER_NAME, opts.cluster_name },
{ RESPONSE_NODES, nodes },
});
}
void
HttpClient::database_exists_view(Request& request)
{
L_CALL("HttpClient::database_exists_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN);
db_handler.reopen(); // Ensure it can be opened.
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
MsgPack
HttpClient::retrieve_database(const query_field_t& query_field, bool is_root)
{
L_CALL("HttpClient::retrieve_database()");
MsgPack schema;
MsgPack settings;
auto obj = MsgPack::MAP();
// Get active schema
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrieve full schema
schema = db_handler.get_schema()->get_full(true);
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Get index settings (from .xapiand/index)
auto id = std::string(endpoints.size() == 1 ? endpoints[0].path : unsharded_path(endpoints[0].path));
endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{".xapiand/index"},
false,
query_field.primary);
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
auto did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
settings = document.get_obj();
// Remove schema, ID and version from document:
auto it_e = settings.end();
auto it = settings.find(SCHEMA_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(ID_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(RESERVED_VERSION);
if (it != it_e) {
settings.erase(it);
}
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Add node information for '/':
if (is_root) {
obj.update(node_obj());
}
if (!settings.empty()) {
obj[RESERVED_SETTINGS].update(settings);
}
if (!schema.empty()) {
obj[RESERVED_SCHEMA].update(schema);
}
return obj;
}
void
HttpClient::retrieve_database_view(Request& request)
{
L_CALL("HttpClient::retrieve_database_view()");
ASSERT(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving database took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve_database"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE DATABASE");
}
void
HttpClient::update_database_view(Request& request)
{
L_CALL("HttpClient::update_database_view()");
ASSERT(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (decoded_body.is_map()) {
auto schema_it = decoded_body.find(RESERVED_SCHEMA);
if (schema_it != decoded_body.end()) {
auto& schema = schema_it.value();
db_handler.write_schema(schema, false);
}
}
db_handler.reopen(); // Ensure touch.
request.ready = std::chrono::system_clock::now();
if (request.echo) {
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating database took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "update_database"},
})
.Observe(took / 1e9);
}
void
HttpClient::delete_database_view(Request& request)
{
L_CALL("HttpClient::delete_database_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::commit_database_view(Request& request)
{
L_CALL("HttpClient::commit_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.commit(); // Ensure touch.
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Commit took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "commit"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_document_view(Request& request)
{
L_CALL("HttpClient::dump_document_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto document_id = request.path_parser.get_id();
ASSERT(!document_id.empty());
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto obj = db_handler.dump_document(document_id);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_database_view(Request& request)
{
L_CALL("HttpClient::dump_database_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto ct_type = resolve_ct_type(request, MSGPACK_CONTENT_TYPE);
if (ct_type.empty()) {
auto dump_ct_type = resolve_ct_type(request, ct_type_t("application/octet-stream"));
if (dump_ct_type.empty()) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type application/octet-stream not provided in the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED SEARCH");
return;
}
char path[] = "/tmp/xapian_dump.XXXXXX";
int file_descriptor = io::mkstemp(path);
try {
db_handler.dump_documents(file_descriptor);
} catch (...) {
io::close(file_descriptor);
io::unlink(path);
throw;
}
request.ready = std::chrono::system_clock::now();
size_t content_length = io::lseek(file_descriptor, 0, SEEK_CUR);
io::close(file_descriptor);
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE, "", "", dump_ct_type.to_string(), "", content_length));
write_file(path, true);
return;
}
auto docs = db_handler.dump_documents();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, docs);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::restore_database_view(Request& request)
{
L_CALL("HttpClient::restore_database_view()");
if (request.mode == Request::Mode::STREAM_MSGPACK || request.mode == Request::Mode::STREAM_NDJSON) {
MsgPack obj;
while (request.next_object(obj)) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments);
}
request.indexer->prepare(std::move(obj));
}
} else {
auto& docs = request.decoded_body();
for (auto& obj : docs) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments);
}
request.indexer->prepare(std::move(obj));
}
}
if (request.ending) {
request.indexer->wait();
request.ready = std::chrono::system_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
MsgPack response_obj = {
// { RESPONSE_ENDPOINT, endpoints.to_string() },
{ RESPONSE_PROCESSED, request.indexer->processed() },
{ RESPONSE_INDEXED, request.indexer->indexed() },
{ RESPONSE_TOTAL, request.indexer->total() },
{ RESPONSE_ITEMS, request.indexer->results() },
};
if (request.human) {
response_obj[RESPONSE_TOOK] = string::from_delta(took);
} else {
response_obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
L_TIME("Restore took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "restore"},
})
.Observe(took / 1e9);
}
}
#if XAPIAND_DATABASE_WAL
void
HttpClient::wal_view(Request& request)
{
L_CALL("HttpClient::wal_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler{endpoints};
request.query_parser.rewind();
bool unserialised = request.query_parser.next("raw") == -1;
auto repr = db_handler.repr_wal(0, std::numeric_limits<Xapian::rev>::max(), unserialised);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, repr);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("WAL took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "wal"},
})
.Observe(took / 1e9);
}
#endif
void
HttpClient::check_database_view(Request& request)
{
L_CALL("HttpClient::check_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler{endpoints};
auto status = db_handler.check();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, status);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Database check took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "db_check"},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_document_view(Request& request)
{
L_CALL("HttpClient::retrieve_document_view()");
auto id = request.path_parser.get_id();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_ID);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
Xapian::docid did;
did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const Data data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto accepted = data.get_accepted(request.accept_set, mime_type(selector));
if (accepted.first == nullptr) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type not accepted by the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED RETRIEVE");
return;
}
auto& locator = *accepted.first;
if (locator.ct_type.empty()) {
// Locator doesn't have a content type, serialize and return as document
auto obj = MsgPack::unserialise(locator.data());
// Detailed info about the document:
if (obj.find(ID_FIELD_NAME) == obj.end()) {
obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
obj[RESPONSE_xSHARD] = shard_num + 1;
// obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
// Locator has content type, return as a blob (an image for instance)
auto ct_type = locator.ct_type;
request.response.blob = locator.data();
#ifdef XAPIAND_DATA_STORAGE
if (locator.type == Locator::Type::stored || locator.type == Locator::Type::compressed_stored) {
if (request.response.blob.empty()) {
auto stored = db_handler.storage_get_stored(locator, did);
request.response.blob = unserialise_string_at(STORED_BLOB, stored);
}
}
#endif
request.ready = std::chrono::system_clock::now();
request.response.ct_type = ct_type;
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, request.response.blob, false, true, true);
if (!encoded.empty() && encoded.size() <= request.response.blob.size()) {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, encoded, "", ct_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string()));
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE");
}
void
HttpClient::search_view(Request& request)
{
L_CALL("HttpClient::search_view()");
std::string selector_string_holder;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
MSet mset{};
MsgPack aggregations;
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
AggregationMatchSpy aggs(decoded_body, db_handler.get_schema());
if (decoded_body.find(RESERVED_QUERYDSL_SELECTOR) != decoded_body.end()) {
auto selector_obj = decoded_body.at(RESERVED_QUERYDSL_SELECTOR);
if (selector_obj.is_string()) {
selector_string_holder = selector_obj.as_str();
selector = selector_string_holder;
} else {
THROW(ClientError, "The {} must be a string", RESERVED_QUERYDSL_SELECTOR);
}
}
mset = db_handler.get_mset(query_field, &decoded_body, &aggs);
aggregations = aggs.get_aggregation().at(RESERVED_AGGS_AGGREGATIONS);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
obj[RESPONSE_COUNT] = mset.size();
if (aggregations) {
obj[RESPONSE_AGGREGATIONS] = aggregations;
}
obj[RESPONSE_HITS] = MsgPack::ARRAY();
auto& hits = obj[RESPONSE_HITS];
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto did = *m;
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const auto data = Data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto hit_obj = MsgPack::MAP();
auto main_locator = data.get("");
if (main_locator != nullptr) {
auto locator_data = main_locator->data();
if (!locator_data.empty()) {
hit_obj = MsgPack::unserialise(locator_data);
}
}
// Detailed info about the document:
if (hit_obj.find(ID_FIELD_NAME) == hit_obj.end()) {
hit_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
hit_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
hit_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
hit_obj[RESPONSE_xSHARD] = shard_num + 1;
// hit_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
hit_obj[RESPONSE_xRANK] = m.get_rank();
hit_obj[RESPONSE_xWEIGHT] = m.get_weight();
hit_obj[RESPONSE_xPERCENT] = m.get_percent();
}
if (!selector.empty()) {
hit_obj = hit_obj.select(selector);
}
hits.append(hit_obj);
}
request.ready = std::chrono::system_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Searching took {}", string::from_delta(took));
if (request.human) {
obj[RESPONSE_TOOK] = string::from_delta(took);
} else {
obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, obj);
if (aggregations) {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "aggregation"},
})
.Observe(took / 1e9);
} else {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "search"},
})
.Observe(took / 1e9);
}
L_SEARCH("FINISH SEARCH");
}
void
HttpClient::count_view(Request& request)
{
L_CALL("HttpClient::count_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
MSet mset{};
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
mset = db_handler.get_mset(query_field, &decoded_body, nullptr);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
}
void
HttpClient::write_status_response(Request& request, enum http_status status, const std::string& message)
{
L_CALL("HttpClient::write_status_response()");
if (request.comments) {
write_http_response(request, status, MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, message.empty() ? MsgPack({ http_status_str(status) }) : string::split(message, '\n') }
}));
} else {
write_http_response(request, status);
}
}
void
HttpClient::url_resolve(Request& request)
{
L_CALL("HttpClient::url_resolve(request)");
struct http_parser_url u;
std::string b = repr(request.path, true, 0);
L_HTTP("URL: {}", b);
if (http_parser_parse_url(request.path.data(), request.path.size(), 0, &u) != 0) {
L_HTTP_PROTO("Parsing not done");
THROW(ClientError, "Invalid HTTP");
}
L_HTTP_PROTO("HTTP parsing done!");
if ((u.field_set & (1 << UF_PATH )) != 0) {
if (request.path_parser.init(std::string_view(request.path.data() + u.field_data[3].off, u.field_data[3].len)) >= PathParser::State::END) {
THROW(ClientError, "Invalid path");
}
}
if ((u.field_set & (1 << UF_QUERY)) != 0) {
if (request.query_parser.init(std::string_view(b.data() + u.field_data[4].off, u.field_data[4].len)) < 0) {
THROW(ClientError, "Invalid query");
}
}
bool pretty = !opts.no_pretty && (opts.pretty || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("pretty") != -1) {
if (request.query_parser.len != 0u) {
try {
pretty = Serialise::boolean(request.query_parser.get()) == "t";
request.indented = pretty ? DEFAULT_INDENTATION : -1;
} catch (const Exception&) { }
} else {
if (request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
} else {
if (pretty && request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
request.query_parser.rewind();
if (request.query_parser.next("human") != -1) {
if (request.query_parser.len != 0u) {
try {
request.human = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.human = true;
}
} else {
request.human = pretty;
}
bool echo = !opts.no_echo && (opts.echo || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("echo") != -1) {
if (request.query_parser.len != 0u) {
try {
request.echo = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.echo = true;
}
} else {
request.echo = echo;
}
bool comments = !opts.no_comments && (opts.comments || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("comments") != -1) {
if (request.query_parser.len != 0u) {
try {
request.comments = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.comments = true;
}
} else {
request.comments = comments;
}
}
size_t
HttpClient::resolve_index_endpoints(Request& request, const query_field_t& query_field, const MsgPack* settings)
{
L_CALL("HttpClient::resolve_index_endpoints(<request>, <query_field>, <settings>)");
auto paths = expand_paths(request);
endpoints.clear();
for (const auto& path : paths) {
auto index_endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{path},
query_field.writable,
query_field.primary,
settings);
if (index_endpoints.empty()) {
throw Xapian::NetworkError("Endpoint node not available");
}
for (auto& endpoint : index_endpoints) {
endpoints.add(endpoint);
}
}
L_HTTP("Endpoint: -> {}", endpoints.to_string());
return paths.size();
}
std::vector<std::string>
HttpClient::expand_paths(Request& request)
{
L_CALL("HttpClient::expand_paths(<request>)");
std::vector<std::string> paths;
request.path_parser.rewind();
PathParser::State state;
while ((state = request.path_parser.next()) < PathParser::State::END) {
std::string index_path;
auto pth = request.path_parser.get_pth();
if (string::startswith(pth, '/')) {
pth.remove_prefix(1);
}
index_path.append(pth);
#ifdef XAPIAND_CLUSTERING
MSet mset;
if (string::endswith(index_path, '*')) {
index_path.pop_back();
auto stripped_index_path = index_path;
if (string::endswith(stripped_index_path, '/')) {
stripped_index_path.pop_back();
}
Endpoints index_endpoints;
for (auto& node : Node::nodes()) {
if (node->idx) {
index_endpoints.add(Endpoint{string::format(".xapiand/{}", node->lower_name())});
}
}
DatabaseHandler db_handler;
db_handler.reset(index_endpoints);
if (stripped_index_path.empty()) {
mset = db_handler.get_all_mset("", 0, 100);
} else {
auto query = Xapian::Query(Xapian::Query::OP_AND_NOT,
Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(prefixed(stripped_index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path + "/.", DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR)))
);
mset = db_handler.get_mset(query, 0, 100);
}
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto document = db_handler.get_document(*m);
index_path = document.get_value(DB_SLOT_ID);
paths.push_back(std::move(index_path));
}
} else {
#endif
paths.push_back(std::move(index_path));
#ifdef XAPIAND_CLUSTERING
}
#endif
}
return paths;
}
query_field_t
HttpClient::query_field_maker(Request& request, int flags)
{
L_CALL("HttpClient::query_field_maker(<request>, <flags>)");
query_field_t query_field;
if ((flags & QUERY_FIELD_WRITABLE) != 0) {
query_field.writable = true;
}
if ((flags & QUERY_FIELD_PRIMARY) != 0) {
query_field.primary = true;
}
if ((flags & QUERY_FIELD_COMMIT) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("commit") != -1) {
query_field.commit = true;
if (request.query_parser.len != 0u) {
try {
query_field.commit = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("version") != -1) {
query_field.version = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_VOLATILE) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("volatile") != -1) {
query_field.primary = true;
if (request.query_parser.len != 0u) {
try {
query_field.primary = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
}
if (((flags & QUERY_FIELD_ID) != 0) || ((flags & QUERY_FIELD_SEARCH) != 0)) {
request.query_parser.rewind();
if (request.query_parser.next("offset") != -1) {
query_field.offset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("check_at_least") != -1) {
query_field.check_at_least = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("limit") != -1) {
query_field.limit = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_SEARCH) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("spelling") != -1) {
query_field.spelling = true;
if (request.query_parser.len != 0u) {
try {
query_field.spelling = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("synonyms") != -1) {
query_field.synonyms = true;
if (request.query_parser.len != 0u) {
try {
query_field.synonyms = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
while (request.query_parser.next("query") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("q") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("sort") != -1) {
query_field.sort.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("metric") != -1) {
query_field.metric = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("icase") != -1) {
query_field.icase = Serialise::boolean(request.query_parser.get()) == "t";
}
request.query_parser.rewind();
if (request.query_parser.next("collapse_max") != -1) {
query_field.collapse_max = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("collapse") != -1) {
query_field.collapse = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy") != -1) {
query_field.is_fuzzy = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_fuzzy = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_fuzzy) {
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_rset") != -1) {
query_field.fuzzy.n_rset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_eset") != -1) {
query_field.fuzzy.n_eset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_term") != -1) {
query_field.fuzzy.n_term = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.field") != -1) {
query_field.fuzzy.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.type") != -1) {
query_field.fuzzy.type.emplace_back(request.query_parser.get());
}
}
request.query_parser.rewind();
if (request.query_parser.next("nearest") != -1) {
query_field.is_nearest = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_nearest = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_nearest) {
query_field.nearest.n_rset = 5;
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_rset") != -1) {
query_field.nearest.n_rset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_eset") != -1) {
query_field.nearest.n_eset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_term") != -1) {
query_field.nearest.n_term = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.field") != -1) {
query_field.nearest.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.type") != -1) {
query_field.nearest.type.emplace_back(request.query_parser.get());
}
}
}
if ((flags & QUERY_FIELD_TIME) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("time") != -1) {
query_field.time = request.query_parser.get();
} else {
query_field.time = "1h";
}
}
if ((flags & QUERY_FIELD_PERIOD) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("period") != -1) {
query_field.period = request.query_parser.get();
} else {
query_field.period = "1m";
}
}
request.query_parser.rewind();
if (request.query_parser.next("selector") != -1) {
query_field.selector = request.query_parser.get();
}
return query_field;
}
void
HttpClient::log_request(Request& request)
{
L_CALL("HttpClient::log_request()");
std::string request_prefix = " 🌎 ";
int priority = LOG_DEBUG;
if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
priority = LOG_INFO;
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
priority = LOG_NOTICE;
}
auto request_text = request.to_text(true);
L(priority, NO_COLOR, "{}{}", request_prefix, string::indent(request_text, ' ', 4, false));
}
void
HttpClient::log_response(Response& response)
{
L_CALL("HttpClient::log_response()");
std::string response_prefix = " 💊 ";
int priority = LOG_DEBUG;
if ((int)response.status >= 300 && (int)response.status <= 399) {
response_prefix = " 💫 ";
} else if ((int)response.status == 404) {
response_prefix = " 🕸 ";
} else if ((int)response.status >= 400 && (int)response.status <= 499) {
response_prefix = " 💥 ";
priority = LOG_INFO;
} else if ((int)response.status >= 500 && (int)response.status <= 599) {
response_prefix = " 🔥 ";
priority = LOG_NOTICE;
}
auto response_text = response.to_text(true);
L(priority, NO_COLOR, "{}{}", response_prefix, string::indent(response_text, ' ', 4, false));
}
void
HttpClient::end_http_request(Request& request)
{
L_CALL("HttpClient::end_http_request()");
request.ends = std::chrono::system_clock::now();
request.atom_ending = true;
request.atom_ended = true;
waiting = false;
if (request.indexer) {
request.indexer->finish();
request.indexer.reset();
}
if (request.log) {
request.log->clear();
request.log.reset();
}
if (request.parser.http_errno != 0u) {
L(LOG_ERR, LIGHT_RED, "HTTP parsing error ({}): {}", http_errno_name(HTTP_PARSER_ERRNO(&request.parser)), http_errno_description(HTTP_PARSER_ERRNO(&request.parser)));
} else {
static constexpr auto fmt_defaut = RED + "\"{}\" {} {} {}";
auto fmt = fmt_defaut.c_str();
int priority = LOG_DEBUG;
if ((int)request.response.status >= 200 && (int)request.response.status <= 299) {
static constexpr auto fmt_2xx = LIGHT_GREY + "\"{}\" {} {} {}";
fmt = fmt_2xx.c_str();
} else if ((int)request.response.status >= 300 && (int)request.response.status <= 399) {
static constexpr auto fmt_3xx = STEEL_BLUE + "\"{}\" {} {} {}";
fmt = fmt_3xx.c_str();
} else if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
static constexpr auto fmt_4xx = SADDLE_BROWN + "\"{}\" {} {} {}";
fmt = fmt_4xx.c_str();
if ((int)request.response.status != 404) {
priority = LOG_INFO;
}
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
static constexpr auto fmt_5xx = LIGHT_PURPLE + "\"{}\" {} {} {}";
fmt = fmt_5xx.c_str();
priority = LOG_NOTICE;
}
if (Logging::log_level > LOG_DEBUG) {
log_response(request.response);
} else if (Logging::log_level == LOG_DEBUG) {
if ((int)request.response.status >= 400 && (int)request.response.status != 404) {
log_request(request);
log_response(request.response);
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count();
Metrics::metrics()
.xapiand_http_requests_summary
.Add({
{"method", http_method_str(request.method)},
{"status", string::format("{}", request.response.status)},
})
.Observe(took / 1e9);
L(priority, NO_COLOR, fmt, request.head(), (int)request.response.status, string::from_bytes(request.response.size), string::from_delta(request.begins, request.ends));
}
L_TIME("Full request took {}, response took {}", string::from_delta(request.begins, request.ends), string::from_delta(request.received, request.ends));
auto sent = total_sent_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_sent_bytes
.Increment(sent);
auto received = total_received_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_received_bytes
.Increment(received);
}
ct_type_t
HttpClient::resolve_ct_type(Request& request, ct_type_t ct_type)
{
L_CALL("HttpClient::resolve_ct_type({})", repr(ct_type.to_string()));
if (ct_type == json_type || ct_type == msgpack_type || ct_type == x_msgpack_type) {
if (is_acceptable_type(get_acceptable_type(request, json_type), json_type) != nullptr) {
ct_type = json_type;
} else if (is_acceptable_type(get_acceptable_type(request, msgpack_type), msgpack_type) != nullptr) {
ct_type = msgpack_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_msgpack_type), x_msgpack_type) != nullptr) {
ct_type = x_msgpack_type;
}
}
std::vector<ct_type_t> ct_types;
if (ct_type == json_type || ct_type == msgpack_type || ct_type == x_msgpack_type) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(std::move(ct_type));
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
const auto accepted_ct_type = is_acceptable_type(accepted_type, ct_types);
if (accepted_ct_type == nullptr) {
return no_type;
}
return *accepted_ct_type;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const ct_type_t& ct_type)
{
L_CALL("HttpClient::is_acceptable_type({}, {})", repr(ct_type_pattern.to_string()), repr(ct_type.to_string()));
bool type_ok = false, subtype_ok = false;
if (ct_type_pattern.first == "*") {
type_ok = true;
} else {
type_ok = ct_type_pattern.first == ct_type.first;
}
if (ct_type_pattern.second == "*") {
subtype_ok = true;
} else {
subtype_ok = ct_type_pattern.second == ct_type.second;
}
if (type_ok && subtype_ok) {
return &ct_type;
}
return nullptr;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const std::vector<ct_type_t>& ct_types)
{
L_CALL("HttpClient::is_acceptable_type(({}, <ct_types>)", repr(ct_type_pattern.to_string()));
for (auto& ct_type : ct_types) {
if (is_acceptable_type(ct_type_pattern, ct_type) != nullptr) {
return &ct_type;
}
}
return nullptr;
}
template <typename T>
const ct_type_t&
HttpClient::get_acceptable_type(Request& request, const T& ct)
{
L_CALL("HttpClient::get_acceptable_type()");
if (request.accept_set.empty()) {
return no_type;
}
for (const auto& accept : request.accept_set) {
if (is_acceptable_type(accept.ct_type, ct)) {
return accept.ct_type;
}
}
const auto& accept = *request.accept_set.begin();
auto indent = accept.indent;
if (indent != -1) {
request.indented = indent;
}
return accept.ct_type;
}
std::pair<std::string, std::string>
HttpClient::serialize_response(const MsgPack& obj, const ct_type_t& ct_type, int indent, bool serialize_error)
{
L_CALL("HttpClient::serialize_response({}, {}, {}, {})", repr(obj.to_string(), true, '\'', 200), repr(ct_type.to_string()), indent, serialize_error);
if (ct_type == no_type) {
return std::make_pair("", "");
}
if (is_acceptable_type(ct_type, json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), x_msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, html_type) != nullptr) {
std::function<std::string(const msgpack::object&)> html_serialize = serialize_error ? msgpack_to_html_error : msgpack_to_html;
return std::make_pair(obj.external(html_serialize), html_type.to_string() + "; charset=utf-8");
}
/*if (is_acceptable_type(ct_type, text_type)) {
error:
{{ ERROR_CODE }} - {{ MESSAGE }}
obj:
{{ key1 }}: {{ val1 }}
{{ key2 }}: {{ val2 }}
...
array:
{{ val1 }}, {{ val2 }}, ...
}*/
THROW(SerialisationError, "Type is not serializable");
}
void
HttpClient::write_http_response(Request& request, enum http_status status, const MsgPack& obj, const std::string& location)
{
L_CALL("HttpClient::write_http_response()");
if (obj.is_undefined()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE, "", location));
return;
}
std::vector<ct_type_t> ct_types;
if (request.ct_type == json_type || request.ct_type == msgpack_type || request.ct_type.empty()) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(request.ct_type);
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
try {
auto result = serialize_response(obj, accepted_type, request.indented, (int)status >= 400);
if (Logging::log_level >= LOG_DEBUG && request.response.size <= 1024 * 10) {
if (is_acceptable_type(accepted_type, json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, html_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, text_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (!obj.empty()) {
request.response.text.append("...");
}
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, result.first, false, true, true);
if (!encoded.empty() && encoded.size() <= result.first.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, result.second, readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, result.first, location, result.second, readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, result.first, location, result.second));
}
} catch (const SerialisationError& exc) {
status = HTTP_STATUS_NOT_ACCEPTABLE;
std::string response_str;
if (request.comments) {
MsgPack response_err = MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type " + accepted_type.to_string() + " " + exc.what() }) } }
});
response_str = response_err.to_string(request.indented);
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, response_str, false, true, true);
if (!encoded.empty() && encoded.size() <= response_str.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, accepted_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, response_str, location, accepted_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, response_str, location, accepted_type.to_string()));
}
return;
}
}
Encoding
HttpClient::resolve_encoding(Request& request)
{
L_CALL("HttpClient::resolve_encoding()");
if (request.accept_encoding_set.empty()) {
return Encoding::none;
}
constexpr static auto _ = phf::make_phf({
hhl("gzip"),
hhl("deflate"),
hhl("identity"),
hhl("*"),
});
for (const auto& encoding : request.accept_encoding_set) {
switch (_.fhhl(encoding.encoding)) {
case _.fhhl("gzip"):
return Encoding::gzip;
case _.fhhl("deflate"):
return Encoding::deflate;
case _.fhhl("identity"):
return Encoding::identity;
case _.fhhl("*"):
return Encoding::identity;
default:
continue;
}
}
return Encoding::unknown;
}
std::string
HttpClient::readable_encoding(Encoding e)
{
L_CALL("Request::readable_encoding()");
switch (e) {
case Encoding::none:
return "none";
case Encoding::gzip:
return "gzip";
case Encoding::deflate:
return "deflate";
case Encoding::identity:
return "identity";
default:
return "Encoding:UNKNOWN";
}
}
std::string
HttpClient::encoding_http_response(Response& response, Encoding e, const std::string& response_obj, bool chunk, bool start, bool end)
{
L_CALL("HttpClient::encoding_http_response({})", repr(response_obj));
bool gzip = false;
switch (e) {
case Encoding::gzip:
gzip = true;
[[fallthrough]];
case Encoding::deflate: {
if (chunk) {
if (start) {
response.encoding_compressor.reset(nullptr, 0, gzip);
response.encoding_compressor.begin();
}
if (end) {
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size(), DeflateCompressData::FINISH_COMPRESS);
return ret;
}
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size());
return ret;
}
response.encoding_compressor.reset(response_obj.data(), response_obj.size(), gzip);
response.it_compressor = response.encoding_compressor.begin();
std::string encoding_respose;
while (response.it_compressor) {
encoding_respose.append(*response.it_compressor);
++response.it_compressor;
}
return encoding_respose;
}
case Encoding::identity:
return response_obj;
default:
return std::string();
}
}
std::string
HttpClient::__repr__() const
{
return string::format("<HttpClient {{cnt:{}, sock:{}}}{}{}{}{}{}{}{}{}>",
use_count(),
sock,
is_runner() ? " (runner)" : " (worker)",
is_running_loop() ? " (running loop)" : " (stopped loop)",
is_detaching() ? " (deteaching)" : "",
is_idle() ? " (idle)" : "",
is_waiting() ? " (waiting)" : "",
is_running() ? " (running)" : "",
is_shutting_down() ? " (shutting down)" : "",
is_closed() ? " (closed)" : "");
}
Request::Request(HttpClient* client)
: mode{Mode::FULL},
view{nullptr},
type_encoding{Encoding::none},
begining{true},
ending{false},
atom_ending{false},
atom_ended{false},
raw_peek{0},
raw_offset{0},
size{0},
echo{false},
human{false},
comments{true},
indented{-1},
expect_100{false},
closing{false},
begins{std::chrono::system_clock::now()}
{
parser.data = client;
http_parser_init(&parser, HTTP_REQUEST);
}
Request::~Request() noexcept
{
try {
if (indexer) {
indexer->finish();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
try {
if (log) {
log->clear();
log.reset();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
MsgPack
Request::decode(std::string_view body)
{
L_CALL("Request::decode({})", repr(body));
std::string ct_type_str = ct_type.to_string();
if (ct_type_str.empty()) {
ct_type_str = JSON_CONTENT_TYPE;
}
MsgPack decoded;
rapidjson::Document rdoc;
constexpr static auto _ = phf::make_phf({
hhl(JSON_CONTENT_TYPE),
hhl(MSGPACK_CONTENT_TYPE),
hhl(X_MSGPACK_CONTENT_TYPE),
hhl(NDJSON_CONTENT_TYPE),
hhl(X_NDJSON_CONTENT_TYPE),
hhl(FORM_URLENCODED_CONTENT_TYPE),
hhl(X_FORM_URLENCODED_CONTENT_TYPE),
});
switch (_.fhhl(ct_type_str)) {
case _.fhhl(NDJSON_CONTENT_TYPE):
case _.fhhl(X_NDJSON_CONTENT_TYPE):
decoded = MsgPack::ARRAY();
for (auto json : Split<std::string_view>(body, '\n')) {
json_load(rdoc, json);
decoded.append(rdoc);
}
ct_type = json_type;
return decoded;
case _.fhhl(JSON_CONTENT_TYPE):
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
return decoded;
case _.fhhl(MSGPACK_CONTENT_TYPE):
case _.fhhl(X_MSGPACK_CONTENT_TYPE):
decoded = MsgPack::unserialise(body);
ct_type = msgpack_type;
return decoded;
case _.fhhl(FORM_URLENCODED_CONTENT_TYPE):
case _.fhhl(X_FORM_URLENCODED_CONTENT_TYPE):
try {
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
} catch (const std::exception&) {
decoded = MsgPack(body);
ct_type = msgpack_type;
}
return decoded;
default:
decoded = MsgPack(body);
return decoded;
}
}
MsgPack&
Request::decoded_body()
{
L_CALL("Request::decoded_body()");
if (_decoded_body.is_undefined()) {
if (!raw.empty()) {
_decoded_body = decode(raw);
}
}
return _decoded_body;
}
bool
Request::append(const char* at, size_t length)
{
L_CALL("Request::append(<at>, <length>)");
bool signal_pending = false;
switch (mode) {
case Mode::FULL:
raw.append(std::string_view(at, length));
break;
case Mode::STREAM:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
raw.append(std::string_view(at, length));
signal_pending = true;
break;
case Mode::STREAM_NDJSON:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
raw.append(std::string_view(at, length));
auto new_raw_offset = raw.find_first_of('\n', raw_peek);
while (new_raw_offset != std::string::npos) {
auto json = std::string_view(raw).substr(raw_offset, new_raw_offset - raw_offset);
raw_offset = raw_peek = new_raw_offset + 1;
new_raw_offset = raw.find_first_of('\n', raw_peek);
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
}
if (!length) {
auto json = std::string_view(raw).substr(raw_offset);
raw_offset = raw_peek = raw.size();
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
break;
case Mode::STREAM_MSGPACK:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
unpacker.reserve_buffer(length);
memcpy(unpacker.buffer(), at, length);
unpacker.buffer_consumed(length);
try {
msgpack::object_handle result;
while (unpacker.next(result)) {
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(result.get());
}
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
break;
}
return signal_pending;
}
bool
Request::wait()
{
if (mode != Request::Mode::FULL) {
// Wait for a pending raw body for one second (1000000us) and flush
// pending signals before processing the request, otherwise retry
// checking for empty/ended requests or closed connections.
if (!pending.wait(1000000)) {
return false;
}
while (pending.tryWaitMany(std::numeric_limits<ssize_t>::max())) { }
}
return true;
}
bool
Request::next(std::string_view& str_view)
{
L_CALL("Request::next(<&str_view>)");
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
ASSERT(mode == Mode::STREAM);
if (raw_offset == raw.size()) {
return false;
}
str_view = std::string_view(raw).substr(raw_offset);
raw_offset = raw.size();
return true;
}
bool
Request::next_object(MsgPack& obj)
{
L_CALL("Request::next_object(<&obj>)");
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
ASSERT(mode == Mode::STREAM_MSGPACK || mode == Mode::STREAM_NDJSON);
std::lock_guard<std::mutex> lk(objects_mtx);
if (objects.empty()) {
return false;
}
obj = std::move(objects.front());
objects.pop_front();
return true;
}
std::string
Request::head()
{
L_CALL("Request::head()");
auto parser_method = HTTP_PARSER_METHOD(&parser);
if (parser_method != method) {
return string::format("{} <- {} {} HTTP/{}.{}",
http_method_str(method),
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
return string::format("{} {} HTTP/{}.{}",
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
std::string
Request::to_text(bool decode)
{
L_CALL("Request::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto request_headers_color = no_col.c_str();
auto request_head_color = no_col.c_str();
auto request_text_color = no_col.c_str();
switch (method) {
case HTTP_OPTIONS: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_INFO: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_HEAD: {
// rgb(144, 18, 254)
static constexpr auto _request_headers_color = rgba(100, 64, 131, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(100, 64, 131);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(100, 64, 131);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_GET: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_SEARCH: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COUNT: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_POST: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DUMP: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_RESTORE: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_OPEN: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_CLOSE: {
// rgb(227, 32, 40)
static constexpr auto _request_headers_color = rgba(101, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(101, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(101, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PATCH: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_STORE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PUT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COMMIT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DELETE: {
// rgb(246, 64, 68)
static constexpr auto _request_headers_color = rgba(151, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(151, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(151, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
default:
break;
};
auto request_text = request_head_color + head() + "\n" + request_headers_color + headers + request_text_color;
if (!raw.empty()) {
if (!decode) {
if (raw.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
} else {
request_text += "<body " + repr(raw, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(raw);
request_text += string::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
request_text += b64_data;
request_text += '\a';
} else {
if (raw.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
} else {
auto& decoded = decoded_body();
if (ct_type == json_type || ct_type == msgpack_type) {
request_text += decoded.to_string(DEFAULT_INDENTATION);
} else {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
}
}
}
} else if (!text.empty()) {
if (!decode) {
if (text.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(text.size()) + ">";
} else {
request_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (text.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(text.size()) + ">";
} else {
request_text += text;
}
} else if (size) {
request_text += "<body " + string::from_bytes(size) + ">";
}
return request_text;
}
Response::Response()
: status{static_cast<http_status>(0)},
size{0}
{
}
std::string
Response::to_text(bool decode)
{
L_CALL("Response::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto response_headers_color = no_col.c_str();
auto response_head_color = no_col.c_str();
auto response_text_color = no_col.c_str();
if ((int)status >= 200 && (int)status <= 299) {
static constexpr auto _response_headers_color = rgba(68, 136, 68, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 68);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 68);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 300 && (int)status <= 399) {
static constexpr auto _response_headers_color = rgba(68, 136, 120, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 120);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 120);
response_text_color = _response_text_color.c_str();
} else if ((int)status == 404) {
static constexpr auto _response_headers_color = rgba(116, 100, 77, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(116, 100, 77);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(116, 100, 77);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 400 && (int)status <= 499) {
static constexpr auto _response_headers_color = rgba(183, 70, 17, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(183, 70, 17);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(183, 70, 17);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 500 && (int)status <= 599) {
static constexpr auto _response_headers_color = rgba(190, 30, 10, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(190, 30, 10);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(190, 30, 10);
response_text_color = _response_text_color.c_str();
}
auto response_text = response_head_color + head + "\n" + response_headers_color + headers + response_text_color;
if (!blob.empty()) {
if (!decode) {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + repr(blob, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(blob);
response_text += string::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
response_text += b64_data;
response_text += '\a';
} else {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
}
}
} else if (!text.empty()) {
if (!decode) {
if (size > 1024 * 10) {
response_text += "<body " + string::from_bytes(size) + ">";
} else {
response_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (size > 1024 * 10) {
response_text += "<body " + string::from_bytes(size) + ">";
} else {
response_text += text;
}
} else if (size) {
response_text += "<body " + string::from_bytes(size) + ">";
}
return response_text;
}
HTTP Client: Using NAMEOF_ENUM to show type
/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "http_client.h"
#include "config.h" // for XAPIAND_CLUSTERING, XAPIAND_CHAISCRIPT, XAPIAND_DATABASE_WAL
#include <errno.h> // for errno
#include <exception> // for std::exception
#include <functional> // for std::function
#include <regex> // for std::regex, std::regex_constants
#include <signal.h> // for SIGTERM
#include <sysexits.h> // for EX_SOFTWARE
#include <syslog.h> // for LOG_WARNING, LOG_ERR, LOG...
#include <utility> // for std::move
#ifdef XAPIAND_CHAISCRIPT
#include "chaiscript/chaiscript_defines.hpp" // for chaiscript::Build_Info
#endif
#include "cppcodec/base64_rfc4648.hpp" // for cppcodec::base64_rfc4648
#include "database/handler.h" // for DatabaseHandler
#include "database/utils.h" // for query_field_t
#include "database/pool.h" // for DatabasePool
#include "database/schema.h" // for Schema
#include "endpoint.h" // for Endpoints, Endpoint
#include "epoch.hh" // for epoch::now
#include "error.hh" // for error:name, error::description
#include "ev/ev++.h" // for async, io, loop_ref (ptr ...
#include "exception.h" // for Exception, SerialisationE...
#include "field_parser.h" // for FieldParser, FieldParserError
#include "hashes.hh" // for hhl
#include "http_utils.h" // for catch_http_errors
#include "io.hh" // for close, write, unlink
#include "log.h" // for L_CALL, L_ERR, LOG_DEBUG
#include "logger.h" // for Logging
#include "manager.h" // for XapiandManager
#include "metrics.h" // for Metrics::metrics
#include "mime_types.hh" // for mime_type
#include "msgpack.h" // for MsgPack, msgpack::object
#include "aggregations/aggregations.h" // for AggregationMatchSpy
#include "node.h" // for Node::local_node, Node::leader_node
#include "nameof.hh" // for NAMEOF_ENUM
#include "opts.h" // for opts::*
#include "package.h" // for Package::*
#include "phf.hh" // for phf::*
#include "rapidjson/document.h" // for Document
#include "reserved/aggregations.h" // for RESERVED_AGGS_*
#include "reserved/fields.h" // for RESERVED_*
#include "reserved/query_dsl.h" // for RESERVED_QUERYDSL_*
#include "reserved/schema.h" // for RESERVED_VERSION
#include "response.h" // for RESPONSE_*
#include "serialise.h" // for Serialise::boolean
#include "string.hh" // for string::from_delta
#include "xapian.h" // for Xapian::major_version, Xapian::minor_version
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_CONN
// #define L_CONN L_GREEN
// #undef L_HTTP
// #define L_HTTP L_RED
// #undef L_HTTP_WIRE
// #define L_HTTP_WIRE L_ORANGE
// #undef L_HTTP_PROTO
// #define L_HTTP_PROTO L_TEAL
#define QUERY_FIELD_PRIMARY (1 << 0)
#define QUERY_FIELD_WRITABLE (1 << 1)
#define QUERY_FIELD_COMMIT (1 << 2)
#define QUERY_FIELD_SEARCH (1 << 3)
#define QUERY_FIELD_ID (1 << 4)
#define QUERY_FIELD_TIME (1 << 5)
#define QUERY_FIELD_PERIOD (1 << 6)
#define QUERY_FIELD_VOLATILE (1 << 7)
#define DEFAULT_INDENTATION 2
static const std::regex header_params_re(R"(\s*;\s*([a-z]+)=(\d+(?:\.\d+)?))", std::regex::optimize);
static const std::regex header_accept_re(R"(([-a-z+]+|\*)/([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::regex header_accept_encoding_re(R"(([-a-z+]+|\*)((?:\s*;\s*[a-z]+=\d+(?:\.\d+)?)*))", std::regex::optimize);
static const std::string eol("\r\n");
// Available commands
#define METHODS_OPTIONS() \
OPTION(DELETE, "delete") \
OPTION(GET, "get") \
OPTION(HEAD, "head") \
OPTION(POST, "post") \
OPTION(PUT, "put") \
OPTION(CONNECT, "connect") \
OPTION(OPTIONS, "options") \
OPTION(TRACE, "trace") \
OPTION(PATCH, "patch") \
OPTION(PURGE, "purge") \
OPTION(LINK, "link") \
OPTION(UNLINK, "unlink") \
OPTION(CHECK, "check") \
OPTION(CLOSE, "close") \
OPTION(COMMIT, "commit") \
OPTION(COPY, "copy") \
OPTION(COUNT, "count") \
OPTION(DUMP, "dump") \
OPTION(FLUSH, "flush") \
OPTION(INFO, "info") \
OPTION(LOCK, "lock") \
OPTION(MERGE, "merge") \
OPTION(MOVE, "move") \
OPTION(OPEN, "open") \
OPTION(QUIT, "quit") \
OPTION(RESTORE, "restore") \
OPTION(SEARCH, "search") \
OPTION(STORE, "store") \
OPTION(UNLOCK, "unlock") \
OPTION(UPDATE, "update")
constexpr static auto http_methods = phf::make_phf({
#define OPTION(name, str) hhl(str),
METHODS_OPTIONS()
#undef OPTION
});
bool is_range(std::string_view str) {
try {
FieldParser fieldparser(str);
fieldparser.parse();
return fieldparser.is_range();
} catch (const FieldParserError&) {
return false;
}
}
bool can_preview(const ct_type_t& ct_type) {
#define CONTENT_TYPE_OPTIONS() \
OPTION("application/eps") \
OPTION("application/pdf") \
OPTION("application/postscript") \
OPTION("application/x-bzpdf") \
OPTION("application/x-eps") \
OPTION("application/x-gzpdf") \
OPTION("application/x-pdf") \
OPTION("application/x-photoshop") \
OPTION("application/photoshop") \
OPTION("application/psd")
constexpr static auto _ = phf::make_phf({
#define OPTION(ct) hhl(ct),
CONTENT_TYPE_OPTIONS()
#undef OPTION
});
switch (_.fhhl(ct_type.to_string())) {
#define OPTION(ct) case _.fhhl(ct):
CONTENT_TYPE_OPTIONS()
#undef OPTION
return true;
default:
return ct_type.first == "image";
}
}
std::string
HttpClient::http_response(Request& request, enum http_status status, int mode, const std::string& body, const std::string& location, const std::string& ct_type, const std::string& ct_encoding, size_t content_length) {
L_CALL("HttpClient::http_response()");
std::string head;
std::string headers;
std::string head_sep;
std::string headers_sep;
std::string response_body;
if ((mode & HTTP_STATUS_RESPONSE) != 0) {
ASSERT(request.response.status == static_cast<http_status>(0));
request.response.status = status;
auto http_major = request.parser.http_major;
auto http_minor = request.parser.http_minor;
if (http_major == 0 && http_minor == 0) {
http_major = 1;
}
head += string::format("HTTP/{}.{} {} ", http_major, http_minor, status);
head += http_status_str(status);
head_sep += eol;
if ((mode & HTTP_HEADER_RESPONSE) == 0) {
headers_sep += eol;
}
}
ASSERT(request.response.status != static_cast<http_status>(0));
if ((mode & HTTP_HEADER_RESPONSE) != 0) {
headers += "Server: " + Package::STRING + eol;
// if (!endpoints.empty()) {
// headers += "Database: " + endpoints.to_string() + eol;
// }
request.ends = std::chrono::system_clock::now();
if (request.human) {
headers += string::format("Response-Time: {}", string::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count())) + eol;
if (request.ready >= request.processing) {
headers += string::format("Operation-Time: {}", string::from_delta(std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count())) + eol;
}
} else {
headers += string::format("Response-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count() / 1e9) + eol;
if (request.ready >= request.processing) {
headers += string::format("Operation-Time: {}", std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count() / 1e9) + eol;
}
}
if ((mode & HTTP_OPTIONS_RESPONSE) != 0) {
headers += "Allow: GET, POST, PUT, PATCH, UPDATE, STORE, DELETE, HEAD, OPTIONS" + eol;
}
if (!location.empty()) {
headers += "Location: " + location + eol;
}
if ((mode & HTTP_CONTENT_TYPE_RESPONSE) != 0 && !ct_type.empty()) {
headers += "Content-Type: " + ct_type + eol;
}
if ((mode & HTTP_CONTENT_ENCODING_RESPONSE) != 0 && !ct_encoding.empty()) {
headers += "Content-Encoding: " + ct_encoding + eol;
}
if ((mode & HTTP_CONTENT_LENGTH_RESPONSE) != 0) {
headers += string::format("Content-Length: {}", content_length) + eol;
} else {
headers += string::format("Content-Length: {}", body.size()) + eol;
}
headers_sep += eol;
}
if ((mode & HTTP_BODY_RESPONSE) != 0) {
response_body += body;
}
auto this_response_size = response_body.size();
request.response.size += this_response_size;
if (Logging::log_level >= LOG_DEBUG) {
request.response.head += head;
request.response.headers += headers;
}
return head + head_sep + headers + headers_sep + response_body;
}
HttpClient::HttpClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_)
: MetaBaseClient<HttpClient>(std::move(parent_), ev_loop_, ev_flags_),
new_request(std::make_shared<Request>(this))
{
++XapiandManager::http_clients();
Metrics::metrics()
.xapiand_http_connections
.Increment();
// Initialize new_request->begins as soon as possible (for correctly timing disconnecting clients)
new_request->begins = std::chrono::system_clock::now();
L_CONN("New Http Client, {} client(s) of a total of {} connected.", XapiandManager::http_clients().load(), XapiandManager::total_clients().load());
}
HttpClient::~HttpClient() noexcept
{
try {
if (XapiandManager::http_clients().fetch_sub(1) == 0) {
L_CRIT("Inconsistency in number of http clients");
sig_exit(-EX_SOFTWARE);
}
if (is_shutting_down() && !is_idle()) {
L_INFO("HTTP client killed!");
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
template <typename Func>
int
HttpClient::handled_errors(Request& request, Func&& func)
{
L_CALL("HttpClient::handled_errors()");
auto http_errors = catch_http_errors(std::forward<Func>(func));
if (http_errors.error_code != HTTP_STATUS_OK) {
if (request.response.status != static_cast<http_status>(0)) {
// There was an error, but request already had written stuff...
// disconnect client!
detach();
} else if (request.comments) {
write_http_response(request, http_errors.error_code, MsgPack({
{ RESPONSE_xSTATUS, static_cast<unsigned>(http_errors.error_code) },
{ RESPONSE_xMESSAGE, string::split(http_errors.error, '\n') }
}));
} else {
write_http_response(request, http_errors.error_code);
}
request.atom_ending = true;
}
return http_errors.ret;
}
size_t
HttpClient::pending_requests() const
{
std::lock_guard<std::mutex> lk(runner_mutex);
auto requests_size = requests.size();
if (requests_size && requests.front()->response.status != static_cast<http_status>(0)) {
--requests_size;
}
return requests_size;
}
bool
HttpClient::is_idle() const
{
L_CALL("RemoteProtocolClient::is_idle() {{is_waiting:{}, is_running:{}, write_queue_empty:{}, pending_requests:{}}}", is_waiting(), is_running(), write_queue.empty(), pending_requests());
return !is_waiting() && !is_running() && write_queue.empty() && !pending_requests();
}
ssize_t
HttpClient::on_read(const char* buf, ssize_t received)
{
L_CALL("HttpClient::on_read(<buf>, {})", received);
unsigned init_state = new_request->parser.state;
if (received <= 0) {
close();
if (received < 0) {
L_NOTICE("HTTP client connection closed unexpectedly after {} {{sock:{}}}: {} ({}): {}", string::from_delta(new_request->begins, std::chrono::system_clock::now()), sock, error::name(errno), errno, error::description(errno));
return received;
}
if (init_state != 18) {
L_NOTICE("HTTP client closed unexpectedly after {}: Not in final HTTP state ({})", string::from_delta(new_request->begins, std::chrono::system_clock::now()), init_state);
return received;
}
if (is_waiting()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There was still a request in progress", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
if (!write_queue.empty()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There is still pending data", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
if (pending_requests()) {
L_NOTICE("HTTP client closed unexpectedly after {}: There are still pending requests", string::from_delta(new_request->begins, std::chrono::system_clock::now()));
return received;
}
// HTTP client normally closed connection.
return received;
}
L_HTTP_WIRE("HttpClient::on_read: {} bytes", received);
ssize_t parsed = http_parser_execute(&new_request->parser, &http_parser_settings, buf, received);
if (parsed != received) {
enum http_status error_code = HTTP_STATUS_BAD_REQUEST;
http_errno err = HTTP_PARSER_ERRNO(&new_request->parser);
if (err == HPE_INVALID_METHOD) {
if (new_request->response.status == static_cast<http_status>(0)) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
end_http_request(*new_request);
}
} else {
std::string message(http_errno_description(err));
L_DEBUG("HTTP parser error: {}", HTTP_PARSER_ERRNO(&new_request->parser) != HPE_OK ? message : "incomplete request");
if (new_request->response.status == static_cast<http_status>(0)) {
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, string::split(message, '\n') }
}));
} else {
write_http_response(*new_request, error_code);
}
end_http_request(*new_request);
}
}
detach();
}
return received;
}
void
HttpClient::on_read_file(const char* /*buf*/, ssize_t received)
{
L_CALL("HttpClient::on_read_file(<buf>, {})", received);
L_ERR("Not Implemented: HttpClient::on_read_file: {} bytes", received);
}
void
HttpClient::on_read_file_done()
{
L_CALL("HttpClient::on_read_file_done()");
L_ERR("Not Implemented: HttpClient::on_read_file_done");
}
// HTTP parser callbacks.
const http_parser_settings HttpClient::http_parser_settings = {
HttpClient::message_begin_cb,
HttpClient::url_cb,
HttpClient::status_cb,
HttpClient::header_field_cb,
HttpClient::header_value_cb,
HttpClient::headers_complete_cb,
HttpClient::body_cb,
HttpClient::message_complete_cb,
HttpClient::chunk_header_cb,
HttpClient::chunk_complete_cb,
};
inline std::string readable_http_parser_flags(http_parser* parser) {
std::vector<std::string> values;
if ((parser->flags & F_CHUNKED) == F_CHUNKED) values.push_back("F_CHUNKED");
if ((parser->flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) values.push_back("F_CONNECTION_KEEP_ALIVE");
if ((parser->flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) values.push_back("F_CONNECTION_CLOSE");
if ((parser->flags & F_CONNECTION_UPGRADE) == F_CONNECTION_UPGRADE) values.push_back("F_CONNECTION_UPGRADE");
if ((parser->flags & F_TRAILING) == F_TRAILING) values.push_back("F_TRAILING");
if ((parser->flags & F_UPGRADE) == F_UPGRADE) values.push_back("F_UPGRADE");
if ((parser->flags & F_SKIPBODY) == F_SKIPBODY) values.push_back("F_SKIPBODY");
if ((parser->flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) values.push_back("F_CONTENTLENGTH");
return string::join(values, "|");
}
int
HttpClient::message_begin_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_begin(parser);
});
}
int
HttpClient::url_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_url(parser, at, length);
});
}
int
HttpClient::status_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_status(parser, at, length);
});
}
int
HttpClient::header_field_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_field(parser, at, length);
});
}
int
HttpClient::header_value_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_header_value(parser, at, length);
});
}
int
HttpClient::headers_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_headers_complete(parser);
});
}
int
HttpClient::body_cb(http_parser* parser, const char* at, size_t length)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_body(parser, at, length);
});
}
int
HttpClient::message_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_message_complete(parser);
});
}
int
HttpClient::chunk_header_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_header(parser);
});
}
int
HttpClient::chunk_complete_cb(http_parser* parser)
{
auto http_client = static_cast<HttpClient *>(parser->data);
return http_client->handled_errors(*http_client->new_request, [&]{
return http_client->on_chunk_complete(parser);
});
}
int
HttpClient::on_message_begin([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_begin(<parser>)");
L_HTTP_PROTO("on_message_begin {{state:{}, header_state:{}}}", NAMEOF_ENUM(HTTP_PARSER_STATE(parser)), NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)));
waiting = true;
new_request->begins = std::chrono::system_clock::now();
L_TIMED_VAR(new_request->log, 10s,
"Request taking too long...",
"Request took too long!");
return 0;
}
int
HttpClient::on_url(http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_url(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_url {{state:{}, header_state:{}}}: {}", NAMEOF_ENUM(HTTP_PARSER_STATE(parser)), NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->method = HTTP_PARSER_METHOD(parser);
new_request->path.append(at, length);
return 0;
}
int
HttpClient::on_status([[maybe_unused]] http_parser* parser, [[maybe_unused]] const char* at, [[maybe_unused]] size_t length)
{
L_CALL("HttpClient::on_status(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_status {{state:{}, header_state:{}}}: {}", NAMEOF_ENUM(HTTP_PARSER_STATE(parser)), NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
return 0;
}
int
HttpClient::on_header_field([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_field(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_field {{state:{}, header_state:{}}}: {}", NAMEOF_ENUM(HTTP_PARSER_STATE(parser)), NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
new_request->_header_name = std::string(at, length);
return 0;
}
int
HttpClient::on_header_value([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_header_value(<parser>, <at>, <length>)");
L_HTTP_PROTO("on_header_value {{state:{}, header_state:{}}}: {}", NAMEOF_ENUM(HTTP_PARSER_STATE(parser)), NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)), repr(at, length));
auto _header_value = std::string_view(at, length);
if (Logging::log_level >= LOG_DEBUG) {
new_request->headers.append(new_request->_header_name);
new_request->headers.append(": ");
new_request->headers.append(_header_value);
new_request->headers.append(eol);
}
constexpr static auto _ = phf::make_phf({
hhl("expect"),
hhl("100-continue"),
hhl("content-type"),
hhl("accept"),
hhl("accept-encoding"),
hhl("http-method-override"),
hhl("x-http-method-override"),
});
switch (_.fhhl(new_request->_header_name)) {
case _.fhhl("expect"):
case _.fhhl("100-continue"):
// Respond with HTTP/1.1 100 Continue
new_request->expect_100 = true;
break;
case _.fhhl("content-type"):
new_request->ct_type = ct_type_t(_header_value);
break;
case _.fhhl("accept"): {
static AcceptLRU accept_sets;
auto value = string::lower(_header_value);
auto lookup = accept_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
int indent = -1;
double q = 1.0;
if (next->length(3) != 0) {
auto param = next->str(3);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
} else if (next_param->str(1) == "indent") {
indent = strict_stoi(next_param->str(2));
if (indent < 0) { indent = 0;
} else if (indent > 16) { indent = 16; }
}
++next_param;
}
}
lookup.second.emplace(i, q, ct_type_t(next->str(1), next->str(2)), indent);
++next;
++i;
}
accept_sets.emplace(value, lookup.second);
}
new_request->accept_set = std::move(lookup.second);
break;
}
case _.fhhl("accept-encoding"): {
static AcceptEncodingLRU accept_encoding_sets;
auto value = string::lower(_header_value);
auto lookup = accept_encoding_sets.lookup(value);
if (!lookup.first) {
std::sregex_iterator next(value.begin(), value.end(), header_accept_encoding_re, std::regex_constants::match_any);
std::sregex_iterator end;
int i = 0;
while (next != end) {
double q = 1.0;
if (next->length(2) != 0) {
auto param = next->str(2);
std::sregex_iterator next_param(param.begin(), param.end(), header_params_re, std::regex_constants::match_any);
while (next_param != end) {
if (next_param->str(1) == "q") {
q = strict_stod(next_param->str(2));
}
++next_param;
}
} else {
}
lookup.second.emplace(i, q, next->str(1));
++next;
++i;
}
accept_encoding_sets.emplace(value, lookup.second);
}
new_request->accept_encoding_set = std::move(lookup.second);
break;
}
case _.fhhl("x-http-method-override"):
case _.fhhl("http-method-override"): {
switch (http_methods.fhhl(_header_value)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "{} header must use the POST method", repr(new_request->_header_name)); \
} \
new_request->method = HTTP_##name; \
break;
METHODS_OPTIONS()
#undef OPTION
default:
parser->http_errno = HPE_INVALID_METHOD;
break;
}
break;
}
}
return 0;
}
int
HttpClient::on_headers_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_headers_complete(<parser>)");
L_HTTP_PROTO("on_headers_complete {{state:{}, header_state:{}, flags:[{}]}}",
NAMEOF_ENUM(HTTP_PARSER_STATE(parser)),
NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
// Prepare the request view
if (int err = prepare()) {
end_http_request(*new_request);
return err;
}
if likely(!closed && !new_request->atom_ending) {
if likely(new_request->view) {
if (new_request->mode != Request::Mode::FULL) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || new_request != requests.front()) {
requests.push_back(new_request); // Enqueue streamed request
}
}
}
}
return 0;
}
int
HttpClient::on_body([[maybe_unused]] http_parser* parser, const char* at, size_t length)
{
L_CALL("HttpClient::on_body(<parser>, <at>, {})", length);
L_HTTP_PROTO("on_body {{state:{}, header_state:{}, flags:[{}]}}: {}",
NAMEOF_ENUM(HTTP_PARSER_STATE(parser)),
NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser),
repr(at, length));
new_request->size += length;
if likely(!closed && !new_request->atom_ending) {
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || new_request->view) {
signal_pending = new_request->append(at, length);
}
if (new_request->view) {
if (signal_pending) {
new_request->pending.signal();
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
}
}
return 0;
}
int
HttpClient::on_message_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_message_complete(<parser>)");
L_HTTP_PROTO("on_message_complete {{state:{}, header_state:{}, flags:[{}]}}",
NAMEOF_ENUM(HTTP_PARSER_STATE(parser)),
NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
if (Logging::log_level > LOG_DEBUG) {
log_request(*new_request);
}
if likely(!closed && !new_request->atom_ending) {
new_request->atom_ending = true;
std::shared_ptr<Request> request = std::make_shared<Request>(this);
std::swap(new_request, request);
bool signal_pending = false;
if (Logging::log_level >= LOG_DEBUG || request->view) {
request->append(nullptr, 0); // flush pending stuff
signal_pending = true; // always signal pending
}
if (request->view) {
if (signal_pending) {
request->pending.signal(); // always signal, so view continues ending
std::lock_guard<std::mutex> lk(runner_mutex);
if (requests.empty() || request != requests.front()) {
requests.push_back(std::move(request)); // Enqueue request
}
if (!running) { // Start a runner if not running
running = true;
XapiandManager::http_client_pool()->enqueue(share_this<HttpClient>());
}
}
} else {
end_http_request(*request);
}
}
waiting = false;
return 0;
}
int
HttpClient::on_chunk_header([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_header(<parser>)");
L_HTTP_PROTO("on_chunk_header {{state:{}, header_state:{}, flags:[{}]}}",
NAMEOF_ENUM(HTTP_PARSER_STATE(parser)),
NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::on_chunk_complete([[maybe_unused]] http_parser* parser)
{
L_CALL("HttpClient::on_chunk_complete(<parser>)");
L_HTTP_PROTO("on_chunk_complete {{state:{}, header_state:{}, flags:[{}]}}",
NAMEOF_ENUM(HTTP_PARSER_STATE(parser)),
NAMEOF_ENUM(HTTP_PARSER_HEADER_STATE(parser)),
readable_http_parser_flags(parser));
return 0;
}
int
HttpClient::prepare()
{
L_CALL("HttpClient::prepare()");
L_TIMED_VAR(request.log, 1s,
"Response taking too long: {}",
"Response took too long: {}",
request.head());
new_request->received = std::chrono::system_clock::now();
if (new_request->parser.http_major == 0 || (new_request->parser.http_major == 1 && new_request->parser.http_minor == 0)) {
new_request->closing = true;
}
if ((new_request->parser.flags & F_CONNECTION_KEEP_ALIVE) == F_CONNECTION_KEEP_ALIVE) {
new_request->closing = false;
}
if ((new_request->parser.flags & F_CONNECTION_CLOSE) == F_CONNECTION_CLOSE) {
new_request->closing = true;
}
if (new_request->accept_set.empty()) {
if (!new_request->ct_type.empty()) {
new_request->accept_set.emplace(0, 1.0, new_request->ct_type, 0);
}
new_request->accept_set.emplace(1, 1.0, any_type, 0);
}
new_request->type_encoding = resolve_encoding(*new_request);
if (new_request->type_encoding == Encoding::unknown) {
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (new_request->comments) {
write_http_response(*new_request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response encoding gzip, deflate or identity not provided in the Accept-Encoding header" }) } }
}));
} else {
write_http_response(*new_request, error_code);
}
return 1;
}
url_resolve(*new_request);
auto id = new_request->path_parser.get_id();
auto has_pth = new_request->path_parser.has_pth();
auto cmd = new_request->path_parser.get_cmd();
if (!cmd.empty()) {
auto mapping = cmd;
mapping.remove_prefix(1);
switch (http_methods.fhhl(mapping)) {
#define OPTION(name, str) \
case http_methods.fhhl(str): \
if ( \
new_request->method != HTTP_POST && \
new_request->method != HTTP_GET && \
new_request->method != HTTP_##name \
) { \
THROW(ClientError, "HTTP Mappings must use GET or POST method"); \
} \
new_request->method = HTTP_##name; \
cmd = ""; \
break;
METHODS_OPTIONS()
#undef OPTION
}
}
switch (new_request->method) {
case HTTP_SEARCH:
if (id.empty()) {
new_request->view = &HttpClient::search_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COUNT:
if (id.empty()) {
new_request->view = &HttpClient::count_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_INFO:
if (id.empty()) {
new_request->view = &HttpClient::info_view;
} else {
new_request->view = &HttpClient::info_view;
}
break;
case HTTP_HEAD:
if (id.empty()) {
new_request->view = &HttpClient::database_exists_view;
} else {
new_request->view = &HttpClient::document_exists_view;
}
break;
case HTTP_GET:
if (!cmd.empty() && id.empty()) {
if (!has_pth && cmd == ":metrics") {
new_request->view = &HttpClient::metrics_view;
#if XAPIAND_DATABASE_WAL
} else if (cmd == ":wal") {
new_request->view = &HttpClient::wal_view;
#endif
#if XAPIAND_CLUSTERING
} else if (!has_pth && cmd == ":nodes") {
new_request->view = &HttpClient::nodes_view;
#endif
} else {
new_request->view = &HttpClient::retrieve_metadata_view;
}
} else if (!id.empty()) {
if (is_range(id)) {
new_request->view = &HttpClient::search_view;
} else {
new_request->view = &HttpClient::retrieve_document_view;
}
} else {
new_request->view = &HttpClient::retrieve_database_view;
}
break;
case HTTP_POST:
if (!cmd.empty() && id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else if (!id.empty()) {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_PUT:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::write_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::write_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_PATCH:
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::update_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
new_request->view = &HttpClient::update_database_view;
}
break;
case HTTP_STORE:
if (!id.empty()) {
new_request->view = &HttpClient::update_document_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DELETE:
if (!cmd.empty() && id.empty()) {
new_request->view = &HttpClient::delete_metadata_view;
} else if (!id.empty()) {
new_request->view = &HttpClient::delete_document_view;
} else if (has_pth) {
new_request->view = &HttpClient::delete_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_COMMIT:
if (id.empty()) {
new_request->view = &HttpClient::commit_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_DUMP:
if (id.empty()) {
new_request->view = &HttpClient::dump_database_view;
} else {
new_request->view = &HttpClient::dump_document_view;
}
break;
case HTTP_RESTORE:
if (id.empty()) {
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH) {
if (new_request->ct_type == ndjson_type || new_request->ct_type == x_ndjson_type) {
new_request->mode = Request::Mode::STREAM_NDJSON;
} else if (new_request->ct_type == msgpack_type || new_request->ct_type == x_msgpack_type) {
new_request->mode = Request::Mode::STREAM_MSGPACK;
}
}
new_request->view = &HttpClient::restore_database_view;
} else {
new_request->view = &HttpClient::write_document_view;
}
break;
case HTTP_CHECK:
if (id.empty()) {
new_request->view = &HttpClient::check_database_view;
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_FLUSH:
if (opts.admin_commands && id.empty() && !has_pth) {
// Flush both databases and clients by default (unless one is specified)
new_request->query_parser.rewind();
int flush_databases = new_request->query_parser.next("databases");
new_request->query_parser.rewind();
int flush_clients = new_request->query_parser.next("clients");
if (flush_databases != -1 || flush_clients == -1) {
XapiandManager::database_pool()->cleanup(true);
}
if (flush_clients != -1 || flush_databases == -1) {
XapiandManager::manager()->shutdown(0, 0);
}
write_http_response(*new_request, HTTP_STATUS_OK);
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
case HTTP_OPTIONS:
write(http_response(*new_request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_OPTIONS_RESPONSE | HTTP_BODY_RESPONSE));
break;
case HTTP_QUIT:
if (opts.admin_commands && !has_pth && id.empty()) {
XapiandManager::try_shutdown(true);
write_http_response(*new_request, HTTP_STATUS_OK);
shutdown();
} else {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
}
break;
default: {
write_status_response(*new_request, HTTP_STATUS_METHOD_NOT_ALLOWED);
new_request->parser.http_errno = HPE_INVALID_METHOD;
return 1;
}
}
if (!new_request->view && Logging::log_level < LOG_DEBUG) {
return 1;
}
if (new_request->expect_100) {
// Return "100 Continue" if client sent "Expect: 100-continue"
write(http_response(*new_request, HTTP_STATUS_CONTINUE, HTTP_STATUS_RESPONSE));
// Go back to unknown response state:
new_request->response.head.clear();
new_request->response.status = static_cast<http_status>(0);
}
if ((new_request->parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH && new_request->parser.content_length) {
if (new_request->mode == Request::Mode::STREAM_MSGPACK) {
new_request->unpacker.reserve_buffer(new_request->parser.content_length);
} else {
new_request->raw.reserve(new_request->parser.content_length);
}
}
return 0;
}
void
HttpClient::process(Request& request)
{
L_CALL("HttpClient::process()");
L_OBJ_BEGIN("HttpClient::process:BEGIN");
L_OBJ_END("HttpClient::process:END");
handled_errors(request, [&]{
(this->*request.view)(request);
return 0;
});
}
void
HttpClient::operator()()
{
L_CALL("HttpClient::operator()()");
L_CONN("Start running in worker...");
std::unique_lock<std::mutex> lk(runner_mutex);
while (!requests.empty() && !closed) {
Request& request = *requests.front();
if (request.atom_ended) {
requests.pop_front();
continue;
}
request.ending = request.atom_ending.load();
lk.unlock();
// wait for the request to be ready
if (!request.ending && !request.wait()) {
lk.lock();
continue;
}
try {
ASSERT(request.view);
process(request);
request.begining = false;
} catch (...) {
request.begining = false;
end_http_request(request);
lk.lock();
requests.pop_front();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: HTTP client ended with an unhandled exception");
detach();
throw;
}
if (request.ending) {
end_http_request(request);
auto closing = request.closing;
lk.lock();
requests.pop_front();
if (closing) {
running = false;
L_CONN("Running in worker ended after request closing.");
lk.unlock();
shutdown();
return;
}
} else {
lk.lock();
}
}
running = false;
L_CONN("Running in replication worker ended. {{requests_empty:{}, closed:{}, is_shutting_down:{}}}", requests.empty(), closed.load(), is_shutting_down());
lk.unlock();
if (is_shutting_down()) {
shutdown();
return;
}
redetach(); // try re-detaching if already flagged as detaching
}
MsgPack
HttpClient::node_obj()
{
L_CALL("HttpClient::node_obj()");
endpoints.clear();
auto leader_node = Node::leader_node();
endpoints.add(Endpoint{".xapiand", leader_node});
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
auto local_node = Node::local_node();
auto document = db_handler.get_document(local_node->lower_name());
auto obj = document.get_obj();
obj.update(MsgPack({
#ifdef XAPIAND_CLUSTERING
{ RESPONSE_CLUSTER_NAME, opts.cluster_name },
#endif
{ RESPONSE_SERVER, Package::STRING },
{ RESPONSE_URL, Package::BUGREPORT },
{ RESPONSE_VERSIONS, {
{ "Xapiand", Package::REVISION.empty() ? Package::VERSION : string::format("{}_{}", Package::VERSION, Package::REVISION) },
{ "Xapian", string::format("{}.{}.{}", Xapian::major_version(), Xapian::minor_version(), Xapian::revision()) },
#ifdef XAPIAND_CHAISCRIPT
{ "ChaiScript", string::format("{}.{}", chaiscript::Build_Info::version_major(), chaiscript::Build_Info::version_minor()) },
#endif
} },
{ "options", {
{ "verbosity", opts.verbosity },
{ "processors", opts.processors },
{ "limits", {
// { "max_clients", opts.max_clients },
{ "max_database_readers", opts.max_database_readers },
} },
{ "cache", {
{ "database_pool_size", opts.database_pool_size },
{ "schema_pool_size", opts.schema_pool_size },
{ "scripts_cache_size", opts.scripts_cache_size },
#ifdef XAPIAND_CLUSTERING
{ "resolver_cache_size", opts.resolver_cache_size },
#endif
} },
{ "thread_pools", {
{ "num_shards", opts.num_shards },
{ "num_replicas", opts.num_replicas },
{ "num_http_servers", opts.num_http_servers },
{ "num_http_clients", opts.num_http_clients },
#ifdef XAPIAND_CLUSTERING
{ "num_remote_servers", opts.num_remote_servers },
{ "num_remote_clients", opts.num_remote_clients },
{ "num_replication_servers", opts.num_replication_servers },
{ "num_replication_clients", opts.num_replication_clients },
#endif
{ "num_async_wal_writers", opts.num_async_wal_writers },
{ "num_doc_preparers", opts.num_doc_preparers },
{ "num_doc_indexers", opts.num_doc_indexers },
{ "num_committers", opts.num_committers },
{ "num_fsynchers", opts.num_fsynchers },
#ifdef XAPIAND_CLUSTERING
{ "num_replicators", opts.num_replicators },
{ "num_discoverers", opts.num_discoverers },
#endif
} },
} },
}));
return obj;
}
void
HttpClient::metrics_view(Request& request)
{
L_CALL("HttpClient::metrics_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
auto server_info = XapiandManager::server_metrics();
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE | HTTP_BODY_RESPONSE, server_info, "", "text/plain", "", server_info.size()));
}
void
HttpClient::document_exists_view(Request& request)
{
L_CALL("HttpClient::document_exists_view()");
auto query_field = query_field_maker(request, 0);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_CREATE_OR_OPEN);
db_handler.get_document(request.path_parser.get_id()).validate();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
void
HttpClient::delete_document_view(Request& request)
{
L_CALL("HttpClient::delete_document_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
std::string document_id(request.path_parser.get_id());
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.delete_document(document_id, query_field.commit);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_NO_CONTENT);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Deletion took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "delete"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_document_view(Request& request)
{
L_CALL("HttpClient::write_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
auto indexed = db_handler.index(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
request.ready = std::chrono::system_clock::now();
std::string location;
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (request.echo) {
auto it = response_obj.find(ID_FIELD_NAME);
if (document_id.empty()) {
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), document_id_obj.as_str());
response_obj[ID_FIELD_NAME] = std::move(document_id_obj);
} else {
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), it.value().as_str());
}
} else {
if (it == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj, location);
} else {
if (document_id.empty()) {
auto it = response_obj.find(ID_FIELD_NAME);
if (it == response_obj.end()) {
auto document_id_obj = document.get_value(ID_FIELD_NAME);
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), document_id_obj.as_str());
} else {
location = string::format("/{}/{}", unsharded_path(endpoints[0].path), it.value().as_str());
}
}
write_http_response(request, document_id.empty() ? HTTP_STATUS_CREATED : HTTP_STATUS_NO_CONTENT, MsgPack(), location);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Indexing took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "index"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_document_view(Request& request)
{
L_CALL("HttpClient::update_document_view()");
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE | QUERY_FIELD_COMMIT);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
auto document_id = request.path_parser.get_id();
ASSERT(!document_id.empty());
request.processing = std::chrono::system_clock::now();
std::string operation;
DataType indexed;
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (request.method == HTTP_PATCH) {
operation = "patch";
indexed = db_handler.patch(document_id, query_field.version, decoded_body, query_field.commit);
} else if (request.method == HTTP_STORE) {
operation = "store";
indexed = db_handler.update(document_id, query_field.version, true, decoded_body, query_field.commit, request.ct_type == json_type || request.ct_type == msgpack_type || request.ct_type.empty() ? mime_type(selector) : request.ct_type);
} else {
operation = "update";
indexed = db_handler.update(document_id, query_field.version, false, decoded_body, query_field.commit, request.ct_type);
}
request.ready = std::chrono::system_clock::now();
if (request.echo) {
auto did = indexed.first;
auto& response_obj = indexed.second;
Document document(did, &db_handler);
if (response_obj.find(ID_FIELD_NAME) == response_obj.end()) {
response_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
response_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
response_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
response_obj[RESPONSE_xSHARD] = shard_num + 1;
// response_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", operation},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_metadata_view(Request& request)
{
L_CALL("HttpClient::retrieve_metadata_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
MsgPack response_obj;
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
ASSERT(!key.empty());
key.remove_prefix(1);
if (key.empty()) {
response_obj = MsgPack::MAP();
for (auto& _key : db_handler.get_metadata_keys()) {
auto metadata = db_handler.get_metadata(_key);
if (!metadata.empty()) {
response_obj[_key] = MsgPack::unserialise(metadata);
}
}
} else {
auto metadata = db_handler.get_metadata(key);
if (metadata.empty()) {
throw Xapian::DocNotFoundError("Metadata not found");
} else {
response_obj = MsgPack::unserialise(metadata);
}
}
request.ready = std::chrono::system_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Get metadata took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "get_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::write_metadata_view(Request& request)
{
L_CALL("HttpClient::write_metadata_view()");
auto& decoded_body = request.decoded_body();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
auto key = request.path_parser.get_cmd();
ASSERT(!key.empty());
key.remove_prefix(1);
if (key.empty() || key == "schema" || key == "wal" || key == "nodes" || key == "metrics") {
THROW(ClientError, "Metadata {} is read-only", repr(request.path_parser.get_cmd()));
}
db_handler.set_metadata(key, decoded_body.serialise());
request.ready = std::chrono::system_clock::now();
if (request.echo) {
write_http_response(request, HTTP_STATUS_OK, selector.empty() ? decoded_body : decoded_body.select(selector));
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Set metadata took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "set_metadata"},
})
.Observe(took / 1e9);
}
void
HttpClient::update_metadata_view(Request& request)
{
L_CALL("HttpClient::update_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::delete_metadata_view(Request& request)
{
L_CALL("HttpClient::delete_metadata_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::info_view(Request& request)
{
L_CALL("HttpClient::info_view()");
MsgPack response_obj;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Info about a specific document was requested
if (request.path_parser.off_id != nullptr) {
auto id = request.path_parser.get_id();
request.query_parser.rewind();
bool raw = request.query_parser.next("raw") != -1;
response_obj = db_handler.get_document_info(id, raw, request.human);
} else {
response_obj = db_handler.get_database_info();
}
request.ready = std::chrono::system_clock::now();
if (!selector.empty()) {
response_obj = response_obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Info took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "info"}
})
.Observe(took / 1e9);
}
void
HttpClient::nodes_view(Request& request)
{
L_CALL("HttpClient::nodes_view()");
auto nodes = MsgPack::ARRAY();
#ifdef XAPIAND_CLUSTERING
for (auto& node : Node::nodes()) {
if (node->idx) {
auto obj = MsgPack::MAP();
obj["idx"] = node->idx;
obj["name"] = node->name();
if (Node::is_active(node)) {
obj["host"] = node->host();
obj["http_port"] = node->http_port;
obj["remote_port"] = node->remote_port;
obj["replication_port"] = node->replication_port;
obj["active"] = true;
} else {
obj["active"] = false;
}
nodes.push_back(obj);
}
}
#endif
write_http_response(request, HTTP_STATUS_OK, {
{ RESPONSE_CLUSTER_NAME, opts.cluster_name },
{ RESPONSE_NODES, nodes },
});
}
void
HttpClient::database_exists_view(Request& request)
{
L_CALL("HttpClient::database_exists_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN);
db_handler.reopen(); // Ensure it can be opened.
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
}
MsgPack
HttpClient::retrieve_database(const query_field_t& query_field, bool is_root)
{
L_CALL("HttpClient::retrieve_database()");
MsgPack schema;
MsgPack settings;
auto obj = MsgPack::MAP();
// Get active schema
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrieve full schema
schema = db_handler.get_schema()->get_full(true);
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Get index settings (from .xapiand/index)
auto id = std::string(endpoints.size() == 1 ? endpoints[0].path : unsharded_path(endpoints[0].path));
endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{".xapiand/index"},
false,
query_field.primary);
try {
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
auto did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
settings = document.get_obj();
// Remove schema, ID and version from document:
auto it_e = settings.end();
auto it = settings.find(SCHEMA_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(ID_FIELD_NAME);
if (it != it_e) {
settings.erase(it);
}
it = settings.find(RESERVED_VERSION);
if (it != it_e) {
settings.erase(it);
}
} catch (const Xapian::DocNotFoundError&) {
if (!is_root) {
throw;
}
} catch (const Xapian::DatabaseNotFoundError&) {
if (!is_root) {
throw;
}
}
// Add node information for '/':
if (is_root) {
obj.update(node_obj());
}
if (!settings.empty()) {
obj[RESERVED_SETTINGS].update(settings);
}
if (!schema.empty()) {
obj[RESERVED_SCHEMA].update(schema);
}
return obj;
}
void
HttpClient::retrieve_database_view(Request& request)
{
L_CALL("HttpClient::retrieve_database_view()");
ASSERT(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving database took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve_database"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE DATABASE");
}
void
HttpClient::update_database_view(Request& request)
{
L_CALL("HttpClient::update_database_view()");
ASSERT(request.path_parser.get_id().empty());
auto is_root = !request.path_parser.has_pth();
auto& decoded_body = request.decoded_body();
MsgPack* settings = nullptr;
if (decoded_body.is_map()) {
auto settings_it = decoded_body.find(RESERVED_SETTINGS);
if (settings_it != decoded_body.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
if (decoded_body.is_map()) {
auto schema_it = decoded_body.find(RESERVED_SCHEMA);
if (schema_it != decoded_body.end()) {
auto& schema = schema_it.value();
db_handler.write_schema(schema, false);
}
}
db_handler.reopen(); // Ensure touch.
request.ready = std::chrono::system_clock::now();
if (request.echo) {
auto obj = retrieve_database(query_field, is_root);
if (!selector.empty()) {
obj = obj.select(selector);
}
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
write_http_response(request, HTTP_STATUS_NO_CONTENT);
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Updating database took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "update_database"},
})
.Observe(took / 1e9);
}
void
HttpClient::delete_database_view(Request& request)
{
L_CALL("HttpClient::delete_database_view()");
write_http_response(request, HTTP_STATUS_NOT_IMPLEMENTED);
}
void
HttpClient::commit_database_view(Request& request)
{
L_CALL("HttpClient::commit_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
resolve_index_endpoints(request, query_field);
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN);
db_handler.commit(); // Ensure touch.
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Commit took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "commit"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_document_view(Request& request)
{
L_CALL("HttpClient::dump_document_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto document_id = request.path_parser.get_id();
ASSERT(!document_id.empty());
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto obj = db_handler.dump_document(document_id);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::dump_database_view(Request& request)
{
L_CALL("HttpClient::dump_database_view()");
auto query_field = query_field_maker(request, 0);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler(endpoints, DB_OPEN | DB_DISABLE_WAL);
auto ct_type = resolve_ct_type(request, MSGPACK_CONTENT_TYPE);
if (ct_type.empty()) {
auto dump_ct_type = resolve_ct_type(request, ct_type_t("application/octet-stream"));
if (dump_ct_type.empty()) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type application/octet-stream not provided in the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED SEARCH");
return;
}
char path[] = "/tmp/xapian_dump.XXXXXX";
int file_descriptor = io::mkstemp(path);
try {
db_handler.dump_documents(file_descriptor);
} catch (...) {
io::close(file_descriptor);
io::unlink(path);
throw;
}
request.ready = std::chrono::system_clock::now();
size_t content_length = io::lseek(file_descriptor, 0, SEEK_CUR);
io::close(file_descriptor);
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_LENGTH_RESPONSE, "", "", dump_ct_type.to_string(), "", content_length));
write_file(path, true);
return;
}
auto docs = db_handler.dump_documents();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, docs);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Dump took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "dump"},
})
.Observe(took / 1e9);
}
void
HttpClient::restore_database_view(Request& request)
{
L_CALL("HttpClient::restore_database_view()");
if (request.mode == Request::Mode::STREAM_MSGPACK || request.mode == Request::Mode::STREAM_NDJSON) {
MsgPack obj;
while (request.next_object(obj)) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments);
}
request.indexer->prepare(std::move(obj));
}
} else {
auto& docs = request.decoded_body();
for (auto& obj : docs) {
if (!request.indexer) {
MsgPack* settings = nullptr;
if (obj.is_map()) {
auto settings_it = obj.find(RESERVED_SETTINGS);
if (settings_it != obj.end()) {
settings = &settings_it.value();
}
}
auto query_field = query_field_maker(request, QUERY_FIELD_WRITABLE);
if (resolve_index_endpoints(request, query_field, settings) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
request.indexer = DocIndexer::make_shared(endpoints, DB_WRITABLE | DB_CREATE_OR_OPEN, request.echo, request.comments);
}
request.indexer->prepare(std::move(obj));
}
}
if (request.ending) {
request.indexer->wait();
request.ready = std::chrono::system_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
MsgPack response_obj = {
// { RESPONSE_ENDPOINT, endpoints.to_string() },
{ RESPONSE_PROCESSED, request.indexer->processed() },
{ RESPONSE_INDEXED, request.indexer->indexed() },
{ RESPONSE_TOTAL, request.indexer->total() },
{ RESPONSE_ITEMS, request.indexer->results() },
};
if (request.human) {
response_obj[RESPONSE_TOOK] = string::from_delta(took);
} else {
response_obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, response_obj);
L_TIME("Restore took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "restore"},
})
.Observe(took / 1e9);
}
}
#if XAPIAND_DATABASE_WAL
void
HttpClient::wal_view(Request& request)
{
L_CALL("HttpClient::wal_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler{endpoints};
request.query_parser.rewind();
bool unserialised = request.query_parser.next("raw") == -1;
auto repr = db_handler.repr_wal(0, std::numeric_limits<Xapian::rev>::max(), unserialised);
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, repr);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("WAL took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "wal"},
})
.Observe(took / 1e9);
}
#endif
void
HttpClient::check_database_view(Request& request)
{
L_CALL("HttpClient::check_database_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_PRIMARY);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
request.processing = std::chrono::system_clock::now();
DatabaseHandler db_handler{endpoints};
auto status = db_handler.check();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, status);
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Database check took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "db_check"},
})
.Observe(took / 1e9);
}
void
HttpClient::retrieve_document_view(Request& request)
{
L_CALL("HttpClient::retrieve_document_view()");
auto id = request.path_parser.get_id();
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_ID);
if (resolve_index_endpoints(request, query_field) > 1) {
THROW(ClientError, "Method can only be used with single indexes");
}
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
// Retrive document ID
Xapian::docid did;
did = db_handler.get_docid(id);
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const Data data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto accepted = data.get_accepted(request.accept_set, mime_type(selector));
if (accepted.first == nullptr) {
// No content type could be resolved, return NOT ACCEPTABLE.
enum http_status error_code = HTTP_STATUS_NOT_ACCEPTABLE;
if (request.comments) {
write_http_response(request, error_code, MsgPack({
{ RESPONSE_xSTATUS, (int)error_code },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type not accepted by the Accept header" }) } }
}));
} else {
write_http_response(request, error_code);
}
L_SEARCH("ABORTED RETRIEVE");
return;
}
auto& locator = *accepted.first;
if (locator.ct_type.empty()) {
// Locator doesn't have a content type, serialize and return as document
auto obj = MsgPack::unserialise(locator.data());
// Detailed info about the document:
if (obj.find(ID_FIELD_NAME) == obj.end()) {
obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
obj[RESPONSE_xSHARD] = shard_num + 1;
// obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
}
if (!selector.empty()) {
obj = obj.select(selector);
}
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
} else {
// Locator has content type, return as a blob (an image for instance)
auto ct_type = locator.ct_type;
request.response.blob = locator.data();
#ifdef XAPIAND_DATA_STORAGE
if (locator.type == Locator::Type::stored || locator.type == Locator::Type::compressed_stored) {
if (request.response.blob.empty()) {
auto stored = db_handler.storage_get_stored(locator, did);
request.response.blob = unserialise_string_at(STORED_BLOB, stored);
}
}
#endif
request.ready = std::chrono::system_clock::now();
request.response.ct_type = ct_type;
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, request.response.blob, false, true, true);
if (!encoded.empty() && encoded.size() <= request.response.blob.size()) {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, encoded, "", ct_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, HTTP_STATUS_OK, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_BODY_RESPONSE, request.response.blob, "", ct_type.to_string()));
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Retrieving took {}", string::from_delta(took));
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "retrieve"},
})
.Observe(took / 1e9);
L_SEARCH("FINISH RETRIEVE");
}
void
HttpClient::search_view(Request& request)
{
L_CALL("HttpClient::search_view()");
std::string selector_string_holder;
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
auto selector = query_field.selector.empty() ? request.path_parser.get_slc() : query_field.selector;
MSet mset{};
MsgPack aggregations;
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
AggregationMatchSpy aggs(decoded_body, db_handler.get_schema());
if (decoded_body.find(RESERVED_QUERYDSL_SELECTOR) != decoded_body.end()) {
auto selector_obj = decoded_body.at(RESERVED_QUERYDSL_SELECTOR);
if (selector_obj.is_string()) {
selector_string_holder = selector_obj.as_str();
selector = selector_string_holder;
} else {
THROW(ClientError, "The {} must be a string", RESERVED_QUERYDSL_SELECTOR);
}
}
mset = db_handler.get_mset(query_field, &decoded_body, &aggs);
aggregations = aggs.get_aggregation().at(RESERVED_AGGS_AGGREGATIONS);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
obj[RESPONSE_COUNT] = mset.size();
if (aggregations) {
obj[RESPONSE_AGGREGATIONS] = aggregations;
}
obj[RESPONSE_HITS] = MsgPack::ARRAY();
auto& hits = obj[RESPONSE_HITS];
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto did = *m;
// Retrive document data
auto document = db_handler.get_document(did);
auto document_data = document.get_data();
const auto data = Data(document_data.empty() ? std::string(DATABASE_DATA_MAP) : std::move(document_data));
auto hit_obj = MsgPack::MAP();
auto main_locator = data.get("");
if (main_locator != nullptr) {
auto locator_data = main_locator->data();
if (!locator_data.empty()) {
hit_obj = MsgPack::unserialise(locator_data);
}
}
// Detailed info about the document:
if (hit_obj.find(ID_FIELD_NAME) == hit_obj.end()) {
hit_obj[ID_FIELD_NAME] = document.get_value(ID_FIELD_NAME);
}
auto version = document.get_value(DB_SLOT_VERSION);
if (!version.empty()) {
hit_obj[RESERVED_VERSION] = static_cast<Xapian::rev>(sortable_unserialise(version));
}
if (request.comments) {
hit_obj[RESPONSE_xDOCID] = did;
size_t n_shards = endpoints.size();
size_t shard_num = (did - 1) % n_shards;
hit_obj[RESPONSE_xSHARD] = shard_num + 1;
// hit_obj[RESPONSE_xENDPOINT] = endpoints[shard_num].to_string();
hit_obj[RESPONSE_xRANK] = m.get_rank();
hit_obj[RESPONSE_xWEIGHT] = m.get_weight();
hit_obj[RESPONSE_xPERCENT] = m.get_percent();
}
if (!selector.empty()) {
hit_obj = hit_obj.select(selector);
}
hits.append(hit_obj);
}
request.ready = std::chrono::system_clock::now();
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ready - request.processing).count();
L_TIME("Searching took {}", string::from_delta(took));
if (request.human) {
obj[RESPONSE_TOOK] = string::from_delta(took);
} else {
obj[RESPONSE_TOOK] = took / 1e9;
}
write_http_response(request, HTTP_STATUS_OK, obj);
if (aggregations) {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "aggregation"},
})
.Observe(took / 1e9);
} else {
Metrics::metrics()
.xapiand_operations_summary
.Add({
{"operation", "search"},
})
.Observe(took / 1e9);
}
L_SEARCH("FINISH SEARCH");
}
void
HttpClient::count_view(Request& request)
{
L_CALL("HttpClient::count_view()");
auto query_field = query_field_maker(request, QUERY_FIELD_VOLATILE | QUERY_FIELD_SEARCH);
resolve_index_endpoints(request, query_field);
MSet mset{};
request.processing = std::chrono::system_clock::now();
// Open database
DatabaseHandler db_handler;
try {
if (query_field.primary) {
db_handler.reset(endpoints, DB_OPEN | DB_WRITABLE);
} else {
db_handler.reset(endpoints, DB_OPEN);
}
if (request.raw.empty()) {
mset = db_handler.get_mset(query_field, nullptr, nullptr);
} else {
auto& decoded_body = request.decoded_body();
mset = db_handler.get_mset(query_field, &decoded_body, nullptr);
}
} catch (const Xapian::DatabaseNotFoundError&) {
/* At the moment when the endpoint does not exist and it is chunck it will return 200 response
* with zero matches this behavior may change in the future for instance ( return 404 ) */
}
MsgPack obj;
obj[RESPONSE_TOTAL] = mset.get_matches_estimated();
request.ready = std::chrono::system_clock::now();
write_http_response(request, HTTP_STATUS_OK, obj);
}
void
HttpClient::write_status_response(Request& request, enum http_status status, const std::string& message)
{
L_CALL("HttpClient::write_status_response()");
if (request.comments) {
write_http_response(request, status, MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, message.empty() ? MsgPack({ http_status_str(status) }) : string::split(message, '\n') }
}));
} else {
write_http_response(request, status);
}
}
void
HttpClient::url_resolve(Request& request)
{
L_CALL("HttpClient::url_resolve(request)");
struct http_parser_url u;
std::string b = repr(request.path, true, 0);
L_HTTP("URL: {}", b);
if (http_parser_parse_url(request.path.data(), request.path.size(), 0, &u) != 0) {
L_HTTP_PROTO("Parsing not done");
THROW(ClientError, "Invalid HTTP");
}
L_HTTP_PROTO("HTTP parsing done!");
if ((u.field_set & (1 << UF_PATH )) != 0) {
if (request.path_parser.init(std::string_view(request.path.data() + u.field_data[3].off, u.field_data[3].len)) >= PathParser::State::END) {
THROW(ClientError, "Invalid path");
}
}
if ((u.field_set & (1 << UF_QUERY)) != 0) {
if (request.query_parser.init(std::string_view(b.data() + u.field_data[4].off, u.field_data[4].len)) < 0) {
THROW(ClientError, "Invalid query");
}
}
bool pretty = !opts.no_pretty && (opts.pretty || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("pretty") != -1) {
if (request.query_parser.len != 0u) {
try {
pretty = Serialise::boolean(request.query_parser.get()) == "t";
request.indented = pretty ? DEFAULT_INDENTATION : -1;
} catch (const Exception&) { }
} else {
if (request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
} else {
if (pretty && request.indented == -1) {
request.indented = DEFAULT_INDENTATION;
}
}
request.query_parser.rewind();
if (request.query_parser.next("human") != -1) {
if (request.query_parser.len != 0u) {
try {
request.human = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.human = true;
}
} else {
request.human = pretty;
}
bool echo = !opts.no_echo && (opts.echo || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("echo") != -1) {
if (request.query_parser.len != 0u) {
try {
request.echo = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.echo = true;
}
} else {
request.echo = echo;
}
bool comments = !opts.no_comments && (opts.comments || opts.verbosity >= 4);
request.query_parser.rewind();
if (request.query_parser.next("comments") != -1) {
if (request.query_parser.len != 0u) {
try {
request.comments = Serialise::boolean(request.query_parser.get()) == "t" ? true : false;
} catch (const Exception&) { }
} else {
request.comments = true;
}
} else {
request.comments = comments;
}
}
size_t
HttpClient::resolve_index_endpoints(Request& request, const query_field_t& query_field, const MsgPack* settings)
{
L_CALL("HttpClient::resolve_index_endpoints(<request>, <query_field>, <settings>)");
auto paths = expand_paths(request);
endpoints.clear();
for (const auto& path : paths) {
auto index_endpoints = XapiandManager::resolve_index_endpoints(
Endpoint{path},
query_field.writable,
query_field.primary,
settings);
if (index_endpoints.empty()) {
throw Xapian::NetworkError("Endpoint node not available");
}
for (auto& endpoint : index_endpoints) {
endpoints.add(endpoint);
}
}
L_HTTP("Endpoint: -> {}", endpoints.to_string());
return paths.size();
}
std::vector<std::string>
HttpClient::expand_paths(Request& request)
{
L_CALL("HttpClient::expand_paths(<request>)");
std::vector<std::string> paths;
request.path_parser.rewind();
PathParser::State state;
while ((state = request.path_parser.next()) < PathParser::State::END) {
std::string index_path;
auto pth = request.path_parser.get_pth();
if (string::startswith(pth, '/')) {
pth.remove_prefix(1);
}
index_path.append(pth);
#ifdef XAPIAND_CLUSTERING
MSet mset;
if (string::endswith(index_path, '*')) {
index_path.pop_back();
auto stripped_index_path = index_path;
if (string::endswith(stripped_index_path, '/')) {
stripped_index_path.pop_back();
}
Endpoints index_endpoints;
for (auto& node : Node::nodes()) {
if (node->idx) {
index_endpoints.add(Endpoint{string::format(".xapiand/{}", node->lower_name())});
}
}
DatabaseHandler db_handler;
db_handler.reset(index_endpoints);
if (stripped_index_path.empty()) {
mset = db_handler.get_all_mset("", 0, 100);
} else {
auto query = Xapian::Query(Xapian::Query::OP_AND_NOT,
Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(prefixed(stripped_index_path, DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR))),
Xapian::Query(Xapian::Query::OP_WILDCARD, Xapian::Query(prefixed(index_path + "/.", DOCUMENT_ID_TERM_PREFIX, KEYWORD_CHAR)))
);
mset = db_handler.get_mset(query, 0, 100);
}
const auto m_e = mset.end();
for (auto m = mset.begin(); m != m_e; ++m) {
auto document = db_handler.get_document(*m);
index_path = document.get_value(DB_SLOT_ID);
paths.push_back(std::move(index_path));
}
} else {
#endif
paths.push_back(std::move(index_path));
#ifdef XAPIAND_CLUSTERING
}
#endif
}
return paths;
}
query_field_t
HttpClient::query_field_maker(Request& request, int flags)
{
L_CALL("HttpClient::query_field_maker(<request>, <flags>)");
query_field_t query_field;
if ((flags & QUERY_FIELD_WRITABLE) != 0) {
query_field.writable = true;
}
if ((flags & QUERY_FIELD_PRIMARY) != 0) {
query_field.primary = true;
}
if ((flags & QUERY_FIELD_COMMIT) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("commit") != -1) {
query_field.commit = true;
if (request.query_parser.len != 0u) {
try {
query_field.commit = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("version") != -1) {
query_field.version = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_VOLATILE) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("volatile") != -1) {
query_field.primary = true;
if (request.query_parser.len != 0u) {
try {
query_field.primary = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
}
if (((flags & QUERY_FIELD_ID) != 0) || ((flags & QUERY_FIELD_SEARCH) != 0)) {
request.query_parser.rewind();
if (request.query_parser.next("offset") != -1) {
query_field.offset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("check_at_least") != -1) {
query_field.check_at_least = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("limit") != -1) {
query_field.limit = strict_stou(nullptr, request.query_parser.get());
}
}
if ((flags & QUERY_FIELD_SEARCH) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("spelling") != -1) {
query_field.spelling = true;
if (request.query_parser.len != 0u) {
try {
query_field.spelling = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
if (request.query_parser.next("synonyms") != -1) {
query_field.synonyms = true;
if (request.query_parser.len != 0u) {
try {
query_field.synonyms = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
request.query_parser.rewind();
while (request.query_parser.next("query") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("q") != -1) {
L_SEARCH("query={}", request.query_parser.get());
query_field.query.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("sort") != -1) {
query_field.sort.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("metric") != -1) {
query_field.metric = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("icase") != -1) {
query_field.icase = Serialise::boolean(request.query_parser.get()) == "t";
}
request.query_parser.rewind();
if (request.query_parser.next("collapse_max") != -1) {
query_field.collapse_max = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("collapse") != -1) {
query_field.collapse = request.query_parser.get();
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy") != -1) {
query_field.is_fuzzy = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_fuzzy = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_fuzzy) {
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_rset") != -1) {
query_field.fuzzy.n_rset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_eset") != -1) {
query_field.fuzzy.n_eset = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("fuzzy.n_term") != -1) {
query_field.fuzzy.n_term = strict_stou(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.field") != -1) {
query_field.fuzzy.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("fuzzy.type") != -1) {
query_field.fuzzy.type.emplace_back(request.query_parser.get());
}
}
request.query_parser.rewind();
if (request.query_parser.next("nearest") != -1) {
query_field.is_nearest = true;
if (request.query_parser.len != 0u) {
try {
query_field.is_nearest = Serialise::boolean(request.query_parser.get()) == "t";
} catch (const Exception&) { }
}
}
if (query_field.is_nearest) {
query_field.nearest.n_rset = 5;
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_rset") != -1) {
query_field.nearest.n_rset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_eset") != -1) {
query_field.nearest.n_eset = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
if (request.query_parser.next("nearest.n_term") != -1) {
query_field.nearest.n_term = strict_stoul(nullptr, request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.field") != -1) {
query_field.nearest.field.emplace_back(request.query_parser.get());
}
request.query_parser.rewind();
while (request.query_parser.next("nearest.type") != -1) {
query_field.nearest.type.emplace_back(request.query_parser.get());
}
}
}
if ((flags & QUERY_FIELD_TIME) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("time") != -1) {
query_field.time = request.query_parser.get();
} else {
query_field.time = "1h";
}
}
if ((flags & QUERY_FIELD_PERIOD) != 0) {
request.query_parser.rewind();
if (request.query_parser.next("period") != -1) {
query_field.period = request.query_parser.get();
} else {
query_field.period = "1m";
}
}
request.query_parser.rewind();
if (request.query_parser.next("selector") != -1) {
query_field.selector = request.query_parser.get();
}
return query_field;
}
void
HttpClient::log_request(Request& request)
{
L_CALL("HttpClient::log_request()");
std::string request_prefix = " 🌎 ";
int priority = LOG_DEBUG;
if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
priority = LOG_INFO;
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
priority = LOG_NOTICE;
}
auto request_text = request.to_text(true);
L(priority, NO_COLOR, "{}{}", request_prefix, string::indent(request_text, ' ', 4, false));
}
void
HttpClient::log_response(Response& response)
{
L_CALL("HttpClient::log_response()");
std::string response_prefix = " 💊 ";
int priority = LOG_DEBUG;
if ((int)response.status >= 300 && (int)response.status <= 399) {
response_prefix = " 💫 ";
} else if ((int)response.status == 404) {
response_prefix = " 🕸 ";
} else if ((int)response.status >= 400 && (int)response.status <= 499) {
response_prefix = " 💥 ";
priority = LOG_INFO;
} else if ((int)response.status >= 500 && (int)response.status <= 599) {
response_prefix = " 🔥 ";
priority = LOG_NOTICE;
}
auto response_text = response.to_text(true);
L(priority, NO_COLOR, "{}{}", response_prefix, string::indent(response_text, ' ', 4, false));
}
void
HttpClient::end_http_request(Request& request)
{
L_CALL("HttpClient::end_http_request()");
request.ends = std::chrono::system_clock::now();
request.atom_ending = true;
request.atom_ended = true;
waiting = false;
if (request.indexer) {
request.indexer->finish();
request.indexer.reset();
}
if (request.log) {
request.log->clear();
request.log.reset();
}
if (request.parser.http_errno != 0u) {
L(LOG_ERR, LIGHT_RED, "HTTP parsing error ({}): {}", http_errno_name(HTTP_PARSER_ERRNO(&request.parser)), http_errno_description(HTTP_PARSER_ERRNO(&request.parser)));
} else {
static constexpr auto fmt_defaut = RED + "\"{}\" {} {} {}";
auto fmt = fmt_defaut.c_str();
int priority = LOG_DEBUG;
if ((int)request.response.status >= 200 && (int)request.response.status <= 299) {
static constexpr auto fmt_2xx = LIGHT_GREY + "\"{}\" {} {} {}";
fmt = fmt_2xx.c_str();
} else if ((int)request.response.status >= 300 && (int)request.response.status <= 399) {
static constexpr auto fmt_3xx = STEEL_BLUE + "\"{}\" {} {} {}";
fmt = fmt_3xx.c_str();
} else if ((int)request.response.status >= 400 && (int)request.response.status <= 499) {
static constexpr auto fmt_4xx = SADDLE_BROWN + "\"{}\" {} {} {}";
fmt = fmt_4xx.c_str();
if ((int)request.response.status != 404) {
priority = LOG_INFO;
}
} else if ((int)request.response.status >= 500 && (int)request.response.status <= 599) {
static constexpr auto fmt_5xx = LIGHT_PURPLE + "\"{}\" {} {} {}";
fmt = fmt_5xx.c_str();
priority = LOG_NOTICE;
}
if (Logging::log_level > LOG_DEBUG) {
log_response(request.response);
} else if (Logging::log_level == LOG_DEBUG) {
if ((int)request.response.status >= 400 && (int)request.response.status != 404) {
log_request(request);
log_response(request.response);
}
}
auto took = std::chrono::duration_cast<std::chrono::nanoseconds>(request.ends - request.begins).count();
Metrics::metrics()
.xapiand_http_requests_summary
.Add({
{"method", http_method_str(request.method)},
{"status", string::format("{}", request.response.status)},
})
.Observe(took / 1e9);
L(priority, NO_COLOR, fmt, request.head(), (int)request.response.status, string::from_bytes(request.response.size), string::from_delta(request.begins, request.ends));
}
L_TIME("Full request took {}, response took {}", string::from_delta(request.begins, request.ends), string::from_delta(request.received, request.ends));
auto sent = total_sent_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_sent_bytes
.Increment(sent);
auto received = total_received_bytes.exchange(0);
Metrics::metrics()
.xapiand_http_received_bytes
.Increment(received);
}
ct_type_t
HttpClient::resolve_ct_type(Request& request, ct_type_t ct_type)
{
L_CALL("HttpClient::resolve_ct_type({})", repr(ct_type.to_string()));
if (ct_type == json_type || ct_type == msgpack_type || ct_type == x_msgpack_type) {
if (is_acceptable_type(get_acceptable_type(request, json_type), json_type) != nullptr) {
ct_type = json_type;
} else if (is_acceptable_type(get_acceptable_type(request, msgpack_type), msgpack_type) != nullptr) {
ct_type = msgpack_type;
} else if (is_acceptable_type(get_acceptable_type(request, x_msgpack_type), x_msgpack_type) != nullptr) {
ct_type = x_msgpack_type;
}
}
std::vector<ct_type_t> ct_types;
if (ct_type == json_type || ct_type == msgpack_type || ct_type == x_msgpack_type) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(std::move(ct_type));
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
const auto accepted_ct_type = is_acceptable_type(accepted_type, ct_types);
if (accepted_ct_type == nullptr) {
return no_type;
}
return *accepted_ct_type;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const ct_type_t& ct_type)
{
L_CALL("HttpClient::is_acceptable_type({}, {})", repr(ct_type_pattern.to_string()), repr(ct_type.to_string()));
bool type_ok = false, subtype_ok = false;
if (ct_type_pattern.first == "*") {
type_ok = true;
} else {
type_ok = ct_type_pattern.first == ct_type.first;
}
if (ct_type_pattern.second == "*") {
subtype_ok = true;
} else {
subtype_ok = ct_type_pattern.second == ct_type.second;
}
if (type_ok && subtype_ok) {
return &ct_type;
}
return nullptr;
}
const ct_type_t*
HttpClient::is_acceptable_type(const ct_type_t& ct_type_pattern, const std::vector<ct_type_t>& ct_types)
{
L_CALL("HttpClient::is_acceptable_type(({}, <ct_types>)", repr(ct_type_pattern.to_string()));
for (auto& ct_type : ct_types) {
if (is_acceptable_type(ct_type_pattern, ct_type) != nullptr) {
return &ct_type;
}
}
return nullptr;
}
template <typename T>
const ct_type_t&
HttpClient::get_acceptable_type(Request& request, const T& ct)
{
L_CALL("HttpClient::get_acceptable_type()");
if (request.accept_set.empty()) {
return no_type;
}
for (const auto& accept : request.accept_set) {
if (is_acceptable_type(accept.ct_type, ct)) {
return accept.ct_type;
}
}
const auto& accept = *request.accept_set.begin();
auto indent = accept.indent;
if (indent != -1) {
request.indented = indent;
}
return accept.ct_type;
}
std::pair<std::string, std::string>
HttpClient::serialize_response(const MsgPack& obj, const ct_type_t& ct_type, int indent, bool serialize_error)
{
L_CALL("HttpClient::serialize_response({}, {}, {}, {})", repr(obj.to_string(), true, '\'', 200), repr(ct_type.to_string()), indent, serialize_error);
if (ct_type == no_type) {
return std::make_pair("", "");
}
if (is_acceptable_type(ct_type, json_type) != nullptr) {
return std::make_pair(obj.to_string(indent), json_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, x_msgpack_type) != nullptr) {
return std::make_pair(obj.serialise(), x_msgpack_type.to_string() + "; charset=utf-8");
}
if (is_acceptable_type(ct_type, html_type) != nullptr) {
std::function<std::string(const msgpack::object&)> html_serialize = serialize_error ? msgpack_to_html_error : msgpack_to_html;
return std::make_pair(obj.external(html_serialize), html_type.to_string() + "; charset=utf-8");
}
/*if (is_acceptable_type(ct_type, text_type)) {
error:
{{ ERROR_CODE }} - {{ MESSAGE }}
obj:
{{ key1 }}: {{ val1 }}
{{ key2 }}: {{ val2 }}
...
array:
{{ val1 }}, {{ val2 }}, ...
}*/
THROW(SerialisationError, "Type is not serializable");
}
void
HttpClient::write_http_response(Request& request, enum http_status status, const MsgPack& obj, const std::string& location)
{
L_CALL("HttpClient::write_http_response()");
if (obj.is_undefined()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE, "", location));
return;
}
std::vector<ct_type_t> ct_types;
if (request.ct_type == json_type || request.ct_type == msgpack_type || request.ct_type.empty()) {
ct_types = msgpack_serializers;
} else {
ct_types.push_back(request.ct_type);
}
const auto& accepted_type = get_acceptable_type(request, ct_types);
try {
auto result = serialize_response(obj, accepted_type, request.indented, (int)status >= 400);
if (Logging::log_level >= LOG_DEBUG && request.response.size <= 1024 * 10) {
if (is_acceptable_type(accepted_type, json_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, x_msgpack_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, html_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (is_acceptable_type(accepted_type, text_type) != nullptr) {
request.response.text.append(obj.to_string(DEFAULT_INDENTATION));
} else if (!obj.empty()) {
request.response.text.append("...");
}
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, result.first, false, true, true);
if (!encoded.empty() && encoded.size() <= result.first.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, result.second, readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, result.first, location, result.second, readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, result.first, location, result.second));
}
} catch (const SerialisationError& exc) {
status = HTTP_STATUS_NOT_ACCEPTABLE;
std::string response_str;
if (request.comments) {
MsgPack response_err = MsgPack({
{ RESPONSE_xSTATUS, (int)status },
{ RESPONSE_xMESSAGE, { MsgPack({ "Response type " + accepted_type.to_string() + " " + exc.what() }) } }
});
response_str = response_err.to_string(request.indented);
}
if (request.type_encoding != Encoding::none) {
auto encoded = encoding_http_response(request.response, request.type_encoding, response_str, false, true, true);
if (!encoded.empty() && encoded.size() <= response_str.size()) {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, encoded, location, accepted_type.to_string(), readable_encoding(request.type_encoding)));
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE | HTTP_CONTENT_ENCODING_RESPONSE, response_str, location, accepted_type.to_string(), readable_encoding(Encoding::identity)));
}
} else {
write(http_response(request, status, HTTP_STATUS_RESPONSE | HTTP_HEADER_RESPONSE | HTTP_BODY_RESPONSE | HTTP_CONTENT_TYPE_RESPONSE, response_str, location, accepted_type.to_string()));
}
return;
}
}
Encoding
HttpClient::resolve_encoding(Request& request)
{
L_CALL("HttpClient::resolve_encoding()");
if (request.accept_encoding_set.empty()) {
return Encoding::none;
}
constexpr static auto _ = phf::make_phf({
hhl("gzip"),
hhl("deflate"),
hhl("identity"),
hhl("*"),
});
for (const auto& encoding : request.accept_encoding_set) {
switch (_.fhhl(encoding.encoding)) {
case _.fhhl("gzip"):
return Encoding::gzip;
case _.fhhl("deflate"):
return Encoding::deflate;
case _.fhhl("identity"):
return Encoding::identity;
case _.fhhl("*"):
return Encoding::identity;
default:
continue;
}
}
return Encoding::unknown;
}
std::string
HttpClient::readable_encoding(Encoding e)
{
L_CALL("Request::readable_encoding()");
switch (e) {
case Encoding::none:
return "none";
case Encoding::gzip:
return "gzip";
case Encoding::deflate:
return "deflate";
case Encoding::identity:
return "identity";
default:
return "Encoding:UNKNOWN";
}
}
std::string
HttpClient::encoding_http_response(Response& response, Encoding e, const std::string& response_obj, bool chunk, bool start, bool end)
{
L_CALL("HttpClient::encoding_http_response({})", repr(response_obj));
bool gzip = false;
switch (e) {
case Encoding::gzip:
gzip = true;
[[fallthrough]];
case Encoding::deflate: {
if (chunk) {
if (start) {
response.encoding_compressor.reset(nullptr, 0, gzip);
response.encoding_compressor.begin();
}
if (end) {
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size(), DeflateCompressData::FINISH_COMPRESS);
return ret;
}
auto ret = response.encoding_compressor.next(response_obj.data(), response_obj.size());
return ret;
}
response.encoding_compressor.reset(response_obj.data(), response_obj.size(), gzip);
response.it_compressor = response.encoding_compressor.begin();
std::string encoding_respose;
while (response.it_compressor) {
encoding_respose.append(*response.it_compressor);
++response.it_compressor;
}
return encoding_respose;
}
case Encoding::identity:
return response_obj;
default:
return std::string();
}
}
std::string
HttpClient::__repr__() const
{
return string::format("<HttpClient {{cnt:{}, sock:{}}}{}{}{}{}{}{}{}{}>",
use_count(),
sock,
is_runner() ? " (runner)" : " (worker)",
is_running_loop() ? " (running loop)" : " (stopped loop)",
is_detaching() ? " (deteaching)" : "",
is_idle() ? " (idle)" : "",
is_waiting() ? " (waiting)" : "",
is_running() ? " (running)" : "",
is_shutting_down() ? " (shutting down)" : "",
is_closed() ? " (closed)" : "");
}
Request::Request(HttpClient* client)
: mode{Mode::FULL},
view{nullptr},
type_encoding{Encoding::none},
begining{true},
ending{false},
atom_ending{false},
atom_ended{false},
raw_peek{0},
raw_offset{0},
size{0},
echo{false},
human{false},
comments{true},
indented{-1},
expect_100{false},
closing{false},
begins{std::chrono::system_clock::now()}
{
parser.data = client;
http_parser_init(&parser, HTTP_REQUEST);
}
Request::~Request() noexcept
{
try {
if (indexer) {
indexer->finish();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
try {
if (log) {
log->clear();
log.reset();
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
MsgPack
Request::decode(std::string_view body)
{
L_CALL("Request::decode({})", repr(body));
std::string ct_type_str = ct_type.to_string();
if (ct_type_str.empty()) {
ct_type_str = JSON_CONTENT_TYPE;
}
MsgPack decoded;
rapidjson::Document rdoc;
constexpr static auto _ = phf::make_phf({
hhl(JSON_CONTENT_TYPE),
hhl(MSGPACK_CONTENT_TYPE),
hhl(X_MSGPACK_CONTENT_TYPE),
hhl(NDJSON_CONTENT_TYPE),
hhl(X_NDJSON_CONTENT_TYPE),
hhl(FORM_URLENCODED_CONTENT_TYPE),
hhl(X_FORM_URLENCODED_CONTENT_TYPE),
});
switch (_.fhhl(ct_type_str)) {
case _.fhhl(NDJSON_CONTENT_TYPE):
case _.fhhl(X_NDJSON_CONTENT_TYPE):
decoded = MsgPack::ARRAY();
for (auto json : Split<std::string_view>(body, '\n')) {
json_load(rdoc, json);
decoded.append(rdoc);
}
ct_type = json_type;
return decoded;
case _.fhhl(JSON_CONTENT_TYPE):
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
return decoded;
case _.fhhl(MSGPACK_CONTENT_TYPE):
case _.fhhl(X_MSGPACK_CONTENT_TYPE):
decoded = MsgPack::unserialise(body);
ct_type = msgpack_type;
return decoded;
case _.fhhl(FORM_URLENCODED_CONTENT_TYPE):
case _.fhhl(X_FORM_URLENCODED_CONTENT_TYPE):
try {
json_load(rdoc, body);
decoded = MsgPack(rdoc);
ct_type = json_type;
} catch (const std::exception&) {
decoded = MsgPack(body);
ct_type = msgpack_type;
}
return decoded;
default:
decoded = MsgPack(body);
return decoded;
}
}
MsgPack&
Request::decoded_body()
{
L_CALL("Request::decoded_body()");
if (_decoded_body.is_undefined()) {
if (!raw.empty()) {
_decoded_body = decode(raw);
}
}
return _decoded_body;
}
bool
Request::append(const char* at, size_t length)
{
L_CALL("Request::append(<at>, <length>)");
bool signal_pending = false;
switch (mode) {
case Mode::FULL:
raw.append(std::string_view(at, length));
break;
case Mode::STREAM:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
raw.append(std::string_view(at, length));
signal_pending = true;
break;
case Mode::STREAM_NDJSON:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
raw.append(std::string_view(at, length));
auto new_raw_offset = raw.find_first_of('\n', raw_peek);
while (new_raw_offset != std::string::npos) {
auto json = std::string_view(raw).substr(raw_offset, new_raw_offset - raw_offset);
raw_offset = raw_peek = new_raw_offset + 1;
new_raw_offset = raw.find_first_of('\n', raw_peek);
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
}
if (!length) {
auto json = std::string_view(raw).substr(raw_offset);
raw_offset = raw_peek = raw.size();
if (!json.empty()) {
try {
rapidjson::Document rdoc;
json_load(rdoc, json);
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(rdoc);
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
}
break;
case Mode::STREAM_MSGPACK:
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
if (length) {
unpacker.reserve_buffer(length);
memcpy(unpacker.buffer(), at, length);
unpacker.buffer_consumed(length);
try {
msgpack::object_handle result;
while (unpacker.next(result)) {
signal_pending = true;
std::lock_guard<std::mutex> lk(objects_mtx);
objects.emplace_back(result.get());
}
} catch (const std::exception&) {
L_EXC("Cannot load object");
}
}
break;
}
return signal_pending;
}
bool
Request::wait()
{
if (mode != Request::Mode::FULL) {
// Wait for a pending raw body for one second (1000000us) and flush
// pending signals before processing the request, otherwise retry
// checking for empty/ended requests or closed connections.
if (!pending.wait(1000000)) {
return false;
}
while (pending.tryWaitMany(std::numeric_limits<ssize_t>::max())) { }
}
return true;
}
bool
Request::next(std::string_view& str_view)
{
L_CALL("Request::next(<&str_view>)");
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
ASSERT(mode == Mode::STREAM);
if (raw_offset == raw.size()) {
return false;
}
str_view = std::string_view(raw).substr(raw_offset);
raw_offset = raw.size();
return true;
}
bool
Request::next_object(MsgPack& obj)
{
L_CALL("Request::next_object(<&obj>)");
ASSERT((parser.flags & F_CONTENTLENGTH) == F_CONTENTLENGTH);
ASSERT(mode == Mode::STREAM_MSGPACK || mode == Mode::STREAM_NDJSON);
std::lock_guard<std::mutex> lk(objects_mtx);
if (objects.empty()) {
return false;
}
obj = std::move(objects.front());
objects.pop_front();
return true;
}
std::string
Request::head()
{
L_CALL("Request::head()");
auto parser_method = HTTP_PARSER_METHOD(&parser);
if (parser_method != method) {
return string::format("{} <- {} {} HTTP/{}.{}",
http_method_str(method),
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
return string::format("{} {} HTTP/{}.{}",
http_method_str(parser_method),
path, parser.http_major,
parser.http_minor);
}
std::string
Request::to_text(bool decode)
{
L_CALL("Request::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto request_headers_color = no_col.c_str();
auto request_head_color = no_col.c_str();
auto request_text_color = no_col.c_str();
switch (method) {
case HTTP_OPTIONS: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_INFO: {
// rgb(13, 90, 167)
static constexpr auto _request_headers_color = rgba(30, 77, 124, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(30, 77, 124);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(30, 77, 124);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_HEAD: {
// rgb(144, 18, 254)
static constexpr auto _request_headers_color = rgba(100, 64, 131, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(100, 64, 131);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(100, 64, 131);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_GET: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_SEARCH: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COUNT: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_POST: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DUMP: {
// rgb(101, 177, 251)
static constexpr auto _request_headers_color = rgba(34, 113, 191, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(34, 113, 191);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(34, 113, 191);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_RESTORE: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_OPEN: {
// rgb(80, 203, 146)
static constexpr auto _request_headers_color = rgba(55, 100, 79, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(55, 100, 79);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(55, 100, 79);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_CLOSE: {
// rgb(227, 32, 40)
static constexpr auto _request_headers_color = rgba(101, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(101, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(101, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PATCH: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_MERGE: // TODO: Remove MERGE (method was renamed to UPDATE)
case HTTP_UPDATE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_STORE: {
// rgb(88, 226, 194)
static constexpr auto _request_headers_color = rgba(51, 136, 116, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(51, 136, 116);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(51, 136, 116);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_PUT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_COMMIT: {
// rgb(250, 160, 63)
static constexpr auto _request_headers_color = rgba(158, 95, 28, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(158, 95, 28);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(158, 95, 28);
request_text_color = _request_text_color.c_str();
break;
}
case HTTP_DELETE: {
// rgb(246, 64, 68)
static constexpr auto _request_headers_color = rgba(151, 31, 34, 0.6);
request_headers_color = _request_headers_color.c_str();
static constexpr auto _request_head_color = brgb(151, 31, 34);
request_head_color = _request_head_color.c_str();
static constexpr auto _request_text_color = rgb(151, 31, 34);
request_text_color = _request_text_color.c_str();
break;
}
default:
break;
};
auto request_text = request_head_color + head() + "\n" + request_headers_color + headers + request_text_color;
if (!raw.empty()) {
if (!decode) {
if (raw.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
} else {
request_text += "<body " + repr(raw, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(raw);
request_text += string::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
request_text += b64_data;
request_text += '\a';
} else {
if (raw.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
} else {
auto& decoded = decoded_body();
if (ct_type == json_type || ct_type == msgpack_type) {
request_text += decoded.to_string(DEFAULT_INDENTATION);
} else {
request_text += "<body " + string::from_bytes(raw.size()) + ">";
}
}
}
} else if (!text.empty()) {
if (!decode) {
if (text.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(text.size()) + ">";
} else {
request_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (text.size() > 1024 * 10) {
request_text += "<body " + string::from_bytes(text.size()) + ">";
} else {
request_text += text;
}
} else if (size) {
request_text += "<body " + string::from_bytes(size) + ">";
}
return request_text;
}
Response::Response()
: status{static_cast<http_status>(0)},
size{0}
{
}
std::string
Response::to_text(bool decode)
{
L_CALL("Response::to_text({})", decode);
static constexpr auto no_col = NO_COLOR;
auto response_headers_color = no_col.c_str();
auto response_head_color = no_col.c_str();
auto response_text_color = no_col.c_str();
if ((int)status >= 200 && (int)status <= 299) {
static constexpr auto _response_headers_color = rgba(68, 136, 68, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 68);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 68);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 300 && (int)status <= 399) {
static constexpr auto _response_headers_color = rgba(68, 136, 120, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(68, 136, 120);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(68, 136, 120);
response_text_color = _response_text_color.c_str();
} else if ((int)status == 404) {
static constexpr auto _response_headers_color = rgba(116, 100, 77, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(116, 100, 77);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(116, 100, 77);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 400 && (int)status <= 499) {
static constexpr auto _response_headers_color = rgba(183, 70, 17, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(183, 70, 17);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(183, 70, 17);
response_text_color = _response_text_color.c_str();
} else if ((int)status >= 500 && (int)status <= 599) {
static constexpr auto _response_headers_color = rgba(190, 30, 10, 0.6);
response_headers_color = _response_headers_color.c_str();
static constexpr auto _response_head_color = brgb(190, 30, 10);
response_head_color = _response_head_color.c_str();
static constexpr auto _response_text_color = rgb(190, 30, 10);
response_text_color = _response_text_color.c_str();
}
auto response_text = response_head_color + head + "\n" + response_headers_color + headers + response_text_color;
if (!blob.empty()) {
if (!decode) {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + repr(blob, true, true, 500) + ">";
}
} else if (Logging::log_level > LOG_DEBUG + 1 && can_preview(ct_type)) {
// From [https://www.iterm2.com/documentation-images.html]
std::string b64_name = cppcodec::base64_rfc4648::encode("");
std::string b64_data = cppcodec::base64_rfc4648::encode(blob);
response_text += string::format("\033]1337;File=name={};inline=1;size={};width=20%:",
b64_name,
b64_data.size());
response_text += b64_data;
response_text += '\a';
} else {
if (blob.size() > 1024 * 10) {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
} else {
response_text += "<blob " + string::from_bytes(blob.size()) + ">";
}
}
} else if (!text.empty()) {
if (!decode) {
if (size > 1024 * 10) {
response_text += "<body " + string::from_bytes(size) + ">";
} else {
response_text += "<body " + repr(text, true, true, 500) + ">";
}
} else if (size > 1024 * 10) {
response_text += "<body " + string::from_bytes(size) + ">";
} else {
response_text += text;
}
} else if (size) {
response_text += "<body " + string::from_bytes(size) + ">";
}
return response_text;
}
|
#include "Optimiser.h"
#include "Hildreth.h"
#include "StaticData.h"
using namespace Moses;
using namespace std;
namespace Mira {
size_t MiraOptimiser::updateWeights(
ScoreComponentCollection& currWeights,
ScoreComponentCollection& weightUpdate,
const vector<vector<ScoreComponentCollection> >& featureValues,
const vector<vector<float> >& losses,
const vector<vector<float> >& bleuScores,
const vector<ScoreComponentCollection>& oracleFeatureValues,
const vector<float> oracleBleuScores,
float learning_rate,
size_t rank,
size_t epoch) {
// vector of feature values differences for all created constraints
vector<ScoreComponentCollection> featureValueDiffs;
vector<float> lossMinusModelScoreDiffs;
vector<float> all_losses;
// most violated constraint in batch
ScoreComponentCollection max_batch_featureValueDiff;
float max_batch_lossMinusModelScoreDiff = -1;
// Make constraints for new hypothesis translations
float epsilon = 0.0001;
int violatedConstraintsBefore = 0;
float oldDistanceFromOptimum = 0;
// iterate over input sentences (1 (online) or more (batch))
for (size_t i = 0; i < featureValues.size(); ++i) {
//size_t sentenceId = sentenceIds[i];
// iterate over hypothesis translations for one input sentence
for (size_t j = 0; j < featureValues[i].size(); ++j) {
ScoreComponentCollection featureValueDiff = oracleFeatureValues[i];
featureValueDiff.MinusEquals(featureValues[i][j]);
cerr << "Rank " << rank << ", epoch " << epoch << ", feature value diff: " << featureValueDiff << endl;
if (featureValueDiff.GetL1Norm() == 0) {
// skip constraint
continue;
}
float loss = losses[i][j];
if (m_scale_margin == 1) {
loss *= oracleBleuScores[i];
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with oracle bleu score " << oracleBleuScores[i] << endl;
}
else if (m_scale_margin == 2) {
loss *= log2(oracleBleuScores[i]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log2 oracle bleu score " << log2(oracleBleuScores[i]) << endl;
}
else if (m_scale_margin == 10) {
loss *= log10(oracleBleuScores[i]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log10 oracle bleu score " << log10(oracleBleuScores[i]) << endl;
}
// check if constraint is violated
bool violated = false;
bool addConstraint = true;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
violated = true;
}
else if (m_onlyViolatedConstraints) {
addConstraint = false;
}
float lossMinusModelScoreDiff = loss - modelScoreDiff;
if (addConstraint) {
featureValueDiffs.push_back(featureValueDiff);
lossMinusModelScoreDiffs.push_back(lossMinusModelScoreDiff);
all_losses.push_back(loss);
if (violated) {
++violatedConstraintsBefore;
oldDistanceFromOptimum += diff;
}
}
}
}
// run optimisation: compute alphas for all given constraints
vector<float> alphas;
ScoreComponentCollection summedUpdate;
if (violatedConstraintsBefore > 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", number of constraints passed to optimizer: " <<
featureValueDiffs.size() << " (of which violated: " << violatedConstraintsBefore << ")" << endl;
if (m_slack != 0) {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs, m_slack);
} else {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs);
}
// Update the weight vector according to the alphas and the feature value differences
// * w' = w' + SUM alpha_i * (h_i(oracle) - h_i(hypothesis))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
float alpha = alphas[k];
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
ScoreComponentCollection update(featureValueDiffs[k]);
update.MultiplyEquals(alpha);
// sum updates
summedUpdate.PlusEquals(update);
}
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", no constraint violated for this batch" << endl;
// return 0;
return 1;
}
// apply learning rate
if (learning_rate != 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", apply learning rate " << learning_rate << " to update." << endl;
summedUpdate.MultiplyEquals(learning_rate);
}
// scale update by BLEU of oracle (for batch size 1 only)
if (oracleBleuScores.size() == 1) {
if (m_scale_update == 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with oracle bleu score " << oracleBleuScores[0] << endl;
summedUpdate.MultiplyEquals(oracleBleuScores[0]);
}
else if (m_scale_update == 2) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log2 oracle bleu score " << log2(oracleBleuScores[0]) << endl;
summedUpdate.MultiplyEquals(log2(oracleBleuScores[0]));
}
else if (m_scale_update == 10) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log10 oracle bleu score " << log10(oracleBleuScores[0]) << endl;
summedUpdate.MultiplyEquals(log10(oracleBleuScores[0]));
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", update: " << summedUpdate << endl;
weightUpdate.PlusEquals(summedUpdate);
// Sanity check: are there still violated constraints after optimisation?
/* int violatedConstraintsAfter = 0;
float newDistanceFromOptimum = 0;
for (size_t i = 0; i < featureValueDiffs.size(); ++i) {
float modelScoreDiff = featureValueDiffs[i].InnerProduct(currWeights);
float loss = all_losses[i];
float diff = loss - (modelScoreDiff + m_margin_slack);
if (diff > epsilon) {
++violatedConstraintsAfter;
newDistanceFromOptimum += diff;
}
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", violated constraint before: " << violatedConstraintsBefore << ", after: " << violatedConstraintsAfter << ", change: " << violatedConstraintsBefore - violatedConstraintsAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);*/
// return violatedConstraintsAfter;
return 0;
}
size_t MiraOptimiser::updateWeightsHopeFear(
Moses::ScoreComponentCollection& currWeights,
Moses::ScoreComponentCollection& weightUpdate,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& featureValuesHope,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& featureValuesFear,
const std::vector<std::vector<float> >& bleuScoresHope,
const std::vector<std::vector<float> >& bleuScoresFear,
float learning_rate,
size_t rank,
size_t epoch) {
// vector of feature values differences for all created constraints
vector<ScoreComponentCollection> featureValueDiffs;
vector<float> lossMinusModelScoreDiffs;
vector<float> all_losses;
// most violated constraint in batch
ScoreComponentCollection max_batch_featureValueDiff;
float max_batch_lossMinusModelScoreDiff = -1;
// Make constraints for new hypothesis translations
float epsilon = 0.0001;
int violatedConstraintsBefore = 0;
float oldDistanceFromOptimum = 0;
// iterate over input sentences (1 (online) or more (batch))
for (size_t i = 0; i < featureValuesHope.size(); ++i) {
// Pair all hope translations with all fear translations for one input sentence
for (size_t j = 0; j < featureValuesHope[i].size(); ++j) {
for (size_t k = 0; k < featureValuesFear[i].size(); ++k) {
ScoreComponentCollection featureValueDiff = featureValuesHope[i][j];
featureValueDiff.MinusEquals(featureValuesFear[i][k]);
cerr << "Rank " << rank << ", epoch " << epoch << ", feature value diff: " << featureValueDiff << endl;
if (featureValueDiff.GetL1Norm() == 0) {
// skip constraint
continue;
}
float loss = bleuScoresHope[i][j] - bleuScoresFear[i][k];
if (m_scale_margin == 1) {
loss *= bleuScoresHope[i][j];
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with oracle bleu score " << bleuScoresHope[i][j] << endl;
}
else if (m_scale_margin == 2) {
loss *= log2(bleuScoresHope[i][j]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log2 oracle bleu score " << log2(bleuScoresHope[i][j]) << endl;
}
else if (m_scale_margin == 10) {
loss *= log10(bleuScoresHope[i][j]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log10 oracle bleu score " << log10(bleuScoresHope[i][j]) << endl;
}
// check if constraint is violated
bool violated = false;
bool addConstraint = true;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
violated = true;
}
else if (m_onlyViolatedConstraints) {
addConstraint = false;
}
float lossMinusModelScoreDiff = loss - (modelScoreDiff + m_margin_slack);
if (addConstraint) {
featureValueDiffs.push_back(featureValueDiff);
lossMinusModelScoreDiffs.push_back(lossMinusModelScoreDiff);
all_losses.push_back(loss);
if (violated) {
++violatedConstraintsBefore;
oldDistanceFromOptimum += diff;
}
}
}
}
}
// run optimisation: compute alphas for all given constraints
vector<float> alphas;
ScoreComponentCollection summedUpdate;
if (violatedConstraintsBefore > 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", number of constraints passed to optimizer: " <<
featureValueDiffs.size() << " (of which violated: " << violatedConstraintsBefore << ")" << endl;
if (m_slack != 0) {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs, m_slack);
} else {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs);
}
// Update the weight vector according to the alphas and the feature value differences
// * w' = w' + SUM alpha_i * (h_i(oracle) - h_i(hypothesis))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
float alpha = alphas[k];
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
ScoreComponentCollection update(featureValueDiffs[k]);
update.MultiplyEquals(alpha);
// sum updates
summedUpdate.PlusEquals(update);
}
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", no constraint violated for this batch" << endl;
// return 0;
return 1;
}
// apply learning rate
if (learning_rate != 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", apply learning rate " << learning_rate << " to update." << endl;
summedUpdate.MultiplyEquals(learning_rate);
}
// scale update by BLEU of oracle (for batch size 1 only)
if (featureValuesHope.size() == 1) {
if (m_scale_update == 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with oracle bleu score " << bleuScoresHope[0][0] << endl;
summedUpdate.MultiplyEquals(bleuScoresHope[0][0]);
}
else if (m_scale_update == 2) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log2 oracle bleu score " << log2(bleuScoresHope[0][0]) << endl;
summedUpdate.MultiplyEquals(log2(bleuScoresHope[0][0]));
}
else if (m_scale_update == 10) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log10 oracle bleu score " << log10(bleuScoresHope[0][0]) << endl;
summedUpdate.MultiplyEquals(log10(bleuScoresHope[0][0]));
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", update: " << summedUpdate << endl;
weightUpdate.PlusEquals(summedUpdate);
// Sanity check: are there still violated constraints after optimisation?
/* int violatedConstraintsAfter = 0;
float newDistanceFromOptimum = 0;
for (size_t i = 0; i < featureValueDiffs.size(); ++i) {
float modelScoreDiff = featureValueDiffs[i].InnerProduct(currWeights);
float loss = all_losses[i];
float diff = loss - (modelScoreDiff + m_margin_slack);
if (diff > epsilon) {
++violatedConstraintsAfter;
newDistanceFromOptimum += diff;
}
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", violated constraint before: " << violatedConstraintsBefore << ", after: " << violatedConstraintsAfter << ", change: " << violatedConstraintsBefore - violatedConstraintsAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);*/
// return violatedConstraintsAfter;
return 0;
}
size_t MiraOptimiser::updateWeightsAnalytically(
ScoreComponentCollection& currWeights,
ScoreComponentCollection& weightUpdate,
ScoreComponentCollection& featureValuesHope,
ScoreComponentCollection& featureValuesFear,
float bleuScoreHope,
float bleuScoreFear,
float learning_rate,
size_t rank,
size_t epoch) {
float epsilon = 0.0001;
float oldDistanceFromOptimum = 0;
bool constraintViolatedBefore = false;
// cerr << "Rank " << rank << ", epoch " << epoch << ", hope: " << featureValuesHope << endl;
// cerr << "Rank " << rank << ", epoch " << epoch << ", fear: " << featureValuesFear << endl;
ScoreComponentCollection featureValueDiff = featureValuesHope;
featureValueDiff.MinusEquals(featureValuesFear);
// cerr << "Rank " << rank << ", epoch " << epoch << ", hope - fear: " << featureValueDiff << endl;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float loss = bleuScoreHope - bleuScoreFear;
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
// constraint violated
oldDistanceFromOptimum += diff;
constraintViolatedBefore = true;
// compute alpha for given constraint: (loss - model score diff) / || feature value diff ||^2
// featureValueDiff.GetL2Norm() * featureValueDiff.GetL2Norm() == featureValueDiff.InnerProduct(featureValueDiff)
// from Crammer&Singer 2006: alpha = min {C , l_t/ ||x||^2}
float squaredNorm = featureValueDiff.GetL2Norm() * featureValueDiff.GetL2Norm();
if (squaredNorm > 0) {
float alpha = diff / squaredNorm;
if (m_slack > 0 ) {
if (alpha > m_slack) {
alpha = m_slack;
}
else if (alpha < m_slack*(-1)) {
alpha = m_slack*(-1);
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
featureValueDiff.MultiplyEquals(alpha);
weightUpdate.PlusEquals(featureValueDiff);
}
else {
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", no update because squared norm is 0" << endl);
}
}
if (!constraintViolatedBefore) {
// constraint satisfied, nothing to do
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint already satisfied" << endl;
return 1;
}
// sanity check: constraint still violated after optimisation?
/* ScoreComponentCollection newWeights(currWeights);
newWeights.PlusEquals(weightUpdate);
bool constraintViolatedAfter = false;
float newDistanceFromOptimum = 0;
featureValueDiff = featureValuesHope;
featureValueDiff.MinusEquals(featureValuesFear);
modelScoreDiff = featureValueDiff.InnerProduct(newWeights);
diff = loss - (modelScoreDiff + m_margin_slack);
// approximate comparison between floats!
if (diff > epsilon) {
constraintViolatedAfter = true;
newDistanceFromOptimum += (loss - modelScoreDiff);
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", check, constraint violated before? " << constraintViolatedBefore << ", after? " << constraintViolatedAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", check, error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);
*/
return 0;
}
}
remove output of feature value difference
#include "Optimiser.h"
#include "Hildreth.h"
#include "StaticData.h"
using namespace Moses;
using namespace std;
namespace Mira {
size_t MiraOptimiser::updateWeights(
ScoreComponentCollection& currWeights,
ScoreComponentCollection& weightUpdate,
const vector<vector<ScoreComponentCollection> >& featureValues,
const vector<vector<float> >& losses,
const vector<vector<float> >& bleuScores,
const vector<ScoreComponentCollection>& oracleFeatureValues,
const vector<float> oracleBleuScores,
float learning_rate,
size_t rank,
size_t epoch) {
// vector of feature values differences for all created constraints
vector<ScoreComponentCollection> featureValueDiffs;
vector<float> lossMinusModelScoreDiffs;
vector<float> all_losses;
// most violated constraint in batch
ScoreComponentCollection max_batch_featureValueDiff;
float max_batch_lossMinusModelScoreDiff = -1;
// Make constraints for new hypothesis translations
float epsilon = 0.0001;
int violatedConstraintsBefore = 0;
float oldDistanceFromOptimum = 0;
// iterate over input sentences (1 (online) or more (batch))
for (size_t i = 0; i < featureValues.size(); ++i) {
//size_t sentenceId = sentenceIds[i];
// iterate over hypothesis translations for one input sentence
for (size_t j = 0; j < featureValues[i].size(); ++j) {
ScoreComponentCollection featureValueDiff = oracleFeatureValues[i];
featureValueDiff.MinusEquals(featureValues[i][j]);
// cerr << "Rank " << rank << ", epoch " << epoch << ", feature value diff: " << featureValueDiff << endl;
if (featureValueDiff.GetL1Norm() == 0) {
// skip constraint
continue;
}
float loss = losses[i][j];
if (m_scale_margin == 1) {
loss *= oracleBleuScores[i];
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with oracle bleu score " << oracleBleuScores[i] << endl;
}
else if (m_scale_margin == 2) {
loss *= log2(oracleBleuScores[i]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log2 oracle bleu score " << log2(oracleBleuScores[i]) << endl;
}
else if (m_scale_margin == 10) {
loss *= log10(oracleBleuScores[i]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log10 oracle bleu score " << log10(oracleBleuScores[i]) << endl;
}
// check if constraint is violated
bool violated = false;
bool addConstraint = true;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
violated = true;
}
else if (m_onlyViolatedConstraints) {
addConstraint = false;
}
float lossMinusModelScoreDiff = loss - modelScoreDiff;
if (addConstraint) {
featureValueDiffs.push_back(featureValueDiff);
lossMinusModelScoreDiffs.push_back(lossMinusModelScoreDiff);
all_losses.push_back(loss);
if (violated) {
++violatedConstraintsBefore;
oldDistanceFromOptimum += diff;
}
}
}
}
// run optimisation: compute alphas for all given constraints
vector<float> alphas;
ScoreComponentCollection summedUpdate;
if (violatedConstraintsBefore > 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", number of constraints passed to optimizer: " <<
featureValueDiffs.size() << " (of which violated: " << violatedConstraintsBefore << ")" << endl;
if (m_slack != 0) {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs, m_slack);
} else {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs);
}
// Update the weight vector according to the alphas and the feature value differences
// * w' = w' + SUM alpha_i * (h_i(oracle) - h_i(hypothesis))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
float alpha = alphas[k];
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
ScoreComponentCollection update(featureValueDiffs[k]);
update.MultiplyEquals(alpha);
// sum updates
summedUpdate.PlusEquals(update);
}
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", no constraint violated for this batch" << endl;
// return 0;
return 1;
}
// apply learning rate
if (learning_rate != 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", apply learning rate " << learning_rate << " to update." << endl;
summedUpdate.MultiplyEquals(learning_rate);
}
// scale update by BLEU of oracle (for batch size 1 only)
if (oracleBleuScores.size() == 1) {
if (m_scale_update == 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with oracle bleu score " << oracleBleuScores[0] << endl;
summedUpdate.MultiplyEquals(oracleBleuScores[0]);
}
else if (m_scale_update == 2) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log2 oracle bleu score " << log2(oracleBleuScores[0]) << endl;
summedUpdate.MultiplyEquals(log2(oracleBleuScores[0]));
}
else if (m_scale_update == 10) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log10 oracle bleu score " << log10(oracleBleuScores[0]) << endl;
summedUpdate.MultiplyEquals(log10(oracleBleuScores[0]));
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", update: " << summedUpdate << endl;
weightUpdate.PlusEquals(summedUpdate);
// Sanity check: are there still violated constraints after optimisation?
/* int violatedConstraintsAfter = 0;
float newDistanceFromOptimum = 0;
for (size_t i = 0; i < featureValueDiffs.size(); ++i) {
float modelScoreDiff = featureValueDiffs[i].InnerProduct(currWeights);
float loss = all_losses[i];
float diff = loss - (modelScoreDiff + m_margin_slack);
if (diff > epsilon) {
++violatedConstraintsAfter;
newDistanceFromOptimum += diff;
}
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", violated constraint before: " << violatedConstraintsBefore << ", after: " << violatedConstraintsAfter << ", change: " << violatedConstraintsBefore - violatedConstraintsAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);*/
// return violatedConstraintsAfter;
return 0;
}
size_t MiraOptimiser::updateWeightsHopeFear(
Moses::ScoreComponentCollection& currWeights,
Moses::ScoreComponentCollection& weightUpdate,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& featureValuesHope,
const std::vector< std::vector<Moses::ScoreComponentCollection> >& featureValuesFear,
const std::vector<std::vector<float> >& bleuScoresHope,
const std::vector<std::vector<float> >& bleuScoresFear,
float learning_rate,
size_t rank,
size_t epoch) {
// vector of feature values differences for all created constraints
vector<ScoreComponentCollection> featureValueDiffs;
vector<float> lossMinusModelScoreDiffs;
vector<float> all_losses;
// most violated constraint in batch
ScoreComponentCollection max_batch_featureValueDiff;
float max_batch_lossMinusModelScoreDiff = -1;
// Make constraints for new hypothesis translations
float epsilon = 0.0001;
int violatedConstraintsBefore = 0;
float oldDistanceFromOptimum = 0;
// iterate over input sentences (1 (online) or more (batch))
for (size_t i = 0; i < featureValuesHope.size(); ++i) {
// Pair all hope translations with all fear translations for one input sentence
for (size_t j = 0; j < featureValuesHope[i].size(); ++j) {
for (size_t k = 0; k < featureValuesFear[i].size(); ++k) {
ScoreComponentCollection featureValueDiff = featureValuesHope[i][j];
featureValueDiff.MinusEquals(featureValuesFear[i][k]);
// cerr << "Rank " << rank << ", epoch " << epoch << ", feature value diff: " << featureValueDiff << endl;
if (featureValueDiff.GetL1Norm() == 0) {
// skip constraint
continue;
}
float loss = bleuScoresHope[i][j] - bleuScoresFear[i][k];
if (m_scale_margin == 1) {
loss *= bleuScoresHope[i][j];
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with oracle bleu score " << bleuScoresHope[i][j] << endl;
}
else if (m_scale_margin == 2) {
loss *= log2(bleuScoresHope[i][j]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log2 oracle bleu score " << log2(bleuScoresHope[i][j]) << endl;
}
else if (m_scale_margin == 10) {
loss *= log10(bleuScoresHope[i][j]);
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling margin with log10 oracle bleu score " << log10(bleuScoresHope[i][j]) << endl;
}
// check if constraint is violated
bool violated = false;
bool addConstraint = true;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
violated = true;
}
else if (m_onlyViolatedConstraints) {
addConstraint = false;
}
float lossMinusModelScoreDiff = loss - (modelScoreDiff + m_margin_slack);
if (addConstraint) {
featureValueDiffs.push_back(featureValueDiff);
lossMinusModelScoreDiffs.push_back(lossMinusModelScoreDiff);
all_losses.push_back(loss);
if (violated) {
++violatedConstraintsBefore;
oldDistanceFromOptimum += diff;
}
}
}
}
}
// run optimisation: compute alphas for all given constraints
vector<float> alphas;
ScoreComponentCollection summedUpdate;
if (violatedConstraintsBefore > 0) {
cerr << "Rank " << rank << ", epoch " << epoch << ", number of constraints passed to optimizer: " <<
featureValueDiffs.size() << " (of which violated: " << violatedConstraintsBefore << ")" << endl;
if (m_slack != 0) {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs, m_slack);
} else {
alphas = Hildreth::optimise(featureValueDiffs, lossMinusModelScoreDiffs);
}
// Update the weight vector according to the alphas and the feature value differences
// * w' = w' + SUM alpha_i * (h_i(oracle) - h_i(hypothesis))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
float alpha = alphas[k];
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
ScoreComponentCollection update(featureValueDiffs[k]);
update.MultiplyEquals(alpha);
// sum updates
summedUpdate.PlusEquals(update);
}
}
else {
cerr << "Rank " << rank << ", epoch " << epoch << ", no constraint violated for this batch" << endl;
// return 0;
return 1;
}
// apply learning rate
if (learning_rate != 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", apply learning rate " << learning_rate << " to update." << endl;
summedUpdate.MultiplyEquals(learning_rate);
}
// scale update by BLEU of oracle (for batch size 1 only)
if (featureValuesHope.size() == 1) {
if (m_scale_update == 1) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with oracle bleu score " << bleuScoresHope[0][0] << endl;
summedUpdate.MultiplyEquals(bleuScoresHope[0][0]);
}
else if (m_scale_update == 2) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log2 oracle bleu score " << log2(bleuScoresHope[0][0]) << endl;
summedUpdate.MultiplyEquals(log2(bleuScoresHope[0][0]));
}
else if (m_scale_update == 10) {
cerr << "Rank " << rank << ", epoch " << epoch << ", scaling summed update with log10 oracle bleu score " << log10(bleuScoresHope[0][0]) << endl;
summedUpdate.MultiplyEquals(log10(bleuScoresHope[0][0]));
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", update: " << summedUpdate << endl;
weightUpdate.PlusEquals(summedUpdate);
// Sanity check: are there still violated constraints after optimisation?
/* int violatedConstraintsAfter = 0;
float newDistanceFromOptimum = 0;
for (size_t i = 0; i < featureValueDiffs.size(); ++i) {
float modelScoreDiff = featureValueDiffs[i].InnerProduct(currWeights);
float loss = all_losses[i];
float diff = loss - (modelScoreDiff + m_margin_slack);
if (diff > epsilon) {
++violatedConstraintsAfter;
newDistanceFromOptimum += diff;
}
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", violated constraint before: " << violatedConstraintsBefore << ", after: " << violatedConstraintsAfter << ", change: " << violatedConstraintsBefore - violatedConstraintsAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);*/
// return violatedConstraintsAfter;
return 0;
}
size_t MiraOptimiser::updateWeightsAnalytically(
ScoreComponentCollection& currWeights,
ScoreComponentCollection& weightUpdate,
ScoreComponentCollection& featureValuesHope,
ScoreComponentCollection& featureValuesFear,
float bleuScoreHope,
float bleuScoreFear,
float learning_rate,
size_t rank,
size_t epoch) {
float epsilon = 0.0001;
float oldDistanceFromOptimum = 0;
bool constraintViolatedBefore = false;
// cerr << "Rank " << rank << ", epoch " << epoch << ", hope: " << featureValuesHope << endl;
// cerr << "Rank " << rank << ", epoch " << epoch << ", fear: " << featureValuesFear << endl;
ScoreComponentCollection featureValueDiff = featureValuesHope;
featureValueDiff.MinusEquals(featureValuesFear);
// cerr << "Rank " << rank << ", epoch " << epoch << ", hope - fear: " << featureValueDiff << endl;
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
float loss = bleuScoreHope - bleuScoreFear;
float diff = 0;
if (loss > (modelScoreDiff + m_margin_slack)) {
diff = loss - (modelScoreDiff + m_margin_slack);
}
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint: " << modelScoreDiff << " + " << m_margin_slack << " >= " << loss << " (current violation: " << diff << ")" << endl;
if (diff > epsilon) {
// constraint violated
oldDistanceFromOptimum += diff;
constraintViolatedBefore = true;
// compute alpha for given constraint: (loss - model score diff) / || feature value diff ||^2
// featureValueDiff.GetL2Norm() * featureValueDiff.GetL2Norm() == featureValueDiff.InnerProduct(featureValueDiff)
// from Crammer&Singer 2006: alpha = min {C , l_t/ ||x||^2}
float squaredNorm = featureValueDiff.GetL2Norm() * featureValueDiff.GetL2Norm();
if (squaredNorm > 0) {
float alpha = diff / squaredNorm;
if (m_slack > 0 ) {
if (alpha > m_slack) {
alpha = m_slack;
}
else if (alpha < m_slack*(-1)) {
alpha = m_slack*(-1);
}
}
cerr << "Rank " << rank << ", epoch " << epoch << ", alpha: " << alpha << endl;
featureValueDiff.MultiplyEquals(alpha);
weightUpdate.PlusEquals(featureValueDiff);
}
else {
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", no update because squared norm is 0" << endl);
}
}
if (!constraintViolatedBefore) {
// constraint satisfied, nothing to do
cerr << "Rank " << rank << ", epoch " << epoch << ", constraint already satisfied" << endl;
return 1;
}
// sanity check: constraint still violated after optimisation?
/* ScoreComponentCollection newWeights(currWeights);
newWeights.PlusEquals(weightUpdate);
bool constraintViolatedAfter = false;
float newDistanceFromOptimum = 0;
featureValueDiff = featureValuesHope;
featureValueDiff.MinusEquals(featureValuesFear);
modelScoreDiff = featureValueDiff.InnerProduct(newWeights);
diff = loss - (modelScoreDiff + m_margin_slack);
// approximate comparison between floats!
if (diff > epsilon) {
constraintViolatedAfter = true;
newDistanceFromOptimum += (loss - modelScoreDiff);
}
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", check, constraint violated before? " << constraintViolatedBefore << ", after? " << constraintViolatedAfter << endl);
VERBOSE(1, "Rank " << rank << ", epoch " << epoch << ", check, error before: " << oldDistanceFromOptimum << ", after: " << newDistanceFromOptimum << ", change: " << oldDistanceFromOptimum - newDistanceFromOptimum << endl);
*/
return 0;
}
}
|
/*
* Copyright (c) 2008, 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 the 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 <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <ros/time.h>
#include <laser_geometry/laser_geometry.h>
#include <rviz/default_plugin/point_cloud_common.h>
#include <rviz/display_context.h>
#include <rviz/frame_manager.h>
#include <rviz/ogre_helpers/point_cloud.h>
#include <rviz/properties/int_property.h>
#include <rviz/validate_floats.h>
#include "laser_scan_display.h"
namespace rviz
{
LaserScanDisplay::LaserScanDisplay()
: point_cloud_common_( new PointCloudCommon( this ))
, projector_( new laser_geometry::LaserProjection() )
{
// PointCloudCommon sets up a callback queue with a thread for each
// instance. Use that for processing incoming messages.
update_nh_.setCallbackQueue( point_cloud_common_->getCallbackQueue() );
}
LaserScanDisplay::~LaserScanDisplay()
{
delete point_cloud_common_;
delete projector_;
}
void LaserScanDisplay::onInitialize()
{
MFDClass::onInitialize();
point_cloud_common_->initialize( context_, scene_node_ );
}
void LaserScanDisplay::processMessage( const sensor_msgs::LaserScanConstPtr& scan )
{
sensor_msgs::PointCloudPtr cloud( new sensor_msgs::PointCloud );
std::string frame_id = scan->header.frame_id;
// Compute tolerance necessary for this scan
ros::Duration tolerance(scan->time_increment * scan->ranges.size());
if (tolerance > filter_tolerance_)
{
filter_tolerance_ = tolerance;
tf_filter_->setTolerance(filter_tolerance_);
}
try
{
// TODO(wjwwood): remove this and use tf2 interface instead
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
auto tf_client = context_->getTFClient();
#ifndef _WIN32
# pragma GCC diagnostic pop
#endif
projector_->transformLaserScanToPointCloud( fixed_frame_.toStdString(), *scan, *cloud, *tf_client,
laser_geometry::channel_option::Intensity );
}
catch (tf::TransformException& e)
{
ROS_DEBUG( "LaserScan [%s]: failed to transform scan: %s. This message should not repeat (tolerance should now be set on our tf::MessageFilter).",
qPrintable( getName() ), e.what() );
return;
}
point_cloud_common_->addMessage( cloud );
}
void LaserScanDisplay::update( float wall_dt, float ros_dt )
{
point_cloud_common_->update( wall_dt, ros_dt );
}
void LaserScanDisplay::reset()
{
MFDClass::reset();
point_cloud_common_->reset();
}
} // namespace rviz
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS( rviz::LaserScanDisplay, rviz::Display )
tf2: port LaserScanDisplay
/*
* Copyright (c) 2008, 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 the 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 <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <ros/time.h>
#include <laser_geometry/laser_geometry.h>
#include <rviz/default_plugin/point_cloud_common.h>
#include <rviz/display_context.h>
#include <rviz/frame_manager.h>
#include <rviz/ogre_helpers/point_cloud.h>
#include <rviz/properties/int_property.h>
#include <rviz/validate_floats.h>
#include "laser_scan_display.h"
namespace rviz
{
LaserScanDisplay::LaserScanDisplay()
: point_cloud_common_( new PointCloudCommon( this ))
, projector_( new laser_geometry::LaserProjection() )
{
// PointCloudCommon sets up a callback queue with a thread for each
// instance. Use that for processing incoming messages.
update_nh_.setCallbackQueue( point_cloud_common_->getCallbackQueue() );
}
LaserScanDisplay::~LaserScanDisplay()
{
delete point_cloud_common_;
delete projector_;
}
void LaserScanDisplay::onInitialize()
{
MFDClass::onInitialize();
point_cloud_common_->initialize( context_, scene_node_ );
}
void LaserScanDisplay::processMessage( const sensor_msgs::LaserScanConstPtr& scan )
{
sensor_msgs::PointCloud2Ptr cloud( new sensor_msgs::PointCloud2 );
// Compute tolerance necessary for this scan
ros::Duration tolerance(scan->time_increment * scan->ranges.size());
if (tolerance > filter_tolerance_)
{
filter_tolerance_ = tolerance;
tf_filter_->setTolerance(filter_tolerance_);
}
try
{
auto tf = context_->getTF2BufferPtr();
projector_->transformLaserScanToPointCloud( fixed_frame_.toStdString(), *scan, *cloud, *tf,
laser_geometry::channel_option::Intensity );
}
catch (tf2::TransformException& e)
{
ROS_DEBUG( "LaserScan [%s]: failed to transform scan: %s. This message should not repeat (tolerance should now be set on our tf2::MessageFilter).",
qPrintable( getName() ), e.what() );
return;
}
point_cloud_common_->addMessage( cloud );
}
void LaserScanDisplay::update( float wall_dt, float ros_dt )
{
point_cloud_common_->update( wall_dt, ros_dt );
}
void LaserScanDisplay::reset()
{
MFDClass::reset();
point_cloud_common_->reset();
}
} // namespace rviz
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS( rviz::LaserScanDisplay, rviz::Display )
|
/*
* Copyright (c) 2008, 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 the 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 <QColor>
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <OgreWireBoundingBox.h>
#include <ros/time.h>
#include <tf/transform_listener.h>
#include <pluginlib/class_loader.h>
#include "rviz/default_plugin/point_cloud_transformer.h"
#include "rviz/default_plugin/point_cloud_transformers.h"
#include "rviz/display.h"
#include "rviz/display_context.h"
#include "rviz/frame_manager.h"
#include "rviz/ogre_helpers/point_cloud.h"
#include "rviz/properties/bool_property.h"
#include "rviz/properties/enum_property.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/vector_property.h"
#include "rviz/uniform_string_stream.h"
#include "rviz/validate_floats.h"
#include "rviz/default_plugin/point_cloud_common.h"
namespace rviz
{
struct IndexAndMessage
{
IndexAndMessage( int _index, const void* _message )
: index( _index )
, message( (uint64_t) _message )
{}
int index;
uint64_t message;
};
uint qHash( IndexAndMessage iam )
{
return
((uint) iam.index) +
((uint) (iam.message >> 32)) +
((uint) (iam.message & 0xffffffff));
}
bool operator==( IndexAndMessage a, IndexAndMessage b )
{
return a.index == b.index && a.message == b.message;
}
PointCloudSelectionHandler::PointCloudSelectionHandler(
float box_size,
PointCloudCommon::CloudInfo *cloud_info,
DisplayContext* context )
: SelectionHandler( context )
, cloud_info_( cloud_info )
, box_size_(box_size)
{
}
PointCloudSelectionHandler::~PointCloudSelectionHandler()
{
// delete all the Property objects on our way out.
QHash<IndexAndMessage, Property*>::const_iterator iter;
for( iter = property_hash_.begin(); iter != property_hash_.end(); iter++ )
{
delete iter.value();
}
}
void PointCloudSelectionHandler::preRenderPass(uint32_t pass)
{
SelectionHandler::preRenderPass(pass);
switch( pass )
{
case 0:
cloud_info_->cloud_->setPickColor( SelectionManager::handleToColor( getHandle() ));
break;
case 1:
cloud_info_->cloud_->setColorByIndex(true);
break;
default:
break;
}
}
void PointCloudSelectionHandler::postRenderPass(uint32_t pass)
{
SelectionHandler::postRenderPass(pass);
if (pass == 1)
{
cloud_info_->cloud_->setColorByIndex(false);
}
}
Ogre::Vector3 pointFromCloud(const sensor_msgs::PointCloud2ConstPtr& cloud, uint32_t index)
{
int32_t xi = findChannelIndex(cloud, "x");
int32_t yi = findChannelIndex(cloud, "y");
int32_t zi = findChannelIndex(cloud, "z");
const uint32_t xoff = cloud->fields[xi].offset;
const uint32_t yoff = cloud->fields[yi].offset;
const uint32_t zoff = cloud->fields[zi].offset;
const uint8_t type = cloud->fields[xi].datatype;
const uint32_t point_step = cloud->point_step;
float x = valueFromCloud<float>(cloud, xoff, type, point_step, index);
float y = valueFromCloud<float>(cloud, yoff, type, point_step, index);
float z = valueFromCloud<float>(cloud, zoff, type, point_step, index);
return Ogre::Vector3(x, y, z);
}
void PointCloudSelectionHandler::createProperties( const Picked& obj, Property* parent_property )
{
typedef std::set<int> S_int;
S_int indices;
{
S_uint64::const_iterator it = obj.extra_handles.begin();
S_uint64::const_iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
uint64_t handle = *it;
indices.insert((handle & 0xffffffff) - 1);
}
}
{
S_int::iterator it = indices.begin();
S_int::iterator end = indices.end();
for (; it != end; ++it)
{
int index = *it;
const sensor_msgs::PointCloud2ConstPtr& message = cloud_info_->message_;
IndexAndMessage hash_key( index, message.get() );
if( !property_hash_.contains( hash_key ))
{
Property* cat = new Property( QString( "Point %1 [cloud 0x%2]" ).arg( index ).arg( (uint64_t) message.get() ),
QVariant(), "", parent_property );
property_hash_.insert( hash_key, cat );
// First add the position.
VectorProperty* pos_prop = new VectorProperty( "Position", cloud_info_->transformed_points_[index].position, "", cat );
pos_prop->setReadOnly( true );
// Then add all other fields as well.
for( size_t field = 0; field < message->fields.size(); ++field )
{
const sensor_msgs::PointField& f = message->fields[ field ];
const std::string& name = f.name;
if( name == "x" || name == "y" || name == "z" || name == "X" || name == "Y" || name == "Z" )
{
continue;
}
if( name == "rgb" )
{
uint32_t val = valueFromCloud<uint32_t>( message, f.offset, f.datatype, message->point_step, index );
ColorProperty* prop = new ColorProperty( QString( "%1: %2" ).arg( field ).arg( QString::fromStdString( name )),
QColor( val >> 16, (val >> 8) & 0xff, val & 0xff ), "", cat );
prop->setReadOnly( true );
}
else
{
float val = valueFromCloud<float>( message, f.offset, f.datatype, message->point_step, index );
FloatProperty* prop = new FloatProperty( QString( "%1: %2" ).arg( field ).arg( QString::fromStdString( name )),
val, "", cat );
prop->setReadOnly( true );
}
}
}
}
}
}
void PointCloudSelectionHandler::destroyProperties( const Picked& obj, Property* parent_property )
{
typedef std::set<int> S_int;
S_int indices;
{
S_uint64::const_iterator it = obj.extra_handles.begin();
S_uint64::const_iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
uint64_t handle = *it;
indices.insert((handle & 0xffffffff) - 1);
}
}
{
S_int::iterator it = indices.begin();
S_int::iterator end = indices.end();
for (; it != end; ++it)
{
int index = *it;
const sensor_msgs::PointCloud2ConstPtr& message = cloud_info_->message_;
IndexAndMessage hash_key( index, message.get() );
Property* prop = property_hash_.take( hash_key );
delete prop;
}
}
}
void PointCloudSelectionHandler::getAABBs(const Picked& obj, V_AABB& aabbs)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
M_HandleToBox::iterator find_it = boxes_.find(std::make_pair(obj.handle, *it - 1));
if (find_it != boxes_.end())
{
Ogre::WireBoundingBox* box = find_it->second.second;
aabbs.push_back(box->getWorldBoundingBox());
}
}
}
void PointCloudSelectionHandler::onSelect(const Picked& obj)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
int index = (*it & 0xffffffff) - 1;
sensor_msgs::PointCloud2ConstPtr message = cloud_info_->message_;
Ogre::Vector3 pos = cloud_info_->transformed_points_[index].position;
pos = cloud_info_->scene_node_->convertLocalToWorldPosition( pos );
float size = box_size_ * 0.5f;
Ogre::AxisAlignedBox aabb(pos - size, pos + size);
createBox(std::make_pair(obj.handle, index), aabb, "RVIZ/Cyan" );
}
}
void PointCloudSelectionHandler::onDeselect(const Picked& obj)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
int global_index = (*it & 0xffffffff) - 1;
destroyBox(std::make_pair(obj.handle, global_index));
}
}
PointCloudCommon::CloudInfo::CloudInfo()
: manager_(0)
, scene_node_(0)
{}
PointCloudCommon::CloudInfo::~CloudInfo()
{
clear();
}
void PointCloudCommon::CloudInfo::clear()
{
if ( scene_node_ )
{
manager_->destroySceneNode( scene_node_ );
scene_node_=0;
}
}
PointCloudCommon::PointCloudCommon( Display* display )
: spinner_(1, &cbqueue_)
, new_xyz_transformer_(false)
, new_color_transformer_(false)
, needs_retransform_(false)
, transformer_class_loader_(NULL)
, display_( display )
, auto_size_(false)
{
selectable_property_ = new BoolProperty( "Selectable", true,
"Whether or not the points in this point cloud are selectable.",
display_, SLOT( updateSelectable() ), this );
style_property_ = new EnumProperty( "Style", "Flat Squares",
"Rendering mode to use, in order of computational complexity.",
display_, SLOT( updateStyle() ), this );
style_property_->addOption( "Points", PointCloud::RM_POINTS );
style_property_->addOption( "Squares", PointCloud::RM_SQUARES );
style_property_->addOption( "Flat Squares", PointCloud::RM_FLAT_SQUARES );
style_property_->addOption( "Spheres", PointCloud::RM_SPHERES );
style_property_->addOption( "Boxes", PointCloud::RM_BOXES );
point_world_size_property_ = new FloatProperty( "Size (m)", 0.01,
"Point size in meters.",
display_, SLOT( updateBillboardSize() ), this );
point_world_size_property_->setMin( 0.0001 );
point_pixel_size_property_ = new FloatProperty( "Size (Pixels)", 3,
"Point size in pixels.",
display_, SLOT( updateBillboardSize() ), this );
point_pixel_size_property_->setMin( 1 );
alpha_property_ = new FloatProperty( "Alpha", 1.0,
"Amount of transparency to apply to the points. Note that this is experimental and does not always look correct.",
display_, SLOT( updateAlpha() ), this );
alpha_property_->setMin( 0 );
alpha_property_->setMax( 1 );
decay_time_property_ = new FloatProperty( "Decay Time", 0,
"Duration, in seconds, to keep the incoming points. 0 means only show the latest points.",
display_, SLOT( queueRender() ));
decay_time_property_->setMin( 0 );
xyz_transformer_property_ = new EnumProperty( "Position Transformer", "",
"Set the transformer to use to set the position of the points.",
display_, SLOT( updateXyzTransformer() ), this );
connect( xyz_transformer_property_, SIGNAL( requestOptions( EnumProperty* )),
this, SLOT( setXyzTransformerOptions( EnumProperty* )));
color_transformer_property_ = new EnumProperty( "Color Transformer", "",
"Set the transformer to use to set the color of the points.",
display_, SLOT( updateColorTransformer() ), this );
connect( color_transformer_property_, SIGNAL( requestOptions( EnumProperty* )),
this, SLOT( setColorTransformerOptions( EnumProperty* )));
}
void PointCloudCommon::initialize( DisplayContext* context, Ogre::SceneNode* scene_node )
{
transformer_class_loader_ = new pluginlib::ClassLoader<PointCloudTransformer>( "rviz", "rviz::PointCloudTransformer" );
loadTransformers();
context_ = context;
scene_node_ = scene_node;
updateStyle();
updateBillboardSize();
updateAlpha();
updateSelectable();
spinner_.start();
}
PointCloudCommon::~PointCloudCommon()
{
spinner_.stop();
if ( transformer_class_loader_ )
{
delete transformer_class_loader_;
}
}
void PointCloudCommon::loadTransformers()
{
std::vector<std::string> classes = transformer_class_loader_->getDeclaredClasses();
std::vector<std::string>::iterator ci;
for( ci = classes.begin(); ci != classes.end(); ci++ )
{
const std::string& lookup_name = *ci;
std::string name = transformer_class_loader_->getName( lookup_name );
if( transformers_.count( name ) > 0 )
{
ROS_ERROR( "Transformer type [%s] is already loaded.", name.c_str() );
continue;
}
PointCloudTransformerPtr trans( transformer_class_loader_->createUnmanagedInstance( lookup_name ));
trans->init();
connect( trans.get(), SIGNAL( needRetransform() ), this, SLOT( causeRetransform() ));
TransformerInfo info;
info.transformer = trans;
info.readable_name = name;
info.lookup_name = lookup_name;
info.transformer->createProperties( display_, PointCloudTransformer::Support_XYZ, info.xyz_props );
setPropertiesHidden( info.xyz_props, true );
info.transformer->createProperties( display_, PointCloudTransformer::Support_Color, info.color_props );
setPropertiesHidden( info.color_props, true );
transformers_[ name ] = info;
}
}
void PointCloudCommon::setAutoSize( bool auto_size )
{
auto_size_ = auto_size;
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setAutoSize( auto_size );
}
}
void PointCloudCommon::updateAlpha()
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setAlpha( alpha_property_->getFloat() );
}
}
void PointCloudCommon::updateSelectable()
{
bool selectable = selectable_property_->getBool();
if( selectable )
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->selection_handler_.reset( new PointCloudSelectionHandler( getSelectionBoxSize(), cloud_infos_[i].get(), context_ ));
cloud_infos_[i]->cloud_->setPickColor( SelectionManager::handleToColor( cloud_infos_[i]->selection_handler_->getHandle() ));
}
}
else
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->selection_handler_.reset( );
cloud_infos_[i]->cloud_->setPickColor( Ogre::ColourValue( 0.0f, 0.0f, 0.0f, 0.0f ) );
}
}
}
void PointCloudCommon::updateStyle()
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
if( mode == PointCloud::RM_POINTS )
{
point_world_size_property_->hide();
point_pixel_size_property_->show();
}
else
{
point_world_size_property_->show();
point_pixel_size_property_->hide();
}
for( unsigned int i = 0; i < cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setRenderMode( mode );
}
updateBillboardSize();
}
void PointCloudCommon::updateBillboardSize()
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
float size;
if( mode == PointCloud::RM_POINTS ) {
size = point_pixel_size_property_->getFloat();
} else {
size = point_world_size_property_->getFloat();
}
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setDimensions( size, size, size );
cloud_infos_[i]->selection_handler_->setBoxSize( getSelectionBoxSize() );
}
context_->queueRender();
}
void PointCloudCommon::reset()
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
cloud_infos_.clear();
new_cloud_infos_.clear();
}
void PointCloudCommon::causeRetransform()
{
needs_retransform_ = true;
}
void PointCloudCommon::update(float wall_dt, float ros_dt)
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
float point_decay_time = decay_time_property_->getFloat();
if (needs_retransform_)
{
retransform();
needs_retransform_ = false;
}
// instead of deleting cloud infos, we just clear them
// and put them into obsolete_cloud_infos, so active selections
// are preserved
ros::Time now = ros::Time::now();
// if decay time == 0, clear the old cloud when we get a new one
// otherwise, clear all the outdated ones
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
if ( point_decay_time > 0.0 || !new_cloud_infos_.empty() )
{
while( !cloud_infos_.empty() && now.toSec() - cloud_infos_.front()->receive_time_.toSec() > point_decay_time )
{
cloud_infos_.front()->clear();
obsolete_cloud_infos_.push_back( cloud_infos_.front() );
cloud_infos_.pop_front();
context_->queueRender();
}
}
}
// garbage-collect old point clouds that don't have an active selection
L_CloudInfo::iterator it = obsolete_cloud_infos_.begin();
L_CloudInfo::iterator end = obsolete_cloud_infos_.end();
for (; it != end; ++it)
{
if ( !(*it)->selection_handler_.get() ||
!(*it)->selection_handler_->hasSelections() )
{
it = obsolete_cloud_infos_.erase(it);
}
}
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
if( !new_cloud_infos_.empty() )
{
float size;
if( mode == PointCloud::RM_POINTS ) {
size = point_pixel_size_property_->getFloat();
} else {
size = point_world_size_property_->getFloat();
}
V_CloudInfo::iterator it = new_cloud_infos_.begin();
V_CloudInfo::iterator end = new_cloud_infos_.end();
for (; it != end; ++it)
{
CloudInfoPtr cloud_info = *it;
V_CloudInfo::iterator next = it; next++;
// ignore point clouds that are too old, but keep at least one
if ( next != end && now.toSec() - cloud_info->receive_time_.toSec() > point_decay_time ) {
continue;
}
cloud_info->cloud_.reset( new PointCloud() );
cloud_info->cloud_->addPoints( &(cloud_info->transformed_points_.front()), cloud_info->transformed_points_.size() );
cloud_info->cloud_->setRenderMode( mode );
cloud_info->cloud_->setAlpha( alpha_property_->getFloat() );
cloud_info->cloud_->setDimensions( size, size, size );
cloud_info->cloud_->setAutoSize(auto_size_);
cloud_info->manager_ = context_->getSceneManager();
cloud_info->scene_node_ = scene_node_->createChildSceneNode( cloud_info->position_, cloud_info->orientation_ );
cloud_info->scene_node_->attachObject( cloud_info->cloud_.get() );
cloud_info->selection_handler_.reset( new PointCloudSelectionHandler( getSelectionBoxSize(), cloud_info.get(), context_ ));
cloud_infos_.push_back(*it);
}
new_cloud_infos_.clear();
}
}
{
boost::recursive_mutex::scoped_try_lock lock( transformers_mutex_ );
if( lock.owns_lock() )
{
if( new_xyz_transformer_ || new_color_transformer_ )
{
M_TransformerInfo::iterator it = transformers_.begin();
M_TransformerInfo::iterator end = transformers_.end();
for (; it != end; ++it)
{
const std::string& name = it->first;
TransformerInfo& info = it->second;
setPropertiesHidden( info.xyz_props, name != xyz_transformer_property_->getStdString() );
setPropertiesHidden( info.color_props, name != color_transformer_property_->getStdString() );
}
}
}
new_xyz_transformer_ = false;
new_color_transformer_ = false;
}
updateStatus();
}
void PointCloudCommon::setPropertiesHidden( const QList<Property*>& props, bool hide )
{
for( int i = 0; i < props.size(); i++ )
{
props[ i ]->setHidden( hide );
}
}
void PointCloudCommon::updateTransformers( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
std::string xyz_name = xyz_transformer_property_->getStdString();
std::string color_name = color_transformer_property_->getStdString();
xyz_transformer_property_->clearOptions();
color_transformer_property_->clearOptions();
// Get the channels that we could potentially render
typedef std::set<std::pair<uint8_t, std::string> > S_string;
S_string valid_xyz, valid_color;
bool cur_xyz_valid = false;
bool cur_color_valid = false;
bool has_rgb_transformer = false;
M_TransformerInfo::iterator trans_it = transformers_.begin();
M_TransformerInfo::iterator trans_end = transformers_.end();
for(;trans_it != trans_end; ++trans_it)
{
const std::string& name = trans_it->first;
const PointCloudTransformerPtr& trans = trans_it->second.transformer;
uint32_t mask = trans->supports(cloud);
if (mask & PointCloudTransformer::Support_XYZ)
{
valid_xyz.insert(std::make_pair(trans->score(cloud), name));
if (name == xyz_name)
{
cur_xyz_valid = true;
}
xyz_transformer_property_->addOptionStd( name );
}
if (mask & PointCloudTransformer::Support_Color)
{
valid_color.insert(std::make_pair(trans->score(cloud), name));
if (name == color_name)
{
cur_color_valid = true;
}
if (name == "RGB8")
{
has_rgb_transformer = true;
}
color_transformer_property_->addOptionStd( name );
}
}
if( !cur_xyz_valid )
{
if( !valid_xyz.empty() )
{
xyz_transformer_property_->setStringStd( valid_xyz.rbegin()->second );
}
}
if( !cur_color_valid )
{
if( !valid_color.empty() )
{
if (has_rgb_transformer)
{
color_transformer_property_->setStringStd( "RGB8" );
} else
{
color_transformer_property_->setStringStd( valid_color.rbegin()->second );
}
}
}
}
void PointCloudCommon::updateStatus()
{
std::stringstream ss;
//ss << "Showing [" << total_point_count_ << "] points from [" << clouds_.size() << "] messages";
display_->setStatusStd(StatusProperty::Ok, "Points", ss.str());
}
void PointCloudCommon::processMessage(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
CloudInfoPtr info(new CloudInfo);
info->message_ = cloud;
info->receive_time_ = ros::Time::now();
if (transformCloud(info, true))
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
new_cloud_infos_.push_back(info);
display_->emitTimeSignal( cloud->header.stamp );
}
}
void PointCloudCommon::updateXyzTransformer()
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
if( transformers_.count( xyz_transformer_property_->getStdString() ) == 0 )
{
return;
}
new_xyz_transformer_ = true;
causeRetransform();
}
void PointCloudCommon::updateColorTransformer()
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
if( transformers_.count( color_transformer_property_->getStdString() ) == 0 )
{
return;
}
new_color_transformer_ = true;
causeRetransform();
}
PointCloudTransformerPtr PointCloudCommon::getXYZTransformer( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_);
M_TransformerInfo::iterator it = transformers_.find( xyz_transformer_property_->getStdString() );
if( it != transformers_.end() )
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if( trans->supports( cloud ) & PointCloudTransformer::Support_XYZ )
{
return trans;
}
}
return PointCloudTransformerPtr();
}
PointCloudTransformerPtr PointCloudCommon::getColorTransformer( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
M_TransformerInfo::iterator it = transformers_.find( color_transformer_property_->getStdString() );
if( it != transformers_.end() )
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if( trans->supports( cloud ) & PointCloudTransformer::Support_Color )
{
return trans;
}
}
return PointCloudTransformerPtr();
}
void PointCloudCommon::retransform()
{
boost::recursive_mutex::scoped_lock lock(transformers_mutex_);
D_CloudInfo::iterator it = cloud_infos_.begin();
D_CloudInfo::iterator end = cloud_infos_.end();
for (; it != end; ++it)
{
const CloudInfoPtr& cloud_info = *it;
transformCloud(cloud_info, false);
cloud_info->cloud_->clear();
cloud_info->cloud_->addPoints(&cloud_info->transformed_points_.front(), cloud_info->transformed_points_.size());
}
}
bool PointCloudCommon::transformCloud(const CloudInfoPtr& cloud_info, bool update_transformers)
{
if ( !cloud_info->scene_node_ )
{
if (!context_->getFrameManager()->getTransform(cloud_info->message_->header, cloud_info->position_, cloud_info->orientation_))
{
std::stringstream ss;
ss << "Failed to transform from frame [" << cloud_info->message_->header.frame_id << "] to frame [" << context_->getFrameManager()->getFixedFrame() << "]";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
}
Ogre::Matrix4 transform;
transform.makeTransform( cloud_info->position_, Ogre::Vector3(1,1,1), cloud_info->orientation_ );
V_PointCloudPoint& cloud_points = cloud_info->transformed_points_;
cloud_points.clear();
size_t size = cloud_info->message_->width * cloud_info->message_->height;
PointCloud::Point default_pt;
default_pt.color = Ogre::ColourValue(1, 1, 1);
default_pt.position = Ogre::Vector3::ZERO;
cloud_points.resize(size, default_pt);
{
boost::recursive_mutex::scoped_lock lock(transformers_mutex_);
if( update_transformers )
{
updateTransformers( cloud_info->message_ );
}
PointCloudTransformerPtr xyz_trans = getXYZTransformer(cloud_info->message_);
PointCloudTransformerPtr color_trans = getColorTransformer(cloud_info->message_);
if (!xyz_trans)
{
std::stringstream ss;
ss << "No position transformer available for cloud";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
if (!color_trans)
{
std::stringstream ss;
ss << "No color transformer available for cloud";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
xyz_trans->transform(cloud_info->message_, PointCloudTransformer::Support_XYZ, transform, cloud_points);
color_trans->transform(cloud_info->message_, PointCloudTransformer::Support_Color, transform, cloud_points);
}
for (V_PointCloudPoint::iterator cloud_point = cloud_points.begin(); cloud_point != cloud_points.end(); ++cloud_point)
{
if (!validateFloats(cloud_point->position))
{
cloud_point->position.x = 999999.0f;
cloud_point->position.y = 999999.0f;
cloud_point->position.z = 999999.0f;
}
}
return true;
}
bool convertPointCloudToPointCloud2(const sensor_msgs::PointCloud& input, sensor_msgs::PointCloud2& output)
{
output.header = input.header;
output.width = input.points.size ();
output.height = 1;
output.fields.resize (3 + input.channels.size ());
// Convert x/y/z to fields
output.fields[0].name = "x"; output.fields[1].name = "y"; output.fields[2].name = "z";
int offset = 0;
// All offsets are *4, as all field data types are float32
for (size_t d = 0; d < output.fields.size (); ++d, offset += 4)
{
output.fields[d].offset = offset;
output.fields[d].datatype = sensor_msgs::PointField::FLOAT32;
}
output.point_step = offset;
output.row_step = output.point_step * output.width;
// Convert the remaining of the channels to fields
for (size_t d = 0; d < input.channels.size (); ++d)
output.fields[3 + d].name = input.channels[d].name;
output.data.resize (input.points.size () * output.point_step);
output.is_bigendian = false; // @todo ?
output.is_dense = false;
// Copy the data points
for (size_t cp = 0; cp < input.points.size (); ++cp)
{
memcpy (&output.data[cp * output.point_step + output.fields[0].offset], &input.points[cp].x, sizeof (float));
memcpy (&output.data[cp * output.point_step + output.fields[1].offset], &input.points[cp].y, sizeof (float));
memcpy (&output.data[cp * output.point_step + output.fields[2].offset], &input.points[cp].z, sizeof (float));
for (size_t d = 0; d < input.channels.size (); ++d)
{
if (input.channels[d].values.size() == input.points.size())
{
memcpy (&output.data[cp * output.point_step + output.fields[3 + d].offset], &input.channels[d].values[cp], sizeof (float));
}
}
}
return (true);
}
void PointCloudCommon::addMessage(const sensor_msgs::PointCloudConstPtr& cloud)
{
sensor_msgs::PointCloud2Ptr out(new sensor_msgs::PointCloud2);
convertPointCloudToPointCloud2(*cloud, *out);
addMessage(out);
}
void PointCloudCommon::addMessage(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
if (cloud->width * cloud->height == 0)
{
return;
}
processMessage(cloud);
}
void PointCloudCommon::fixedFrameChanged()
{
reset();
}
void PointCloudCommon::setXyzTransformerOptions( EnumProperty* prop )
{
fillTransformerOptions( prop, PointCloudTransformer::Support_XYZ );
}
void PointCloudCommon::setColorTransformerOptions( EnumProperty* prop )
{
fillTransformerOptions( prop, PointCloudTransformer::Support_Color );
}
void PointCloudCommon::fillTransformerOptions( EnumProperty* prop, uint32_t mask )
{
prop->clearOptions();
if (cloud_infos_.empty())
{
return;
}
boost::recursive_mutex::scoped_lock tlock(transformers_mutex_);
const sensor_msgs::PointCloud2ConstPtr& msg = cloud_infos_.front()->message_;
M_TransformerInfo::iterator it = transformers_.begin();
M_TransformerInfo::iterator end = transformers_.end();
for (; it != end; ++it)
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if ((trans->supports(msg) & mask) == mask)
{
prop->addOption( QString::fromStdString( it->first ));
}
}
}
float PointCloudCommon::getSelectionBoxSize()
{
if( style_property_->getOptionInt() != PointCloud::RM_POINTS )
{
return point_world_size_property_->getFloat();
}
else
{
return 0.004;
}
}
} // namespace rviz
also process empty pointclouds
Otherwise, given a stream of clouds with some of them empty,
the last non-empty message will still be displayed until
a the next non-empty cloud comes in.
/*
* Copyright (c) 2008, 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 the 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 <QColor>
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <OgreWireBoundingBox.h>
#include <ros/time.h>
#include <tf/transform_listener.h>
#include <pluginlib/class_loader.h>
#include "rviz/default_plugin/point_cloud_transformer.h"
#include "rviz/default_plugin/point_cloud_transformers.h"
#include "rviz/display.h"
#include "rviz/display_context.h"
#include "rviz/frame_manager.h"
#include "rviz/ogre_helpers/point_cloud.h"
#include "rviz/properties/bool_property.h"
#include "rviz/properties/enum_property.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/vector_property.h"
#include "rviz/uniform_string_stream.h"
#include "rviz/validate_floats.h"
#include "rviz/default_plugin/point_cloud_common.h"
namespace rviz
{
struct IndexAndMessage
{
IndexAndMessage( int _index, const void* _message )
: index( _index )
, message( (uint64_t) _message )
{}
int index;
uint64_t message;
};
uint qHash( IndexAndMessage iam )
{
return
((uint) iam.index) +
((uint) (iam.message >> 32)) +
((uint) (iam.message & 0xffffffff));
}
bool operator==( IndexAndMessage a, IndexAndMessage b )
{
return a.index == b.index && a.message == b.message;
}
PointCloudSelectionHandler::PointCloudSelectionHandler(
float box_size,
PointCloudCommon::CloudInfo *cloud_info,
DisplayContext* context )
: SelectionHandler( context )
, cloud_info_( cloud_info )
, box_size_(box_size)
{
}
PointCloudSelectionHandler::~PointCloudSelectionHandler()
{
// delete all the Property objects on our way out.
QHash<IndexAndMessage, Property*>::const_iterator iter;
for( iter = property_hash_.begin(); iter != property_hash_.end(); iter++ )
{
delete iter.value();
}
}
void PointCloudSelectionHandler::preRenderPass(uint32_t pass)
{
SelectionHandler::preRenderPass(pass);
switch( pass )
{
case 0:
cloud_info_->cloud_->setPickColor( SelectionManager::handleToColor( getHandle() ));
break;
case 1:
cloud_info_->cloud_->setColorByIndex(true);
break;
default:
break;
}
}
void PointCloudSelectionHandler::postRenderPass(uint32_t pass)
{
SelectionHandler::postRenderPass(pass);
if (pass == 1)
{
cloud_info_->cloud_->setColorByIndex(false);
}
}
Ogre::Vector3 pointFromCloud(const sensor_msgs::PointCloud2ConstPtr& cloud, uint32_t index)
{
int32_t xi = findChannelIndex(cloud, "x");
int32_t yi = findChannelIndex(cloud, "y");
int32_t zi = findChannelIndex(cloud, "z");
const uint32_t xoff = cloud->fields[xi].offset;
const uint32_t yoff = cloud->fields[yi].offset;
const uint32_t zoff = cloud->fields[zi].offset;
const uint8_t type = cloud->fields[xi].datatype;
const uint32_t point_step = cloud->point_step;
float x = valueFromCloud<float>(cloud, xoff, type, point_step, index);
float y = valueFromCloud<float>(cloud, yoff, type, point_step, index);
float z = valueFromCloud<float>(cloud, zoff, type, point_step, index);
return Ogre::Vector3(x, y, z);
}
void PointCloudSelectionHandler::createProperties( const Picked& obj, Property* parent_property )
{
typedef std::set<int> S_int;
S_int indices;
{
S_uint64::const_iterator it = obj.extra_handles.begin();
S_uint64::const_iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
uint64_t handle = *it;
indices.insert((handle & 0xffffffff) - 1);
}
}
{
S_int::iterator it = indices.begin();
S_int::iterator end = indices.end();
for (; it != end; ++it)
{
int index = *it;
const sensor_msgs::PointCloud2ConstPtr& message = cloud_info_->message_;
IndexAndMessage hash_key( index, message.get() );
if( !property_hash_.contains( hash_key ))
{
Property* cat = new Property( QString( "Point %1 [cloud 0x%2]" ).arg( index ).arg( (uint64_t) message.get() ),
QVariant(), "", parent_property );
property_hash_.insert( hash_key, cat );
// First add the position.
VectorProperty* pos_prop = new VectorProperty( "Position", cloud_info_->transformed_points_[index].position, "", cat );
pos_prop->setReadOnly( true );
// Then add all other fields as well.
for( size_t field = 0; field < message->fields.size(); ++field )
{
const sensor_msgs::PointField& f = message->fields[ field ];
const std::string& name = f.name;
if( name == "x" || name == "y" || name == "z" || name == "X" || name == "Y" || name == "Z" )
{
continue;
}
if( name == "rgb" )
{
uint32_t val = valueFromCloud<uint32_t>( message, f.offset, f.datatype, message->point_step, index );
ColorProperty* prop = new ColorProperty( QString( "%1: %2" ).arg( field ).arg( QString::fromStdString( name )),
QColor( val >> 16, (val >> 8) & 0xff, val & 0xff ), "", cat );
prop->setReadOnly( true );
}
else
{
float val = valueFromCloud<float>( message, f.offset, f.datatype, message->point_step, index );
FloatProperty* prop = new FloatProperty( QString( "%1: %2" ).arg( field ).arg( QString::fromStdString( name )),
val, "", cat );
prop->setReadOnly( true );
}
}
}
}
}
}
void PointCloudSelectionHandler::destroyProperties( const Picked& obj, Property* parent_property )
{
typedef std::set<int> S_int;
S_int indices;
{
S_uint64::const_iterator it = obj.extra_handles.begin();
S_uint64::const_iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
uint64_t handle = *it;
indices.insert((handle & 0xffffffff) - 1);
}
}
{
S_int::iterator it = indices.begin();
S_int::iterator end = indices.end();
for (; it != end; ++it)
{
int index = *it;
const sensor_msgs::PointCloud2ConstPtr& message = cloud_info_->message_;
IndexAndMessage hash_key( index, message.get() );
Property* prop = property_hash_.take( hash_key );
delete prop;
}
}
}
void PointCloudSelectionHandler::getAABBs(const Picked& obj, V_AABB& aabbs)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
M_HandleToBox::iterator find_it = boxes_.find(std::make_pair(obj.handle, *it - 1));
if (find_it != boxes_.end())
{
Ogre::WireBoundingBox* box = find_it->second.second;
aabbs.push_back(box->getWorldBoundingBox());
}
}
}
void PointCloudSelectionHandler::onSelect(const Picked& obj)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
int index = (*it & 0xffffffff) - 1;
sensor_msgs::PointCloud2ConstPtr message = cloud_info_->message_;
Ogre::Vector3 pos = cloud_info_->transformed_points_[index].position;
pos = cloud_info_->scene_node_->convertLocalToWorldPosition( pos );
float size = box_size_ * 0.5f;
Ogre::AxisAlignedBox aabb(pos - size, pos + size);
createBox(std::make_pair(obj.handle, index), aabb, "RVIZ/Cyan" );
}
}
void PointCloudSelectionHandler::onDeselect(const Picked& obj)
{
S_uint64::iterator it = obj.extra_handles.begin();
S_uint64::iterator end = obj.extra_handles.end();
for (; it != end; ++it)
{
int global_index = (*it & 0xffffffff) - 1;
destroyBox(std::make_pair(obj.handle, global_index));
}
}
PointCloudCommon::CloudInfo::CloudInfo()
: manager_(0)
, scene_node_(0)
{}
PointCloudCommon::CloudInfo::~CloudInfo()
{
clear();
}
void PointCloudCommon::CloudInfo::clear()
{
if ( scene_node_ )
{
manager_->destroySceneNode( scene_node_ );
scene_node_=0;
}
}
PointCloudCommon::PointCloudCommon( Display* display )
: spinner_(1, &cbqueue_)
, new_xyz_transformer_(false)
, new_color_transformer_(false)
, needs_retransform_(false)
, transformer_class_loader_(NULL)
, display_( display )
, auto_size_(false)
{
selectable_property_ = new BoolProperty( "Selectable", true,
"Whether or not the points in this point cloud are selectable.",
display_, SLOT( updateSelectable() ), this );
style_property_ = new EnumProperty( "Style", "Flat Squares",
"Rendering mode to use, in order of computational complexity.",
display_, SLOT( updateStyle() ), this );
style_property_->addOption( "Points", PointCloud::RM_POINTS );
style_property_->addOption( "Squares", PointCloud::RM_SQUARES );
style_property_->addOption( "Flat Squares", PointCloud::RM_FLAT_SQUARES );
style_property_->addOption( "Spheres", PointCloud::RM_SPHERES );
style_property_->addOption( "Boxes", PointCloud::RM_BOXES );
point_world_size_property_ = new FloatProperty( "Size (m)", 0.01,
"Point size in meters.",
display_, SLOT( updateBillboardSize() ), this );
point_world_size_property_->setMin( 0.0001 );
point_pixel_size_property_ = new FloatProperty( "Size (Pixels)", 3,
"Point size in pixels.",
display_, SLOT( updateBillboardSize() ), this );
point_pixel_size_property_->setMin( 1 );
alpha_property_ = new FloatProperty( "Alpha", 1.0,
"Amount of transparency to apply to the points. Note that this is experimental and does not always look correct.",
display_, SLOT( updateAlpha() ), this );
alpha_property_->setMin( 0 );
alpha_property_->setMax( 1 );
decay_time_property_ = new FloatProperty( "Decay Time", 0,
"Duration, in seconds, to keep the incoming points. 0 means only show the latest points.",
display_, SLOT( queueRender() ));
decay_time_property_->setMin( 0 );
xyz_transformer_property_ = new EnumProperty( "Position Transformer", "",
"Set the transformer to use to set the position of the points.",
display_, SLOT( updateXyzTransformer() ), this );
connect( xyz_transformer_property_, SIGNAL( requestOptions( EnumProperty* )),
this, SLOT( setXyzTransformerOptions( EnumProperty* )));
color_transformer_property_ = new EnumProperty( "Color Transformer", "",
"Set the transformer to use to set the color of the points.",
display_, SLOT( updateColorTransformer() ), this );
connect( color_transformer_property_, SIGNAL( requestOptions( EnumProperty* )),
this, SLOT( setColorTransformerOptions( EnumProperty* )));
}
void PointCloudCommon::initialize( DisplayContext* context, Ogre::SceneNode* scene_node )
{
transformer_class_loader_ = new pluginlib::ClassLoader<PointCloudTransformer>( "rviz", "rviz::PointCloudTransformer" );
loadTransformers();
context_ = context;
scene_node_ = scene_node;
updateStyle();
updateBillboardSize();
updateAlpha();
updateSelectable();
spinner_.start();
}
PointCloudCommon::~PointCloudCommon()
{
spinner_.stop();
if ( transformer_class_loader_ )
{
delete transformer_class_loader_;
}
}
void PointCloudCommon::loadTransformers()
{
std::vector<std::string> classes = transformer_class_loader_->getDeclaredClasses();
std::vector<std::string>::iterator ci;
for( ci = classes.begin(); ci != classes.end(); ci++ )
{
const std::string& lookup_name = *ci;
std::string name = transformer_class_loader_->getName( lookup_name );
if( transformers_.count( name ) > 0 )
{
ROS_ERROR( "Transformer type [%s] is already loaded.", name.c_str() );
continue;
}
PointCloudTransformerPtr trans( transformer_class_loader_->createUnmanagedInstance( lookup_name ));
trans->init();
connect( trans.get(), SIGNAL( needRetransform() ), this, SLOT( causeRetransform() ));
TransformerInfo info;
info.transformer = trans;
info.readable_name = name;
info.lookup_name = lookup_name;
info.transformer->createProperties( display_, PointCloudTransformer::Support_XYZ, info.xyz_props );
setPropertiesHidden( info.xyz_props, true );
info.transformer->createProperties( display_, PointCloudTransformer::Support_Color, info.color_props );
setPropertiesHidden( info.color_props, true );
transformers_[ name ] = info;
}
}
void PointCloudCommon::setAutoSize( bool auto_size )
{
auto_size_ = auto_size;
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setAutoSize( auto_size );
}
}
void PointCloudCommon::updateAlpha()
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setAlpha( alpha_property_->getFloat() );
}
}
void PointCloudCommon::updateSelectable()
{
bool selectable = selectable_property_->getBool();
if( selectable )
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->selection_handler_.reset( new PointCloudSelectionHandler( getSelectionBoxSize(), cloud_infos_[i].get(), context_ ));
cloud_infos_[i]->cloud_->setPickColor( SelectionManager::handleToColor( cloud_infos_[i]->selection_handler_->getHandle() ));
}
}
else
{
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->selection_handler_.reset( );
cloud_infos_[i]->cloud_->setPickColor( Ogre::ColourValue( 0.0f, 0.0f, 0.0f, 0.0f ) );
}
}
}
void PointCloudCommon::updateStyle()
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
if( mode == PointCloud::RM_POINTS )
{
point_world_size_property_->hide();
point_pixel_size_property_->show();
}
else
{
point_world_size_property_->show();
point_pixel_size_property_->hide();
}
for( unsigned int i = 0; i < cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setRenderMode( mode );
}
updateBillboardSize();
}
void PointCloudCommon::updateBillboardSize()
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
float size;
if( mode == PointCloud::RM_POINTS ) {
size = point_pixel_size_property_->getFloat();
} else {
size = point_world_size_property_->getFloat();
}
for ( unsigned i=0; i<cloud_infos_.size(); i++ )
{
cloud_infos_[i]->cloud_->setDimensions( size, size, size );
cloud_infos_[i]->selection_handler_->setBoxSize( getSelectionBoxSize() );
}
context_->queueRender();
}
void PointCloudCommon::reset()
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
cloud_infos_.clear();
new_cloud_infos_.clear();
}
void PointCloudCommon::causeRetransform()
{
needs_retransform_ = true;
}
void PointCloudCommon::update(float wall_dt, float ros_dt)
{
PointCloud::RenderMode mode = (PointCloud::RenderMode) style_property_->getOptionInt();
float point_decay_time = decay_time_property_->getFloat();
if (needs_retransform_)
{
retransform();
needs_retransform_ = false;
}
// instead of deleting cloud infos, we just clear them
// and put them into obsolete_cloud_infos, so active selections
// are preserved
ros::Time now = ros::Time::now();
// if decay time == 0, clear the old cloud when we get a new one
// otherwise, clear all the outdated ones
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
if ( point_decay_time > 0.0 || !new_cloud_infos_.empty() )
{
while( !cloud_infos_.empty() && now.toSec() - cloud_infos_.front()->receive_time_.toSec() > point_decay_time )
{
cloud_infos_.front()->clear();
obsolete_cloud_infos_.push_back( cloud_infos_.front() );
cloud_infos_.pop_front();
context_->queueRender();
}
}
}
// garbage-collect old point clouds that don't have an active selection
L_CloudInfo::iterator it = obsolete_cloud_infos_.begin();
L_CloudInfo::iterator end = obsolete_cloud_infos_.end();
for (; it != end; ++it)
{
if ( !(*it)->selection_handler_.get() ||
!(*it)->selection_handler_->hasSelections() )
{
it = obsolete_cloud_infos_.erase(it);
}
}
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
if( !new_cloud_infos_.empty() )
{
float size;
if( mode == PointCloud::RM_POINTS ) {
size = point_pixel_size_property_->getFloat();
} else {
size = point_world_size_property_->getFloat();
}
V_CloudInfo::iterator it = new_cloud_infos_.begin();
V_CloudInfo::iterator end = new_cloud_infos_.end();
for (; it != end; ++it)
{
CloudInfoPtr cloud_info = *it;
V_CloudInfo::iterator next = it; next++;
// ignore point clouds that are too old, but keep at least one
if ( next != end && now.toSec() - cloud_info->receive_time_.toSec() > point_decay_time ) {
continue;
}
cloud_info->cloud_.reset( new PointCloud() );
cloud_info->cloud_->addPoints( &(cloud_info->transformed_points_.front()), cloud_info->transformed_points_.size() );
cloud_info->cloud_->setRenderMode( mode );
cloud_info->cloud_->setAlpha( alpha_property_->getFloat() );
cloud_info->cloud_->setDimensions( size, size, size );
cloud_info->cloud_->setAutoSize(auto_size_);
cloud_info->manager_ = context_->getSceneManager();
cloud_info->scene_node_ = scene_node_->createChildSceneNode( cloud_info->position_, cloud_info->orientation_ );
cloud_info->scene_node_->attachObject( cloud_info->cloud_.get() );
cloud_info->selection_handler_.reset( new PointCloudSelectionHandler( getSelectionBoxSize(), cloud_info.get(), context_ ));
cloud_infos_.push_back(*it);
}
new_cloud_infos_.clear();
}
}
{
boost::recursive_mutex::scoped_try_lock lock( transformers_mutex_ );
if( lock.owns_lock() )
{
if( new_xyz_transformer_ || new_color_transformer_ )
{
M_TransformerInfo::iterator it = transformers_.begin();
M_TransformerInfo::iterator end = transformers_.end();
for (; it != end; ++it)
{
const std::string& name = it->first;
TransformerInfo& info = it->second;
setPropertiesHidden( info.xyz_props, name != xyz_transformer_property_->getStdString() );
setPropertiesHidden( info.color_props, name != color_transformer_property_->getStdString() );
}
}
}
new_xyz_transformer_ = false;
new_color_transformer_ = false;
}
updateStatus();
}
void PointCloudCommon::setPropertiesHidden( const QList<Property*>& props, bool hide )
{
for( int i = 0; i < props.size(); i++ )
{
props[ i ]->setHidden( hide );
}
}
void PointCloudCommon::updateTransformers( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
std::string xyz_name = xyz_transformer_property_->getStdString();
std::string color_name = color_transformer_property_->getStdString();
xyz_transformer_property_->clearOptions();
color_transformer_property_->clearOptions();
// Get the channels that we could potentially render
typedef std::set<std::pair<uint8_t, std::string> > S_string;
S_string valid_xyz, valid_color;
bool cur_xyz_valid = false;
bool cur_color_valid = false;
bool has_rgb_transformer = false;
M_TransformerInfo::iterator trans_it = transformers_.begin();
M_TransformerInfo::iterator trans_end = transformers_.end();
for(;trans_it != trans_end; ++trans_it)
{
const std::string& name = trans_it->first;
const PointCloudTransformerPtr& trans = trans_it->second.transformer;
uint32_t mask = trans->supports(cloud);
if (mask & PointCloudTransformer::Support_XYZ)
{
valid_xyz.insert(std::make_pair(trans->score(cloud), name));
if (name == xyz_name)
{
cur_xyz_valid = true;
}
xyz_transformer_property_->addOptionStd( name );
}
if (mask & PointCloudTransformer::Support_Color)
{
valid_color.insert(std::make_pair(trans->score(cloud), name));
if (name == color_name)
{
cur_color_valid = true;
}
if (name == "RGB8")
{
has_rgb_transformer = true;
}
color_transformer_property_->addOptionStd( name );
}
}
if( !cur_xyz_valid )
{
if( !valid_xyz.empty() )
{
xyz_transformer_property_->setStringStd( valid_xyz.rbegin()->second );
}
}
if( !cur_color_valid )
{
if( !valid_color.empty() )
{
if (has_rgb_transformer)
{
color_transformer_property_->setStringStd( "RGB8" );
} else
{
color_transformer_property_->setStringStd( valid_color.rbegin()->second );
}
}
}
}
void PointCloudCommon::updateStatus()
{
std::stringstream ss;
//ss << "Showing [" << total_point_count_ << "] points from [" << clouds_.size() << "] messages";
display_->setStatusStd(StatusProperty::Ok, "Points", ss.str());
}
void PointCloudCommon::processMessage(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
CloudInfoPtr info(new CloudInfo);
info->message_ = cloud;
info->receive_time_ = ros::Time::now();
if (transformCloud(info, true))
{
boost::mutex::scoped_lock lock(new_clouds_mutex_);
new_cloud_infos_.push_back(info);
display_->emitTimeSignal( cloud->header.stamp );
}
}
void PointCloudCommon::updateXyzTransformer()
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
if( transformers_.count( xyz_transformer_property_->getStdString() ) == 0 )
{
return;
}
new_xyz_transformer_ = true;
causeRetransform();
}
void PointCloudCommon::updateColorTransformer()
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
if( transformers_.count( color_transformer_property_->getStdString() ) == 0 )
{
return;
}
new_color_transformer_ = true;
causeRetransform();
}
PointCloudTransformerPtr PointCloudCommon::getXYZTransformer( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_);
M_TransformerInfo::iterator it = transformers_.find( xyz_transformer_property_->getStdString() );
if( it != transformers_.end() )
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if( trans->supports( cloud ) & PointCloudTransformer::Support_XYZ )
{
return trans;
}
}
return PointCloudTransformerPtr();
}
PointCloudTransformerPtr PointCloudCommon::getColorTransformer( const sensor_msgs::PointCloud2ConstPtr& cloud )
{
boost::recursive_mutex::scoped_lock lock( transformers_mutex_ );
M_TransformerInfo::iterator it = transformers_.find( color_transformer_property_->getStdString() );
if( it != transformers_.end() )
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if( trans->supports( cloud ) & PointCloudTransformer::Support_Color )
{
return trans;
}
}
return PointCloudTransformerPtr();
}
void PointCloudCommon::retransform()
{
boost::recursive_mutex::scoped_lock lock(transformers_mutex_);
D_CloudInfo::iterator it = cloud_infos_.begin();
D_CloudInfo::iterator end = cloud_infos_.end();
for (; it != end; ++it)
{
const CloudInfoPtr& cloud_info = *it;
transformCloud(cloud_info, false);
cloud_info->cloud_->clear();
cloud_info->cloud_->addPoints(&cloud_info->transformed_points_.front(), cloud_info->transformed_points_.size());
}
}
bool PointCloudCommon::transformCloud(const CloudInfoPtr& cloud_info, bool update_transformers)
{
if ( !cloud_info->scene_node_ )
{
if (!context_->getFrameManager()->getTransform(cloud_info->message_->header, cloud_info->position_, cloud_info->orientation_))
{
std::stringstream ss;
ss << "Failed to transform from frame [" << cloud_info->message_->header.frame_id << "] to frame [" << context_->getFrameManager()->getFixedFrame() << "]";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
}
Ogre::Matrix4 transform;
transform.makeTransform( cloud_info->position_, Ogre::Vector3(1,1,1), cloud_info->orientation_ );
V_PointCloudPoint& cloud_points = cloud_info->transformed_points_;
cloud_points.clear();
size_t size = cloud_info->message_->width * cloud_info->message_->height;
PointCloud::Point default_pt;
default_pt.color = Ogre::ColourValue(1, 1, 1);
default_pt.position = Ogre::Vector3::ZERO;
cloud_points.resize(size, default_pt);
{
boost::recursive_mutex::scoped_lock lock(transformers_mutex_);
if( update_transformers )
{
updateTransformers( cloud_info->message_ );
}
PointCloudTransformerPtr xyz_trans = getXYZTransformer(cloud_info->message_);
PointCloudTransformerPtr color_trans = getColorTransformer(cloud_info->message_);
if (!xyz_trans)
{
std::stringstream ss;
ss << "No position transformer available for cloud";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
if (!color_trans)
{
std::stringstream ss;
ss << "No color transformer available for cloud";
display_->setStatusStd(StatusProperty::Error, "Message", ss.str());
return false;
}
xyz_trans->transform(cloud_info->message_, PointCloudTransformer::Support_XYZ, transform, cloud_points);
color_trans->transform(cloud_info->message_, PointCloudTransformer::Support_Color, transform, cloud_points);
}
for (V_PointCloudPoint::iterator cloud_point = cloud_points.begin(); cloud_point != cloud_points.end(); ++cloud_point)
{
if (!validateFloats(cloud_point->position))
{
cloud_point->position.x = 999999.0f;
cloud_point->position.y = 999999.0f;
cloud_point->position.z = 999999.0f;
}
}
return true;
}
bool convertPointCloudToPointCloud2(const sensor_msgs::PointCloud& input, sensor_msgs::PointCloud2& output)
{
output.header = input.header;
output.width = input.points.size ();
output.height = 1;
output.fields.resize (3 + input.channels.size ());
// Convert x/y/z to fields
output.fields[0].name = "x"; output.fields[1].name = "y"; output.fields[2].name = "z";
int offset = 0;
// All offsets are *4, as all field data types are float32
for (size_t d = 0; d < output.fields.size (); ++d, offset += 4)
{
output.fields[d].offset = offset;
output.fields[d].datatype = sensor_msgs::PointField::FLOAT32;
}
output.point_step = offset;
output.row_step = output.point_step * output.width;
// Convert the remaining of the channels to fields
for (size_t d = 0; d < input.channels.size (); ++d)
output.fields[3 + d].name = input.channels[d].name;
output.data.resize (input.points.size () * output.point_step);
output.is_bigendian = false; // @todo ?
output.is_dense = false;
// Copy the data points
for (size_t cp = 0; cp < input.points.size (); ++cp)
{
memcpy (&output.data[cp * output.point_step + output.fields[0].offset], &input.points[cp].x, sizeof (float));
memcpy (&output.data[cp * output.point_step + output.fields[1].offset], &input.points[cp].y, sizeof (float));
memcpy (&output.data[cp * output.point_step + output.fields[2].offset], &input.points[cp].z, sizeof (float));
for (size_t d = 0; d < input.channels.size (); ++d)
{
if (input.channels[d].values.size() == input.points.size())
{
memcpy (&output.data[cp * output.point_step + output.fields[3 + d].offset], &input.channels[d].values[cp], sizeof (float));
}
}
}
return (true);
}
void PointCloudCommon::addMessage(const sensor_msgs::PointCloudConstPtr& cloud)
{
sensor_msgs::PointCloud2Ptr out(new sensor_msgs::PointCloud2);
convertPointCloudToPointCloud2(*cloud, *out);
addMessage(out);
}
void PointCloudCommon::addMessage(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
processMessage(cloud);
}
void PointCloudCommon::fixedFrameChanged()
{
reset();
}
void PointCloudCommon::setXyzTransformerOptions( EnumProperty* prop )
{
fillTransformerOptions( prop, PointCloudTransformer::Support_XYZ );
}
void PointCloudCommon::setColorTransformerOptions( EnumProperty* prop )
{
fillTransformerOptions( prop, PointCloudTransformer::Support_Color );
}
void PointCloudCommon::fillTransformerOptions( EnumProperty* prop, uint32_t mask )
{
prop->clearOptions();
if (cloud_infos_.empty())
{
return;
}
boost::recursive_mutex::scoped_lock tlock(transformers_mutex_);
const sensor_msgs::PointCloud2ConstPtr& msg = cloud_infos_.front()->message_;
M_TransformerInfo::iterator it = transformers_.begin();
M_TransformerInfo::iterator end = transformers_.end();
for (; it != end; ++it)
{
const PointCloudTransformerPtr& trans = it->second.transformer;
if ((trans->supports(msg) & mask) == mask)
{
prop->addOption( QString::fromStdString( it->first ));
}
}
}
float PointCloudCommon::getSelectionBoxSize()
{
if( style_property_->getOptionInt() != PointCloud::RM_POINTS )
{
return point_world_size_property_->getFloat();
}
else
{
return 0.004;
}
}
} // namespace rviz
|
//
// Copyright (c) 2011 Regents of the University of California. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. The names of its contributors may not 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 "snn.h"
#include <sstream>
#if (_WIN32 || _WIN64)
#include <float.h>
#include <time.h>
#ifndef isnan
#define isnan(x) _isnan(x)
#endif
#ifndef isinf
#define isinf(x) (!_finite(x))
#endif
#ifndef srand48
#define srand48(x) srand(x)
#endif
#ifndef drand48
#define drand48() (double(rand())/RAND_MAX)
#endif
#else
#include <string.h>
#define strcmpi(s1,s2) strcasecmp(s1,s2)
#endif
// includes, project
#include <cutil.h>
MTRand_closed getRandClosed;
MTRand getRand;
RNG_rand48* gpuRand48 = NULL;
/*********************************************/
void CpuSNN::resetPointers()
{
voltage = NULL;
recovery = NULL;
Izh_a = NULL;
Izh_b = NULL;
Izh_c = NULL;
Izh_d = NULL;
current = NULL;
Npre = NULL;
Npost = NULL;
lastSpikeTime = NULL;
postSynapticIds = NULL;
postDelayInfo = NULL;
wt = NULL;
maxSynWt = NULL;
wtChange = NULL;
//stdpChanged = NULL;
synSpikeTime = NULL;
spikeGenBits = NULL;
firingTableD2 = NULL;
firingTableD1 = NULL;
fpParam = NULL;
fpLog = NULL;
fpProgLog = stderr;
fpTuningLog = NULL;
cntTuning = 0;
}
void CpuSNN::resetCurrent()
{
assert(current != NULL);
memset(current, 0, sizeof(float)*numNReg);
}
void CpuSNN::resetCounters()
{
assert(numNReg <= numN);
memset( curSpike, 0, sizeof(bool)*numN);
}
void CpuSNN::resetConductances()
{
if (sim_with_conductances) {
assert(gAMPA != NULL);
memset(gAMPA, 0, sizeof(float)*numNReg);
memset(gNMDA, 0, sizeof(float)*numNReg);
memset(gGABAa, 0, sizeof(float)*numNReg);
memset(gGABAb, 0, sizeof(float)*numNReg);
}
}
void CpuSNN::resetTimingTable()
{
memset(timeTableD2, 0, sizeof(int)*(1000+D+1));
memset(timeTableD1, 0, sizeof(int)*(1000+D+1));
}
void CpuSNN::CpuSNNInit(unsigned int _numN, unsigned int _numPostSynapses, unsigned int _numPreSynapses, unsigned int _D)
{
numN = _numN;
numPostSynapses = _numPostSynapses;
D = _D;
numPreSynapses = _numPreSynapses;
voltage = new float[numNReg];
recovery = new float[numNReg];
Izh_a = new float[numNReg];
Izh_b = new float[numNReg];
Izh_c = new float[numNReg];
Izh_d = new float[numNReg];
current = new float[numNReg];
nextTaste = new unsigned int[numNReg];
nextDeath = new unsigned int[numNReg];
cpuSnnSz.neuronInfoSize += (sizeof(int)*numNReg*12);
if (sim_with_conductances) {
for (int g=0;g<numGrp;g++)
if (!grp_Info[g].WithConductances && ((grp_Info[g].Type&POISSON_NEURON)==0)) {
printf("If one group enables conductances then all groups, except for generators, must enable conductances. Group '%s' is not enabled.\n", grp_Info2[g].Name.c_str());
assert(false);
}
gAMPA = new float[numNReg];
gNMDA = new float[numNReg];
gGABAa = new float[numNReg];
gGABAb = new float[numNReg];
cpuSnnSz.neuronInfoSize += sizeof(int)*numNReg*4;
}
resetCurrent();
resetConductances();
lastSpikeTime = new uint32_t[numN];
cpuSnnSz.neuronInfoSize += sizeof(int)*numN;
memset(lastSpikeTime,0,sizeof(lastSpikeTime[0]*numN));
curSpike = new bool[numN];
nSpikeCnt = new unsigned int[numN];
intrinsicWeight = new float[numN];
memset(intrinsicWeight,0,sizeof(float)*numN);
cpuSnnSz.neuronInfoSize += (sizeof(int)*numN*2+sizeof(bool)*numN);
if (sim_with_stp) {
stpu = new float[numN*STP_BUF_SIZE];
stpx = new float[numN*STP_BUF_SIZE];
for (int i=0; i < numN*STP_BUF_SIZE; i++) {
//MDR this should be set later.. (adding a default value)
stpu[i] = 1;
stpx[i] = 1;
}
cpuSnnSz.synapticInfoSize += (sizeof(stpu[0])*numN*STP_BUF_SIZE);
}
Npre = new unsigned short[numN];
Npre_plastic = new unsigned short[numN];
Npost = new unsigned short[numN];
cumulativePost = new unsigned int[numN];
cumulativePre = new unsigned int[numN];
cpuSnnSz.networkInfoSize += (int)(sizeof(int)*numN*3.5);
postSynCnt = 0; // stores the total number of post-synaptic connections in the network
preSynCnt = 0; // stores the total number of pre-synaptic connections in the network
for(int g=0; g < numGrp; g++) {
postSynCnt += (grp_Info[g].SizeN*grp_Info[g].numPostSynapses);
preSynCnt += (grp_Info[g].SizeN*grp_Info[g].numPreSynapses);
}
assert(postSynCnt/numN <= numPostSynapses); // divide by numN to prevent INT overflow
postSynapticIds = new post_info_t[postSynCnt+100];
tmp_SynapticDelay = new uint8_t[postSynCnt+100]; // Temporary array to store the delays of each connection
postDelayInfo = new delay_info_t[numN*(D+1)]; // Possible delay values are 0....D (inclusive of D)
cpuSnnSz.networkInfoSize += ((sizeof(post_info_t)+sizeof(uint8_t))*postSynCnt+100) + (sizeof(delay_info_t)*numN*(D+1));
assert(preSynCnt/numN <= numPreSynapses); // divide by numN to prevent INT overflow
wt = new float[preSynCnt+100];
maxSynWt = new float[preSynCnt+100];
// Temporary array to hold pre-syn connections. will be deleted later if necessary
preSynapticIds = new post_info_t[preSynCnt+100];
// size due to weights and maximum weights
cpuSnnSz.synapticInfoSize += ((2*sizeof(float)+sizeof(post_info_t))*(preSynCnt+100));
timeTableD2 = new unsigned int[1000+D+1];
timeTableD1 = new unsigned int[1000+D+1];
resetTimingTable();
cpuSnnSz.spikingInfoSize += sizeof(int)*2*(1000+D+1);
// random thalamic current included...
// randNeuronId = new int[numN];
// cpuSnnSz.addInfoSize += (sizeof(int)*numN);
// poisson Firing Rate
cpuSnnSz.neuronInfoSize += (sizeof(int)*numNPois);
tmp_SynapseMatrix_fixed = NULL;
tmp_SynapseMatrix_plastic = NULL;
}
void CpuSNN::makePtrInfo()
{
// create the CPU Net Ptrs..
cpuNetPtrs.voltage = voltage;
cpuNetPtrs.recovery = recovery;
cpuNetPtrs.current = current;
cpuNetPtrs.Npre = Npre;
cpuNetPtrs.Npost = Npost;
cpuNetPtrs.cumulativePost = cumulativePost;
cpuNetPtrs.cumulativePre = cumulativePre;
cpuNetPtrs.synSpikeTime = synSpikeTime;
cpuNetPtrs.wt = wt;
cpuNetPtrs.wtChange = wtChange;
cpuNetPtrs.nSpikeCnt = nSpikeCnt;
cpuNetPtrs.curSpike = curSpike;
cpuNetPtrs.firingTableD2 = firingTableD2;
cpuNetPtrs.firingTableD1 = firingTableD1;
cpuNetPtrs.gAMPA = gAMPA;
cpuNetPtrs.gNMDA = gNMDA;
cpuNetPtrs.gGABAa = gGABAa;
cpuNetPtrs.gGABAb = gGABAb;
cpuNetPtrs.allocated = true;
cpuNetPtrs.memType = CPU_MODE;
cpuNetPtrs.stpu = stpu;
cpuNetPtrs.stpx = stpx;
}
void CpuSNN::resetSpikeCnt(int my_grpId )
{
int startGrp, endGrp;
if(!doneReorganization)
return;
if (my_grpId == -1) {
startGrp = 0;
endGrp = numGrp;
}
else {
startGrp = my_grpId;
endGrp = my_grpId+numConfig;
}
for( int grpId=startGrp; grpId < endGrp; grpId++) {
int startN = grp_Info[grpId].StartN;
int endN = grp_Info[grpId].EndN+1;
for (int i=startN; i < endN; i++)
nSpikeCnt[i] = 0;
}
}
CpuSNN::CpuSNN(const string& _name, int _numConfig, int _randSeed, int _mode)
{
fprintf(stdout, "************************************************\n");
fprintf(stdout, "***** GPU-SNN Simulation Begins Version 0.3 *** \n");
fprintf(stdout, "************************************************\n");
// initialize propogated spike buffers.....
pbuf = new PropagatedSpikeBuffer(0, PROPOGATED_BUFFER_SIZE);
numConfig = _numConfig;
finishedPoissonGroup = false;
assert(numConfig > 0);
assert(numConfig < 100);
resetPointers();
numN = 0; numPostSynapses = 0; D = 0;
memset(&cpuSnnSz, 0, sizeof(cpuSnnSz));
enableSimLogs = false;
simLogDirName = "logs";//strdup("logs");
fpLog=fopen("tmp_debug.log","w");
fpProgLog = NULL;
showLog = 0; // disable showing log..
showLogMode = 0; // show only basic logs. if set higher more logs generated
showGrpFiringInfo = true;
currentMode = _mode;
memset(&cpu_gpuNetPtrs,0,sizeof(network_ptr_t));
memset(&net_Info,0,sizeof(network_info_t));
cpu_gpuNetPtrs.allocated = false;
memset(&cpuNetPtrs,0, sizeof(network_ptr_t));
cpuNetPtrs.allocated = false;
#ifndef VIEW_DOTTY
#define VIEW_DOTTY false
#endif
showDotty = VIEW_DOTTY;
numSpikeMonitor = 0;
for (int i=0; i < MAX_GRP_PER_SNN; i++) {
grp_Info[i].Type = UNKNOWN_NEURON;
grp_Info[i].MaxFiringRate = UNKNOWN_NEURON_MAX_FIRING_RATE;
grp_Info[i].MonitorId = -1;
grp_Info[i].FiringCount1sec=0;
grp_Info[i].numPostSynapses = 0; // default value
grp_Info[i].numPreSynapses = 0; // default value
grp_Info[i].WithSTP = false;
grp_Info[i].WithSTDP = false;
grp_Info[i].FixedInputWts = true; // Default is true. This value changed to false
// if any incoming connections are plastic
grp_Info[i].WithConductances = false;
grp_Info[i].isSpikeGenerator = false;
grp_Info[i].RatePtr = NULL;
/* grp_Info[i].STP_U = STP_U_Exc;
grp_Info[i].STP_tD = STP_tD_Exc;
grp_Info[i].STP_tF = STP_tF_Exc;
*/
grp_Info[i].dAMPA=1-(1.0/5);
grp_Info[i].dNMDA=1-(1.0/150);
grp_Info[i].dGABAa=1-(1.0/6);
grp_Info[i].dGABAb=1-(1.0/150);
grp_Info[i].spikeGen = NULL;
grp_Info[i].StartN = -1;
grp_Info[i].EndN = -1;
grp_Info2[i].numPostConn = 0;
grp_Info2[i].numPreConn = 0;
grp_Info2[i].enablePrint = false;
grp_Info2[i].maxPostConn = 0;
grp_Info2[i].maxPreConn = 0;
grp_Info2[i].sumPostConn = 0;
grp_Info2[i].sumPreConn = 0;
}
connectBegin = NULL;
numProbe = 0;
neuronProbe = NULL;
simTimeMs = 0; simTimeSec = 0; simTime = 0;
spikeCountAll1sec = 0; secD1fireCnt = 0; secD2fireCnt = 0;
spikeCountAll = 0; spikeCountD2 = 0; spikeCountD1 = 0;
nPoissonSpikes = 0;
networkName = _name; //new char[sizeof(_name)];
//strcpy(networkName, _name);
numGrp = 0;
numConnections = 0;
numSpikeGenGrps = 0;
NgenFunc = 0;
// numNoise = 0;
// numRandNeurons = 0;
simulatorDeleted = false;
allocatedN = 0;
allocatedPre = 0;
allocatedPost = 0;
doneReorganization = false;
memoryOptimized = false;
if (_randSeed == -1) {
randSeed = time(NULL);
}
else if(_randSeed==0) {
randSeed=123;
}
srand48(randSeed);
getRand.seed(randSeed*2);
getRandClosed.seed(randSeed*3);
fpParam = fopen("param.txt", "w");
if (fpParam==NULL) {
fprintf(stderr, "WARNING !!! Unable to open/create parameter file 'param.txt'; check if current directory is writable \n");
exit(1);
return;
}
fprintf(fpParam, "// *****************************************\n");
time_t rawtime; struct tm * timeinfo;
time ( &rawtime ); timeinfo = localtime ( &rawtime );
fprintf ( fpParam, "// program name : %s \n", _name.c_str());
fprintf ( fpParam, "// rand val : %d \n", randSeed);
fprintf ( fpParam, "// Current local time and date: %s\n", asctime (timeinfo));
fflush(fpParam);
cutCreateTimer(&timer);
cutResetTimer(timer);
cumExecutionTime = 0.0;
spikeRateUpdated = false;
sim_with_conductances = false;
sim_with_stp = false;
maxSpikesD2 = maxSpikesD1 = 0;
readNetworkFID = NULL;
}
void CpuSNN::deleteObjects()
{
try
{
if(simulatorDeleted)
return;
if(fpLog) {
printSimSummary(fpLog);
printSimSummary();
fclose(fpLog);
}
// if(val==0)
// saveConnectionWeights();
if(voltage!=NULL) delete[] voltage;
if(recovery!=NULL) delete[] recovery;
if(Izh_a!=NULL) delete[] Izh_a;
if(Izh_b!=NULL) delete[] Izh_b;
if(Izh_c!=NULL) delete[] Izh_c;
if(Izh_d!=NULL) delete[] Izh_d;
if(current!=NULL) delete[] current;
if(Npre!=NULL) delete[] Npre;
if(Npost!=NULL) delete[] Npost;
if(lastSpikeTime!=NULL) delete[] lastSpikeTime;
if(lastSpikeTime!=NULL) delete[] postSynapticIds;
if(postDelayInfo!=NULL) delete[] postDelayInfo;
if(wt!=NULL) delete[] wt;
if(maxSynWt!=NULL) delete[] maxSynWt;
if(wtChange !=NULL) delete[] wtChange;
if(synSpikeTime !=NULL) delete[] synSpikeTime;
if(firingTableD2) delete[] firingTableD2;
if(firingTableD1) delete[] firingTableD1;
delete pbuf;
// clear all existing connection info...
while (connectBegin) {
grpConnectInfo_t* nextConn = connectBegin->next;
free(connectBegin);
connectBegin = nextConn;
}
for (int i = 0; i < numSpikeMonitor; i++) {
delete[] monBufferFiring[i];
delete[] monBufferTimeCnt[i];
}
if(spikeGenBits) delete[] spikeGenBits;
simulatorDeleted = true;
}
catch(...)
{
fprintf(stderr, "Unknow exception ...\n");
}
}
void CpuSNN::exitSimulation(int val)
{
deleteObjects();
exit(val);
}
CpuSNN::~CpuSNN()
{
if (!simulatorDeleted)
deleteObjects();
}
void CpuSNN::setSTDP( int grpId, bool enable, int configId)
{
assert(enable==false);
setSTDP(grpId,false,0,0,0,0,configId);
}
void CpuSNN::setSTDP( int grpId, bool enable, float ALPHA_LTP, float TAU_LTP, float ALPHA_LTD, float TAU_LTD, int configId)
{
assert(TAU_LTP >= 0.0);
assert(TAU_LTD >= 0.0);
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setSTDP(g, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setSTDP(g, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSTDP(grpId, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, c);
} else {
int cGrpId = getGroupId(grpId, configId);
grp_Info[cGrpId].WithSTDP = enable;
grp_Info[cGrpId].ALPHA_LTP = ALPHA_LTP;
grp_Info[cGrpId].ALPHA_LTD = ALPHA_LTD;
grp_Info[cGrpId].TAU_LTP_INV = 1.0/TAU_LTP;
grp_Info[cGrpId].TAU_LTD_INV = 1.0/TAU_LTD;
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "STDP %s for %d (%s): %f, %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), ALPHA_LTP, ALPHA_LTD, TAU_LTP, TAU_LTD);
}
}
void CpuSNN::setSTP( int grpId, bool enable, int configId)
{
assert(enable==false);
setSTP(grpId,false,0,0,0,configId);
}
void CpuSNN::setSTP(int grpId, bool enable, float STP_U, float STP_tD, float STP_tF, int configId)
{
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setSTP(g, enable, STP_U, STP_tD, STP_tF, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setSTP(g, enable, STP_U, STP_tD, STP_tF, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSTP(grpId, enable, STP_U, STP_tD, STP_tF, c);
} else {
int cGrpId = getGroupId(grpId, configId);
sim_with_stp |= enable;
//printf("sim_with_stp: %d\n",sim_with_stp);
grp_Info[cGrpId].WithSTP = enable;
grp_Info[cGrpId].STP_U=STP_U;
grp_Info[cGrpId].STP_tD=STP_tD;
grp_Info[cGrpId].STP_tF=STP_tF;
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "STP %s for %d (%s): %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), STP_U, STP_tD, STP_tF);
}
}
void CpuSNN::setConductances( int grpId, bool enable, int configId)
{
assert(enable==false);
setConductances(grpId,false,0,0,0,0,configId);
}
void CpuSNN::setConductances(int grpId, bool enable, float tAMPA, float tNMDA, float tGABAa, float tGABAb, int configId)
{
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setConductances(g, enable, tAMPA, tNMDA, tGABAa, tGABAb, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setConductances(g, enable, tAMPA, tNMDA, tGABAa, tGABAb, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setConductances(grpId, enable, tAMPA, tNMDA, tGABAa, tGABAb, c);
} else {
int cGrpId = getGroupId(grpId, configId);
sim_with_conductances |= enable;
grp_Info[cGrpId].WithConductances = enable;
grp_Info[cGrpId].dAMPA=1-(1.0/tAMPA);
grp_Info[cGrpId].dNMDA=1-(1.0/tNMDA);
grp_Info[cGrpId].dGABAa=1-(1.0/tGABAa);
grp_Info[cGrpId].dGABAb=1-(1.0/tGABAb);
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "Conductances %s for %d (%s): %f, %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), tAMPA, tNMDA, tGABAa, tGABAb);
}
}
int CpuSNN::createGroup(const string& _name, unsigned int _numN, int _nType, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
createGroup(_name, _numN, _nType, c);
return (numGrp-numConfig);
} else {
assert(numGrp < MAX_GRP_PER_SNN);
if ( (!(_nType&TARGET_AMPA) && !(_nType&TARGET_NMDA) &&
!(_nType&TARGET_GABAa) && !(_nType&TARGET_GABAb)) || (_nType&POISSON_NEURON)) {
fprintf(stderr, "Invalid type using createGroup...\n");
fprintf(stderr, "can not create poisson generators here...\n");
exitSimulation(1);
}
grp_Info[numGrp].SizeN = _numN;
grp_Info[numGrp].Type = _nType;
grp_Info[numGrp].WithConductances = false;
grp_Info[numGrp].WithSTP = false;
grp_Info[numGrp].WithSTDP = false;
if ( (_nType&TARGET_GABAa) || (_nType&TARGET_GABAb)) {
grp_Info[numGrp].MaxFiringRate = INHIBITORY_NEURON_MAX_FIRING_RATE;
}
else {
grp_Info[numGrp].MaxFiringRate = EXCITATORY_NEURON_MAX_FIRING_RATE;
}
grp_Info2[numGrp].ConfigId = configId;
grp_Info2[numGrp].Name = _name;//new char[strlen(_name)];
grp_Info[numGrp].isSpikeGenerator = false;
grp_Info[numGrp].MaxDelay = 1;
grp_Info2[numGrp].IzhGen = NULL;
grp_Info2[numGrp].Izh_a = -1;
std::stringstream outStr;
outStr << configId;
if (configId == 0)
grp_Info2[numGrp].Name = _name;
else
grp_Info2[numGrp].Name = _name + "_" + outStr.str();
finishedPoissonGroup = true;
numGrp++;
return (numGrp-1);
}
}
int CpuSNN::createSpikeGeneratorGroup(const string& _name, unsigned int size_n, int type, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
createSpikeGeneratorGroup(_name, size_n, type, c);
return (numGrp-numConfig);
} else {
grp_Info[numGrp].SizeN = size_n;
grp_Info[numGrp].Type = type | POISSON_NEURON;
grp_Info[numGrp].WithConductances = false;
grp_Info[numGrp].WithSTP = false;
grp_Info[numGrp].WithSTDP = false;
grp_Info[numGrp].isSpikeGenerator = true; // these belong to the spike generator class...
grp_Info2[numGrp].ConfigId = configId;
grp_Info2[numGrp].Name = _name; //new char[strlen(_name)];
grp_Info[numGrp].MaxFiringRate = POISSON_MAX_FIRING_RATE;
std::stringstream outStr ;
outStr << configId;
if (configId != 0)
grp_Info2[numGrp].Name = _name + outStr.str();
numGrp++;
numSpikeGenGrps++;
return (numGrp-1);
}
}
int CpuSNN::getGroupId(int groupId, int configId)
{
assert(configId < numConfig);
int cGrpId = (groupId+configId);
assert(cGrpId < numGrp);
return cGrpId;
}
int CpuSNN::getConnectionId(int connId, int configId)
{
if(configId >= numConfig) {
fprintf(stderr, "getConnectionId(int, int): Assertion `configId(%d) < numConfig(%d)' failed\n", configId, numConfig);
assert(0);
}
connId = connId+configId;
if (connId >= numConnections) {
fprintf(stderr, "getConnectionId(int, int): Assertion `connId(%d) < numConnections(%d)' failed\n", connId, numConnections);
assert(0);
}
return connId;
}
void CpuSNN::setNeuronParameters(int groupId, float _a, float _b, float _c, float _d, int configId)
{
setNeuronParameters(groupId, _a, 0, _b, 0, _c, 0, _d, 0, configId);
}
void CpuSNN::setNeuronParameters(int groupId, float _a, float a_sd, float _b, float b_sd, float _c, float c_sd, float _d, float d_sd, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setNeuronParameters(groupId, _a, a_sd, _b, b_sd, _c, c_sd, _d, d_sd, c);
} else {
int cGrpId = getGroupId(groupId, configId);
grp_Info2[cGrpId].Izh_a = _a;
grp_Info2[cGrpId].Izh_a_sd = a_sd;
grp_Info2[cGrpId].Izh_b = _b;
grp_Info2[cGrpId].Izh_b_sd = b_sd;
grp_Info2[cGrpId].Izh_c = _c;
grp_Info2[cGrpId].Izh_c_sd = c_sd;
grp_Info2[cGrpId].Izh_d = _d;
grp_Info2[cGrpId].Izh_d_sd = d_sd;
}
}
void CpuSNN::setNeuronParameters(int groupId, IzhGenerator* IzhGen, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setNeuronParameters(groupId, IzhGen, c);
} else {
int cGrpId = getGroupId(groupId, configId);
grp_Info2[cGrpId].IzhGen = IzhGen;
}
}
void CpuSNN::setGroupInfo(int grpId, group_info_t info, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setGroupInfo(grpId, info, c);
} else {
int cGrpId = getGroupId(grpId, configId);
grp_Info[cGrpId] = info;
}
}
group_info_t CpuSNN::getGroupInfo(int grpId, int configId)
{
int cGrpId = getGroupId(grpId, configId);
return grp_Info[cGrpId];
}
void CpuSNN::buildPoissonGroup(int grpId)
{
assert(grp_Info[grpId].StartN == -1);
grp_Info[grpId].StartN = allocatedN;
grp_Info[grpId].EndN = allocatedN + grp_Info[grpId].SizeN - 1;
fprintf(fpLog, "Allocation for %d(%s), St=%d, End=%d\n",
grpId, grp_Info2[grpId].Name.c_str(), grp_Info[grpId].StartN, grp_Info[grpId].EndN);
resetSpikeCnt(grpId);
allocatedN = allocatedN + grp_Info[grpId].SizeN;
assert(allocatedN <= numN);
for(int i=grp_Info[grpId].StartN; i <= grp_Info[grpId].EndN; i++) {
resetPoissonNeuron(i, grpId);
Npre_plastic[i] = 0;
Npre[i] = 0;
Npost[i] = 0;
cumulativePost[i] = allocatedPost;
cumulativePre[i] = allocatedPre;
allocatedPost += grp_Info[grpId].numPostSynapses;
allocatedPre += grp_Info[grpId].numPreSynapses;
}
assert(allocatedPost <= postSynCnt);
assert(allocatedPre <= preSynCnt);
}
void CpuSNN::resetPoissonNeuron(unsigned int nid, int grpId)
{
assert(nid < numN);
lastSpikeTime[nid] = MAX_SIMULATION_TIME;
if(grp_Info[grpId].WithSTP) {
for (int j=0; j < STP_BUF_SIZE; j++) {
int ind=STP_BUF_POS(nid,j);
stpu[ind] = grp_Info[grpId].STP_U;
stpx[ind] = 1;
}
}
}
void CpuSNN::resetNeuron(unsigned int nid, int grpId)
{
assert(nid < numNReg);
if (grp_Info2[grpId].IzhGen == NULL) {
if (grp_Info2[grpId].Izh_a == -1) {
printf("setNeuronParameters much be called for group %s (%d)\n",grp_Info2[grpId].Name.c_str(),grpId);
exit(-1);
}
Izh_a[nid] = grp_Info2[grpId].Izh_a + grp_Info2[grpId].Izh_a_sd*(float)getRandClosed();
Izh_b[nid] = grp_Info2[grpId].Izh_b + grp_Info2[grpId].Izh_b_sd*(float)getRandClosed();
Izh_c[nid] = grp_Info2[grpId].Izh_c + grp_Info2[grpId].Izh_c_sd*(float)getRandClosed();
Izh_d[nid] = grp_Info2[grpId].Izh_d + grp_Info2[grpId].Izh_d_sd*(float)getRandClosed();
} else {
grp_Info2[grpId].IzhGen->set(this, grpId, nid, Izh_a[nid], Izh_b[nid], Izh_c[nid], Izh_d[nid]);
}
voltage[nid] = Izh_c[nid]; // initial values for new_v
recovery[nid] = 0.2f*voltage[nid]; // initial values for u
lastSpikeTime[nid] = MAX_SIMULATION_TIME;
if(grp_Info[grpId].WithSTP) {
for (int j=0; j < STP_BUF_SIZE; j++) {
int ind=STP_BUF_POS(nid,j);
stpu[ind] = grp_Info[grpId].STP_U;
stpx[ind] = 1;
}
}
}
void CpuSNN::buildGroup(int grpId)
{
assert(grp_Info[grpId].StartN == -1);
grp_Info[grpId].StartN = allocatedN;
grp_Info[grpId].EndN = allocatedN + grp_Info[grpId].SizeN - 1;
fprintf(fpLog, "Allocation for %d(%s), St=%d, End=%d\n",
grpId, grp_Info2[grpId].Name.c_str(), grp_Info[grpId].StartN, grp_Info[grpId].EndN);
resetSpikeCnt(grpId);
allocatedN = allocatedN + grp_Info[grpId].SizeN;
assert(allocatedN <= numN);
for(int i=grp_Info[grpId].StartN; i <= grp_Info[grpId].EndN; i++) {
resetNeuron(i, grpId);
Npre_plastic[i] = 0;
Npre[i] = 0;
Npost[i] = 0;
cumulativePost[i] = allocatedPost;
cumulativePre[i] = allocatedPre;
allocatedPost += grp_Info[grpId].numPostSynapses;
allocatedPre += grp_Info[grpId].numPreSynapses;
}
assert(allocatedPost <= postSynCnt);
assert(allocatedPre <= preSynCnt);
}
// set one specific connection from neuron id 'src' to neuron id 'dest'
inline void CpuSNN::setConnection(int srcGrp, int destGrp, unsigned int src, unsigned int dest, float synWt, float maxWt, uint8_t dVal, int connProp)
{
assert(dest<=CONN_SYN_NEURON_MASK); // total number of neurons is less than 1 million within a GPU
assert((dVal >=1) && (dVal <= D));
// we have exceeded the number of possible connection for one neuron
if(Npost[src] >= grp_Info[srcGrp].numPostSynapses) {
fprintf(stderr, "setConnection(%d (Grp=%s), %d (Grp=%s), %f, %d)\n", src, grp_Info2[srcGrp].Name.c_str(), dest, grp_Info2[destGrp].Name.c_str(), synWt, dVal);
fprintf(stderr, "(Npost[%d] = %d ) >= (numPostSynapses = %d) value given for the network very less\n", src, Npost[src], grp_Info[srcGrp].numPostSynapses);
fprintf(stderr, "Large number of postsynaptic connections is established\n");
fprintf(stderr, "Increase the numPostSynapses value for the Group = %s \n", grp_Info2[srcGrp].Name.c_str());
assert(0);
}
if(Npre[dest] >= grp_Info[destGrp].numPreSynapses) {
fprintf(stderr, "setConnection(%d (Grp=%s), %d (Grp=%s), %f, %d)\n", src, grp_Info2[srcGrp].Name.c_str(), dest, grp_Info2[destGrp].Name.c_str(), synWt, dVal);
fprintf(stderr, "(Npre[%d] = %d) >= (numPreSynapses = %d) value given for the network very less\n", dest, Npre[dest], grp_Info[destGrp].numPreSynapses);
fprintf(stderr, "Large number of presynaptic connections established\n");
fprintf(stderr, "Increase the numPostSynapses for the Grp = %s value \n", grp_Info2[destGrp].Name.c_str());
assert(0);
}
int p = Npost[src];
assert(Npost[src] >= 0);
assert(Npre[dest] >= 0);
assert((src*numPostSynapses+p)/numN < numPostSynapses); // divide by numN to prevent INT overflow
int post_pos = cumulativePost[src] + Npost[src];
int pre_pos = cumulativePre[dest] + Npre[dest];
assert(post_pos < postSynCnt);
assert(pre_pos < preSynCnt);
postSynapticIds[post_pos] = SET_CONN_ID(dest, Npre[dest], destGrp); //generate a new postSynapticIds id for the current connection
tmp_SynapticDelay[post_pos] = dVal;
preSynapticIds[pre_pos] = SET_CONN_ID(src, Npost[src], srcGrp);
wt[pre_pos] = synWt;
maxSynWt[pre_pos] = maxWt;
bool synWtType = GET_FIXED_PLASTIC(connProp);
if (synWtType == SYN_PLASTIC) {
Npre_plastic[dest]++;
}
Npre[dest]+=1;
Npost[src]+=1;
grp_Info2[srcGrp].numPostConn++;
grp_Info2[destGrp].numPreConn++;
if (Npost[src] > grp_Info2[srcGrp].maxPostConn)
grp_Info2[srcGrp].maxPostConn = Npost[src];
if (Npre[dest] > grp_Info2[destGrp].maxPreConn)
grp_Info2[destGrp].maxPreConn = Npre[src];
#if _DEBUG_
//fprintf(fpLog, "setConnection(%d, %d, %f, %d Npost[%d]=%d, Npre[%d]=%d)\n", src, dest, initWt, dVal, src, Npost[src], dest, Npre[dest]);
#endif
}
float CpuSNN::getWeights(int connProp, float initWt, float maxWt, unsigned int nid, int grpId)
{
float actWts;
bool setRandomWeights = GET_INITWTS_RANDOM(connProp);
bool setRampDownWeights = GET_INITWTS_RAMPDOWN(connProp);
bool setRampUpWeights = GET_INITWTS_RAMPUP(connProp);
if ( setRandomWeights )
actWts=initWt*drand48();
else if (setRampUpWeights)
actWts=(initWt+((nid-grp_Info[grpId].StartN)*(maxWt-initWt)/grp_Info[grpId].SizeN));
else if (setRampDownWeights)
actWts=(maxWt-((nid-grp_Info[grpId].StartN)*(maxWt-initWt)/grp_Info[grpId].SizeN));
else
actWts=initWt;
return actWts;
}
// make 'C' random connections from grpSrc to grpDest
void CpuSNN::connectRandom (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
for(int pre_nid=grp_Info[grpSrc].StartN; pre_nid<=grp_Info[grpSrc].EndN; pre_nid++) {
for(int post_nid=grp_Info[grpDest].StartN; post_nid<=grp_Info[grpDest].EndN; post_nid++) {
if (getRand() < info->p) {
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, pre_nid, grpSrc);
setConnection(grpSrc, grpDest, pre_nid, post_nid, synWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
}
}
}
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
void CpuSNN::connectOneToOne (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
assert( grp_Info[grpDest].SizeN == grp_Info[grpSrc].SizeN );
// C = grp_Info[grpDest].SizeN;
for(int nid=grp_Info[grpSrc].StartN,j=grp_Info[grpDest].StartN; nid<=grp_Info[grpSrc].EndN; nid++, j++) {
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, nid, grpSrc);
setConnection(grpSrc, grpDest, nid, j, synWt, info->maxWt, dVal, info->connProp);
//setConnection(grpSrc, grpDest, nid, j, info->initWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
}
// //dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"numPostSynapses=%d, wt=%3.3f , Dm=%d \"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", info->numPostSynapses, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating One-to-One Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
// fprintf(fpLog, "Creating One-to-One Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
// user-defined functions called here...
void CpuSNN::connectUserDefined (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
info->maxDelay = 0;
for(int nid=grp_Info[grpSrc].StartN; nid<=grp_Info[grpSrc].EndN; nid++) {
for(int nid2=grp_Info[grpDest].StartN; nid2 <= grp_Info[grpDest].EndN; nid2++) {
int srcId = nid - grp_Info[grpSrc].StartN;
int destId = nid2 - grp_Info[grpDest].StartN;
float weight, maxWt, delay;
bool connected;
info->conn->connect(this, grpSrc, srcId, grpDest, destId, weight, maxWt, delay, connected);
if(connected) {
if (GET_FIXED_PLASTIC(info->connProp) == SYN_FIXED) maxWt = weight;
assert(delay>=1);
assert(delay<=MAX_SynapticDelay);
assert(weight<=maxWt);
setConnection(grpSrc, grpDest, nid, nid2, weight, maxWt, delay, info->connProp);
info->numberOfConnections++;
if(delay > info->maxDelay)
info->maxDelay = delay;
}
}
}
// // dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"user-defined\"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted");
// fprintf(stdout, "Creating User-defined Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
// fprintf(fpLog, "Creating User-defined Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
// make 'C' full connections from grpSrc to grpDest
void CpuSNN::connectFull (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
bool noDirect = (info->type == CONN_FULL_NO_DIRECT);
for(int nid=grp_Info[grpSrc].StartN; nid<=grp_Info[grpSrc].EndN; nid++) {
for(int j=grp_Info[grpDest].StartN; j <= grp_Info[grpDest].EndN; j++) {
if((noDirect) && (nid - grp_Info[grpSrc].StartN) == (j - grp_Info[grpDest].StartN))
continue;
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, nid, grpSrc);
setConnection(grpSrc, grpDest, nid, j, synWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
//setConnection(grpSrc, grpDest, nid, j, info->initWt, info->maxWt, dVal, info->connProp);
}
}
// //dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"numPostSynapses=%d, wt=%3.3f, Dm=%d \"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", info->numPostSynapses, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating Full Connection %s from '%s' to '%s' with Probability %f\n",
// (noDirect?"no-direct":" "), grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), info->numPostSynapses*1.0/grp_Info[grpDest].SizeN);
// fprintf(fpLog, "Creating Full Connection %s from '%s' to '%s' with Probability %f\n",
// (noDirect?"no-direct":" "), grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), info->numPostSynapses*1.0/grp_Info[grpDest].SizeN);
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
void CpuSNN::connectFromMatrix(SparseWeightDelayMatrix* mat, int connProp)
{
for (int i=0;i<mat->count;i++) {
int nIDpre = mat->preIds[i];
int nIDpost = mat->postIds[i];
float weight = mat->weights[i];
float maxWeight = mat->maxWeights[i];
uint8_t delay = mat->delay_opts[i];
int gIDpre = findGrpId(nIDpre);
int gIDpost = findGrpId(nIDpost);
setConnection(gIDpre, gIDpost, nIDpre, nIDpost, weight, maxWeight, delay, connProp);
grp_Info2[gIDpre].sumPostConn++;
grp_Info2[gIDpost].sumPreConn++;
if (delay > grp_Info[gIDpre].MaxDelay) grp_Info[gIDpre].MaxDelay = delay;
}
}
void CpuSNN::printDotty ()
{
string fname(networkName+".dot");
fpDotty = fopen(fname.c_str(),"w");
fprintf(fpDotty, "\
digraph G {\n\
\t\tnode [style=filled];\n\
\t\tcolor=blue;\n");
for(int g=0; g < numGrp; g++) {
//add a node to the dotty output
char stype = grp_Info[g].Type;
assert(grp_Info2[g].numPostConn == grp_Info2[g].sumPostConn);
assert(grp_Info2[g].numPreConn == grp_Info2[g].sumPreConn);
// fprintf(stdout, "Creating Spike Generator Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// fprintf(fpLog, "Creating Spike Generator Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// add a node to the dotty output
fprintf (fpDotty, "\t\tg%d [%s label=\"id=%d:%s \\n numN=%d avgPost=%3.2f avgPre=%3.2f \\n maxPost=%d maxPre=%d\"];\n", g,
(stype&POISSON_NEURON) ? "shape = box, ": " ", g, grp_Info2[g].Name.c_str(),
grp_Info[g].SizeN, grp_Info2[g].numPostConn*1.0/grp_Info[g].SizeN,
grp_Info2[g].numPreConn*1.0/grp_Info[g].SizeN, grp_Info2[g].maxPostConn, grp_Info2[g].maxPreConn);
// fprintf(stdout, "Creating Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// fprintf(fpLog, "Creating Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
}
/*
for (int noiseId=0; noiseId < numNoise; noiseId++) {
int groupId = noiseGenGroup[noiseId].groupId;
float currentStrength = noiseGenGroup[noiseId].currentStrength;
float neuronPercentage = noiseGenGroup[noiseId].neuronPercentage;
int numNeuron = ((groupId==-1)? -1: grp_Info[groupId].SizeN);
if(groupId==-1)
fprintf(fpDotty, "\t\tr%d [shape=box, label=\"Global Random Noise\\n(I=%2.2fmA, frac=%2.2f%%)\"];\n", noiseId, currentStrength, neuronPercentage);
else
fprintf(fpDotty, "\t\tr%d [shape=box, label=\"Random Noise\\n(I=%2.2fmA, frac=%2.2f%%)\"];\n", noiseId, currentStrength, neuronPercentage);
if (groupId !=- 1)
fprintf(fpDotty, "\t\tr%d -> g%d [label=\" n=%d \"];\n", noiseId, groupId, (int) (numNeuron*(neuronPercentage/100.0)));
}
*/
grpConnectInfo_t* info = connectBegin;
while(info) {
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
float avgPostM = info->numberOfConnections/grp_Info[grpSrc].SizeN;
float avgPreM = info->numberOfConnections/grp_Info[grpDest].SizeN;
//dotty printf output
fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, arrowType=%s, label=\"avgPost=%3.2f, avgPre=%3.2f, wt=%3.3f, maxD=%d \"]\n",
grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", (info->initWt > 0)?"normal":"dot", avgPostM, avgPreM, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating Connection from '%s' to '%s' with Probability %1.3f\n",
// grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), avgPostM/grp_Info[grpDest].SizeN);
// fprintf(fpLog, "Creating Connection from '%s' to '%s' with Probability %1.3f\n",
// grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), avgPostM/grp_Info[grpDest].SizeN);
info = info->next;
}
fprintf(fpDotty, "\n}\n");
fclose(fpDotty);
//std::stringstream cmd;
//cmd << "kgraphviewer " << networkName << ".dot";
char cmd[100];
int dbg = sprintf(cmd, "kgraphviewer %s.dot", networkName.c_str());
int retVal;
showDotty = false;
if(showDotty) {
retVal = system(cmd);
assert(retVal >= 0);
}
fprintf(stdout, "\trun cmd to view graph: %s\n", cmd);
}
// make from each neuron in grpId1 to 'numPostSynapses' neurons in grpId2
int CpuSNN::connect(int grpId1, int grpId2, ConnectionGenerator* conn, bool synWtType, int maxM, int maxPreM)
{
int retId=-1;
for(int c=0; c < numConfig; c++, grpId1++, grpId2++) {
assert(grpId1 < numGrp);
assert(grpId2 < numGrp);
if (maxM == 0)
maxM = grp_Info[grpId2].SizeN;
if (maxPreM == 0)
maxPreM = grp_Info[grpId1].SizeN;
if (maxM > MAX_numPostSynapses) {
printf("Connection from %s (%d) to %s (%d) exceeded the maximum number of output synapses (%d), has %d.\n",grp_Info2[grpId1].Name.c_str(),grpId1,grp_Info2[grpId2].Name.c_str(), grpId2, MAX_numPostSynapses,maxM);
assert(maxM <= MAX_numPostSynapses);
}
if (maxPreM > MAX_numPreSynapses) {
printf("Connection from %s (%d) to %s (%d) exceeded the maximum number of input synapses (%d), has %d.\n",grp_Info2[grpId1].Name.c_str(), grpId1,grp_Info2[grpId2].Name.c_str(), grpId2,MAX_numPreSynapses,maxPreM);
assert(maxPreM <= MAX_numPreSynapses);
}
grpConnectInfo_t* newInfo = (grpConnectInfo_t*) calloc(1, sizeof(grpConnectInfo_t));
newInfo->grpSrc = grpId1;
newInfo->grpDest = grpId2;
newInfo->initWt = 1;
newInfo->maxWt = 1;
newInfo->maxDelay = 1;
newInfo->minDelay = 1;
newInfo->connProp = SET_CONN_PRESENT(1) | SET_FIXED_PLASTIC(synWtType);
newInfo->type = CONN_USER_DEFINED;
newInfo->numPostSynapses = maxM;
newInfo->numPreSynapses = maxPreM;
newInfo->conn = conn;
newInfo->next = connectBegin; // build a linked list
connectBegin = newInfo;
// update the pre and post size...
grp_Info[grpId1].numPostSynapses += newInfo->numPostSynapses;
grp_Info[grpId2].numPreSynapses += newInfo->numPreSynapses;
if (showLogMode >= 1)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",grpId1,grp_Info2[grpId1].Name.c_str(),grp_Info[grpId1].numPostSynapses,grpId2,grp_Info2[grpId2].Name.c_str(),grp_Info[grpId2].numPreSynapses);
newInfo->connId = numConnections++;
if(c==0)
retId = newInfo->connId;
}
assert(retId != -1);
return retId;
}
// make from each neuron in grpId1 to 'numPostSynapses' neurons in grpId2
int CpuSNN::connect(int grpId1, int grpId2, const string& _type, float initWt, float maxWt, float p, uint8_t minDelay, uint8_t maxDelay, bool synWtType, const string& wtType)
{
int retId=-1;
for(int c=0; c < numConfig; c++, grpId1++, grpId2++) {
assert(grpId1 < numGrp);
assert(grpId2 < numGrp);
assert(minDelay <= maxDelay);
bool useRandWts = (wtType.find("random") != string::npos);
bool useRampDownWts = (wtType.find("ramp-down") != string::npos);
bool useRampUpWts = (wtType.find("ramp-up") != string::npos);
uint32_t connProp = SET_INITWTS_RANDOM(useRandWts)
| SET_CONN_PRESENT(1)
| SET_FIXED_PLASTIC(synWtType)
| SET_INITWTS_RAMPUP(useRampUpWts)
| SET_INITWTS_RAMPDOWN(useRampDownWts);
grpConnectInfo_t* newInfo = (grpConnectInfo_t*) calloc(1, sizeof(grpConnectInfo_t));
newInfo->grpSrc = grpId1;
newInfo->grpDest = grpId2;
newInfo->initWt = initWt;
newInfo->maxWt = maxWt;
newInfo->maxDelay = maxDelay;
newInfo->minDelay = minDelay;
newInfo->connProp = connProp;
newInfo->p = p;
newInfo->type = CONN_UNKNOWN;
newInfo->numPostSynapses = 1;
newInfo->next = connectBegin; //linked list of connection..
connectBegin = newInfo;
if ( _type.find("random") != string::npos) {
newInfo->type = CONN_RANDOM;
newInfo->numPostSynapses = MIN(grp_Info[grpId2].SizeN,((int) (p*grp_Info[grpId2].SizeN +5*sqrt(p*(1-p)*grp_Info[grpId2].SizeN)+0.5))); // estimate the maximum number of connections we need. This uses a binomial distribution at 5 stds.
newInfo->numPreSynapses = MIN(grp_Info[grpId1].SizeN,((int) (p*grp_Info[grpId1].SizeN +5*sqrt(p*(1-p)*grp_Info[grpId1].SizeN)+0.5))); // estimate the maximum number of connections we need. This uses a binomial distribution at 5 stds.
}
else if ( _type.find("full") != string::npos) {
newInfo->type = CONN_FULL;
newInfo->numPostSynapses = grp_Info[grpId2].SizeN;
newInfo->numPreSynapses = grp_Info[grpId1].SizeN;
}
else if ( _type.find("full-no-direct") != string::npos) {
newInfo->type = CONN_FULL_NO_DIRECT;
newInfo->numPostSynapses = grp_Info[grpId2].SizeN-1;
newInfo->numPreSynapses = grp_Info[grpId1].SizeN-1;
}
else if ( _type.find("one-to-one") != string::npos) {
newInfo->type = CONN_ONE_TO_ONE;
newInfo->numPostSynapses = 1;
newInfo->numPreSynapses = 1;
}
else {
fprintf(stderr, "Invalid connection type (should be 'random', or 'full' or 'one-to-one' or 'full-no-direct')\n");
exitSimulation(-1);
}
if (newInfo->numPostSynapses > MAX_numPostSynapses) {
printf("Connection exceeded the maximum number of output synapses (%d), has %d.\n",MAX_numPostSynapses,newInfo->numPostSynapses);
assert(newInfo->numPostSynapses <= MAX_numPostSynapses);
}
if (newInfo->numPreSynapses > MAX_numPreSynapses) {
printf("Connection exceeded the maximum number of input synapses (%d), has %d.\n",MAX_numPreSynapses,newInfo->numPreSynapses);
assert(newInfo->numPreSynapses <= MAX_numPreSynapses);
}
// update the pre and post size...
grp_Info[grpId1].numPostSynapses += newInfo->numPostSynapses;
grp_Info[grpId2].numPreSynapses += newInfo->numPreSynapses;
if (showLogMode >= 1)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",grpId1,grp_Info2[grpId1].Name.c_str(),grp_Info[grpId1].numPostSynapses,grpId2,grp_Info2[grpId2].Name.c_str(),grp_Info[grpId2].numPreSynapses);
newInfo->connId = numConnections++;
if(c==0)
retId = newInfo->connId;
}
assert(retId != -1);
return retId;
}
int CpuSNN::updateSpikeTables()
{
int curD = 0;
int grpSrc;
// find the maximum delay in the given network
// and also the maximum delay for each group.
grpConnectInfo_t* newInfo = connectBegin;
while(newInfo) {
grpSrc = newInfo->grpSrc;
if (newInfo->maxDelay > curD)
curD = newInfo->maxDelay;
// check if the current connection's delay meaning grp1's delay
// is greater than the MaxDelay for grp1. We find the maximum
// delay for the grp1 by this scheme.
if (newInfo->maxDelay > grp_Info[grpSrc].MaxDelay)
grp_Info[grpSrc].MaxDelay = newInfo->maxDelay;
newInfo = newInfo->next;
}
for(int g=0; g < numGrp; g++) {
if ( grp_Info[g].MaxDelay == 1)
maxSpikesD1 += (grp_Info[g].SizeN*grp_Info[g].MaxFiringRate);
else
maxSpikesD2 += (grp_Info[g].SizeN*grp_Info[g].MaxFiringRate);
}
// maxSpikesD1 = (maxSpikesD1 == 0)? 1 : maxSpikesD1;
// maxSpikesD2 = (maxSpikesD2 == 0)? 1 : maxSpikesD2;
if ((maxSpikesD1+maxSpikesD2) < (numNExcReg+numNInhReg+numNPois)*UNKNOWN_NEURON_MAX_FIRING_RATE) {
fprintf(stderr, "Insufficient amount of buffer allocated...\n");
exitSimulation(1);
}
// maxSpikesD2 = (maxSpikesD1 > maxSpikesD2)?maxSpikesD1:maxSpikesD2;
// maxSpikesD1 = (maxSpikesD1 > maxSpikesD2)?maxSpikesD1:maxSpikesD2;
firingTableD2 = new unsigned int[maxSpikesD2];
firingTableD1 = new unsigned int[maxSpikesD1];
cpuSnnSz.spikingInfoSize += sizeof(int)*((maxSpikesD2+maxSpikesD1) + 2*(1000+D+1));
return curD;
}
void CpuSNN::buildNetwork()
{
grpConnectInfo_t* newInfo = connectBegin;
int curN = 0, curD = 0, numPostSynapses = 0, numPreSynapses = 0;
assert(numConfig > 0);
//update main set of parameters
updateParameters(&curN, &numPostSynapses, &numPreSynapses, numConfig);
curD = updateSpikeTables();
assert((curN > 0)&& (curN == numNExcReg + numNInhReg + numNPois));
assert(numPostSynapses > 0);
assert(numPreSynapses > 0);
// display the evaluated network and delay length....
fprintf(stdout, ">>>>>>>>>>>>>> NUM_CONFIGURATIONS = %d <<<<<<<<<<<<<<<<<<\n", numConfig);
fprintf(stdout, "**********************************\n");
fprintf(stdout, "numN = %d, numPostSynapses = %d, numPreSynapses = %d, D = %d\n", curN, numPostSynapses, numPreSynapses, curD);
fprintf(stdout, "**********************************\n");
fprintf(fpLog, "**********************************\n");
fprintf(fpLog, "numN = %d, numPostSynapses = %d, numPreSynapses = %d, D = %d\n", curN, numPostSynapses, numPreSynapses, curD);
fprintf(fpLog, "**********************************\n");
assert(curD != 0); assert(numPostSynapses != 0); assert(curN != 0); assert(numPreSynapses != 0);
if (showLogMode >= 1)
for (int g=0;g<numGrp;g++)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",g,grp_Info2[g].Name.c_str(),grp_Info[g].numPostSynapses,g,grp_Info2[g].Name.c_str(),grp_Info[g].numPreSynapses);
if (numPostSynapses > MAX_numPostSynapses) {
for (int g=0;g<numGrp;g++)
if (grp_Info[g].numPostSynapses>MAX_numPostSynapses) printf("Grp: %s(%d) has too many output synapses (%d), max %d.\n",grp_Info2[g].Name.c_str(),g,grp_Info[g].numPostSynapses,MAX_numPostSynapses);
assert(numPostSynapses <= MAX_numPostSynapses);
}
if (numPreSynapses > MAX_numPreSynapses) {
for (int g=0;g<numGrp;g++)
if (grp_Info[g].numPreSynapses>MAX_numPreSynapses) printf("Grp: %s(%d) has too many input synapses (%d), max %d.\n",grp_Info2[g].Name.c_str(),g,grp_Info[g].numPreSynapses,MAX_numPreSynapses);
assert(numPreSynapses <= MAX_numPreSynapses);
}
assert(curD <= MAX_SynapticDelay); assert(curN <= 1000000);
// initialize all the parameters....
CpuSNNInit(curN, numPostSynapses, numPreSynapses, curD);
// we build network in the order...
///// !!!!!!! IMPORTANT : NEURON ORGANIZATION/ARRANGEMENT MAP !!!!!!!!!!
//// <--- Excitatory --> | <-------- Inhibitory REGION ----------> | <-- Excitatory -->
/// Excitatory-Regular | Inhibitory-Regular | Inhibitory-Poisson | Excitatory-Poisson
int allocatedGrp = 0;
for(int order=0; order < 4; order++) {
for(int configId=0; configId < numConfig; configId++) {
for(int g=0; g < numGrp; g++) {
if (grp_Info2[g].ConfigId == configId) {
if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON) && order==3) {
buildPoissonGroup(g);
allocatedGrp++;
} else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON) && order==2) {
buildPoissonGroup(g);
allocatedGrp++;
} else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON) && order==0) {
buildGroup(g);
allocatedGrp++;
} else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON) && order==1) {
buildGroup(g);
allocatedGrp++;
}
}
}
}
}
assert(allocatedGrp == numGrp);
if (readNetworkFID != NULL) {
// we the user specified readNetwork the synaptic weights will be restored here...
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
// read the plastic synapses first
assert(readNetwork_internal(true) >= 0);
// read the fixed synapses secon
assert(readNetwork_internal(false) >= 0);
#else
assert(readNetwork_internal() >= 0);
connectFromMatrix(tmp_SynapseMatrix_plastic, SET_FIXED_PLASTIC(SYN_PLASTIC));
connectFromMatrix(tmp_SynapseMatrix_fixed, SET_FIXED_PLASTIC(SYN_FIXED));
#endif
} else {
// build all the connections here...
// we run over the linked list two times...
// first time, we make all plastic connections...
// second time, we make all fixed connections...
// this ensures that all the initial pre and post-synaptic
// connections are of fixed type and later if of plastic type
for(int con=0; con < 2; con++) {
newInfo = connectBegin;
while(newInfo) {
bool synWtType = GET_FIXED_PLASTIC(newInfo->connProp);
if (synWtType == SYN_PLASTIC) {
grp_Info[newInfo->grpDest].FixedInputWts = false; // given group has plastic connection, and we need to apply STDP rule...
}
if( ((con == 0) && (synWtType == SYN_PLASTIC)) ||
((con == 1) && (synWtType == SYN_FIXED)))
{
switch(newInfo->type)
{
case CONN_RANDOM:
connectRandom(newInfo);
break;
case CONN_FULL:
connectFull(newInfo);
break;
case CONN_FULL_NO_DIRECT:
connectFull(newInfo);
break;
case CONN_ONE_TO_ONE:
connectOneToOne(newInfo);
break;
case CONN_USER_DEFINED:
connectUserDefined(newInfo);
break;
default:
printf("Invalid connection type( should be 'random', or 'full')\n");
}
float avgPostM = newInfo->numberOfConnections/grp_Info[newInfo->grpSrc].SizeN;
float avgPreM = newInfo->numberOfConnections/grp_Info[newInfo->grpDest].SizeN;
fprintf(stderr, "connect(%s(%d) => %s(%d), iWt=%f, mWt=%f, numPostSynapses=%d, numPreSynapses=%d, minD=%d, maxD=%d, %s)\n",
grp_Info2[newInfo->grpSrc].Name.c_str(), newInfo->grpSrc, grp_Info2[newInfo->grpDest].Name.c_str(),
newInfo->grpDest, newInfo->initWt, newInfo->maxWt, (int)avgPostM, (int)avgPreM,
newInfo->minDelay, newInfo->maxDelay, synWtType?"Plastic":"Fixed");
}
newInfo = newInfo->next;
}
}
}
}
int CpuSNN::findGrpId(int nid)
{
for(int g=0; g < numGrp; g++) {
//printf("%d:%s s=%d e=%d\n", g, grp_Info2[g].Name.c_str(), grp_Info[g].StartN, grp_Info[g].EndN);
if(nid >=grp_Info[g].StartN && (nid <=grp_Info[g].EndN)) {
return g;
}
}
fprintf(stderr, "findGrp(): cannot find the group for neuron %d\n", nid);
assert(0);
}
void CpuSNN::writeNetwork(FILE* fid)
{
unsigned int version = 1;
fwrite(&version,sizeof(int),1,fid);
fwrite(&numGrp,sizeof(int),1,fid);
char name[100];
for (int g=0;g<numGrp;g++) {
fwrite(&grp_Info[g].StartN,sizeof(int),1,fid);
fwrite(&grp_Info[g].EndN,sizeof(int),1,fid);
strncpy(name,grp_Info2[g].Name.c_str(),100);
fwrite(name,1,100,fid);
}
int nrCells = numN;
fwrite(&nrCells,sizeof(int),1,fid);
for (unsigned int i=0;i<nrCells;i++) {
int offset = cumulativePost[i];
unsigned int count = 0;
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1)
count++;
}
fwrite(&count,sizeof(int),1,fid);
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
unsigned int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
// get syn id
unsigned int s_i = GET_CONN_SYN_ID(post_info);
//>>POST_SYN_NEURON_BITS)&POST_SYN_CONN_MASK;
assert(s_i<(Npre[p_i]));
// get the cumulative position for quick access...
unsigned int pos_i = cumulativePre[p_i] + s_i;
uint8_t delay = t+1;
uint8_t plastic = s_i < Npre_plastic[p_i]; // plastic or fixed.
fwrite(&i,sizeof(int),1,fid);
fwrite(&p_i,sizeof(int),1,fid);
fwrite(&(wt[pos_i]),sizeof(float),1,fid);
fwrite(&(maxSynWt[pos_i]),sizeof(float),1,fid);
fwrite(&delay,sizeof(uint8_t),1,fid);
fwrite(&plastic,sizeof(uint8_t),1,fid);
}
}
}
}
void CpuSNN::readNetwork(FILE* fid)
{
readNetworkFID = fid;
}
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
int CpuSNN::readNetwork_internal(bool onlyPlastic)
#else
int CpuSNN::readNetwork_internal()
#endif
{
long file_position = ftell(readNetworkFID); // so that we can restore the file position later...
unsigned int version;
if (!fread(&version,sizeof(int),1,readNetworkFID)) return -11;
if (version > 1) return -10;
int _numGrp;
if (!fread(&_numGrp,sizeof(int),1,readNetworkFID)) return -11;
if (numGrp != _numGrp) return -1;
char name[100];
int startN, endN;
for (int g=0;g<numGrp;g++) {
if (!fread(&startN,sizeof(int),1,readNetworkFID)) return -11;
if (!fread(&endN,sizeof(int),1,readNetworkFID)) return -11;
if (startN != grp_Info[g].StartN) return -2;
if (endN != grp_Info[g].EndN) return -3;
if (!fread(name,1,100,readNetworkFID)) return -11;
if (strcmp(name,grp_Info2[g].Name.c_str()) != 0) return -4;
}
int nrCells;
if (!fread(&nrCells,sizeof(int),1,readNetworkFID)) return -11;
if (nrCells != numN) return -5;
tmp_SynapseMatrix_fixed = new SparseWeightDelayMatrix(nrCells,nrCells,nrCells*10);
tmp_SynapseMatrix_plastic = new SparseWeightDelayMatrix(nrCells,nrCells,nrCells*10);
for (unsigned int i=0;i<nrCells;i++) {
unsigned int nrSynapses = 0;
if (!fread(&nrSynapses,sizeof(int),1,readNetworkFID)) return -11;
for (int j=0;j<nrSynapses;j++) {
unsigned int nIDpre;
unsigned int nIDpost;
float weight, maxWeight;
uint8_t delay;
uint8_t plastic;
if (!fread(&nIDpre,sizeof(int),1,readNetworkFID)) return -11;
if (nIDpre != i) return -6;
if (!fread(&nIDpost,sizeof(int),1,readNetworkFID)) return -11;
if (nIDpost >= nrCells) return -7;
if (!fread(&weight,sizeof(float),1,readNetworkFID)) return -11;
int gIDpre = findGrpId(nIDpre);
if (IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (weight>0) || !IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (weight<0)) return -8;
if (!fread(&maxWeight,sizeof(float),1,readNetworkFID)) return -11;
if (IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (maxWeight>=0) || !IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (maxWeight<=0)) return -8;
if (!fread(&delay,sizeof(uint8_t),1,readNetworkFID)) return -11;
if (delay > MAX_SynapticDelay) return -9;
if (!fread(&plastic,sizeof(uint8_t),1,readNetworkFID)) return -11;
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
if ((plastic && onlyPlastic) || (!plastic && !onlyPlastic)) {
int gIDpost = findGrpId(nIDpost);
int connProp = SET_FIXED_PLASTIC(plastic?SYN_PLASTIC:SYN_FIXED);
setConnection(gIDpre, gIDpost, nIDpre, nIDpost, weight, maxWeight, delay, connProp);
grp_Info2[gIDpre].sumPostConn++;
grp_Info2[gIDpost].sumPreConn++;
if (delay > grp_Info[gIDpre].MaxDelay) grp_Info[gIDpre].MaxDelay = delay;
}
#else
// add the synapse to the temporary Matrix so that it can be used in buildNetwork()
if (plastic) {
tmp_SynapseMatrix_plastic->add(nIDpre,nIDpost,weight,maxWeight,delay,plastic);
} else {
tmp_SynapseMatrix_fixed->add(nIDpre,nIDpost,weight,maxWeight,delay,plastic);
}
#endif
}
}
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
fseek(readNetworkFID,file_position,SEEK_SET);
#endif
return 0;
}
float* CpuSNN::getWeights(int gIDpre, int gIDpost, int& Npre, int& Npost, float* weights) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (weights==NULL) weights = new float[Npre*Npost];
memset(weights,0,Npre*Npost*sizeof(float));
// copy the pre synaptic data from GPU, if needed
if (currentMode == GPU_MODE) copyWeightState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, gIDpost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
weights[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = cpuNetPtrs.wt[pos_i];
}
}
}
}
return weights;
}
float* CpuSNN::getWeightChanges(int gIDpre, int gIDpost, int& Npre, int& Npost, float* weightChanges) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (weightChanges==NULL) weightChanges = new float[Npre*Npost];
memset(weightChanges,0,Npre*Npost*sizeof(float));
// copy the pre synaptic data from GPU, if needed
if (currentMode == GPU_MODE) copyWeightState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, gIDpost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
weightChanges[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = wtChange[pos_i];
}
}
}
}
return weightChanges;
}
uint8_t* CpuSNN::getDelays(int gIDpre, int gIDpost, int& Npre, int& Npost, uint8_t* delays) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (delays == NULL) delays = new uint8_t[Npre*Npost];
memset(delays,0,Npre*Npost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
delays[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = t+1;
}
}
}
}
return delays;
}
// This function is called every second by simulator...
// This function updates the firingTable by removing older firing values...
// and also update the synaptic weights from its derivatives..
void CpuSNN::updateStateAndFiringTable()
{
// Read the neuron ids that fired in the last D seconds
// and put it to the beginning of the firing table...
for(int p=timeTableD2[999],k=0;p<timeTableD2[999+D+1];p++,k++) {
firingTableD2[k]=firingTableD2[p];
}
for(int i=0; i < D; i++) {
timeTableD2[i+1] = timeTableD2[1000+i+1]-timeTableD2[1000];
}
timeTableD1[D] = 0;
// update synaptic weights here for all the neurons..
for(int g=0; g < numGrp; g++) {
// no changable weights so continue without changing..
if(grp_Info[g].FixedInputWts || !(grp_Info[g].WithSTDP)) {
// for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++)
// nSpikeCnt[i]=0;
continue;
}
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
///nSpikeCnt[i] = 0;
assert(i < numNReg);
int offset = cumulativePre[i];
float diff_firing = 0.0;
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"Weights, Change at %lu (diff_firing:%f) \n", simTimeSec, diff_firing);
for(int j=0; j < Npre_plastic[i]; j++) {
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"%1.2f %1.2f \t", wt[offset+j]*10, wtChange[offset+j]*10);
wt[offset+j] += wtChange[offset+j];
//MDR - don't decay weights, just set to 0
//wtChange[offset+j]*=0.99f;
wtChange[offset+j] = 0;
// if this is an excitatory or inhibitory synapse
if (maxSynWt[offset+j] >= 0) {
if (wt[offset+j]>=maxSynWt[offset+j])
wt[offset+j] = maxSynWt[offset+j];
if (wt[offset+j]<0)
wt[offset+j] = 0.0;
} else {
if (wt[offset+j]<=maxSynWt[offset+j])
wt[offset+j] = maxSynWt[offset+j];
if (wt[offset+j]>0)
wt[offset+j] = 0.0;
}
}
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"\n");
}
}
spikeCountAll += spikeCountAll1sec;
spikeCountD2 += (secD2fireCnt-timeTableD2[D]);
spikeCountD1 += secD1fireCnt;
secD1fireCnt = 0;
spikeCountAll1sec = 0;
secD2fireCnt = timeTableD2[D];
for(int i=0; i < numGrp; i++) {
grp_Info[i].FiringCount1sec=0;
}
}
// This method loops through all spikes that are generated by neurons with a delay of 2+ms
// and delivers the spikes to the appropriate post-synaptic neuron
void CpuSNN::doD2CurrentUpdate()
{
int k = secD2fireCnt-1;
int k_end = timeTableD2[simTimeMs+1];
int t_pos = simTimeMs;
while((k>=k_end)&& (k >=0)) {
// get the neuron id from the index k
int i = firingTableD2[k];
// find the time of firing from the timeTable using index k
while (!((k >= timeTableD2[t_pos+D])&&(k < timeTableD2[t_pos+D+1]))) {
t_pos = t_pos - 1;
assert((t_pos+D-1)>=0);
}
// TODO: Instead of using the complex timeTable, can neuronFiringTime value...???
// Calculate the time difference between time of firing of neuron and the current time...
int tD = simTimeMs - t_pos;
assert((tD<D)&&(tD>=0));
assert(i<numN);
delay_info_t dPar = postDelayInfo[i*(D+1)+tD];
int offset = cumulativePost[i];
// for each delay variables
for(int idx_d = dPar.delay_index_start;
idx_d < (dPar.delay_index_start + dPar.delay_length);
idx_d = idx_d+1) {
generatePostSpike( i, idx_d, offset, tD);
}
k=k-1;
}
}
// This method loops through all spikes that are generated by neurons with a delay of 1ms
// and delivers the spikes to the appropriate post-synaptic neuron
void CpuSNN::doD1CurrentUpdate()
{
int k = secD1fireCnt-1;
int k_end = timeTableD1[simTimeMs+D];
while((k>=k_end) && (k>=0)) {
int neuron_id = firingTableD1[k];
assert(neuron_id<numN);
delay_info_t dPar = postDelayInfo[neuron_id*(D+1)];
int offset = cumulativePost[neuron_id];
for(int idx_d = dPar.delay_index_start;
idx_d < (dPar.delay_index_start + dPar.delay_length);
idx_d = idx_d+1) {
generatePostSpike( neuron_id, idx_d, offset, 0);
}
k=k-1;
}
}
void CpuSNN::generatePostSpike(unsigned int pre_i, unsigned int idx_d, unsigned int offset, unsigned int tD)
{
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
unsigned int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
assert(s_i<(Npre[p_i]));
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
assert(p_i < numNReg);
float change;
int pre_grpId = findGrpId(pre_i);
char type = grp_Info[pre_grpId].Type;
// TODO: MNJ TEST THESE CONDITIONS FOR CORRECTNESS...
int ind = STP_BUF_POS(pre_i,(simTime-tD-1));
// if the source group STP is disabled. we need to skip it..
if (grp_Info[pre_grpId].WithSTP) {
change = wt[pos_i]*stpx[ind]*stpu[ind];
} else
change = wt[pos_i];
if (grp_Info[pre_grpId].WithConductances) {
if (type & TARGET_AMPA) gAMPA [p_i] += change;
if (type & TARGET_NMDA) gNMDA [p_i] += change;
if (type & TARGET_GABAa) gGABAa[p_i] -= change; // wt should be negative for GABAa and GABAb
if (type & TARGET_GABAb) gGABAb[p_i] -= change;
} else
current[p_i] += change;
int post_grpId = findGrpId(p_i);
if ((showLogMode >= 3) && (p_i==grp_Info[post_grpId].StartN))
printf("%d => %d (%d) am=%f ga=%f wt=%f stpu=%f stpx=%f td=%d\n",
pre_i, p_i, findGrpId(p_i), gAMPA[p_i], gGABAa[p_i],
wt[pos_i],(grp_Info[post_grpId].WithSTP?stpx[ind]:1.0),(grp_Info[post_grpId].WithSTP?stpu[ind]:1.0),tD);
// STDP calculation....
if (grp_Info[post_grpId].WithSTDP) {
//stdpChanged[pos_i]=false;
//assert((simTime-lastSpikeTime[p_i])>=0);
int stdp_tDiff = (simTime-lastSpikeTime[p_i]);
if (stdp_tDiff >= 0) {
#ifdef INHIBITORY_STDP
if ((type & TARGET_GABAa) || (type & TARGET_GABAb))
{
//printf("I");
if ((stdp_tDiff*grp_Info[post_grpId].TAU_LTD_INV)<25)
wtChange[pos_i] -= (STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTP, grp_Info[post_grpId].TAU_LTP_INV) - STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTD*1.5, grp_Info[post_grpId].TAU_LTD_INV));
}
else
#endif
{
//printf("E");
if ((stdp_tDiff*grp_Info[post_grpId].TAU_LTD_INV)<25)
wtChange[pos_i] -= STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTD, grp_Info[post_grpId].TAU_LTD_INV);
}
}
assert(!((stdp_tDiff < 0) && (lastSpikeTime[p_i] != MAX_SIMULATION_TIME)));
}
synSpikeTime[pos_i] = simTime;
}
void CpuSNN::globalStateUpdate()
{
#define CUR_DEBUG 1
//fprintf(stdout, "---%d ----\n", simTime);
// now we update the state of all the neurons
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].Type&POISSON_NEURON) continue;
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
assert(i < numNReg);
if (grp_Info[g].WithConductances) {
for (int j=0; j<COND_INTEGRATION_SCALE; j++) {
float NMDAtmp = (voltage[i]+80)*(voltage[i]+80)/60/60;
float tmpI = - ( gAMPA[i]*(voltage[i]-0)
+ gNMDA[i]*NMDAtmp/(1+NMDAtmp)*(voltage[i]-0)
+ gGABAa[i]*(voltage[i]+70)
+ gGABAb[i]*(voltage[i]+90));
#ifdef NEURON_NOISE
float noiseI = -intrinsicWeight[i]*log(getRand());
if (isnan(noiseI) || isinf(noiseI)) noiseI = 0;
tmpI += noiseI;
#endif
// Icurrent[i] = tmpI;
voltage[i]+=((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+tmpI)/COND_INTEGRATION_SCALE;
assert(!isnan(voltage[i]) && !isinf(voltage[i]));
if (voltage[i] > 30) {
voltage[i] = 30;
j=COND_INTEGRATION_SCALE; // break the loop but evaluate u[i]
}
if (voltage[i] < -90) voltage[i] = -90;
recovery[i]+=Izh_a[i]*(Izh_b[i]*voltage[i]-recovery[i])/COND_INTEGRATION_SCALE;
}
//if (i==grp_Info[6].StartN) printf("voltage: %f AMPA: %f NMDA: %f GABAa: %f GABAb: %f\n",voltage[i],gAMPA[i],gNMDA[i],gGABAa[i],gGABAb[i]);
} else {
voltage[i]+=0.5f*((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+current[i]); // for numerical stability
voltage[i]+=0.5f*((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+current[i]); // time step is 0.5 ms
if (voltage[i] > 30) voltage[i] = 30;
if (voltage[i] < -90) voltage[i] = -90;
recovery[i]+=Izh_a[i]*(Izh_b[i]*voltage[i]-recovery[i]);
}
if ((showLogMode >= 2) && (i==grp_Info[g].StartN))
fprintf(stdout, "%d: voltage=%0.3f, recovery=%0.5f, AMPA=%0.5f, NMDA=%0.5f\n",
i, voltage[i], recovery[i], gAMPA[i], gNMDA[i]);
}
}
}
void CpuSNN::printWeight(int grpId, const char *str)
{
int stg, endg;
if(grpId == -1) {
stg = 0;
endg = numGrp;
}
else {
stg = grpId;
endg = grpId+1;
}
for(int g=stg; (g < endg) ; g++) {
fprintf(stderr, "%s", str);
if (!grp_Info[g].FixedInputWts) {
//fprintf(stderr, "w=\t");
if (currentMode == GPU_MODE) {
copyWeightState (&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, g);
}
int i=grp_Info[g].StartN;
int offset = cumulativePre[i];
//fprintf(stderr, "time=%d, Neuron synaptic weights %d:\n", simTime, i);
for(int j=0; j < Npre[i]; j++) {
//fprintf(stderr, "w=%f c=%f spt=%d\t", wt[offset+j], wtChange[offset+j], synSpikeTime[offset+j]);
fprintf(stdout, "%1.3f,%1.3f\t", cpuNetPtrs.wt[offset+j], cpuNetPtrs.wtChange[offset+j]);
}
fprintf(stdout, "\n");
}
}
}
// show the status of the simulator...
// when onlyCnt is set, we print the actual count instead of frequency of firing
void CpuSNN::showStatus(int simType)
{
DBG(2, fpLog, AT, "showStatus() called");
printState("showStatus");
if(simType == GPU_MODE) {
showStatus_GPU();
return;
}
FILE* fpVal[2];
fpVal[0] = fpLog;
fpVal[1] = fpProgLog;
for(int k=0; k < 2; k++) {
if(k==0)
printWeight(-1);
fprintf(fpVal[k], "(time=%lld) =========\n\n", (unsigned long long) simTimeSec);
#if REG_TESTING
// if the overall firing rate is very low... then report error...
if((spikeCountAll1sec*1.0f/numN) < 1.0) {
fprintf(fpVal[k], " SIMULATION WARNING !!! Very Low Firing happened...\n");
fflush(fpVal[k]);
}
#endif
fflush(fpVal[k]);
}
#if REG_TESTING
if(spikeCountAll1sec == 0) {
fprintf(stderr, " SIMULATION ERROR !!! Very Low or no firing happened...\n");
//exit(-1);
}
#endif
}
void CpuSNN::startCPUTiming()
{
prevCpuExecutionTime = cumExecutionTime;
}
void CpuSNN::resetCPUTiming()
{
prevCpuExecutionTime = cumExecutionTime;
cpuExecutionTime = 0.0;
}
void CpuSNN::stopCPUTiming()
{
cpuExecutionTime += (cumExecutionTime - prevCpuExecutionTime);
prevCpuExecutionTime = cumExecutionTime;
}
void CpuSNN::startGPUTiming()
{
prevGpuExecutionTime = cumExecutionTime;
}
void CpuSNN::resetGPUTiming()
{
prevGpuExecutionTime = cumExecutionTime;
gpuExecutionTime = 0.0;
}
void CpuSNN::stopGPUTiming()
{
gpuExecutionTime += (cumExecutionTime - prevGpuExecutionTime);
prevGpuExecutionTime = cumExecutionTime;
}
// reorganize the network and do the necessary allocation
// of all variable for carrying out the simulation..
// this code is run only one time during network initialization
void CpuSNN::setupNetwork(int simType, bool removeTempMem)
{
if(!doneReorganization)
reorganizeNetwork(removeTempMem, simType);
if((simType == GPU_MODE) && (cpu_gpuNetPtrs.allocated == false))
allocateSNN_GPU();
}
bool CpuSNN::updateTime()
{
bool finishedOneSec = false;
// done one second worth of simulation
// update relevant parameters...now
if(++simTimeMs == 1000) {
simTimeMs = 0;
simTimeSec++;
finishedOneSec = true;
}
simTime++;
if(simTime >= MAX_SIMULATION_TIME){
// reached the maximum limit of the simulation time using 32 bit value...
updateAfterMaxTime();
}
return finishedOneSec;
}
// Run the simulation for n sec
int CpuSNN::runNetwork(int _nsec, int _nmsec, int simType, bool enablePrint, int copyState)
{
DBG(2, fpLog, AT, "runNetwork() called");
assert(_nmsec >= 0);
assert(_nsec >= 0);
assert(simType == CPU_MODE || simType == GPU_MODE);
int runDuration = _nsec*1000 + _nmsec;
setGrpTimeSlice(ALL, MAX(1,MIN(runDuration,PROPOGATED_BUFFER_SIZE-1))); // set the Poisson generation time slice to be at the run duration up to PROPOGATED_BUFFER_SIZE ms.
// First time when the network is run we do various kind of space compression,
// and data structure optimization to improve performance and save memory.
setupNetwork(simType);
currentMode = simType;
cutResetTimer(timer);
cutStartTimer(timer);
// if nsec=0, simTimeMs=10, we need to run the simulator for 10 timeStep;
// if nsec=1, simTimeMs=10, we need to run the simulator for 1*1000+10, time Step;
for(int i=0; i < runDuration; i++) {
// initThalInput();
if(simType == CPU_MODE)
doSnnSim();
else
doGPUSim();
if (enablePrint) {
printState();
}
if (updateTime()) {
// finished one sec of simulation...
if(showLog)
if(showLogCycle==showLog++) {
showStatus(currentMode);
showLog=1;
}
updateSpikeMonitor();
if(simType == CPU_MODE)
updateStateAndFiringTable();
else
updateStateAndFiringTable_GPU();
}
}
if(copyState) {
// copy the state from GPU to GPU
for(int g=0; g < numGrp; g++) {
if ((!grp_Info[g].isSpikeGenerator) && (currentMode==GPU_MODE)) {
copyNeuronState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, g);
}
}
}
// keep track of simulation time...
cutStopTimer(timer);
lastExecutionTime = cutGetTimerValue(timer);
if(0) {
fprintf(fpLog, "(t%s = %2.2f sec)\n", (currentMode == GPU_MODE)?"GPU":"CPU", lastExecutionTime/1000);
fprintf(stdout, "(t%s = %2.2f sec)\n", (currentMode == GPU_MODE)?"GPU":"CPU", lastExecutionTime/1000);
}
cumExecutionTime += lastExecutionTime;
return 0;
}
void CpuSNN::updateAfterMaxTime()
{
fprintf(stderr, "Maximum Simulation Time Reached...Resetting simulation time\n");
// This will be our cut of time. All other time values
// that are less than cutOffTime will be set to zero
unsigned int cutOffTime = (MAX_SIMULATION_TIME - 10*1000);
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].isSpikeGenerator) {
int diffTime = (grp_Info[g].SliceUpdateTime - cutOffTime);
grp_Info[g].SliceUpdateTime = (diffTime < 0) ? 0 : diffTime;
}
// no STDP then continue...
if(!grp_Info[g].FixedInputWts) {
continue;
}
for(int k=0, nid = grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++,k++) {
assert(nid < numNReg);
// calculate the difference in time
signed diffTime = (lastSpikeTime[nid] - cutOffTime);
lastSpikeTime[nid] = (diffTime < 0) ? 0 : diffTime;
// do the same thing with all synaptic connections..
unsigned* synTime = &synSpikeTime[cumulativePre[nid]];
for(int i=0; i < Npre[nid]; i++, synTime++) {
// calculate the difference in time
signed diffTime = (synTime[0] - cutOffTime);
synTime[0] = (diffTime < 0) ? 0 : diffTime;
}
}
}
simTime = MAX_SIMULATION_TIME - cutOffTime;
resetPropogationBuffer();
}
void CpuSNN::resetPropogationBuffer()
{
pbuf->reset(0, 1023);
}
unsigned int poissonSpike(unsigned int currTime, float frate, int refractPeriod)
{
bool done = false;
unsigned int nextTime = 0;
assert(refractPeriod>0); // refractory period must be 1 or greater, 0 means could have multiple spikes specified at the same time.
static int cnt = 0;
while(!done)
{
float randVal = drand48();
unsigned int tmpVal = -log(randVal)/frate;
nextTime = currTime + tmpVal;
//fprintf(stderr, "%d: next random = %f, frate = %f, currTime = %d, nextTime = %d tmpVal = %d\n", cnt++, randVal, frate, currTime, nextTime, tmpVal);
if ((nextTime - currTime) >= (unsigned) refractPeriod)
done = true;
}
assert(nextTime != 0);
return nextTime;
}
//
void CpuSNN::updateSpikeGeneratorsInit()
{
int cnt=0;
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator) {
// This is done only during initialization
grp_Info[g].CurrTimeSlice = grp_Info[g].NewTimeSlice;
// we only need NgenFunc for spike generator callbacks that need to transfer their spikes to the GPU
if (grp_Info[g].spikeGen) {
grp_Info[g].Noffset = NgenFunc;
NgenFunc += grp_Info[g].SizeN;
}
updateSpikesFromGrp(g);
cnt++;
assert(cnt <= numSpikeGenGrps);
}
}
// spikeGenBits can be set only once..
assert(spikeGenBits == NULL);
if (NgenFunc) {
spikeGenBits = new uint32_t[NgenFunc/32+1];
cpuNetPtrs.spikeGenBits = spikeGenBits;
// increase the total memory size used by the routine...
cpuSnnSz.addInfoSize += sizeof(spikeGenBits[0])*(NgenFunc/32+1);
}
}
void CpuSNN::updateSpikeGenerators()
{
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator) {
// This evaluation is done to check if its time to get new set of spikes..
// fprintf(stderr, "[MODE=%s] simtime = %d, NumTimeSlice = %d, SliceUpdate = %d, currTime = %d\n",
// (currentMode==GPU_MODE)?"GPU_MODE":"CPU_MODE", simTime, grp_Info[g].NumTimeSlice,
// grp_Info[g].SliceUpdateTime, grp_Info[g].CurrTimeSlice);
if(((simTime-grp_Info[g].SliceUpdateTime) >= (unsigned) grp_Info[g].CurrTimeSlice))
updateSpikesFromGrp(g);
}
}
}
void CpuSNN::generateSpikesFromFuncPtr(int grpId)
{
bool done;
SpikeGenerator* spikeGen = grp_Info[grpId].spikeGen;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
unsigned int currTime = simTime;
int spikeCnt=0;
for(int i=grp_Info[grpId].StartN;i<=grp_Info[grpId].EndN;i++) {
// start the time from the last time it spiked, that way we can ensure that the refractory period is maintained
unsigned int nextTime = lastSpikeTime[i];
if (nextTime == MAX_SIMULATION_TIME)
nextTime = 0;
done = false;
while (!done) {
nextTime = spikeGen->nextSpikeTime(this, grpId, i-grp_Info[grpId].StartN, nextTime);
// found a valid time window
if (nextTime < (currTime+timeSlice)) {
if (nextTime >= currTime) {
// scheduled spike...
//fprintf(stderr, "scheduled time = %d, nid = %d\n", nextTime, i);
pbuf->scheduleSpikeTargetGroup(i, nextTime-currTime);
spikeCnt++;
}
}
else {
done=true;
}
}
}
}
void CpuSNN::generateSpikesFromRate(int grpId)
{
bool done;
PoissonRate* rate = grp_Info[grpId].RatePtr;
float refPeriod = grp_Info[grpId].RefractPeriod;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
unsigned int currTime = simTime;
int spikeCnt = 0;
if (rate == NULL) return;
if (rate->onGPU) {
printf("specifying rates on the GPU but using the CPU SNN is not supported.\n");
return;
}
const float* ptr = rate->rates;
for (int cnt=0;cnt<rate->len;cnt++,ptr++) {
float frate = *ptr;
unsigned int nextTime = lastSpikeTime[grp_Info[grpId].StartN+cnt]; // start the time from the last time it spiked, that way we can ensure that the refractory period is maintained
if (nextTime == MAX_SIMULATION_TIME)
nextTime = 0;
done = false;
while (!done && frate>0) {
nextTime = poissonSpike (nextTime, frate/1000.0, refPeriod);
// found a valid timeSlice
if (nextTime < (currTime+timeSlice)) {
if (nextTime >= currTime) {
int nid = grp_Info[grpId].StartN+cnt;
pbuf->scheduleSpikeTargetGroup(nid, nextTime-currTime);
spikeCnt++;
}
}
else {
done=true;
}
}
}
}
void CpuSNN::updateSpikesFromGrp(int grpId)
{
assert(grp_Info[grpId].isSpikeGenerator==true);
bool done;
//static FILE* fp = fopen("spikes.txt", "w");
unsigned int currTime = simTime;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
grp_Info[grpId].SliceUpdateTime = simTime;
// we dont generate any poisson spike if during the
// current call we might exceed the maximum 32 bit integer value
if (((uint64_t) currTime + timeSlice) >= MAX_SIMULATION_TIME)
return;
if (grp_Info[grpId].spikeGen) {
generateSpikesFromFuncPtr(grpId);
} else {
// current mode is GPU, and GPU would take care of poisson generators
// and other information about refractor period etc. So no need to continue further...
#if !TESTING_CPU_GPU_POISSON
if(currentMode == GPU_MODE)
return;
#endif
generateSpikesFromRate(grpId);
}
}
inline int CpuSNN::getPoissNeuronPos(int nid)
{
int nPos = nid-numNReg;
assert(nid >= numNReg);
assert(nid < numN);
assert((nid-numNReg) < numNPois);
return nPos;
}
void CpuSNN::setSpikeRate(int grpId, PoissonRate* ratePtr, int refPeriod, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeRate(grpId, ratePtr, refPeriod,c);
} else {
int cGrpId = getGroupId(grpId, configId);
if(grp_Info[cGrpId].RatePtr==NULL) {
fprintf(fpParam, " // refPeriod = %d\n", refPeriod);
}
assert(ratePtr);
if (ratePtr->len != grp_Info[cGrpId].SizeN) {
fprintf(stderr,"The PoissonRate length did not match the number of neurons in group %s(%d).\n", grp_Info2[cGrpId].Name.c_str(),grpId);
assert(0);
}
assert (grp_Info[cGrpId].isSpikeGenerator);
grp_Info[cGrpId].RatePtr = ratePtr;
grp_Info[cGrpId].RefractPeriod = refPeriod;
spikeRateUpdated = true;
}
}
void CpuSNN::setSpikeGenerator(int grpId, SpikeGenerator* spikeGen, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeGenerator(grpId, spikeGen,c);
} else {
int cGrpId = getGroupId(grpId, configId);
assert(spikeGen);
assert (grp_Info[cGrpId].isSpikeGenerator);
grp_Info[cGrpId].spikeGen = spikeGen;
}
}
void CpuSNN::generateSpikes()
{
PropagatedSpikeBuffer::const_iterator srg_iter;
PropagatedSpikeBuffer::const_iterator srg_iter_end = pbuf->endSpikeTargetGroups();
for( srg_iter = pbuf->beginSpikeTargetGroups(); srg_iter != srg_iter_end; ++srg_iter ) {
// Get the target neurons for the given groupId
int nid = srg_iter->stg;
//delaystep_t del = srg_iter->delay;
//generate a spike to all the target neurons from source neuron nid with a delay of del
int g = findGrpId(nid);
addSpikeToTable (nid, g);
//fprintf(stderr, "nid = %d\t", nid);
spikeCountAll1sec++;
nPoissonSpikes++;
}
//fprintf(stderr, "\n");
// advance the time step to the next phase...
pbuf->nextTimeStep();
}
void CpuSNN::setGrpTimeSlice(int grpId, int timeSlice)
{
if (grpId == ALL) {
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator)
setGrpTimeSlice(g, timeSlice);
}
} else {
assert((timeSlice > 0 ) && (timeSlice < PROPOGATED_BUFFER_SIZE));
// the group should be poisson spike generator group
grp_Info[grpId].NewTimeSlice = timeSlice;
grp_Info[grpId].CurrTimeSlice = timeSlice;
}
}
int CpuSNN::addSpikeToTable(int nid, int g)
{
int spikeBufferFull = 0;
lastSpikeTime[nid] = simTime;
curSpike[nid] = true;
nSpikeCnt[nid]++;
if(showLogMode >= 3)
if (nid<128) printf("spiked: %d\n",nid);
if (currentMode == GPU_MODE) {
assert(grp_Info[g].isSpikeGenerator == true);
setSpikeGenBit_GPU(nid, g);
return 0;
}
if (grp_Info[g].WithSTP) {
// implements Mongillo, Barak and Tsodyks model of Short term plasticity
int ind = STP_BUF_POS(nid,simTime);
int ind_1 = STP_BUF_POS(nid,(simTime-1)); // MDR -1 is correct, we use the value before the decay has been applied for the current time step.
stpx[ind] = stpx[ind] - stpu[ind_1]*stpx[ind_1];
stpu[ind] = stpu[ind] + grp_Info[g].STP_U*(1-stpu[ind_1]);
}
if (grp_Info[g].MaxDelay == 1) {
assert(nid < numN);
firingTableD1[secD1fireCnt] = nid;
secD1fireCnt++;
grp_Info[g].FiringCount1sec++;
if (secD1fireCnt >= maxSpikesD1) {
spikeBufferFull = 2;
secD1fireCnt = maxSpikesD1-1;
}
}
else {
assert(nid < numN);
firingTableD2[secD2fireCnt] = nid;
grp_Info[g].FiringCount1sec++;
secD2fireCnt++;
if (secD2fireCnt >= maxSpikesD2) {
spikeBufferFull = 1;
secD2fireCnt = maxSpikesD2-1;
}
}
return spikeBufferFull;
}
void CpuSNN::findFiring()
{
int spikeBufferFull = 0;
for(int g=0; (g < numGrp) & !spikeBufferFull; g++) {
// given group of neurons belong to the poisson group....
if (grp_Info[g].Type&POISSON_NEURON)
continue;
// his flag is set if with_stdp is set and also grpType is set to have GROUP_SYN_FIXED
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
assert(i < numNReg);
if (grp_Info[g].WithConductances) {
gAMPA[i] *= grp_Info[g].dAMPA;
gNMDA[i] *= grp_Info[g].dNMDA;
gGABAa[i] *= grp_Info[g].dGABAa;
gGABAb[i] *= grp_Info[g].dGABAb;
}
if (voltage[i] >= 30.0) {
voltage[i] = Izh_c[i];
recovery[i] += Izh_d[i];
spikeBufferFull = addSpikeToTable(i, g);
if (spikeBufferFull) break;
if (grp_Info[g].WithSTDP) {
int pos_ij = cumulativePre[i];
for(int j=0; j < Npre_plastic[i]; pos_ij++, j++) {
//stdpChanged[pos_ij] = true;
int stdp_tDiff = (simTime-synSpikeTime[pos_ij]);
assert(!((stdp_tDiff < 0) && (synSpikeTime[pos_ij] != MAX_SIMULATION_TIME)));
// don't do LTP if time difference is a lot..
if (stdp_tDiff > 0)
#ifdef INHIBITORY_STDP
// if this is an excitatory or inhibitory synapse
if (maxSynWt[pos_ij] >= 0)
#endif
if ((stdp_tDiff*grp_Info[g].TAU_LTP_INV)<25)
wtChange[pos_ij] += STDP(stdp_tDiff, grp_Info[g].ALPHA_LTP, grp_Info[g].TAU_LTP_INV);
#ifdef INHIBITORY_STDP
else
if ((stdp_tDiff > 0) && ((stdp_tDiff*grp_Info[g].TAU_LTD_INV)<25))
wtChange[pos_ij] -= (STDP(stdp_tDiff, grp_Info[g].ALPHA_LTP, grp_Info[g].TAU_LTP_INV) - STDP(stdp_tDiff, grp_Info[g].ALPHA_LTD*1.5, grp_Info[g].TAU_LTD_INV));
#endif
}
}
spikeCountAll1sec++;
}
}
}
}
void CpuSNN::doSTPUpdates()
{
int spikeBufferFull = 0;
//decay the STP variables before adding new spikes.
for(int g=0; (g < numGrp) & !spikeBufferFull; g++) {
if (grp_Info[g].WithSTP) {
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
int ind = 0, ind_1 = 0;
ind = STP_BUF_POS(i,simTime);
ind_1 = STP_BUF_POS(i,(simTime-1));
stpx[ind] = stpx[ind_1] + (1-stpx[ind_1])/grp_Info[g].STP_tD;
stpu[ind] = stpu[ind_1] + (grp_Info[g].STP_U - stpu[ind_1])/grp_Info[g].STP_tF;
}
}
}
}
void CpuSNN::doSnnSim()
{
doSTPUpdates();
//return;
updateSpikeGenerators();
//generate all the scheduled spikes from the spikeBuffer..
generateSpikes();
if(0) fprintf(fpProgLog, "\nLTP time=%d, \n", simTime);
// find the neurons that has fired..
findFiring();
timeTableD2[simTimeMs+D+1] = secD2fireCnt;
timeTableD1[simTimeMs+D+1] = secD1fireCnt;
if(0) fprintf(fpProgLog, "\nLTD time=%d,\n", simTime);
doD2CurrentUpdate();
doD1CurrentUpdate();
globalStateUpdate();
updateMonitors();
return;
}
void CpuSNN::swapConnections(int nid, int oldPos, int newPos)
{
int cumN=cumulativePost[nid];
// Put the node oldPos to the top of the delay queue
post_info_t tmp = postSynapticIds[cumN+oldPos];
postSynapticIds[cumN+oldPos]= postSynapticIds[cumN+newPos];
postSynapticIds[cumN+newPos]= tmp;
// Ensure that you have shifted the delay accordingly....
uint8_t tmp_delay = tmp_SynapticDelay[cumN+oldPos];
tmp_SynapticDelay[cumN+oldPos] = tmp_SynapticDelay[cumN+newPos];
tmp_SynapticDelay[cumN+newPos] = tmp_delay;
// update the pre-information for the postsynaptic neuron at the position oldPos.
post_info_t postInfo = postSynapticIds[cumN+oldPos];
int post_nid = GET_CONN_NEURON_ID(postInfo);
int post_sid = GET_CONN_SYN_ID(postInfo);
post_info_t* preId = &preSynapticIds[cumulativePre[post_nid]+post_sid];
int pre_nid = GET_CONN_NEURON_ID((*preId));
int pre_sid = GET_CONN_SYN_ID((*preId));
int pre_gid = GET_CONN_GRP_ID((*preId));
assert (pre_nid == nid);
assert (pre_sid == newPos);
*preId = SET_CONN_ID( pre_nid, oldPos, pre_gid);
// update the pre-information for the postsynaptic neuron at the position newPos
postInfo = postSynapticIds[cumN+newPos];
post_nid = GET_CONN_NEURON_ID(postInfo);
post_sid = GET_CONN_SYN_ID(postInfo);
preId = &preSynapticIds[cumulativePre[post_nid]+post_sid];
pre_nid = GET_CONN_NEURON_ID((*preId));
pre_sid = GET_CONN_SYN_ID((*preId));
pre_gid = GET_CONN_GRP_ID((*preId));
assert (pre_nid == nid);
assert (pre_sid == oldPos);
*preId = SET_CONN_ID( pre_nid, newPos, pre_gid);
}
// The post synaptic connections are sorted based on delay here so that we can reduce storage requirement
// and generation of spike at the post-synaptic side.
// We also create the delay_info array has the delay_start and delay_length parameter
void CpuSNN::reorganizeDelay()
{
for(int grpId=0; grpId < numGrp; grpId++) {
for(int nid=grp_Info[grpId].StartN; nid <= grp_Info[grpId].EndN; nid++) {
int jPos=0; // this points to the top of the delay queue
int cumN=cumulativePost[nid];
int cumDelayStart=0;
for(int td = 0; td < D; td++) {
int j=jPos; // start searching from top of the queue until the end
int cnt=0; // store the number of nodes with a delay of td;
while(j < Npost[nid]) {
// found a node j with delay=td and we put
// the delay value = 1 at array location td=0;
if(td==(tmp_SynapticDelay[cumN+j]-1)) {
assert(jPos<Npost[nid]);
swapConnections(nid, j, jPos);
jPos=jPos+1;
cnt=cnt+1;
}
j=j+1;
}
// update the delay_length and start values...
postDelayInfo[nid*(D+1)+td].delay_length = cnt;
postDelayInfo[nid*(D+1)+td].delay_index_start = cumDelayStart;
cumDelayStart += cnt;
assert(cumDelayStart <= Npost[nid]);
}
//total cumulative delay should be equal to number of post-synaptic connections at the end of the loop
assert(cumDelayStart == Npost[nid]);
for( int j=1; j < Npost[nid]; j++) {
int cumN=cumulativePost[nid];
if( tmp_SynapticDelay[cumN+j] < tmp_SynapticDelay[cumN+j-1]) {
fprintf(stderr, "Post-synaptic delays not sorted corrected...\n");
fprintf(stderr, "id=%d, delay[%d]=%d, delay[%d]=%d\n",
nid, j, tmp_SynapticDelay[cumN+j], j-1, tmp_SynapticDelay[cumN+j-1]);
assert( tmp_SynapticDelay[cumN+j] >= tmp_SynapticDelay[cumN+j-1]);
}
}
}
}
}
char* extractFileName(char *fname)
{
char* varname = strrchr(fname, '\\');
size_t len1 = strlen(varname+1);
char* extname = strchr(varname, '.');
size_t len2 = strlen(extname);
varname[len1-len2]='\0';
return (varname+1);
}
#define COMPACTION_ALIGNMENT_PRE 16
#define COMPACTION_ALIGNMENT_POST 0
#define SETPOST_INFO(name, nid, sid, val) name[cumulativePost[nid]+sid]=val;
#define SETPRE_INFO(name, nid, sid, val) name[cumulativePre[nid]+sid]=val;
// initialize all the synaptic weights to appropriate values..
// total size of the synaptic connection is 'length' ...
void CpuSNN::initSynapticWeights()
{
// Initialize the network wtChange, wt, synaptic firing time
wtChange = new float[preSynCnt];
synSpikeTime = new uint32_t[preSynCnt];
// memset(synSpikeTime,0,sizeof(uint32_t)*preSynCnt);
cpuSnnSz.synapticInfoSize = sizeof(float)*(preSynCnt*2);
resetSynapticConnections(false);
}
// We parallelly cleanup the postSynapticIds array to minimize any other wastage in that array by compacting the store
// Appropriate alignment specified by ALIGN_COMPACTION macro is used to ensure some level of alignment (if necessary)
void CpuSNN::compactConnections()
{
unsigned int* tmp_cumulativePost = new unsigned int[numN];
unsigned int* tmp_cumulativePre = new unsigned int[numN];
unsigned int lastCnt_pre = 0;
unsigned int lastCnt_post = 0;
tmp_cumulativePost[0] = 0;
tmp_cumulativePre[0] = 0;
for(int i=1; i < numN; i++) {
lastCnt_post = tmp_cumulativePost[i-1]+Npost[i-1]; //position of last pointer
lastCnt_pre = tmp_cumulativePre[i-1]+Npre[i-1]; //position of last pointer
#if COMPACTION_ALIGNMENT_POST
lastCnt_post= lastCnt_post + COMPACTION_ALIGNMENT_POST-lastCnt_post%COMPACTION_ALIGNMENT_POST;
lastCnt_pre = lastCnt_pre + COMPACTION_ALIGNMENT_PRE- lastCnt_pre%COMPACTION_ALIGNMENT_PRE;
#endif
tmp_cumulativePost[i] = lastCnt_post;
tmp_cumulativePre[i] = lastCnt_pre;
assert(tmp_cumulativePost[i] <= cumulativePost[i]);
assert(tmp_cumulativePre[i] <= cumulativePre[i]);
}
// compress the post_synaptic array according to the new values of the tmp_cumulative counts....
unsigned int tmp_postSynCnt = tmp_cumulativePost[numN-1]+Npost[numN-1];
unsigned int tmp_preSynCnt = tmp_cumulativePre[numN-1]+Npre[numN-1];
assert(tmp_postSynCnt <= allocatedPost);
assert(tmp_preSynCnt <= allocatedPre);
assert(tmp_postSynCnt <= postSynCnt);
assert(tmp_preSynCnt <= preSynCnt);
fprintf(fpLog, "******************\n");
fprintf(fpLog, "CompactConnection: \n");
fprintf(fpLog, "******************\n");
fprintf(fpLog, "old_postCnt = %d, new_postCnt = %d\n", postSynCnt, tmp_postSynCnt);
fprintf(fpLog, "old_preCnt = %d, new_postCnt = %d\n", preSynCnt, tmp_preSynCnt);
// new buffer with required size + 100 bytes of additional space just to provide limited overflow
post_info_t* tmp_postSynapticIds = new post_info_t[tmp_postSynCnt+100];
// new buffer with required size + 100 bytes of additional space just to provide limited overflow
post_info_t* tmp_preSynapticIds = new post_info_t[tmp_preSynCnt+100];
float* tmp_wt = new float[tmp_preSynCnt+100];
float* tmp_maxSynWt = new float[tmp_preSynCnt+100];
for(int i=0; i < numN; i++) {
assert(tmp_cumulativePost[i] <= cumulativePost[i]);
assert(tmp_cumulativePre[i] <= cumulativePre[i]);
for( int j=0; j < Npost[i]; j++) {
unsigned int tmpPos = tmp_cumulativePost[i]+j;
unsigned int oldPos = cumulativePost[i]+j;
tmp_postSynapticIds[tmpPos] = postSynapticIds[oldPos];
tmp_SynapticDelay[tmpPos] = tmp_SynapticDelay[oldPos];
}
for( int j=0; j < Npre[i]; j++) {
unsigned int tmpPos = tmp_cumulativePre[i]+j;
unsigned int oldPos = cumulativePre[i]+j;
tmp_preSynapticIds[tmpPos] = preSynapticIds[oldPos];
tmp_maxSynWt[tmpPos] = maxSynWt[oldPos];
tmp_wt[tmpPos] = wt[oldPos];
}
}
// delete old buffer space
delete[] postSynapticIds;
postSynapticIds = tmp_postSynapticIds;
cpuSnnSz.networkInfoSize -= (sizeof(post_info_t)*postSynCnt);
cpuSnnSz.networkInfoSize += (sizeof(post_info_t)*(tmp_postSynCnt+100));
delete[] cumulativePost;
cumulativePost = tmp_cumulativePost;
delete[] cumulativePre;
cumulativePre = tmp_cumulativePre;
delete[] maxSynWt;
maxSynWt = tmp_maxSynWt;
cpuSnnSz.synapticInfoSize -= (sizeof(float)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(int)*(tmp_preSynCnt+100));
delete[] wt;
wt = tmp_wt;
cpuSnnSz.synapticInfoSize -= (sizeof(float)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(int)*(tmp_preSynCnt+100));
delete[] preSynapticIds;
preSynapticIds = tmp_preSynapticIds;
cpuSnnSz.synapticInfoSize -= (sizeof(post_info_t)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(post_info_t)*(tmp_preSynCnt+100));
preSynCnt = tmp_preSynCnt;
postSynCnt = tmp_postSynCnt;
}
void CpuSNN::updateParameters(int* curN, int* numPostSynapses, int* numPreSynapses, int nConfig)
{
assert(nConfig > 0);
numNExcPois = 0; numNInhPois = 0; numNExcReg = 0; numNInhReg = 0;
*numPostSynapses = 0; *numPreSynapses = 0;
// scan all the groups and find the required information
// about the group (numN, numPostSynapses, numPreSynapses and others).
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].Type==UNKNOWN_NEURON) {
fprintf(stderr, "Unknown group for %d (%s)\n", g, grp_Info2[g].Name.c_str());
exitSimulation(1);
}
if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON))
numNInhReg += grp_Info[g].SizeN;
else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON))
numNExcReg += grp_Info[g].SizeN;
else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON))
numNExcPois += grp_Info[g].SizeN;
else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON))
numNInhPois += grp_Info[g].SizeN;
// find the values for maximum postsynaptic length
// and maximum pre-synaptic length
if (grp_Info[g].numPostSynapses >= *numPostSynapses)
*numPostSynapses = grp_Info[g].numPostSynapses;
if (grp_Info[g].numPreSynapses >= *numPreSynapses)
*numPreSynapses = grp_Info[g].numPreSynapses;
}
*curN = numNExcReg + numNInhReg + numNExcPois + numNInhPois;
numNPois = numNExcPois + numNInhPois;
numNReg = numNExcReg +numNInhReg;
}
void CpuSNN::resetSynapticConnections(bool changeWeights)
{
int j;
// Reset wt,wtChange,pre-firingtime values to default values...
for(int destGrp=0; destGrp < numGrp; destGrp++) {
const char* updateStr = (grp_Info[destGrp].newUpdates == true)?"(**)":"";
fprintf(stdout, "Grp: %d:%s s=%d e=%d %s\n", destGrp, grp_Info2[destGrp].Name.c_str(), grp_Info[destGrp].StartN, grp_Info[destGrp].EndN, updateStr);
fprintf(fpLog, "Grp: %d:%s s=%d e=%d %s\n", destGrp, grp_Info2[destGrp].Name.c_str(), grp_Info[destGrp].StartN, grp_Info[destGrp].EndN, updateStr);
for(int nid=grp_Info[destGrp].StartN; nid <= grp_Info[destGrp].EndN; nid++) {
int offset = cumulativePre[nid];
for (j=0;j<Npre[nid]; j++) wtChange[offset+j] = 0.0; // synaptic derivatives is reset
for (j=0;j<Npre[nid]; j++) synSpikeTime[offset+j] = MAX_SIMULATION_TIME; // some large negative value..
post_info_t *preIdPtr = &preSynapticIds[cumulativePre[nid]];
float* synWtPtr = &wt[cumulativePre[nid]];
float* maxWtPtr = &maxSynWt[cumulativePre[nid]];
int prevPreGrp = -1;
/* MDR -- this code no longer works because grpConnInfo is no longer used/defined
for (j=0; j < Npre[nid]; j++,preIdPtr++, synWtPtr++, maxWtPtr++) {
int preId = GET_CONN_NEURON_ID((*preIdPtr));
assert(preId < numN);
int srcGrp = findGrpId(preId);
grpConnectInfo_t* connInfo = grpConnInfo[srcGrp][destGrp];
assert(connInfo != NULL);
int connProp = connInfo->connProp;
bool synWtType = GET_FIXED_PLASTIC(connProp);
if ( j >= Npre_plastic[nid] ) {
// if the j is greater than Npre_plastic it means the
// connection should be fixed type..
//MDR unfortunately, for user defined connections, this check is not valid if they have a mixture of fixed and plastic
//MDR assert(synWtType == SYN_FIXED);
}
// print debug information...
if( prevPreGrp != srcGrp) {
if(nid==grp_Info[destGrp].StartN) {
const char* updateStr = (connInfo->newUpdates==true)? "(**)":"";
fprintf(stdout, "\t%d (%s) start=%d, type=%s maxWts = %f %s\n", srcGrp,
grp_Info2[srcGrp].Name.c_str(), j, (j<Npre_plastic[nid]?"P":"F"), connInfo->maxWt, updateStr);
fprintf(fpLog, "\t%d (%s) start=%d, type=%s maxWts = %f %s\n", srcGrp,
grp_Info2[srcGrp].Name.c_str(), j, (j<Npre_plastic[nid]?"P":"F"), connInfo->maxWt, updateStr);
}
prevPreGrp = srcGrp;
}
if(!changeWeights)
continue;
// if connection was of plastic type or if the connection weights were updated we need to reset the weights..
// TODO: How to account for user-defined connection reset...
if ((synWtType == SYN_PLASTIC) || connInfo->newUpdates) {
*synWtPtr = getWeights(connInfo->connProp, connInfo->initWt, connInfo->maxWt, nid, srcGrp);
*maxWtPtr = connInfo->maxWt;
}
}
*/
}
grp_Info[destGrp].newUpdates = false;
}
grpConnectInfo_t* connInfo = connectBegin;
// clear all existing connection info...
while (connInfo) {
connInfo->newUpdates = false;
connInfo = connInfo->next;
}
}
void CpuSNN::resetGroups()
{
for(int g=0; (g < numGrp); g++) {
// reset spike generator group...
if (grp_Info[g].isSpikeGenerator) {
grp_Info[g].CurrTimeSlice = grp_Info[g].NewTimeSlice;
grp_Info[g].SliceUpdateTime = 0;
for(int nid=grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++)
resetPoissonNeuron(nid, g);
}
// reset regular neuron group...
else {
for(int nid=grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++)
resetNeuron(nid, g);
}
}
// reset the currents for each neuron
resetCurrent();
// reset the conductances...
resetConductances();
// reset various counters in the group...
resetCounters();
}
void CpuSNN::resetFiringInformation()
{
// Reset firing tables and time tables to default values..
// reset Various Times..
spikeCountAll = 0;
spikeCountAll1sec = 0;
spikeCountD2 = 0;
spikeCountD1 = 0;
secD1fireCnt = 0;
secD2fireCnt = 0;
for(int i=0; i < numGrp; i++) {
grp_Info[i].FiringCount1sec = 0;
}
// reset various times...
simTimeMs = 0;
simTimeSec = 0;
simTime = 0;
// reset the propogation Buffer.
resetPropogationBuffer();
// reset Timing Table..
resetTimingTable();
}
void CpuSNN::printTuningLog()
{
if (fpTuningLog) {
fprintf(fpTuningLog, "Generating Tuning log %d\n", cntTuning);
printParameters(fpTuningLog);
cntTuning++;
}
}
// after all the initalization. Its time to create the synaptic weights, weight change and also
// time of firing these are the mostly costly arrays so dense packing is essential to minimize wastage of space
void CpuSNN::reorganizeNetwork(bool removeTempMemory, int simType)
{
//Double check...sometimes by mistake we might call reorganize network again...
if(doneReorganization)
return;
fprintf(stdout, "Beginning reorganization of network....\n");
// time to build the complete network with relevant parameters..
buildNetwork();
//..minimize any other wastage in that array by compacting the store
compactConnections();
// The post synaptic connections are sorted based on delay here
reorganizeDelay();
// Print statistics of the memory used to stdout...
printMemoryInfo();
// Print the statistics again but dump the results to a file
printMemoryInfo(fpLog);
// initialize the synaptic weights accordingly..
initSynapticWeights();
//not of much use currently
// updateRandomProperty();
updateSpikeGeneratorsInit();
//ensure that we dont do all the above optimizations again
doneReorganization = true;
//printParameters(fpParam);
printParameters(fpLog);
printTuningLog();
makePtrInfo();
// if our initial operating mode is GPU_MODE, then it is time to
// allocate necessary data within the GPU
// assert(simType != GPU_MODE || cpu_gpuNetPtrs.allocated);
// if(netInitMode==GPU_MODE)
// allocateSNN_GPU();
if(simType==GPU_MODE)
fprintf(stdout, "Starting GPU-SNN Simulations ....\n");
else
fprintf(stdout, "Starting CPU-SNN Simulations ....\n");
FILE* fconn = NULL;
#if TESTING
if (simType == GPU_MODE)
fconn = fopen("gpu_conn.txt", "w");
else
fconn = fopen("conn.txt", "w");
//printCheckDetailedInfo(fconn);
#endif
#if 0
printPostConnection(fconn);
printPreConnection(fconn);
#endif
//printNetworkInfo();
printDotty();
#if TESTING
fclose(fconn);
#endif
if(removeTempMemory) {
memoryOptimized = true;
delete[] tmp_SynapticDelay;
tmp_SynapticDelay = NULL;
}
}
void CpuSNN::setDefaultParameters(float alpha_ltp, float tau_ltp, float alpha_ltd, float tau_ltd)
{
printf("Warning: setDefaultParameters() is deprecated and may be removed in the future.\nIt is recommended that you set the desired parameters explicitly.\n");
#define DEFAULT_COND_tAMPA 5.0
#define DEFAULT_COND_tNMDA 150.0
#define DEFAULT_COND_tGABAa 6.0
#define DEFAULT_COND_tGABAb 150.0
#define DEFAULT_STP_U_Inh 0.5
#define DEFAULT_STP_tD_Inh 800
#define DEFAULT_STP_tF_Inh 1000
#define DEFAULT_STP_U_Exc 0.2
#define DEFAULT_STP_tD_Exc 700
#define DEFAULT_STP_tF_Exc 20
// setup the conductance parameter for the given network
setConductances(ALL, true, DEFAULT_COND_tAMPA, DEFAULT_COND_tNMDA, DEFAULT_COND_tGABAa, DEFAULT_COND_tGABAb);
// setting the STP values for different groups...
for(int g=0; g < getNumGroups(); g++) {
// default STDP is set to false for all groups..
setSTDP(g, false);
// setup the excitatory group properties here..
if(isExcitatoryGroup(g)) {
setSTP(g, true, DEFAULT_STP_U_Exc, DEFAULT_STP_tD_Exc, DEFAULT_STP_tF_Exc);
if ((alpha_ltp!=0.0) && (!isPoissonGroup(g)))
setSTDP(g, true, alpha_ltp, tau_ltp, alpha_ltd, tau_ltd);
}
else {
setSTP(g, true, DEFAULT_STP_U_Inh, DEFAULT_STP_tD_Inh, DEFAULT_STP_tF_Inh);
}
}
}
#if ! (_WIN32 || _WIN64)
#include <string.h>
#define strcmpi(s1,s2) strcasecmp(s1,s2)
#endif
#define PROBE_CURRENT (1 << 1)
#define PROBE_VOLTAGE (1 << 2)
#define PROBE_FIRING_RATE (1 << 3)
void CpuSNN::setProbe(int g, const string& type, int startId, int cnt, uint32_t _printProbe)
{
int endId;
assert(startId >= 0);
assert(startId <= grp_Info[g].SizeN);
//assert(cnt!=0);
int i=grp_Info[g].StartN+startId;
if (cnt<=0)
endId = grp_Info[g].EndN;
else
endId = i + cnt - 1;
if(endId > grp_Info[g].EndN)
endId = grp_Info[g].EndN;
for(; i <= endId; i++) {
probeParam_t* n = new probeParam_t;
memset(n, 0, sizeof(probeParam_t));
n->next = neuronProbe;
if(type.find("current") != string::npos) {
n->type |= PROBE_CURRENT;
n->bufferI = new float[1000];
cpuSnnSz.probeInfoSize += sizeof(float)*1000;
}
if(type.find("voltage") != string::npos) {
n->type |= PROBE_VOLTAGE;
n->bufferV = new float[1000];
cpuSnnSz.probeInfoSize += sizeof(float)*1000;
}
if(type.find("firing-rate") != string::npos) {
n->type |= PROBE_FIRING_RATE;
n->spikeBins = new bool[1000];
n->bufferFRate = new float[1000];
cpuSnnSz.probeInfoSize += (sizeof(float)+sizeof(bool))*1000;
n->cumCount = 0;
}
n->vmax = 40.0; n->vmin = -80.0;
n->imax = 50.0; n->imin = -50.0;
n->debugCnt = 0;
n->printProbe = _printProbe;
n->nid = i;
neuronProbe = n;
numProbe++;
}
}
void CpuSNN::updateMonitors()
{
int cnt=0;
probeParam_t* n = neuronProbe;
while(n) {
int nid = n->nid;
if(n->printProbe) {
// if there is an input inhspike or excSpike or curSpike then display values..
//if( I[nid] != 0 ) {
/* FIXME
MDR I broke this because I removed inhSpikes and excSpikes because they are incorrectly named...
if (inhSpikes[nid] || excSpikes[nid] || curSpike[nid] || (n->debugCnt++ > n->printProbe)) {
fprintf(stderr, "[t=%d, n=%d] voltage=%3.3f current=%3.3f ", simTime, nid, voltage[nid], current[nid]);
//FIXME should check to see if conductances are enabled for this group
if (true) {
fprintf(stderr, " ampa=%3.4f nmda=%3.4f gabaA=%3.4f gabaB=%3.4f ",
gAMPA[nid], gNMDA[nid], gGABAa[nid], gGABAb[nid]);
}
fprintf(stderr, " +Spike=%d ", excSpikes[nid]);
if (inhSpikes[nid])
fprintf(stderr, " -Spike=%d ", inhSpikes[nid]);
if (curSpike[nid])
fprintf(stderr, " | ");
fprintf(stderr, "\n");
if(n->debugCnt > n->printProbe) {
n->debugCnt = 0;
}
}
*/
}
if (n->type & PROBE_CURRENT)
n->bufferI[simTimeMs] = current[nid];
if (n->type & PROBE_VOLTAGE)
n->bufferV[simTimeMs] = voltage[nid];
#define NUM_BIN 256
#define BIN_SIZE 0.001 /* 1ms bin size */
if (n->type & PROBE_FIRING_RATE) {
int oldSpike = 0;
if (simTime >= NUM_BIN)
oldSpike = n->spikeBins[simTimeMs%NUM_BIN];
int newSpike = (voltage[nid] >= 30.0 ) ? 1 : 0;
n->cumCount = n->cumCount - oldSpike + newSpike;
float frate = n->cumCount/(NUM_BIN*BIN_SIZE);
n->spikeBins[simTimeMs % NUM_BIN] = newSpike;
if (simTime >= NUM_BIN)
n->bufferFRate[(simTime-NUM_BIN)%1000] = frate;
}
n=n->next;
cnt++;
}
//fclose(fp);
// ensure that we checked all the nodes in the list
assert(cnt==numProbe);
}
class WriteSpikeToFile: public SpikeMonitor {
public:
WriteSpikeToFile(FILE* _fid) {
fid = _fid;
}
void update(CpuSNN* s, int grpId, unsigned int* Nids, unsigned int* timeCnts)
{
int pos = 0;
for (int t=0; t < 1000; t++) {
for(int i=0; i<timeCnts[t];i++,pos++) {
int time = t + s->getSimTime() - 1000;
int id = Nids[pos];
int cnt = fwrite(&time,sizeof(int),1,fid);
assert(cnt != 0);
cnt = fwrite(&id,sizeof(int),1,fid);
assert(cnt != 0);
}
}
fflush(fid);
}
FILE* fid;
};
void CpuSNN::setSpikeMonitor(int gid, const string& fname, int configId) {
FILE* fid = fopen(fname.c_str(),"wb");
assert(configId != ALL);
setSpikeMonitor(gid, new WriteSpikeToFile(fid), configId);
}
void CpuSNN::setSpikeMonitor(int grpId, SpikeMonitor* spikeMon, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeMonitor(grpId, spikeMon,c);
} else {
int cGrpId = getGroupId(grpId, configId);
DBG(2, fpLog, AT, "spikeMonitor Added");
// store the gid for further reference
monGrpId[numSpikeMonitor] = cGrpId;
// also inform the grp that it is being monitored...
grp_Info[cGrpId].MonitorId = numSpikeMonitor;
float maxRate = grp_Info[cGrpId].MaxFiringRate;
// count the size of the buffer for storing 1 sec worth of info..
// only the last second is stored in this buffer...
int buffSize = (int)(maxRate*grp_Info[cGrpId].SizeN);
// store the size for future comparison etc.
monBufferSize[numSpikeMonitor] = buffSize;
// reset the position of the buffer pointer..
monBufferPos[numSpikeMonitor] = 0;
monBufferCallback[numSpikeMonitor] = spikeMon;
// create the new buffer for keeping track of all the spikes in the system
monBufferFiring[numSpikeMonitor] = new unsigned int[buffSize];
monBufferTimeCnt[numSpikeMonitor]= new unsigned int[1000];
memset(monBufferTimeCnt[numSpikeMonitor],0,sizeof(int)*(1000));
numSpikeMonitor++;
// oh. finally update the size info that will be useful to see
// how much memory are we eating...
cpuSnnSz.monitorInfoSize += sizeof(int)*buffSize;
cpuSnnSz.monitorInfoSize += sizeof(int)*(1000);
}
}
void CpuSNN::updateSpikeMonitor()
{
// dont continue if numSpikeMonitor is zero
if(numSpikeMonitor==0)
return;
bool bufferOverFlow[MAX_GRP_PER_SNN];
memset(bufferOverFlow,0,sizeof(bufferOverFlow));
/* Reset buffer time counter */
for(int i=0; i < numSpikeMonitor; i++)
memset(monBufferTimeCnt[i],0,sizeof(int)*(1000));
/* Reset buffer position */
memset(monBufferPos,0,sizeof(int)*numSpikeMonitor);
if(currentMode == GPU_MODE) {
updateSpikeMonitor_GPU();
}
/* Read one spike at a time from the buffer and
put the spikes to an appopriate monitor buffer.
Later the user may need need to dump these spikes
to an output file */
for(int k=0; k < 2; k++) {
unsigned int* timeTablePtr = (k==0)?timeTableD2:timeTableD1;
unsigned int* fireTablePtr = (k==0)?firingTableD2:firingTableD1;
for(int t=0; t < 1000; t++) {
for(int i=timeTablePtr[t+D]; i<timeTablePtr[t+D+1];i++) {
/* retrieve the neuron id */
int nid = fireTablePtr[i];
if (currentMode == GPU_MODE)
nid = GET_FIRING_TABLE_NID(nid);
//fprintf(fpLog, "%d %d \n", t, nid);
assert(nid < numN);
int grpId = findGrpId(nid);
int monitorId = grp_Info[grpId].MonitorId;
if(monitorId!= -1) {
assert(nid >= grp_Info[grpId].StartN);
assert(nid <= grp_Info[grpId].EndN);
int pos = monBufferPos[monitorId];
if((pos >= monBufferSize[monitorId]))
{
if(!bufferOverFlow[monitorId])
fprintf(stderr, "Buffer Monitor size (%d) is small. Increase buffer firing rate for %s\n", monBufferSize[monitorId], grp_Info2[grpId].Name.c_str());
bufferOverFlow[monitorId] = true;
}
else {
monBufferPos[monitorId]++;
monBufferFiring[monitorId][pos] = nid-grp_Info[grpId].StartN; // store the Neuron ID relative to the start of the group
// we store the total firing at time t...
monBufferTimeCnt[monitorId][t]++;
}
} /* if monitoring is enabled for this spike */
} /* for all spikes happening at time t */
} /* for all time t */
}
for (int grpId=0;grpId<numGrp;grpId++) {
int monitorId = grp_Info[grpId].MonitorId;
if(monitorId!= -1) {
fprintf(stderr, "Spike Monitor for Group %s has %d spikes (%f Hz)\n",grp_Info2[grpId].Name.c_str(),monBufferPos[monitorId],((float)monBufferPos[monitorId])/(grp_Info[grpId].SizeN));
// call the callback function
if (monBufferCallback[monitorId])
monBufferCallback[monitorId]->update(this,grpId,monBufferFiring[monitorId],monBufferTimeCnt[monitorId]);
}
}
}
/* MDR -- DEPRECATED
void CpuSNN::initThalInput()
{
DBG(2, fpLog, AT, "initThalInput()");
#define I_EXPONENTIAL_DECAY 5.0f
// reset thalamic currents here..
//KILLME NOW
//resetCurrent();
resetCounters();
// first we do the initial simulation corresponding to the random number generator
int randCnt=0;
//fprintf(stderr, "Thalamic inputs: ");
for (int i=0; i < numNoise; i++)
{
float currentStrength = noiseGenGroup[i].currentStrength;
int ncount = noiseGenGroup[i].ncount;
int nstart = noiseGenGroup[i].nstart;
int nrands = noiseGenGroup[i].rand_ncount;
assert(ncount > 0);
assert(nstart >= 0);
assert(nrands > 0);
for(int j=0; j < nrands; j++,randCnt++) {
int rneuron = nstart + (int)(ncount*getRand());
randNeuronId[randCnt]= rneuron;
// assuming there is only one driver at a time.
// More than one noise input is not correct...
current[rneuron] = currentStrength;
//fprintf(stderr, " %d ", rneuron);
}
}
//fprintf(stderr, "\n");
}
// This would supply the required random current to the specific percentage of neurons. If groupId=-1,
// then the neuron is picked from the full population.
// If the groupId=n, then only neurons are picked from selected group n.
void CpuSNN::randomNoiseCurrent(float neuronPercentage, float currentStrength, int groupId)
{
DBG(2, fpLog, AT, "randomNoiseCurrent() added");
int numNeuron = ((groupId==-1)? -1: grp_Info[groupId].SizeN);
int nstart = ((groupId==-1)? -1: grp_Info[groupId].StartN);
noiseGenGroup[numNoise].groupId = groupId;
noiseGenGroup[numNoise].currentStrength = currentStrength;
noiseGenGroup[numNoise].neuronPercentage = neuronPercentage;
noiseGenGroup[numNoise].ncount = numNeuron;
noiseGenGroup[numNoise].nstart = nstart;
noiseGenGroup[numNoise].rand_ncount = (int)(numNeuron*(neuronPercentage/100.0));
if(noiseGenGroup[numNoise].rand_ncount<=0)
noiseGenGroup[numNoise].rand_ncount = 1;
numNoise++;
// i have already reorganized the network. hence it is important to update the random neuron property..
if (doneReorganization == true)
updateRandomProperty();
}
// we calculate global properties like how many random number need to be generated
//each cycle, etc
void CpuSNN::updateRandomProperty()
{
numRandNeurons = 0;
for (int i=0; i < numNoise; i++) {
// paramters for few noise generator has not been updated...update now !!!
if(noiseGenGroup[i].groupId == -1) {
int numNeuron = numNReg;
int nstart = 0;
noiseGenGroup[i].groupId = -1;
int neuronPercentage = noiseGenGroup[i].neuronPercentage;
noiseGenGroup[i].ncount = numNeuron;
noiseGenGroup[i].nstart = nstart;
noiseGenGroup[i].rand_ncount = (int)(numNeuron*(neuronPercentage/100.0));
if(noiseGenGroup[i].rand_ncount<=0)
noiseGenGroup[i].rand_ncount = 1;
}
// update the number of random counts...
numRandNeurons += noiseGenGroup[i].rand_ncount;
}
assert(numRandNeurons>=0);
}
*/
fixed several INT overflow issues in CpuSNN::reorganizeDelay(). This is not over yet!! See the Wiki page for more info.
//
// Copyright (c) 2011 Regents of the University of California. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. The names of its contributors may not 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 "snn.h"
#include <sstream>
#if (_WIN32 || _WIN64)
#include <float.h>
#include <time.h>
#ifndef isnan
#define isnan(x) _isnan(x)
#endif
#ifndef isinf
#define isinf(x) (!_finite(x))
#endif
#ifndef srand48
#define srand48(x) srand(x)
#endif
#ifndef drand48
#define drand48() (double(rand())/RAND_MAX)
#endif
#else
#include <string.h>
#define strcmpi(s1,s2) strcasecmp(s1,s2)
#endif
// includes, project
#include <cutil.h>
MTRand_closed getRandClosed;
MTRand getRand;
RNG_rand48* gpuRand48 = NULL;
/*********************************************/
void CpuSNN::resetPointers()
{
voltage = NULL;
recovery = NULL;
Izh_a = NULL;
Izh_b = NULL;
Izh_c = NULL;
Izh_d = NULL;
current = NULL;
Npre = NULL;
Npost = NULL;
lastSpikeTime = NULL;
postSynapticIds = NULL;
postDelayInfo = NULL;
wt = NULL;
maxSynWt = NULL;
wtChange = NULL;
//stdpChanged = NULL;
synSpikeTime = NULL;
spikeGenBits = NULL;
firingTableD2 = NULL;
firingTableD1 = NULL;
fpParam = NULL;
fpLog = NULL;
fpProgLog = stderr;
fpTuningLog = NULL;
cntTuning = 0;
}
void CpuSNN::resetCurrent()
{
assert(current != NULL);
memset(current, 0, sizeof(float)*numNReg);
}
void CpuSNN::resetCounters()
{
assert(numNReg <= numN);
memset( curSpike, 0, sizeof(bool)*numN);
}
void CpuSNN::resetConductances()
{
if (sim_with_conductances) {
assert(gAMPA != NULL);
memset(gAMPA, 0, sizeof(float)*numNReg);
memset(gNMDA, 0, sizeof(float)*numNReg);
memset(gGABAa, 0, sizeof(float)*numNReg);
memset(gGABAb, 0, sizeof(float)*numNReg);
}
}
void CpuSNN::resetTimingTable()
{
memset(timeTableD2, 0, sizeof(int)*(1000+D+1));
memset(timeTableD1, 0, sizeof(int)*(1000+D+1));
}
void CpuSNN::CpuSNNInit(unsigned int _numN, unsigned int _numPostSynapses, unsigned int _numPreSynapses, unsigned int _D)
{
numN = _numN;
numPostSynapses = _numPostSynapses;
D = _D;
numPreSynapses = _numPreSynapses;
voltage = new float[numNReg];
recovery = new float[numNReg];
Izh_a = new float[numNReg];
Izh_b = new float[numNReg];
Izh_c = new float[numNReg];
Izh_d = new float[numNReg];
current = new float[numNReg];
nextTaste = new unsigned int[numNReg];
nextDeath = new unsigned int[numNReg];
cpuSnnSz.neuronInfoSize += (sizeof(int)*numNReg*12);
if (sim_with_conductances) {
for (int g=0;g<numGrp;g++)
if (!grp_Info[g].WithConductances && ((grp_Info[g].Type&POISSON_NEURON)==0)) {
printf("If one group enables conductances then all groups, except for generators, must enable conductances. Group '%s' is not enabled.\n", grp_Info2[g].Name.c_str());
assert(false);
}
gAMPA = new float[numNReg];
gNMDA = new float[numNReg];
gGABAa = new float[numNReg];
gGABAb = new float[numNReg];
cpuSnnSz.neuronInfoSize += sizeof(int)*numNReg*4;
}
resetCurrent();
resetConductances();
lastSpikeTime = new uint32_t[numN];
cpuSnnSz.neuronInfoSize += sizeof(int)*numN;
memset(lastSpikeTime,0,sizeof(lastSpikeTime[0]*numN));
curSpike = new bool[numN];
nSpikeCnt = new unsigned int[numN];
intrinsicWeight = new float[numN];
memset(intrinsicWeight,0,sizeof(float)*numN);
cpuSnnSz.neuronInfoSize += (sizeof(int)*numN*2+sizeof(bool)*numN);
if (sim_with_stp) {
stpu = new float[numN*STP_BUF_SIZE];
stpx = new float[numN*STP_BUF_SIZE];
for (int i=0; i < numN*STP_BUF_SIZE; i++) {
//MDR this should be set later.. (adding a default value)
stpu[i] = 1;
stpx[i] = 1;
}
cpuSnnSz.synapticInfoSize += (sizeof(stpu[0])*numN*STP_BUF_SIZE);
}
Npre = new unsigned short[numN];
Npre_plastic = new unsigned short[numN];
Npost = new unsigned short[numN];
cumulativePost = new unsigned int[numN];
cumulativePre = new unsigned int[numN];
cpuSnnSz.networkInfoSize += (int)(sizeof(int)*numN*3.5);
postSynCnt = 0; // stores the total number of post-synaptic connections in the network
preSynCnt = 0; // stores the total number of pre-synaptic connections in the network
for(int g=0; g < numGrp; g++) {
postSynCnt += (grp_Info[g].SizeN*grp_Info[g].numPostSynapses);
preSynCnt += (grp_Info[g].SizeN*grp_Info[g].numPreSynapses);
}
assert(postSynCnt/numN <= numPostSynapses); // divide by numN to prevent INT overflow
postSynapticIds = new post_info_t[postSynCnt+100];
tmp_SynapticDelay = new uint8_t[postSynCnt+100]; // Temporary array to store the delays of each connection
postDelayInfo = new delay_info_t[numN*(D+1)]; // Possible delay values are 0....D (inclusive of D)
cpuSnnSz.networkInfoSize += ((sizeof(post_info_t)+sizeof(uint8_t))*postSynCnt+100) + (sizeof(delay_info_t)*numN*(D+1));
assert(preSynCnt/numN <= numPreSynapses); // divide by numN to prevent INT overflow
wt = new float[preSynCnt+100];
maxSynWt = new float[preSynCnt+100];
// Temporary array to hold pre-syn connections. will be deleted later if necessary
preSynapticIds = new post_info_t[preSynCnt+100];
// size due to weights and maximum weights
cpuSnnSz.synapticInfoSize += ((2*sizeof(float)+sizeof(post_info_t))*(preSynCnt+100));
timeTableD2 = new unsigned int[1000+D+1];
timeTableD1 = new unsigned int[1000+D+1];
resetTimingTable();
cpuSnnSz.spikingInfoSize += sizeof(int)*2*(1000+D+1);
// random thalamic current included...
// randNeuronId = new int[numN];
// cpuSnnSz.addInfoSize += (sizeof(int)*numN);
// poisson Firing Rate
cpuSnnSz.neuronInfoSize += (sizeof(int)*numNPois);
tmp_SynapseMatrix_fixed = NULL;
tmp_SynapseMatrix_plastic = NULL;
}
void CpuSNN::makePtrInfo()
{
// create the CPU Net Ptrs..
cpuNetPtrs.voltage = voltage;
cpuNetPtrs.recovery = recovery;
cpuNetPtrs.current = current;
cpuNetPtrs.Npre = Npre;
cpuNetPtrs.Npost = Npost;
cpuNetPtrs.cumulativePost = cumulativePost;
cpuNetPtrs.cumulativePre = cumulativePre;
cpuNetPtrs.synSpikeTime = synSpikeTime;
cpuNetPtrs.wt = wt;
cpuNetPtrs.wtChange = wtChange;
cpuNetPtrs.nSpikeCnt = nSpikeCnt;
cpuNetPtrs.curSpike = curSpike;
cpuNetPtrs.firingTableD2 = firingTableD2;
cpuNetPtrs.firingTableD1 = firingTableD1;
cpuNetPtrs.gAMPA = gAMPA;
cpuNetPtrs.gNMDA = gNMDA;
cpuNetPtrs.gGABAa = gGABAa;
cpuNetPtrs.gGABAb = gGABAb;
cpuNetPtrs.allocated = true;
cpuNetPtrs.memType = CPU_MODE;
cpuNetPtrs.stpu = stpu;
cpuNetPtrs.stpx = stpx;
}
void CpuSNN::resetSpikeCnt(int my_grpId )
{
int startGrp, endGrp;
if(!doneReorganization)
return;
if (my_grpId == -1) {
startGrp = 0;
endGrp = numGrp;
}
else {
startGrp = my_grpId;
endGrp = my_grpId+numConfig;
}
for( int grpId=startGrp; grpId < endGrp; grpId++) {
int startN = grp_Info[grpId].StartN;
int endN = grp_Info[grpId].EndN+1;
for (int i=startN; i < endN; i++)
nSpikeCnt[i] = 0;
}
}
CpuSNN::CpuSNN(const string& _name, int _numConfig, int _randSeed, int _mode)
{
fprintf(stdout, "************************************************\n");
fprintf(stdout, "***** GPU-SNN Simulation Begins Version 0.3 *** \n");
fprintf(stdout, "************************************************\n");
// initialize propogated spike buffers.....
pbuf = new PropagatedSpikeBuffer(0, PROPOGATED_BUFFER_SIZE);
numConfig = _numConfig;
finishedPoissonGroup = false;
assert(numConfig > 0);
assert(numConfig < 100);
resetPointers();
numN = 0; numPostSynapses = 0; D = 0;
memset(&cpuSnnSz, 0, sizeof(cpuSnnSz));
enableSimLogs = false;
simLogDirName = "logs";//strdup("logs");
fpLog=fopen("tmp_debug.log","w");
fpProgLog = NULL;
showLog = 0; // disable showing log..
showLogMode = 0; // show only basic logs. if set higher more logs generated
showGrpFiringInfo = true;
currentMode = _mode;
memset(&cpu_gpuNetPtrs,0,sizeof(network_ptr_t));
memset(&net_Info,0,sizeof(network_info_t));
cpu_gpuNetPtrs.allocated = false;
memset(&cpuNetPtrs,0, sizeof(network_ptr_t));
cpuNetPtrs.allocated = false;
#ifndef VIEW_DOTTY
#define VIEW_DOTTY false
#endif
showDotty = VIEW_DOTTY;
numSpikeMonitor = 0;
for (int i=0; i < MAX_GRP_PER_SNN; i++) {
grp_Info[i].Type = UNKNOWN_NEURON;
grp_Info[i].MaxFiringRate = UNKNOWN_NEURON_MAX_FIRING_RATE;
grp_Info[i].MonitorId = -1;
grp_Info[i].FiringCount1sec=0;
grp_Info[i].numPostSynapses = 0; // default value
grp_Info[i].numPreSynapses = 0; // default value
grp_Info[i].WithSTP = false;
grp_Info[i].WithSTDP = false;
grp_Info[i].FixedInputWts = true; // Default is true. This value changed to false
// if any incoming connections are plastic
grp_Info[i].WithConductances = false;
grp_Info[i].isSpikeGenerator = false;
grp_Info[i].RatePtr = NULL;
/* grp_Info[i].STP_U = STP_U_Exc;
grp_Info[i].STP_tD = STP_tD_Exc;
grp_Info[i].STP_tF = STP_tF_Exc;
*/
grp_Info[i].dAMPA=1-(1.0/5);
grp_Info[i].dNMDA=1-(1.0/150);
grp_Info[i].dGABAa=1-(1.0/6);
grp_Info[i].dGABAb=1-(1.0/150);
grp_Info[i].spikeGen = NULL;
grp_Info[i].StartN = -1;
grp_Info[i].EndN = -1;
grp_Info2[i].numPostConn = 0;
grp_Info2[i].numPreConn = 0;
grp_Info2[i].enablePrint = false;
grp_Info2[i].maxPostConn = 0;
grp_Info2[i].maxPreConn = 0;
grp_Info2[i].sumPostConn = 0;
grp_Info2[i].sumPreConn = 0;
}
connectBegin = NULL;
numProbe = 0;
neuronProbe = NULL;
simTimeMs = 0; simTimeSec = 0; simTime = 0;
spikeCountAll1sec = 0; secD1fireCnt = 0; secD2fireCnt = 0;
spikeCountAll = 0; spikeCountD2 = 0; spikeCountD1 = 0;
nPoissonSpikes = 0;
networkName = _name; //new char[sizeof(_name)];
//strcpy(networkName, _name);
numGrp = 0;
numConnections = 0;
numSpikeGenGrps = 0;
NgenFunc = 0;
// numNoise = 0;
// numRandNeurons = 0;
simulatorDeleted = false;
allocatedN = 0;
allocatedPre = 0;
allocatedPost = 0;
doneReorganization = false;
memoryOptimized = false;
if (_randSeed == -1) {
randSeed = time(NULL);
}
else if(_randSeed==0) {
randSeed=123;
}
srand48(randSeed);
getRand.seed(randSeed*2);
getRandClosed.seed(randSeed*3);
fpParam = fopen("param.txt", "w");
if (fpParam==NULL) {
fprintf(stderr, "WARNING !!! Unable to open/create parameter file 'param.txt'; check if current directory is writable \n");
exit(1);
return;
}
fprintf(fpParam, "// *****************************************\n");
time_t rawtime; struct tm * timeinfo;
time ( &rawtime ); timeinfo = localtime ( &rawtime );
fprintf ( fpParam, "// program name : %s \n", _name.c_str());
fprintf ( fpParam, "// rand val : %d \n", randSeed);
fprintf ( fpParam, "// Current local time and date: %s\n", asctime (timeinfo));
fflush(fpParam);
cutCreateTimer(&timer);
cutResetTimer(timer);
cumExecutionTime = 0.0;
spikeRateUpdated = false;
sim_with_conductances = false;
sim_with_stp = false;
maxSpikesD2 = maxSpikesD1 = 0;
readNetworkFID = NULL;
}
void CpuSNN::deleteObjects()
{
try
{
if(simulatorDeleted)
return;
if(fpLog) {
printSimSummary(fpLog);
printSimSummary();
fclose(fpLog);
}
// if(val==0)
// saveConnectionWeights();
if(voltage!=NULL) delete[] voltage;
if(recovery!=NULL) delete[] recovery;
if(Izh_a!=NULL) delete[] Izh_a;
if(Izh_b!=NULL) delete[] Izh_b;
if(Izh_c!=NULL) delete[] Izh_c;
if(Izh_d!=NULL) delete[] Izh_d;
if(current!=NULL) delete[] current;
if(Npre!=NULL) delete[] Npre;
if(Npost!=NULL) delete[] Npost;
if(lastSpikeTime!=NULL) delete[] lastSpikeTime;
if(lastSpikeTime!=NULL) delete[] postSynapticIds;
if(postDelayInfo!=NULL) delete[] postDelayInfo;
if(wt!=NULL) delete[] wt;
if(maxSynWt!=NULL) delete[] maxSynWt;
if(wtChange !=NULL) delete[] wtChange;
if(synSpikeTime !=NULL) delete[] synSpikeTime;
if(firingTableD2) delete[] firingTableD2;
if(firingTableD1) delete[] firingTableD1;
delete pbuf;
// clear all existing connection info...
while (connectBegin) {
grpConnectInfo_t* nextConn = connectBegin->next;
free(connectBegin);
connectBegin = nextConn;
}
for (int i = 0; i < numSpikeMonitor; i++) {
delete[] monBufferFiring[i];
delete[] monBufferTimeCnt[i];
}
if(spikeGenBits) delete[] spikeGenBits;
simulatorDeleted = true;
}
catch(...)
{
fprintf(stderr, "Unknow exception ...\n");
}
}
void CpuSNN::exitSimulation(int val)
{
deleteObjects();
exit(val);
}
CpuSNN::~CpuSNN()
{
if (!simulatorDeleted)
deleteObjects();
}
void CpuSNN::setSTDP( int grpId, bool enable, int configId)
{
assert(enable==false);
setSTDP(grpId,false,0,0,0,0,configId);
}
void CpuSNN::setSTDP( int grpId, bool enable, float ALPHA_LTP, float TAU_LTP, float ALPHA_LTD, float TAU_LTD, int configId)
{
assert(TAU_LTP >= 0.0);
assert(TAU_LTD >= 0.0);
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setSTDP(g, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setSTDP(g, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSTDP(grpId, enable, ALPHA_LTP,TAU_LTP,ALPHA_LTD,TAU_LTD, c);
} else {
int cGrpId = getGroupId(grpId, configId);
grp_Info[cGrpId].WithSTDP = enable;
grp_Info[cGrpId].ALPHA_LTP = ALPHA_LTP;
grp_Info[cGrpId].ALPHA_LTD = ALPHA_LTD;
grp_Info[cGrpId].TAU_LTP_INV = 1.0/TAU_LTP;
grp_Info[cGrpId].TAU_LTD_INV = 1.0/TAU_LTD;
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "STDP %s for %d (%s): %f, %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), ALPHA_LTP, ALPHA_LTD, TAU_LTP, TAU_LTD);
}
}
void CpuSNN::setSTP( int grpId, bool enable, int configId)
{
assert(enable==false);
setSTP(grpId,false,0,0,0,configId);
}
void CpuSNN::setSTP(int grpId, bool enable, float STP_U, float STP_tD, float STP_tF, int configId)
{
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setSTP(g, enable, STP_U, STP_tD, STP_tF, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setSTP(g, enable, STP_U, STP_tD, STP_tF, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSTP(grpId, enable, STP_U, STP_tD, STP_tF, c);
} else {
int cGrpId = getGroupId(grpId, configId);
sim_with_stp |= enable;
//printf("sim_with_stp: %d\n",sim_with_stp);
grp_Info[cGrpId].WithSTP = enable;
grp_Info[cGrpId].STP_U=STP_U;
grp_Info[cGrpId].STP_tD=STP_tD;
grp_Info[cGrpId].STP_tF=STP_tF;
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "STP %s for %d (%s): %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), STP_U, STP_tD, STP_tF);
}
}
void CpuSNN::setConductances( int grpId, bool enable, int configId)
{
assert(enable==false);
setConductances(grpId,false,0,0,0,0,configId);
}
void CpuSNN::setConductances(int grpId, bool enable, float tAMPA, float tNMDA, float tGABAa, float tGABAb, int configId)
{
if (grpId == ALL && configId == ALL) {
for(int g=0; g < numGrp; g++)
setConductances(g, enable, tAMPA, tNMDA, tGABAa, tGABAb, 0);
} else if (grpId == ALL) {
for(int grpId1=0; grpId1 < numGrp; grpId1 += numConfig) {
int g = getGroupId(grpId1, configId);
setConductances(g, enable, tAMPA, tNMDA, tGABAa, tGABAb, configId);
}
} else if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setConductances(grpId, enable, tAMPA, tNMDA, tGABAa, tGABAb, c);
} else {
int cGrpId = getGroupId(grpId, configId);
sim_with_conductances |= enable;
grp_Info[cGrpId].WithConductances = enable;
grp_Info[cGrpId].dAMPA=1-(1.0/tAMPA);
grp_Info[cGrpId].dNMDA=1-(1.0/tNMDA);
grp_Info[cGrpId].dGABAa=1-(1.0/tGABAa);
grp_Info[cGrpId].dGABAb=1-(1.0/tGABAb);
grp_Info[cGrpId].newUpdates = true;
fprintf(stderr, "Conductances %s for %d (%s): %f, %f, %f, %f\n", enable?"enabled":"disabled",
cGrpId, grp_Info2[cGrpId].Name.c_str(), tAMPA, tNMDA, tGABAa, tGABAb);
}
}
int CpuSNN::createGroup(const string& _name, unsigned int _numN, int _nType, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
createGroup(_name, _numN, _nType, c);
return (numGrp-numConfig);
} else {
assert(numGrp < MAX_GRP_PER_SNN);
if ( (!(_nType&TARGET_AMPA) && !(_nType&TARGET_NMDA) &&
!(_nType&TARGET_GABAa) && !(_nType&TARGET_GABAb)) || (_nType&POISSON_NEURON)) {
fprintf(stderr, "Invalid type using createGroup...\n");
fprintf(stderr, "can not create poisson generators here...\n");
exitSimulation(1);
}
grp_Info[numGrp].SizeN = _numN;
grp_Info[numGrp].Type = _nType;
grp_Info[numGrp].WithConductances = false;
grp_Info[numGrp].WithSTP = false;
grp_Info[numGrp].WithSTDP = false;
if ( (_nType&TARGET_GABAa) || (_nType&TARGET_GABAb)) {
grp_Info[numGrp].MaxFiringRate = INHIBITORY_NEURON_MAX_FIRING_RATE;
}
else {
grp_Info[numGrp].MaxFiringRate = EXCITATORY_NEURON_MAX_FIRING_RATE;
}
grp_Info2[numGrp].ConfigId = configId;
grp_Info2[numGrp].Name = _name;//new char[strlen(_name)];
grp_Info[numGrp].isSpikeGenerator = false;
grp_Info[numGrp].MaxDelay = 1;
grp_Info2[numGrp].IzhGen = NULL;
grp_Info2[numGrp].Izh_a = -1;
std::stringstream outStr;
outStr << configId;
if (configId == 0)
grp_Info2[numGrp].Name = _name;
else
grp_Info2[numGrp].Name = _name + "_" + outStr.str();
finishedPoissonGroup = true;
numGrp++;
return (numGrp-1);
}
}
int CpuSNN::createSpikeGeneratorGroup(const string& _name, unsigned int size_n, int type, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
createSpikeGeneratorGroup(_name, size_n, type, c);
return (numGrp-numConfig);
} else {
grp_Info[numGrp].SizeN = size_n;
grp_Info[numGrp].Type = type | POISSON_NEURON;
grp_Info[numGrp].WithConductances = false;
grp_Info[numGrp].WithSTP = false;
grp_Info[numGrp].WithSTDP = false;
grp_Info[numGrp].isSpikeGenerator = true; // these belong to the spike generator class...
grp_Info2[numGrp].ConfigId = configId;
grp_Info2[numGrp].Name = _name; //new char[strlen(_name)];
grp_Info[numGrp].MaxFiringRate = POISSON_MAX_FIRING_RATE;
std::stringstream outStr ;
outStr << configId;
if (configId != 0)
grp_Info2[numGrp].Name = _name + outStr.str();
numGrp++;
numSpikeGenGrps++;
return (numGrp-1);
}
}
int CpuSNN::getGroupId(int groupId, int configId)
{
assert(configId < numConfig);
int cGrpId = (groupId+configId);
assert(cGrpId < numGrp);
return cGrpId;
}
int CpuSNN::getConnectionId(int connId, int configId)
{
if(configId >= numConfig) {
fprintf(stderr, "getConnectionId(int, int): Assertion `configId(%d) < numConfig(%d)' failed\n", configId, numConfig);
assert(0);
}
connId = connId+configId;
if (connId >= numConnections) {
fprintf(stderr, "getConnectionId(int, int): Assertion `connId(%d) < numConnections(%d)' failed\n", connId, numConnections);
assert(0);
}
return connId;
}
void CpuSNN::setNeuronParameters(int groupId, float _a, float _b, float _c, float _d, int configId)
{
setNeuronParameters(groupId, _a, 0, _b, 0, _c, 0, _d, 0, configId);
}
void CpuSNN::setNeuronParameters(int groupId, float _a, float a_sd, float _b, float b_sd, float _c, float c_sd, float _d, float d_sd, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setNeuronParameters(groupId, _a, a_sd, _b, b_sd, _c, c_sd, _d, d_sd, c);
} else {
int cGrpId = getGroupId(groupId, configId);
grp_Info2[cGrpId].Izh_a = _a;
grp_Info2[cGrpId].Izh_a_sd = a_sd;
grp_Info2[cGrpId].Izh_b = _b;
grp_Info2[cGrpId].Izh_b_sd = b_sd;
grp_Info2[cGrpId].Izh_c = _c;
grp_Info2[cGrpId].Izh_c_sd = c_sd;
grp_Info2[cGrpId].Izh_d = _d;
grp_Info2[cGrpId].Izh_d_sd = d_sd;
}
}
void CpuSNN::setNeuronParameters(int groupId, IzhGenerator* IzhGen, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setNeuronParameters(groupId, IzhGen, c);
} else {
int cGrpId = getGroupId(groupId, configId);
grp_Info2[cGrpId].IzhGen = IzhGen;
}
}
void CpuSNN::setGroupInfo(int grpId, group_info_t info, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setGroupInfo(grpId, info, c);
} else {
int cGrpId = getGroupId(grpId, configId);
grp_Info[cGrpId] = info;
}
}
group_info_t CpuSNN::getGroupInfo(int grpId, int configId)
{
int cGrpId = getGroupId(grpId, configId);
return grp_Info[cGrpId];
}
void CpuSNN::buildPoissonGroup(int grpId)
{
assert(grp_Info[grpId].StartN == -1);
grp_Info[grpId].StartN = allocatedN;
grp_Info[grpId].EndN = allocatedN + grp_Info[grpId].SizeN - 1;
fprintf(fpLog, "Allocation for %d(%s), St=%d, End=%d\n",
grpId, grp_Info2[grpId].Name.c_str(), grp_Info[grpId].StartN, grp_Info[grpId].EndN);
resetSpikeCnt(grpId);
allocatedN = allocatedN + grp_Info[grpId].SizeN;
assert(allocatedN <= numN);
for(int i=grp_Info[grpId].StartN; i <= grp_Info[grpId].EndN; i++) {
resetPoissonNeuron(i, grpId);
Npre_plastic[i] = 0;
Npre[i] = 0;
Npost[i] = 0;
cumulativePost[i] = allocatedPost;
cumulativePre[i] = allocatedPre;
allocatedPost += grp_Info[grpId].numPostSynapses;
allocatedPre += grp_Info[grpId].numPreSynapses;
}
assert(allocatedPost <= postSynCnt);
assert(allocatedPre <= preSynCnt);
}
void CpuSNN::resetPoissonNeuron(unsigned int nid, int grpId)
{
assert(nid < numN);
lastSpikeTime[nid] = MAX_SIMULATION_TIME;
if(grp_Info[grpId].WithSTP) {
for (int j=0; j < STP_BUF_SIZE; j++) {
int ind=STP_BUF_POS(nid,j);
stpu[ind] = grp_Info[grpId].STP_U;
stpx[ind] = 1;
}
}
}
void CpuSNN::resetNeuron(unsigned int nid, int grpId)
{
assert(nid < numNReg);
if (grp_Info2[grpId].IzhGen == NULL) {
if (grp_Info2[grpId].Izh_a == -1) {
printf("setNeuronParameters much be called for group %s (%d)\n",grp_Info2[grpId].Name.c_str(),grpId);
exit(-1);
}
Izh_a[nid] = grp_Info2[grpId].Izh_a + grp_Info2[grpId].Izh_a_sd*(float)getRandClosed();
Izh_b[nid] = grp_Info2[grpId].Izh_b + grp_Info2[grpId].Izh_b_sd*(float)getRandClosed();
Izh_c[nid] = grp_Info2[grpId].Izh_c + grp_Info2[grpId].Izh_c_sd*(float)getRandClosed();
Izh_d[nid] = grp_Info2[grpId].Izh_d + grp_Info2[grpId].Izh_d_sd*(float)getRandClosed();
} else {
grp_Info2[grpId].IzhGen->set(this, grpId, nid, Izh_a[nid], Izh_b[nid], Izh_c[nid], Izh_d[nid]);
}
voltage[nid] = Izh_c[nid]; // initial values for new_v
recovery[nid] = 0.2f*voltage[nid]; // initial values for u
lastSpikeTime[nid] = MAX_SIMULATION_TIME;
if(grp_Info[grpId].WithSTP) {
for (int j=0; j < STP_BUF_SIZE; j++) {
int ind=STP_BUF_POS(nid,j);
stpu[ind] = grp_Info[grpId].STP_U;
stpx[ind] = 1;
}
}
}
void CpuSNN::buildGroup(int grpId)
{
assert(grp_Info[grpId].StartN == -1);
grp_Info[grpId].StartN = allocatedN;
grp_Info[grpId].EndN = allocatedN + grp_Info[grpId].SizeN - 1;
fprintf(fpLog, "Allocation for %d(%s), St=%d, End=%d\n",
grpId, grp_Info2[grpId].Name.c_str(), grp_Info[grpId].StartN, grp_Info[grpId].EndN);
resetSpikeCnt(grpId);
allocatedN = allocatedN + grp_Info[grpId].SizeN;
assert(allocatedN <= numN);
for(int i=grp_Info[grpId].StartN; i <= grp_Info[grpId].EndN; i++) {
resetNeuron(i, grpId);
Npre_plastic[i] = 0;
Npre[i] = 0;
Npost[i] = 0;
cumulativePost[i] = allocatedPost;
cumulativePre[i] = allocatedPre;
allocatedPost += grp_Info[grpId].numPostSynapses;
allocatedPre += grp_Info[grpId].numPreSynapses;
}
assert(allocatedPost <= postSynCnt);
assert(allocatedPre <= preSynCnt);
}
// set one specific connection from neuron id 'src' to neuron id 'dest'
inline void CpuSNN::setConnection(int srcGrp, int destGrp, unsigned int src, unsigned int dest, float synWt, float maxWt, uint8_t dVal, int connProp)
{
assert(dest<=CONN_SYN_NEURON_MASK); // total number of neurons is less than 1 million within a GPU
assert((dVal >=1) && (dVal <= D));
// we have exceeded the number of possible connection for one neuron
if(Npost[src] >= grp_Info[srcGrp].numPostSynapses) {
fprintf(stderr, "setConnection(%d (Grp=%s), %d (Grp=%s), %f, %d)\n", src, grp_Info2[srcGrp].Name.c_str(), dest, grp_Info2[destGrp].Name.c_str(), synWt, dVal);
fprintf(stderr, "(Npost[%d] = %d ) >= (numPostSynapses = %d) value given for the network very less\n", src, Npost[src], grp_Info[srcGrp].numPostSynapses);
fprintf(stderr, "Large number of postsynaptic connections is established\n");
fprintf(stderr, "Increase the numPostSynapses value for the Group = %s \n", grp_Info2[srcGrp].Name.c_str());
assert(0);
}
if(Npre[dest] >= grp_Info[destGrp].numPreSynapses) {
fprintf(stderr, "setConnection(%d (Grp=%s), %d (Grp=%s), %f, %d)\n", src, grp_Info2[srcGrp].Name.c_str(), dest, grp_Info2[destGrp].Name.c_str(), synWt, dVal);
fprintf(stderr, "(Npre[%d] = %d) >= (numPreSynapses = %d) value given for the network very less\n", dest, Npre[dest], grp_Info[destGrp].numPreSynapses);
fprintf(stderr, "Large number of presynaptic connections established\n");
fprintf(stderr, "Increase the numPostSynapses for the Grp = %s value \n", grp_Info2[destGrp].Name.c_str());
assert(0);
}
int p = Npost[src];
assert(Npost[src] >= 0);
assert(Npre[dest] >= 0);
assert((src*numPostSynapses+p)/numN < numPostSynapses); // divide by numN to prevent INT overflow
int post_pos = cumulativePost[src] + Npost[src];
int pre_pos = cumulativePre[dest] + Npre[dest];
assert(post_pos < postSynCnt);
assert(pre_pos < preSynCnt);
postSynapticIds[post_pos] = SET_CONN_ID(dest, Npre[dest], destGrp); //generate a new postSynapticIds id for the current connection
tmp_SynapticDelay[post_pos] = dVal;
preSynapticIds[pre_pos] = SET_CONN_ID(src, Npost[src], srcGrp);
wt[pre_pos] = synWt;
maxSynWt[pre_pos] = maxWt;
bool synWtType = GET_FIXED_PLASTIC(connProp);
if (synWtType == SYN_PLASTIC) {
Npre_plastic[dest]++;
}
Npre[dest]+=1;
Npost[src]+=1;
grp_Info2[srcGrp].numPostConn++;
grp_Info2[destGrp].numPreConn++;
if (Npost[src] > grp_Info2[srcGrp].maxPostConn)
grp_Info2[srcGrp].maxPostConn = Npost[src];
if (Npre[dest] > grp_Info2[destGrp].maxPreConn)
grp_Info2[destGrp].maxPreConn = Npre[src];
#if _DEBUG_
//fprintf(fpLog, "setConnection(%d, %d, %f, %d Npost[%d]=%d, Npre[%d]=%d)\n", src, dest, initWt, dVal, src, Npost[src], dest, Npre[dest]);
#endif
}
float CpuSNN::getWeights(int connProp, float initWt, float maxWt, unsigned int nid, int grpId)
{
float actWts;
bool setRandomWeights = GET_INITWTS_RANDOM(connProp);
bool setRampDownWeights = GET_INITWTS_RAMPDOWN(connProp);
bool setRampUpWeights = GET_INITWTS_RAMPUP(connProp);
if ( setRandomWeights )
actWts=initWt*drand48();
else if (setRampUpWeights)
actWts=(initWt+((nid-grp_Info[grpId].StartN)*(maxWt-initWt)/grp_Info[grpId].SizeN));
else if (setRampDownWeights)
actWts=(maxWt-((nid-grp_Info[grpId].StartN)*(maxWt-initWt)/grp_Info[grpId].SizeN));
else
actWts=initWt;
return actWts;
}
// make 'C' random connections from grpSrc to grpDest
void CpuSNN::connectRandom (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
for(int pre_nid=grp_Info[grpSrc].StartN; pre_nid<=grp_Info[grpSrc].EndN; pre_nid++) {
for(int post_nid=grp_Info[grpDest].StartN; post_nid<=grp_Info[grpDest].EndN; post_nid++) {
if (getRand() < info->p) {
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, pre_nid, grpSrc);
setConnection(grpSrc, grpDest, pre_nid, post_nid, synWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
}
}
}
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
void CpuSNN::connectOneToOne (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
assert( grp_Info[grpDest].SizeN == grp_Info[grpSrc].SizeN );
// C = grp_Info[grpDest].SizeN;
for(int nid=grp_Info[grpSrc].StartN,j=grp_Info[grpDest].StartN; nid<=grp_Info[grpSrc].EndN; nid++, j++) {
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, nid, grpSrc);
setConnection(grpSrc, grpDest, nid, j, synWt, info->maxWt, dVal, info->connProp);
//setConnection(grpSrc, grpDest, nid, j, info->initWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
}
// //dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"numPostSynapses=%d, wt=%3.3f , Dm=%d \"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", info->numPostSynapses, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating One-to-One Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
// fprintf(fpLog, "Creating One-to-One Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
// user-defined functions called here...
void CpuSNN::connectUserDefined (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
info->maxDelay = 0;
for(int nid=grp_Info[grpSrc].StartN; nid<=grp_Info[grpSrc].EndN; nid++) {
for(int nid2=grp_Info[grpDest].StartN; nid2 <= grp_Info[grpDest].EndN; nid2++) {
int srcId = nid - grp_Info[grpSrc].StartN;
int destId = nid2 - grp_Info[grpDest].StartN;
float weight, maxWt, delay;
bool connected;
info->conn->connect(this, grpSrc, srcId, grpDest, destId, weight, maxWt, delay, connected);
if(connected) {
if (GET_FIXED_PLASTIC(info->connProp) == SYN_FIXED) maxWt = weight;
assert(delay>=1);
assert(delay<=MAX_SynapticDelay);
assert(weight<=maxWt);
setConnection(grpSrc, grpDest, nid, nid2, weight, maxWt, delay, info->connProp);
info->numberOfConnections++;
if(delay > info->maxDelay)
info->maxDelay = delay;
}
}
}
// // dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"user-defined\"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted");
// fprintf(stdout, "Creating User-defined Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
// fprintf(fpLog, "Creating User-defined Connection from '%s' to '%s'\n", grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str());
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
// make 'C' full connections from grpSrc to grpDest
void CpuSNN::connectFull (grpConnectInfo_t* info)
{
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
bool noDirect = (info->type == CONN_FULL_NO_DIRECT);
for(int nid=grp_Info[grpSrc].StartN; nid<=grp_Info[grpSrc].EndN; nid++) {
for(int j=grp_Info[grpDest].StartN; j <= grp_Info[grpDest].EndN; j++) {
if((noDirect) && (nid - grp_Info[grpSrc].StartN) == (j - grp_Info[grpDest].StartN))
continue;
uint8_t dVal = info->minDelay + (int)(0.5+(getRandClosed()*(info->maxDelay-info->minDelay)));
assert((dVal >= info->minDelay) && (dVal <= info->maxDelay));
float synWt = getWeights(info->connProp, info->initWt, info->maxWt, nid, grpSrc);
setConnection(grpSrc, grpDest, nid, j, synWt, info->maxWt, dVal, info->connProp);
info->numberOfConnections++;
//setConnection(grpSrc, grpDest, nid, j, info->initWt, info->maxWt, dVal, info->connProp);
}
}
// //dotty printf output
// fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, label=\"numPostSynapses=%d, wt=%3.3f, Dm=%d \"]\n", grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", info->numPostSynapses, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating Full Connection %s from '%s' to '%s' with Probability %f\n",
// (noDirect?"no-direct":" "), grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), info->numPostSynapses*1.0/grp_Info[grpDest].SizeN);
// fprintf(fpLog, "Creating Full Connection %s from '%s' to '%s' with Probability %f\n",
// (noDirect?"no-direct":" "), grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), info->numPostSynapses*1.0/grp_Info[grpDest].SizeN);
grp_Info2[grpSrc].sumPostConn += info->numberOfConnections;
grp_Info2[grpDest].sumPreConn += info->numberOfConnections;
}
void CpuSNN::connectFromMatrix(SparseWeightDelayMatrix* mat, int connProp)
{
for (int i=0;i<mat->count;i++) {
int nIDpre = mat->preIds[i];
int nIDpost = mat->postIds[i];
float weight = mat->weights[i];
float maxWeight = mat->maxWeights[i];
uint8_t delay = mat->delay_opts[i];
int gIDpre = findGrpId(nIDpre);
int gIDpost = findGrpId(nIDpost);
setConnection(gIDpre, gIDpost, nIDpre, nIDpost, weight, maxWeight, delay, connProp);
grp_Info2[gIDpre].sumPostConn++;
grp_Info2[gIDpost].sumPreConn++;
if (delay > grp_Info[gIDpre].MaxDelay) grp_Info[gIDpre].MaxDelay = delay;
}
}
void CpuSNN::printDotty ()
{
string fname(networkName+".dot");
fpDotty = fopen(fname.c_str(),"w");
fprintf(fpDotty, "\
digraph G {\n\
\t\tnode [style=filled];\n\
\t\tcolor=blue;\n");
for(int g=0; g < numGrp; g++) {
//add a node to the dotty output
char stype = grp_Info[g].Type;
assert(grp_Info2[g].numPostConn == grp_Info2[g].sumPostConn);
assert(grp_Info2[g].numPreConn == grp_Info2[g].sumPreConn);
// fprintf(stdout, "Creating Spike Generator Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// fprintf(fpLog, "Creating Spike Generator Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// add a node to the dotty output
fprintf (fpDotty, "\t\tg%d [%s label=\"id=%d:%s \\n numN=%d avgPost=%3.2f avgPre=%3.2f \\n maxPost=%d maxPre=%d\"];\n", g,
(stype&POISSON_NEURON) ? "shape = box, ": " ", g, grp_Info2[g].Name.c_str(),
grp_Info[g].SizeN, grp_Info2[g].numPostConn*1.0/grp_Info[g].SizeN,
grp_Info2[g].numPreConn*1.0/grp_Info[g].SizeN, grp_Info2[g].maxPostConn, grp_Info2[g].maxPreConn);
// fprintf(stdout, "Creating Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
// fprintf(fpLog, "Creating Group %s(id=%d) with numN=%d\n", grp_Info2[g].Name.c_str(), g, grp_Info[g].SizeN);
}
/*
for (int noiseId=0; noiseId < numNoise; noiseId++) {
int groupId = noiseGenGroup[noiseId].groupId;
float currentStrength = noiseGenGroup[noiseId].currentStrength;
float neuronPercentage = noiseGenGroup[noiseId].neuronPercentage;
int numNeuron = ((groupId==-1)? -1: grp_Info[groupId].SizeN);
if(groupId==-1)
fprintf(fpDotty, "\t\tr%d [shape=box, label=\"Global Random Noise\\n(I=%2.2fmA, frac=%2.2f%%)\"];\n", noiseId, currentStrength, neuronPercentage);
else
fprintf(fpDotty, "\t\tr%d [shape=box, label=\"Random Noise\\n(I=%2.2fmA, frac=%2.2f%%)\"];\n", noiseId, currentStrength, neuronPercentage);
if (groupId !=- 1)
fprintf(fpDotty, "\t\tr%d -> g%d [label=\" n=%d \"];\n", noiseId, groupId, (int) (numNeuron*(neuronPercentage/100.0)));
}
*/
grpConnectInfo_t* info = connectBegin;
while(info) {
int grpSrc = info->grpSrc;
int grpDest = info->grpDest;
float avgPostM = info->numberOfConnections/grp_Info[grpSrc].SizeN;
float avgPreM = info->numberOfConnections/grp_Info[grpDest].SizeN;
//dotty printf output
fprintf(fpDotty, "\t\tg%d -> g%d [style=%s, arrowType=%s, label=\"avgPost=%3.2f, avgPre=%3.2f, wt=%3.3f, maxD=%d \"]\n",
grpSrc, grpDest, (info->initWt > 0)?"bold":"dotted", (info->initWt > 0)?"normal":"dot", avgPostM, avgPreM, info->maxWt, info->maxDelay);
// fprintf(stdout, "Creating Connection from '%s' to '%s' with Probability %1.3f\n",
// grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), avgPostM/grp_Info[grpDest].SizeN);
// fprintf(fpLog, "Creating Connection from '%s' to '%s' with Probability %1.3f\n",
// grp_Info2[grpSrc].Name.c_str(), grp_Info2[grpDest].Name.c_str(), avgPostM/grp_Info[grpDest].SizeN);
info = info->next;
}
fprintf(fpDotty, "\n}\n");
fclose(fpDotty);
//std::stringstream cmd;
//cmd << "kgraphviewer " << networkName << ".dot";
char cmd[100];
int dbg = sprintf(cmd, "kgraphviewer %s.dot", networkName.c_str());
int retVal;
showDotty = false;
if(showDotty) {
retVal = system(cmd);
assert(retVal >= 0);
}
fprintf(stdout, "\trun cmd to view graph: %s\n", cmd);
}
// make from each neuron in grpId1 to 'numPostSynapses' neurons in grpId2
int CpuSNN::connect(int grpId1, int grpId2, ConnectionGenerator* conn, bool synWtType, int maxM, int maxPreM)
{
int retId=-1;
for(int c=0; c < numConfig; c++, grpId1++, grpId2++) {
assert(grpId1 < numGrp);
assert(grpId2 < numGrp);
if (maxM == 0)
maxM = grp_Info[grpId2].SizeN;
if (maxPreM == 0)
maxPreM = grp_Info[grpId1].SizeN;
if (maxM > MAX_numPostSynapses) {
printf("Connection from %s (%d) to %s (%d) exceeded the maximum number of output synapses (%d), has %d.\n",grp_Info2[grpId1].Name.c_str(),grpId1,grp_Info2[grpId2].Name.c_str(), grpId2, MAX_numPostSynapses,maxM);
assert(maxM <= MAX_numPostSynapses);
}
if (maxPreM > MAX_numPreSynapses) {
printf("Connection from %s (%d) to %s (%d) exceeded the maximum number of input synapses (%d), has %d.\n",grp_Info2[grpId1].Name.c_str(), grpId1,grp_Info2[grpId2].Name.c_str(), grpId2,MAX_numPreSynapses,maxPreM);
assert(maxPreM <= MAX_numPreSynapses);
}
grpConnectInfo_t* newInfo = (grpConnectInfo_t*) calloc(1, sizeof(grpConnectInfo_t));
newInfo->grpSrc = grpId1;
newInfo->grpDest = grpId2;
newInfo->initWt = 1;
newInfo->maxWt = 1;
newInfo->maxDelay = 1;
newInfo->minDelay = 1;
newInfo->connProp = SET_CONN_PRESENT(1) | SET_FIXED_PLASTIC(synWtType);
newInfo->type = CONN_USER_DEFINED;
newInfo->numPostSynapses = maxM;
newInfo->numPreSynapses = maxPreM;
newInfo->conn = conn;
newInfo->next = connectBegin; // build a linked list
connectBegin = newInfo;
// update the pre and post size...
grp_Info[grpId1].numPostSynapses += newInfo->numPostSynapses;
grp_Info[grpId2].numPreSynapses += newInfo->numPreSynapses;
if (showLogMode >= 1)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",grpId1,grp_Info2[grpId1].Name.c_str(),grp_Info[grpId1].numPostSynapses,grpId2,grp_Info2[grpId2].Name.c_str(),grp_Info[grpId2].numPreSynapses);
newInfo->connId = numConnections++;
if(c==0)
retId = newInfo->connId;
}
assert(retId != -1);
return retId;
}
// make from each neuron in grpId1 to 'numPostSynapses' neurons in grpId2
int CpuSNN::connect(int grpId1, int grpId2, const string& _type, float initWt, float maxWt, float p, uint8_t minDelay, uint8_t maxDelay, bool synWtType, const string& wtType)
{
int retId=-1;
for(int c=0; c < numConfig; c++, grpId1++, grpId2++) {
assert(grpId1 < numGrp);
assert(grpId2 < numGrp);
assert(minDelay <= maxDelay);
bool useRandWts = (wtType.find("random") != string::npos);
bool useRampDownWts = (wtType.find("ramp-down") != string::npos);
bool useRampUpWts = (wtType.find("ramp-up") != string::npos);
uint32_t connProp = SET_INITWTS_RANDOM(useRandWts)
| SET_CONN_PRESENT(1)
| SET_FIXED_PLASTIC(synWtType)
| SET_INITWTS_RAMPUP(useRampUpWts)
| SET_INITWTS_RAMPDOWN(useRampDownWts);
grpConnectInfo_t* newInfo = (grpConnectInfo_t*) calloc(1, sizeof(grpConnectInfo_t));
newInfo->grpSrc = grpId1;
newInfo->grpDest = grpId2;
newInfo->initWt = initWt;
newInfo->maxWt = maxWt;
newInfo->maxDelay = maxDelay;
newInfo->minDelay = minDelay;
newInfo->connProp = connProp;
newInfo->p = p;
newInfo->type = CONN_UNKNOWN;
newInfo->numPostSynapses = 1;
newInfo->next = connectBegin; //linked list of connection..
connectBegin = newInfo;
if ( _type.find("random") != string::npos) {
newInfo->type = CONN_RANDOM;
newInfo->numPostSynapses = MIN(grp_Info[grpId2].SizeN,((int) (p*grp_Info[grpId2].SizeN +5*sqrt(p*(1-p)*grp_Info[grpId2].SizeN)+0.5))); // estimate the maximum number of connections we need. This uses a binomial distribution at 5 stds.
newInfo->numPreSynapses = MIN(grp_Info[grpId1].SizeN,((int) (p*grp_Info[grpId1].SizeN +5*sqrt(p*(1-p)*grp_Info[grpId1].SizeN)+0.5))); // estimate the maximum number of connections we need. This uses a binomial distribution at 5 stds.
}
else if ( _type.find("full") != string::npos) {
newInfo->type = CONN_FULL;
newInfo->numPostSynapses = grp_Info[grpId2].SizeN;
newInfo->numPreSynapses = grp_Info[grpId1].SizeN;
}
else if ( _type.find("full-no-direct") != string::npos) {
newInfo->type = CONN_FULL_NO_DIRECT;
newInfo->numPostSynapses = grp_Info[grpId2].SizeN-1;
newInfo->numPreSynapses = grp_Info[grpId1].SizeN-1;
}
else if ( _type.find("one-to-one") != string::npos) {
newInfo->type = CONN_ONE_TO_ONE;
newInfo->numPostSynapses = 1;
newInfo->numPreSynapses = 1;
}
else {
fprintf(stderr, "Invalid connection type (should be 'random', or 'full' or 'one-to-one' or 'full-no-direct')\n");
exitSimulation(-1);
}
if (newInfo->numPostSynapses > MAX_numPostSynapses) {
printf("Connection exceeded the maximum number of output synapses (%d), has %d.\n",MAX_numPostSynapses,newInfo->numPostSynapses);
assert(newInfo->numPostSynapses <= MAX_numPostSynapses);
}
if (newInfo->numPreSynapses > MAX_numPreSynapses) {
printf("Connection exceeded the maximum number of input synapses (%d), has %d.\n",MAX_numPreSynapses,newInfo->numPreSynapses);
assert(newInfo->numPreSynapses <= MAX_numPreSynapses);
}
// update the pre and post size...
grp_Info[grpId1].numPostSynapses += newInfo->numPostSynapses;
grp_Info[grpId2].numPreSynapses += newInfo->numPreSynapses;
if (showLogMode >= 1)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",grpId1,grp_Info2[grpId1].Name.c_str(),grp_Info[grpId1].numPostSynapses,grpId2,grp_Info2[grpId2].Name.c_str(),grp_Info[grpId2].numPreSynapses);
newInfo->connId = numConnections++;
if(c==0)
retId = newInfo->connId;
}
assert(retId != -1);
return retId;
}
int CpuSNN::updateSpikeTables()
{
int curD = 0;
int grpSrc;
// find the maximum delay in the given network
// and also the maximum delay for each group.
grpConnectInfo_t* newInfo = connectBegin;
while(newInfo) {
grpSrc = newInfo->grpSrc;
if (newInfo->maxDelay > curD)
curD = newInfo->maxDelay;
// check if the current connection's delay meaning grp1's delay
// is greater than the MaxDelay for grp1. We find the maximum
// delay for the grp1 by this scheme.
if (newInfo->maxDelay > grp_Info[grpSrc].MaxDelay)
grp_Info[grpSrc].MaxDelay = newInfo->maxDelay;
newInfo = newInfo->next;
}
for(int g=0; g < numGrp; g++) {
if ( grp_Info[g].MaxDelay == 1)
maxSpikesD1 += (grp_Info[g].SizeN*grp_Info[g].MaxFiringRate);
else
maxSpikesD2 += (grp_Info[g].SizeN*grp_Info[g].MaxFiringRate);
}
// maxSpikesD1 = (maxSpikesD1 == 0)? 1 : maxSpikesD1;
// maxSpikesD2 = (maxSpikesD2 == 0)? 1 : maxSpikesD2;
if ((maxSpikesD1+maxSpikesD2) < (numNExcReg+numNInhReg+numNPois)*UNKNOWN_NEURON_MAX_FIRING_RATE) {
fprintf(stderr, "Insufficient amount of buffer allocated...\n");
exitSimulation(1);
}
// maxSpikesD2 = (maxSpikesD1 > maxSpikesD2)?maxSpikesD1:maxSpikesD2;
// maxSpikesD1 = (maxSpikesD1 > maxSpikesD2)?maxSpikesD1:maxSpikesD2;
firingTableD2 = new unsigned int[maxSpikesD2];
firingTableD1 = new unsigned int[maxSpikesD1];
cpuSnnSz.spikingInfoSize += sizeof(int)*((maxSpikesD2+maxSpikesD1) + 2*(1000+D+1));
return curD;
}
void CpuSNN::buildNetwork()
{
grpConnectInfo_t* newInfo = connectBegin;
int curN = 0, curD = 0, numPostSynapses = 0, numPreSynapses = 0;
assert(numConfig > 0);
//update main set of parameters
updateParameters(&curN, &numPostSynapses, &numPreSynapses, numConfig);
curD = updateSpikeTables();
assert((curN > 0)&& (curN == numNExcReg + numNInhReg + numNPois));
assert(numPostSynapses > 0);
assert(numPreSynapses > 0);
// display the evaluated network and delay length....
fprintf(stdout, ">>>>>>>>>>>>>> NUM_CONFIGURATIONS = %d <<<<<<<<<<<<<<<<<<\n", numConfig);
fprintf(stdout, "**********************************\n");
fprintf(stdout, "numN = %d, numPostSynapses = %d, numPreSynapses = %d, D = %d\n", curN, numPostSynapses, numPreSynapses, curD);
fprintf(stdout, "**********************************\n");
fprintf(fpLog, "**********************************\n");
fprintf(fpLog, "numN = %d, numPostSynapses = %d, numPreSynapses = %d, D = %d\n", curN, numPostSynapses, numPreSynapses, curD);
fprintf(fpLog, "**********************************\n");
assert(curD != 0); assert(numPostSynapses != 0); assert(curN != 0); assert(numPreSynapses != 0);
if (showLogMode >= 1)
for (int g=0;g<numGrp;g++)
printf("grp_Info[%d, %s].numPostSynapses = %d, grp_Info[%d, %s].numPreSynapses = %d\n",g,grp_Info2[g].Name.c_str(),grp_Info[g].numPostSynapses,g,grp_Info2[g].Name.c_str(),grp_Info[g].numPreSynapses);
if (numPostSynapses > MAX_numPostSynapses) {
for (int g=0;g<numGrp;g++)
if (grp_Info[g].numPostSynapses>MAX_numPostSynapses) printf("Grp: %s(%d) has too many output synapses (%d), max %d.\n",grp_Info2[g].Name.c_str(),g,grp_Info[g].numPostSynapses,MAX_numPostSynapses);
assert(numPostSynapses <= MAX_numPostSynapses);
}
if (numPreSynapses > MAX_numPreSynapses) {
for (int g=0;g<numGrp;g++)
if (grp_Info[g].numPreSynapses>MAX_numPreSynapses) printf("Grp: %s(%d) has too many input synapses (%d), max %d.\n",grp_Info2[g].Name.c_str(),g,grp_Info[g].numPreSynapses,MAX_numPreSynapses);
assert(numPreSynapses <= MAX_numPreSynapses);
}
assert(curD <= MAX_SynapticDelay); assert(curN <= 1000000);
// initialize all the parameters....
CpuSNNInit(curN, numPostSynapses, numPreSynapses, curD);
// we build network in the order...
///// !!!!!!! IMPORTANT : NEURON ORGANIZATION/ARRANGEMENT MAP !!!!!!!!!!
//// <--- Excitatory --> | <-------- Inhibitory REGION ----------> | <-- Excitatory -->
/// Excitatory-Regular | Inhibitory-Regular | Inhibitory-Poisson | Excitatory-Poisson
int allocatedGrp = 0;
for(int order=0; order < 4; order++) {
for(int configId=0; configId < numConfig; configId++) {
for(int g=0; g < numGrp; g++) {
if (grp_Info2[g].ConfigId == configId) {
if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON) && order==3) {
buildPoissonGroup(g);
allocatedGrp++;
} else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON) && order==2) {
buildPoissonGroup(g);
allocatedGrp++;
} else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON) && order==0) {
buildGroup(g);
allocatedGrp++;
} else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON) && order==1) {
buildGroup(g);
allocatedGrp++;
}
}
}
}
}
assert(allocatedGrp == numGrp);
if (readNetworkFID != NULL) {
// we the user specified readNetwork the synaptic weights will be restored here...
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
// read the plastic synapses first
assert(readNetwork_internal(true) >= 0);
// read the fixed synapses secon
assert(readNetwork_internal(false) >= 0);
#else
assert(readNetwork_internal() >= 0);
connectFromMatrix(tmp_SynapseMatrix_plastic, SET_FIXED_PLASTIC(SYN_PLASTIC));
connectFromMatrix(tmp_SynapseMatrix_fixed, SET_FIXED_PLASTIC(SYN_FIXED));
#endif
} else {
// build all the connections here...
// we run over the linked list two times...
// first time, we make all plastic connections...
// second time, we make all fixed connections...
// this ensures that all the initial pre and post-synaptic
// connections are of fixed type and later if of plastic type
for(int con=0; con < 2; con++) {
newInfo = connectBegin;
while(newInfo) {
bool synWtType = GET_FIXED_PLASTIC(newInfo->connProp);
if (synWtType == SYN_PLASTIC) {
grp_Info[newInfo->grpDest].FixedInputWts = false; // given group has plastic connection, and we need to apply STDP rule...
}
if( ((con == 0) && (synWtType == SYN_PLASTIC)) ||
((con == 1) && (synWtType == SYN_FIXED)))
{
switch(newInfo->type)
{
case CONN_RANDOM:
connectRandom(newInfo);
break;
case CONN_FULL:
connectFull(newInfo);
break;
case CONN_FULL_NO_DIRECT:
connectFull(newInfo);
break;
case CONN_ONE_TO_ONE:
connectOneToOne(newInfo);
break;
case CONN_USER_DEFINED:
connectUserDefined(newInfo);
break;
default:
printf("Invalid connection type( should be 'random', or 'full')\n");
}
float avgPostM = newInfo->numberOfConnections/grp_Info[newInfo->grpSrc].SizeN;
float avgPreM = newInfo->numberOfConnections/grp_Info[newInfo->grpDest].SizeN;
fprintf(stderr, "connect(%s(%d) => %s(%d), iWt=%f, mWt=%f, numPostSynapses=%d, numPreSynapses=%d, minD=%d, maxD=%d, %s)\n",
grp_Info2[newInfo->grpSrc].Name.c_str(), newInfo->grpSrc, grp_Info2[newInfo->grpDest].Name.c_str(),
newInfo->grpDest, newInfo->initWt, newInfo->maxWt, (int)avgPostM, (int)avgPreM,
newInfo->minDelay, newInfo->maxDelay, synWtType?"Plastic":"Fixed");
}
newInfo = newInfo->next;
}
}
}
}
int CpuSNN::findGrpId(int nid)
{
for(int g=0; g < numGrp; g++) {
//printf("%d:%s s=%d e=%d\n", g, grp_Info2[g].Name.c_str(), grp_Info[g].StartN, grp_Info[g].EndN);
if(nid >=grp_Info[g].StartN && (nid <=grp_Info[g].EndN)) {
return g;
}
}
fprintf(stderr, "findGrp(): cannot find the group for neuron %d\n", nid);
assert(0);
}
void CpuSNN::writeNetwork(FILE* fid)
{
unsigned int version = 1;
fwrite(&version,sizeof(int),1,fid);
fwrite(&numGrp,sizeof(int),1,fid);
char name[100];
for (int g=0;g<numGrp;g++) {
fwrite(&grp_Info[g].StartN,sizeof(int),1,fid);
fwrite(&grp_Info[g].EndN,sizeof(int),1,fid);
strncpy(name,grp_Info2[g].Name.c_str(),100);
fwrite(name,1,100,fid);
}
int nrCells = numN;
fwrite(&nrCells,sizeof(int),1,fid);
for (unsigned int i=0;i<nrCells;i++) {
int offset = cumulativePost[i];
unsigned int count = 0;
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1)
count++;
}
fwrite(&count,sizeof(int),1,fid);
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
unsigned int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
// get syn id
unsigned int s_i = GET_CONN_SYN_ID(post_info);
//>>POST_SYN_NEURON_BITS)&POST_SYN_CONN_MASK;
assert(s_i<(Npre[p_i]));
// get the cumulative position for quick access...
unsigned int pos_i = cumulativePre[p_i] + s_i;
uint8_t delay = t+1;
uint8_t plastic = s_i < Npre_plastic[p_i]; // plastic or fixed.
fwrite(&i,sizeof(int),1,fid);
fwrite(&p_i,sizeof(int),1,fid);
fwrite(&(wt[pos_i]),sizeof(float),1,fid);
fwrite(&(maxSynWt[pos_i]),sizeof(float),1,fid);
fwrite(&delay,sizeof(uint8_t),1,fid);
fwrite(&plastic,sizeof(uint8_t),1,fid);
}
}
}
}
void CpuSNN::readNetwork(FILE* fid)
{
readNetworkFID = fid;
}
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
int CpuSNN::readNetwork_internal(bool onlyPlastic)
#else
int CpuSNN::readNetwork_internal()
#endif
{
long file_position = ftell(readNetworkFID); // so that we can restore the file position later...
unsigned int version;
if (!fread(&version,sizeof(int),1,readNetworkFID)) return -11;
if (version > 1) return -10;
int _numGrp;
if (!fread(&_numGrp,sizeof(int),1,readNetworkFID)) return -11;
if (numGrp != _numGrp) return -1;
char name[100];
int startN, endN;
for (int g=0;g<numGrp;g++) {
if (!fread(&startN,sizeof(int),1,readNetworkFID)) return -11;
if (!fread(&endN,sizeof(int),1,readNetworkFID)) return -11;
if (startN != grp_Info[g].StartN) return -2;
if (endN != grp_Info[g].EndN) return -3;
if (!fread(name,1,100,readNetworkFID)) return -11;
if (strcmp(name,grp_Info2[g].Name.c_str()) != 0) return -4;
}
int nrCells;
if (!fread(&nrCells,sizeof(int),1,readNetworkFID)) return -11;
if (nrCells != numN) return -5;
tmp_SynapseMatrix_fixed = new SparseWeightDelayMatrix(nrCells,nrCells,nrCells*10);
tmp_SynapseMatrix_plastic = new SparseWeightDelayMatrix(nrCells,nrCells,nrCells*10);
for (unsigned int i=0;i<nrCells;i++) {
unsigned int nrSynapses = 0;
if (!fread(&nrSynapses,sizeof(int),1,readNetworkFID)) return -11;
for (int j=0;j<nrSynapses;j++) {
unsigned int nIDpre;
unsigned int nIDpost;
float weight, maxWeight;
uint8_t delay;
uint8_t plastic;
if (!fread(&nIDpre,sizeof(int),1,readNetworkFID)) return -11;
if (nIDpre != i) return -6;
if (!fread(&nIDpost,sizeof(int),1,readNetworkFID)) return -11;
if (nIDpost >= nrCells) return -7;
if (!fread(&weight,sizeof(float),1,readNetworkFID)) return -11;
int gIDpre = findGrpId(nIDpre);
if (IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (weight>0) || !IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (weight<0)) return -8;
if (!fread(&maxWeight,sizeof(float),1,readNetworkFID)) return -11;
if (IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (maxWeight>=0) || !IS_INHIBITORY_TYPE(grp_Info[gIDpre].Type) && (maxWeight<=0)) return -8;
if (!fread(&delay,sizeof(uint8_t),1,readNetworkFID)) return -11;
if (delay > MAX_SynapticDelay) return -9;
if (!fread(&plastic,sizeof(uint8_t),1,readNetworkFID)) return -11;
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
if ((plastic && onlyPlastic) || (!plastic && !onlyPlastic)) {
int gIDpost = findGrpId(nIDpost);
int connProp = SET_FIXED_PLASTIC(plastic?SYN_PLASTIC:SYN_FIXED);
setConnection(gIDpre, gIDpost, nIDpre, nIDpost, weight, maxWeight, delay, connProp);
grp_Info2[gIDpre].sumPostConn++;
grp_Info2[gIDpost].sumPreConn++;
if (delay > grp_Info[gIDpre].MaxDelay) grp_Info[gIDpre].MaxDelay = delay;
}
#else
// add the synapse to the temporary Matrix so that it can be used in buildNetwork()
if (plastic) {
tmp_SynapseMatrix_plastic->add(nIDpre,nIDpost,weight,maxWeight,delay,plastic);
} else {
tmp_SynapseMatrix_fixed->add(nIDpre,nIDpost,weight,maxWeight,delay,plastic);
}
#endif
}
}
#if READNETWORK_ADD_SYNAPSES_FROM_FILE
fseek(readNetworkFID,file_position,SEEK_SET);
#endif
return 0;
}
float* CpuSNN::getWeights(int gIDpre, int gIDpost, int& Npre, int& Npost, float* weights) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (weights==NULL) weights = new float[Npre*Npost];
memset(weights,0,Npre*Npost*sizeof(float));
// copy the pre synaptic data from GPU, if needed
if (currentMode == GPU_MODE) copyWeightState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, gIDpost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
weights[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = cpuNetPtrs.wt[pos_i];
}
}
}
}
return weights;
}
float* CpuSNN::getWeightChanges(int gIDpre, int gIDpost, int& Npre, int& Npost, float* weightChanges) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (weightChanges==NULL) weightChanges = new float[Npre*Npost];
memset(weightChanges,0,Npre*Npost*sizeof(float));
// copy the pre synaptic data from GPU, if needed
if (currentMode == GPU_MODE) copyWeightState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, gIDpost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
weightChanges[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = wtChange[pos_i];
}
}
}
}
return weightChanges;
}
uint8_t* CpuSNN::getDelays(int gIDpre, int gIDpost, int& Npre, int& Npost, uint8_t* delays) {
Npre = grp_Info[gIDpre].SizeN;
Npost = grp_Info[gIDpost].SizeN;
if (delays == NULL) delays = new uint8_t[Npre*Npost];
memset(delays,0,Npre*Npost);
for (int i=grp_Info[gIDpre].StartN;i<grp_Info[gIDpre].EndN;i++) {
int offset = cumulativePost[i];
for (int t=0;t<D;t++) {
delay_info_t dPar = postDelayInfo[i*(D+1)+t];
for(int idx_d = dPar.delay_index_start; idx_d < (dPar.delay_index_start + dPar.delay_length); idx_d = idx_d+1) {
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
//int p_i = (post_info&POST_SYN_NEURON_MASK);
int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
if (p_i >= grp_Info[gIDpost].StartN && p_i <= grp_Info[gIDpost].EndN) {
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
delays[i+Npre*(p_i-grp_Info[gIDpost].StartN)] = t+1;
}
}
}
}
return delays;
}
// This function is called every second by simulator...
// This function updates the firingTable by removing older firing values...
// and also update the synaptic weights from its derivatives..
void CpuSNN::updateStateAndFiringTable()
{
// Read the neuron ids that fired in the last D seconds
// and put it to the beginning of the firing table...
for(int p=timeTableD2[999],k=0;p<timeTableD2[999+D+1];p++,k++) {
firingTableD2[k]=firingTableD2[p];
}
for(int i=0; i < D; i++) {
timeTableD2[i+1] = timeTableD2[1000+i+1]-timeTableD2[1000];
}
timeTableD1[D] = 0;
// update synaptic weights here for all the neurons..
for(int g=0; g < numGrp; g++) {
// no changable weights so continue without changing..
if(grp_Info[g].FixedInputWts || !(grp_Info[g].WithSTDP)) {
// for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++)
// nSpikeCnt[i]=0;
continue;
}
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
///nSpikeCnt[i] = 0;
assert(i < numNReg);
int offset = cumulativePre[i];
float diff_firing = 0.0;
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"Weights, Change at %lu (diff_firing:%f) \n", simTimeSec, diff_firing);
for(int j=0; j < Npre_plastic[i]; j++) {
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"%1.2f %1.2f \t", wt[offset+j]*10, wtChange[offset+j]*10);
wt[offset+j] += wtChange[offset+j];
//MDR - don't decay weights, just set to 0
//wtChange[offset+j]*=0.99f;
wtChange[offset+j] = 0;
// if this is an excitatory or inhibitory synapse
if (maxSynWt[offset+j] >= 0) {
if (wt[offset+j]>=maxSynWt[offset+j])
wt[offset+j] = maxSynWt[offset+j];
if (wt[offset+j]<0)
wt[offset+j] = 0.0;
} else {
if (wt[offset+j]<=maxSynWt[offset+j])
wt[offset+j] = maxSynWt[offset+j];
if (wt[offset+j]>0)
wt[offset+j] = 0.0;
}
}
if ((showLogMode >= 1) && (i==grp_Info[g].StartN))
fprintf(fpProgLog,"\n");
}
}
spikeCountAll += spikeCountAll1sec;
spikeCountD2 += (secD2fireCnt-timeTableD2[D]);
spikeCountD1 += secD1fireCnt;
secD1fireCnt = 0;
spikeCountAll1sec = 0;
secD2fireCnt = timeTableD2[D];
for(int i=0; i < numGrp; i++) {
grp_Info[i].FiringCount1sec=0;
}
}
// This method loops through all spikes that are generated by neurons with a delay of 2+ms
// and delivers the spikes to the appropriate post-synaptic neuron
void CpuSNN::doD2CurrentUpdate()
{
int k = secD2fireCnt-1;
int k_end = timeTableD2[simTimeMs+1];
int t_pos = simTimeMs;
while((k>=k_end)&& (k >=0)) {
// get the neuron id from the index k
int i = firingTableD2[k];
// find the time of firing from the timeTable using index k
while (!((k >= timeTableD2[t_pos+D])&&(k < timeTableD2[t_pos+D+1]))) {
t_pos = t_pos - 1;
assert((t_pos+D-1)>=0);
}
// TODO: Instead of using the complex timeTable, can neuronFiringTime value...???
// Calculate the time difference between time of firing of neuron and the current time...
int tD = simTimeMs - t_pos;
assert((tD<D)&&(tD>=0));
assert(i<numN);
delay_info_t dPar = postDelayInfo[i*(D+1)+tD];
int offset = cumulativePost[i];
// for each delay variables
for(int idx_d = dPar.delay_index_start;
idx_d < (dPar.delay_index_start + dPar.delay_length);
idx_d = idx_d+1) {
generatePostSpike( i, idx_d, offset, tD);
}
k=k-1;
}
}
// This method loops through all spikes that are generated by neurons with a delay of 1ms
// and delivers the spikes to the appropriate post-synaptic neuron
void CpuSNN::doD1CurrentUpdate()
{
int k = secD1fireCnt-1;
int k_end = timeTableD1[simTimeMs+D];
while((k>=k_end) && (k>=0)) {
int neuron_id = firingTableD1[k];
assert(neuron_id<numN);
delay_info_t dPar = postDelayInfo[neuron_id*(D+1)];
int offset = cumulativePost[neuron_id];
for(int idx_d = dPar.delay_index_start;
idx_d < (dPar.delay_index_start + dPar.delay_length);
idx_d = idx_d+1) {
generatePostSpike( neuron_id, idx_d, offset, 0);
}
k=k-1;
}
}
void CpuSNN::generatePostSpike(unsigned int pre_i, unsigned int idx_d, unsigned int offset, unsigned int tD)
{
// get synaptic info...
post_info_t post_info = postSynapticIds[offset + idx_d];
// get neuron id
unsigned int p_i = GET_CONN_NEURON_ID(post_info);
assert(p_i<numN);
// get syn id
int s_i = GET_CONN_SYN_ID(post_info);
assert(s_i<(Npre[p_i]));
// get the cumulative position for quick access...
int pos_i = cumulativePre[p_i] + s_i;
assert(p_i < numNReg);
float change;
int pre_grpId = findGrpId(pre_i);
char type = grp_Info[pre_grpId].Type;
// TODO: MNJ TEST THESE CONDITIONS FOR CORRECTNESS...
int ind = STP_BUF_POS(pre_i,(simTime-tD-1));
// if the source group STP is disabled. we need to skip it..
if (grp_Info[pre_grpId].WithSTP) {
change = wt[pos_i]*stpx[ind]*stpu[ind];
} else
change = wt[pos_i];
if (grp_Info[pre_grpId].WithConductances) {
if (type & TARGET_AMPA) gAMPA [p_i] += change;
if (type & TARGET_NMDA) gNMDA [p_i] += change;
if (type & TARGET_GABAa) gGABAa[p_i] -= change; // wt should be negative for GABAa and GABAb
if (type & TARGET_GABAb) gGABAb[p_i] -= change;
} else
current[p_i] += change;
int post_grpId = findGrpId(p_i);
if ((showLogMode >= 3) && (p_i==grp_Info[post_grpId].StartN))
printf("%d => %d (%d) am=%f ga=%f wt=%f stpu=%f stpx=%f td=%d\n",
pre_i, p_i, findGrpId(p_i), gAMPA[p_i], gGABAa[p_i],
wt[pos_i],(grp_Info[post_grpId].WithSTP?stpx[ind]:1.0),(grp_Info[post_grpId].WithSTP?stpu[ind]:1.0),tD);
// STDP calculation....
if (grp_Info[post_grpId].WithSTDP) {
//stdpChanged[pos_i]=false;
//assert((simTime-lastSpikeTime[p_i])>=0);
int stdp_tDiff = (simTime-lastSpikeTime[p_i]);
if (stdp_tDiff >= 0) {
#ifdef INHIBITORY_STDP
if ((type & TARGET_GABAa) || (type & TARGET_GABAb))
{
//printf("I");
if ((stdp_tDiff*grp_Info[post_grpId].TAU_LTD_INV)<25)
wtChange[pos_i] -= (STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTP, grp_Info[post_grpId].TAU_LTP_INV) - STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTD*1.5, grp_Info[post_grpId].TAU_LTD_INV));
}
else
#endif
{
//printf("E");
if ((stdp_tDiff*grp_Info[post_grpId].TAU_LTD_INV)<25)
wtChange[pos_i] -= STDP(stdp_tDiff, grp_Info[post_grpId].ALPHA_LTD, grp_Info[post_grpId].TAU_LTD_INV);
}
}
assert(!((stdp_tDiff < 0) && (lastSpikeTime[p_i] != MAX_SIMULATION_TIME)));
}
synSpikeTime[pos_i] = simTime;
}
void CpuSNN::globalStateUpdate()
{
#define CUR_DEBUG 1
//fprintf(stdout, "---%d ----\n", simTime);
// now we update the state of all the neurons
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].Type&POISSON_NEURON) continue;
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
assert(i < numNReg);
if (grp_Info[g].WithConductances) {
for (int j=0; j<COND_INTEGRATION_SCALE; j++) {
float NMDAtmp = (voltage[i]+80)*(voltage[i]+80)/60/60;
float tmpI = - ( gAMPA[i]*(voltage[i]-0)
+ gNMDA[i]*NMDAtmp/(1+NMDAtmp)*(voltage[i]-0)
+ gGABAa[i]*(voltage[i]+70)
+ gGABAb[i]*(voltage[i]+90));
#ifdef NEURON_NOISE
float noiseI = -intrinsicWeight[i]*log(getRand());
if (isnan(noiseI) || isinf(noiseI)) noiseI = 0;
tmpI += noiseI;
#endif
// Icurrent[i] = tmpI;
voltage[i]+=((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+tmpI)/COND_INTEGRATION_SCALE;
assert(!isnan(voltage[i]) && !isinf(voltage[i]));
if (voltage[i] > 30) {
voltage[i] = 30;
j=COND_INTEGRATION_SCALE; // break the loop but evaluate u[i]
}
if (voltage[i] < -90) voltage[i] = -90;
recovery[i]+=Izh_a[i]*(Izh_b[i]*voltage[i]-recovery[i])/COND_INTEGRATION_SCALE;
}
//if (i==grp_Info[6].StartN) printf("voltage: %f AMPA: %f NMDA: %f GABAa: %f GABAb: %f\n",voltage[i],gAMPA[i],gNMDA[i],gGABAa[i],gGABAb[i]);
} else {
voltage[i]+=0.5f*((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+current[i]); // for numerical stability
voltage[i]+=0.5f*((0.04f*voltage[i]+5)*voltage[i]+140-recovery[i]+current[i]); // time step is 0.5 ms
if (voltage[i] > 30) voltage[i] = 30;
if (voltage[i] < -90) voltage[i] = -90;
recovery[i]+=Izh_a[i]*(Izh_b[i]*voltage[i]-recovery[i]);
}
if ((showLogMode >= 2) && (i==grp_Info[g].StartN))
fprintf(stdout, "%d: voltage=%0.3f, recovery=%0.5f, AMPA=%0.5f, NMDA=%0.5f\n",
i, voltage[i], recovery[i], gAMPA[i], gNMDA[i]);
}
}
}
void CpuSNN::printWeight(int grpId, const char *str)
{
int stg, endg;
if(grpId == -1) {
stg = 0;
endg = numGrp;
}
else {
stg = grpId;
endg = grpId+1;
}
for(int g=stg; (g < endg) ; g++) {
fprintf(stderr, "%s", str);
if (!grp_Info[g].FixedInputWts) {
//fprintf(stderr, "w=\t");
if (currentMode == GPU_MODE) {
copyWeightState (&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, g);
}
int i=grp_Info[g].StartN;
int offset = cumulativePre[i];
//fprintf(stderr, "time=%d, Neuron synaptic weights %d:\n", simTime, i);
for(int j=0; j < Npre[i]; j++) {
//fprintf(stderr, "w=%f c=%f spt=%d\t", wt[offset+j], wtChange[offset+j], synSpikeTime[offset+j]);
fprintf(stdout, "%1.3f,%1.3f\t", cpuNetPtrs.wt[offset+j], cpuNetPtrs.wtChange[offset+j]);
}
fprintf(stdout, "\n");
}
}
}
// show the status of the simulator...
// when onlyCnt is set, we print the actual count instead of frequency of firing
void CpuSNN::showStatus(int simType)
{
DBG(2, fpLog, AT, "showStatus() called");
printState("showStatus");
if(simType == GPU_MODE) {
showStatus_GPU();
return;
}
FILE* fpVal[2];
fpVal[0] = fpLog;
fpVal[1] = fpProgLog;
for(int k=0; k < 2; k++) {
if(k==0)
printWeight(-1);
fprintf(fpVal[k], "(time=%lld) =========\n\n", (unsigned long long) simTimeSec);
#if REG_TESTING
// if the overall firing rate is very low... then report error...
if((spikeCountAll1sec*1.0f/numN) < 1.0) {
fprintf(fpVal[k], " SIMULATION WARNING !!! Very Low Firing happened...\n");
fflush(fpVal[k]);
}
#endif
fflush(fpVal[k]);
}
#if REG_TESTING
if(spikeCountAll1sec == 0) {
fprintf(stderr, " SIMULATION ERROR !!! Very Low or no firing happened...\n");
//exit(-1);
}
#endif
}
void CpuSNN::startCPUTiming()
{
prevCpuExecutionTime = cumExecutionTime;
}
void CpuSNN::resetCPUTiming()
{
prevCpuExecutionTime = cumExecutionTime;
cpuExecutionTime = 0.0;
}
void CpuSNN::stopCPUTiming()
{
cpuExecutionTime += (cumExecutionTime - prevCpuExecutionTime);
prevCpuExecutionTime = cumExecutionTime;
}
void CpuSNN::startGPUTiming()
{
prevGpuExecutionTime = cumExecutionTime;
}
void CpuSNN::resetGPUTiming()
{
prevGpuExecutionTime = cumExecutionTime;
gpuExecutionTime = 0.0;
}
void CpuSNN::stopGPUTiming()
{
gpuExecutionTime += (cumExecutionTime - prevGpuExecutionTime);
prevGpuExecutionTime = cumExecutionTime;
}
// reorganize the network and do the necessary allocation
// of all variable for carrying out the simulation..
// this code is run only one time during network initialization
void CpuSNN::setupNetwork(int simType, bool removeTempMem)
{
if(!doneReorganization)
reorganizeNetwork(removeTempMem, simType);
if((simType == GPU_MODE) && (cpu_gpuNetPtrs.allocated == false))
allocateSNN_GPU();
}
bool CpuSNN::updateTime()
{
bool finishedOneSec = false;
// done one second worth of simulation
// update relevant parameters...now
if(++simTimeMs == 1000) {
simTimeMs = 0;
simTimeSec++;
finishedOneSec = true;
}
simTime++;
if(simTime >= MAX_SIMULATION_TIME){
// reached the maximum limit of the simulation time using 32 bit value...
updateAfterMaxTime();
}
return finishedOneSec;
}
// Run the simulation for n sec
int CpuSNN::runNetwork(int _nsec, int _nmsec, int simType, bool enablePrint, int copyState)
{
DBG(2, fpLog, AT, "runNetwork() called");
assert(_nmsec >= 0);
assert(_nsec >= 0);
assert(simType == CPU_MODE || simType == GPU_MODE);
int runDuration = _nsec*1000 + _nmsec;
setGrpTimeSlice(ALL, MAX(1,MIN(runDuration,PROPOGATED_BUFFER_SIZE-1))); // set the Poisson generation time slice to be at the run duration up to PROPOGATED_BUFFER_SIZE ms.
// First time when the network is run we do various kind of space compression,
// and data structure optimization to improve performance and save memory.
setupNetwork(simType);
currentMode = simType;
cutResetTimer(timer);
cutStartTimer(timer);
// if nsec=0, simTimeMs=10, we need to run the simulator for 10 timeStep;
// if nsec=1, simTimeMs=10, we need to run the simulator for 1*1000+10, time Step;
for(int i=0; i < runDuration; i++) {
// initThalInput();
if(simType == CPU_MODE)
doSnnSim();
else
doGPUSim();
if (enablePrint) {
printState();
}
if (updateTime()) {
// finished one sec of simulation...
if(showLog)
if(showLogCycle==showLog++) {
showStatus(currentMode);
showLog=1;
}
updateSpikeMonitor();
if(simType == CPU_MODE)
updateStateAndFiringTable();
else
updateStateAndFiringTable_GPU();
}
}
if(copyState) {
// copy the state from GPU to GPU
for(int g=0; g < numGrp; g++) {
if ((!grp_Info[g].isSpikeGenerator) && (currentMode==GPU_MODE)) {
copyNeuronState(&cpuNetPtrs, &cpu_gpuNetPtrs, cudaMemcpyDeviceToHost, false, g);
}
}
}
// keep track of simulation time...
cutStopTimer(timer);
lastExecutionTime = cutGetTimerValue(timer);
if(0) {
fprintf(fpLog, "(t%s = %2.2f sec)\n", (currentMode == GPU_MODE)?"GPU":"CPU", lastExecutionTime/1000);
fprintf(stdout, "(t%s = %2.2f sec)\n", (currentMode == GPU_MODE)?"GPU":"CPU", lastExecutionTime/1000);
}
cumExecutionTime += lastExecutionTime;
return 0;
}
void CpuSNN::updateAfterMaxTime()
{
fprintf(stderr, "Maximum Simulation Time Reached...Resetting simulation time\n");
// This will be our cut of time. All other time values
// that are less than cutOffTime will be set to zero
unsigned int cutOffTime = (MAX_SIMULATION_TIME - 10*1000);
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].isSpikeGenerator) {
int diffTime = (grp_Info[g].SliceUpdateTime - cutOffTime);
grp_Info[g].SliceUpdateTime = (diffTime < 0) ? 0 : diffTime;
}
// no STDP then continue...
if(!grp_Info[g].FixedInputWts) {
continue;
}
for(int k=0, nid = grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++,k++) {
assert(nid < numNReg);
// calculate the difference in time
signed diffTime = (lastSpikeTime[nid] - cutOffTime);
lastSpikeTime[nid] = (diffTime < 0) ? 0 : diffTime;
// do the same thing with all synaptic connections..
unsigned* synTime = &synSpikeTime[cumulativePre[nid]];
for(int i=0; i < Npre[nid]; i++, synTime++) {
// calculate the difference in time
signed diffTime = (synTime[0] - cutOffTime);
synTime[0] = (diffTime < 0) ? 0 : diffTime;
}
}
}
simTime = MAX_SIMULATION_TIME - cutOffTime;
resetPropogationBuffer();
}
void CpuSNN::resetPropogationBuffer()
{
pbuf->reset(0, 1023);
}
unsigned int poissonSpike(unsigned int currTime, float frate, int refractPeriod)
{
bool done = false;
unsigned int nextTime = 0;
assert(refractPeriod>0); // refractory period must be 1 or greater, 0 means could have multiple spikes specified at the same time.
static int cnt = 0;
while(!done)
{
float randVal = drand48();
unsigned int tmpVal = -log(randVal)/frate;
nextTime = currTime + tmpVal;
//fprintf(stderr, "%d: next random = %f, frate = %f, currTime = %d, nextTime = %d tmpVal = %d\n", cnt++, randVal, frate, currTime, nextTime, tmpVal);
if ((nextTime - currTime) >= (unsigned) refractPeriod)
done = true;
}
assert(nextTime != 0);
return nextTime;
}
//
void CpuSNN::updateSpikeGeneratorsInit()
{
int cnt=0;
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator) {
// This is done only during initialization
grp_Info[g].CurrTimeSlice = grp_Info[g].NewTimeSlice;
// we only need NgenFunc for spike generator callbacks that need to transfer their spikes to the GPU
if (grp_Info[g].spikeGen) {
grp_Info[g].Noffset = NgenFunc;
NgenFunc += grp_Info[g].SizeN;
}
updateSpikesFromGrp(g);
cnt++;
assert(cnt <= numSpikeGenGrps);
}
}
// spikeGenBits can be set only once..
assert(spikeGenBits == NULL);
if (NgenFunc) {
spikeGenBits = new uint32_t[NgenFunc/32+1];
cpuNetPtrs.spikeGenBits = spikeGenBits;
// increase the total memory size used by the routine...
cpuSnnSz.addInfoSize += sizeof(spikeGenBits[0])*(NgenFunc/32+1);
}
}
void CpuSNN::updateSpikeGenerators()
{
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator) {
// This evaluation is done to check if its time to get new set of spikes..
// fprintf(stderr, "[MODE=%s] simtime = %d, NumTimeSlice = %d, SliceUpdate = %d, currTime = %d\n",
// (currentMode==GPU_MODE)?"GPU_MODE":"CPU_MODE", simTime, grp_Info[g].NumTimeSlice,
// grp_Info[g].SliceUpdateTime, grp_Info[g].CurrTimeSlice);
if(((simTime-grp_Info[g].SliceUpdateTime) >= (unsigned) grp_Info[g].CurrTimeSlice))
updateSpikesFromGrp(g);
}
}
}
void CpuSNN::generateSpikesFromFuncPtr(int grpId)
{
bool done;
SpikeGenerator* spikeGen = grp_Info[grpId].spikeGen;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
unsigned int currTime = simTime;
int spikeCnt=0;
for(int i=grp_Info[grpId].StartN;i<=grp_Info[grpId].EndN;i++) {
// start the time from the last time it spiked, that way we can ensure that the refractory period is maintained
unsigned int nextTime = lastSpikeTime[i];
if (nextTime == MAX_SIMULATION_TIME)
nextTime = 0;
done = false;
while (!done) {
nextTime = spikeGen->nextSpikeTime(this, grpId, i-grp_Info[grpId].StartN, nextTime);
// found a valid time window
if (nextTime < (currTime+timeSlice)) {
if (nextTime >= currTime) {
// scheduled spike...
//fprintf(stderr, "scheduled time = %d, nid = %d\n", nextTime, i);
pbuf->scheduleSpikeTargetGroup(i, nextTime-currTime);
spikeCnt++;
}
}
else {
done=true;
}
}
}
}
void CpuSNN::generateSpikesFromRate(int grpId)
{
bool done;
PoissonRate* rate = grp_Info[grpId].RatePtr;
float refPeriod = grp_Info[grpId].RefractPeriod;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
unsigned int currTime = simTime;
int spikeCnt = 0;
if (rate == NULL) return;
if (rate->onGPU) {
printf("specifying rates on the GPU but using the CPU SNN is not supported.\n");
return;
}
const float* ptr = rate->rates;
for (int cnt=0;cnt<rate->len;cnt++,ptr++) {
float frate = *ptr;
unsigned int nextTime = lastSpikeTime[grp_Info[grpId].StartN+cnt]; // start the time from the last time it spiked, that way we can ensure that the refractory period is maintained
if (nextTime == MAX_SIMULATION_TIME)
nextTime = 0;
done = false;
while (!done && frate>0) {
nextTime = poissonSpike (nextTime, frate/1000.0, refPeriod);
// found a valid timeSlice
if (nextTime < (currTime+timeSlice)) {
if (nextTime >= currTime) {
int nid = grp_Info[grpId].StartN+cnt;
pbuf->scheduleSpikeTargetGroup(nid, nextTime-currTime);
spikeCnt++;
}
}
else {
done=true;
}
}
}
}
void CpuSNN::updateSpikesFromGrp(int grpId)
{
assert(grp_Info[grpId].isSpikeGenerator==true);
bool done;
//static FILE* fp = fopen("spikes.txt", "w");
unsigned int currTime = simTime;
int timeSlice = grp_Info[grpId].CurrTimeSlice;
grp_Info[grpId].SliceUpdateTime = simTime;
// we dont generate any poisson spike if during the
// current call we might exceed the maximum 32 bit integer value
if (((uint64_t) currTime + timeSlice) >= MAX_SIMULATION_TIME)
return;
if (grp_Info[grpId].spikeGen) {
generateSpikesFromFuncPtr(grpId);
} else {
// current mode is GPU, and GPU would take care of poisson generators
// and other information about refractor period etc. So no need to continue further...
#if !TESTING_CPU_GPU_POISSON
if(currentMode == GPU_MODE)
return;
#endif
generateSpikesFromRate(grpId);
}
}
inline int CpuSNN::getPoissNeuronPos(int nid)
{
int nPos = nid-numNReg;
assert(nid >= numNReg);
assert(nid < numN);
assert((nid-numNReg) < numNPois);
return nPos;
}
void CpuSNN::setSpikeRate(int grpId, PoissonRate* ratePtr, int refPeriod, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeRate(grpId, ratePtr, refPeriod,c);
} else {
int cGrpId = getGroupId(grpId, configId);
if(grp_Info[cGrpId].RatePtr==NULL) {
fprintf(fpParam, " // refPeriod = %d\n", refPeriod);
}
assert(ratePtr);
if (ratePtr->len != grp_Info[cGrpId].SizeN) {
fprintf(stderr,"The PoissonRate length did not match the number of neurons in group %s(%d).\n", grp_Info2[cGrpId].Name.c_str(),grpId);
assert(0);
}
assert (grp_Info[cGrpId].isSpikeGenerator);
grp_Info[cGrpId].RatePtr = ratePtr;
grp_Info[cGrpId].RefractPeriod = refPeriod;
spikeRateUpdated = true;
}
}
void CpuSNN::setSpikeGenerator(int grpId, SpikeGenerator* spikeGen, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeGenerator(grpId, spikeGen,c);
} else {
int cGrpId = getGroupId(grpId, configId);
assert(spikeGen);
assert (grp_Info[cGrpId].isSpikeGenerator);
grp_Info[cGrpId].spikeGen = spikeGen;
}
}
void CpuSNN::generateSpikes()
{
PropagatedSpikeBuffer::const_iterator srg_iter;
PropagatedSpikeBuffer::const_iterator srg_iter_end = pbuf->endSpikeTargetGroups();
for( srg_iter = pbuf->beginSpikeTargetGroups(); srg_iter != srg_iter_end; ++srg_iter ) {
// Get the target neurons for the given groupId
int nid = srg_iter->stg;
//delaystep_t del = srg_iter->delay;
//generate a spike to all the target neurons from source neuron nid with a delay of del
int g = findGrpId(nid);
addSpikeToTable (nid, g);
//fprintf(stderr, "nid = %d\t", nid);
spikeCountAll1sec++;
nPoissonSpikes++;
}
//fprintf(stderr, "\n");
// advance the time step to the next phase...
pbuf->nextTimeStep();
}
void CpuSNN::setGrpTimeSlice(int grpId, int timeSlice)
{
if (grpId == ALL) {
for(int g=0; (g < numGrp); g++) {
if (grp_Info[g].isSpikeGenerator)
setGrpTimeSlice(g, timeSlice);
}
} else {
assert((timeSlice > 0 ) && (timeSlice < PROPOGATED_BUFFER_SIZE));
// the group should be poisson spike generator group
grp_Info[grpId].NewTimeSlice = timeSlice;
grp_Info[grpId].CurrTimeSlice = timeSlice;
}
}
int CpuSNN::addSpikeToTable(int nid, int g)
{
int spikeBufferFull = 0;
lastSpikeTime[nid] = simTime;
curSpike[nid] = true;
nSpikeCnt[nid]++;
if(showLogMode >= 3)
if (nid<128) printf("spiked: %d\n",nid);
if (currentMode == GPU_MODE) {
assert(grp_Info[g].isSpikeGenerator == true);
setSpikeGenBit_GPU(nid, g);
return 0;
}
if (grp_Info[g].WithSTP) {
// implements Mongillo, Barak and Tsodyks model of Short term plasticity
int ind = STP_BUF_POS(nid,simTime);
int ind_1 = STP_BUF_POS(nid,(simTime-1)); // MDR -1 is correct, we use the value before the decay has been applied for the current time step.
stpx[ind] = stpx[ind] - stpu[ind_1]*stpx[ind_1];
stpu[ind] = stpu[ind] + grp_Info[g].STP_U*(1-stpu[ind_1]);
}
if (grp_Info[g].MaxDelay == 1) {
assert(nid < numN);
firingTableD1[secD1fireCnt] = nid;
secD1fireCnt++;
grp_Info[g].FiringCount1sec++;
if (secD1fireCnt >= maxSpikesD1) {
spikeBufferFull = 2;
secD1fireCnt = maxSpikesD1-1;
}
}
else {
assert(nid < numN);
firingTableD2[secD2fireCnt] = nid;
grp_Info[g].FiringCount1sec++;
secD2fireCnt++;
if (secD2fireCnt >= maxSpikesD2) {
spikeBufferFull = 1;
secD2fireCnt = maxSpikesD2-1;
}
}
return spikeBufferFull;
}
void CpuSNN::findFiring()
{
int spikeBufferFull = 0;
for(int g=0; (g < numGrp) & !spikeBufferFull; g++) {
// given group of neurons belong to the poisson group....
if (grp_Info[g].Type&POISSON_NEURON)
continue;
// his flag is set if with_stdp is set and also grpType is set to have GROUP_SYN_FIXED
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
assert(i < numNReg);
if (grp_Info[g].WithConductances) {
gAMPA[i] *= grp_Info[g].dAMPA;
gNMDA[i] *= grp_Info[g].dNMDA;
gGABAa[i] *= grp_Info[g].dGABAa;
gGABAb[i] *= grp_Info[g].dGABAb;
}
if (voltage[i] >= 30.0) {
voltage[i] = Izh_c[i];
recovery[i] += Izh_d[i];
spikeBufferFull = addSpikeToTable(i, g);
if (spikeBufferFull) break;
if (grp_Info[g].WithSTDP) {
int pos_ij = cumulativePre[i];
for(int j=0; j < Npre_plastic[i]; pos_ij++, j++) {
//stdpChanged[pos_ij] = true;
int stdp_tDiff = (simTime-synSpikeTime[pos_ij]);
assert(!((stdp_tDiff < 0) && (synSpikeTime[pos_ij] != MAX_SIMULATION_TIME)));
// don't do LTP if time difference is a lot..
if (stdp_tDiff > 0)
#ifdef INHIBITORY_STDP
// if this is an excitatory or inhibitory synapse
if (maxSynWt[pos_ij] >= 0)
#endif
if ((stdp_tDiff*grp_Info[g].TAU_LTP_INV)<25)
wtChange[pos_ij] += STDP(stdp_tDiff, grp_Info[g].ALPHA_LTP, grp_Info[g].TAU_LTP_INV);
#ifdef INHIBITORY_STDP
else
if ((stdp_tDiff > 0) && ((stdp_tDiff*grp_Info[g].TAU_LTD_INV)<25))
wtChange[pos_ij] -= (STDP(stdp_tDiff, grp_Info[g].ALPHA_LTP, grp_Info[g].TAU_LTP_INV) - STDP(stdp_tDiff, grp_Info[g].ALPHA_LTD*1.5, grp_Info[g].TAU_LTD_INV));
#endif
}
}
spikeCountAll1sec++;
}
}
}
}
void CpuSNN::doSTPUpdates()
{
int spikeBufferFull = 0;
//decay the STP variables before adding new spikes.
for(int g=0; (g < numGrp) & !spikeBufferFull; g++) {
if (grp_Info[g].WithSTP) {
for(int i=grp_Info[g].StartN; i <= grp_Info[g].EndN; i++) {
int ind = 0, ind_1 = 0;
ind = STP_BUF_POS(i,simTime);
ind_1 = STP_BUF_POS(i,(simTime-1));
stpx[ind] = stpx[ind_1] + (1-stpx[ind_1])/grp_Info[g].STP_tD;
stpu[ind] = stpu[ind_1] + (grp_Info[g].STP_U - stpu[ind_1])/grp_Info[g].STP_tF;
}
}
}
}
void CpuSNN::doSnnSim()
{
doSTPUpdates();
//return;
updateSpikeGenerators();
//generate all the scheduled spikes from the spikeBuffer..
generateSpikes();
if(0) fprintf(fpProgLog, "\nLTP time=%d, \n", simTime);
// find the neurons that has fired..
findFiring();
timeTableD2[simTimeMs+D+1] = secD2fireCnt;
timeTableD1[simTimeMs+D+1] = secD1fireCnt;
if(0) fprintf(fpProgLog, "\nLTD time=%d,\n", simTime);
doD2CurrentUpdate();
doD1CurrentUpdate();
globalStateUpdate();
updateMonitors();
return;
}
void CpuSNN::swapConnections(int nid, int oldPos, int newPos)
{
int cumN=cumulativePost[nid];
// Put the node oldPos to the top of the delay queue
post_info_t tmp = postSynapticIds[cumN+oldPos];
postSynapticIds[cumN+oldPos]= postSynapticIds[cumN+newPos];
postSynapticIds[cumN+newPos]= tmp;
// Ensure that you have shifted the delay accordingly....
uint8_t tmp_delay = tmp_SynapticDelay[cumN+oldPos];
tmp_SynapticDelay[cumN+oldPos] = tmp_SynapticDelay[cumN+newPos];
tmp_SynapticDelay[cumN+newPos] = tmp_delay;
// update the pre-information for the postsynaptic neuron at the position oldPos.
post_info_t postInfo = postSynapticIds[cumN+oldPos];
int post_nid = GET_CONN_NEURON_ID(postInfo);
int post_sid = GET_CONN_SYN_ID(postInfo);
post_info_t* preId = &preSynapticIds[cumulativePre[post_nid]+post_sid];
int pre_nid = GET_CONN_NEURON_ID((*preId));
int pre_sid = GET_CONN_SYN_ID((*preId));
int pre_gid = GET_CONN_GRP_ID((*preId));
assert (pre_nid == nid);
assert (pre_sid == newPos);
*preId = SET_CONN_ID( pre_nid, oldPos, pre_gid);
// update the pre-information for the postsynaptic neuron at the position newPos
postInfo = postSynapticIds[cumN+newPos];
post_nid = GET_CONN_NEURON_ID(postInfo);
post_sid = GET_CONN_SYN_ID(postInfo);
preId = &preSynapticIds[cumulativePre[post_nid]+post_sid];
pre_nid = GET_CONN_NEURON_ID((*preId));
pre_sid = GET_CONN_SYN_ID((*preId));
pre_gid = GET_CONN_GRP_ID((*preId));
assert (pre_nid == nid);
assert (pre_sid == oldPos);
*preId = SET_CONN_ID( pre_nid, newPos, pre_gid);
}
// The post synaptic connections are sorted based on delay here so that we can reduce storage requirement
// and generation of spike at the post-synaptic side.
// We also create the delay_info array has the delay_start and delay_length parameter
void CpuSNN::reorganizeDelay()
{
for(int grpId=0; grpId < numGrp; grpId++) {
for(int nid=grp_Info[grpId].StartN; nid <= grp_Info[grpId].EndN; nid++) {
unsigned int jPos=0; // this points to the top of the delay queue
unsigned int cumN=cumulativePost[nid]; // cumulativePost[] is unsigned int
unsigned int cumDelayStart=0; // Npost[] is unsigned short
for(int td = 0; td < D; td++) {
unsigned int j=jPos; // start searching from top of the queue until the end
unsigned int cnt=0; // store the number of nodes with a delay of td;
while(j < Npost[nid]) {
// found a node j with delay=td and we put
// the delay value = 1 at array location td=0;
if(td==(tmp_SynapticDelay[cumN+j]-1)) {
assert(jPos<Npost[nid]);
swapConnections(nid, j, jPos);
jPos=jPos+1;
cnt=cnt+1;
}
j=j+1;
}
// update the delay_length and start values...
postDelayInfo[nid*(D+1)+td].delay_length = cnt;
postDelayInfo[nid*(D+1)+td].delay_index_start = cumDelayStart;
cumDelayStart += cnt;
assert(cumDelayStart <= Npost[nid]);
}
// total cumulative delay should be equal to number of post-synaptic connections at the end of the loop
assert(cumDelayStart == Npost[nid]);
for(unsigned int j=1; j < Npost[nid]; j++) {
unsigned int cumN=cumulativePost[nid]; // cumulativePost[] is unsigned int
if( tmp_SynapticDelay[cumN+j] < tmp_SynapticDelay[cumN+j-1]) {
fprintf(stderr, "Post-synaptic delays not sorted correctly...\n");
fprintf(stderr, "id=%d, delay[%d]=%d, delay[%d]=%d\n",
nid, j, tmp_SynapticDelay[cumN+j], j-1, tmp_SynapticDelay[cumN+j-1]);
assert( tmp_SynapticDelay[cumN+j] >= tmp_SynapticDelay[cumN+j-1]);
}
}
}
}
}
char* extractFileName(char *fname)
{
char* varname = strrchr(fname, '\\');
size_t len1 = strlen(varname+1);
char* extname = strchr(varname, '.');
size_t len2 = strlen(extname);
varname[len1-len2]='\0';
return (varname+1);
}
#define COMPACTION_ALIGNMENT_PRE 16
#define COMPACTION_ALIGNMENT_POST 0
#define SETPOST_INFO(name, nid, sid, val) name[cumulativePost[nid]+sid]=val;
#define SETPRE_INFO(name, nid, sid, val) name[cumulativePre[nid]+sid]=val;
// initialize all the synaptic weights to appropriate values..
// total size of the synaptic connection is 'length' ...
void CpuSNN::initSynapticWeights()
{
// Initialize the network wtChange, wt, synaptic firing time
wtChange = new float[preSynCnt];
synSpikeTime = new uint32_t[preSynCnt];
// memset(synSpikeTime,0,sizeof(uint32_t)*preSynCnt);
cpuSnnSz.synapticInfoSize = sizeof(float)*(preSynCnt*2);
resetSynapticConnections(false);
}
// We parallelly cleanup the postSynapticIds array to minimize any other wastage in that array by compacting the store
// Appropriate alignment specified by ALIGN_COMPACTION macro is used to ensure some level of alignment (if necessary)
void CpuSNN::compactConnections()
{
unsigned int* tmp_cumulativePost = new unsigned int[numN];
unsigned int* tmp_cumulativePre = new unsigned int[numN];
unsigned int lastCnt_pre = 0;
unsigned int lastCnt_post = 0;
tmp_cumulativePost[0] = 0;
tmp_cumulativePre[0] = 0;
for(int i=1; i < numN; i++) {
lastCnt_post = tmp_cumulativePost[i-1]+Npost[i-1]; //position of last pointer
lastCnt_pre = tmp_cumulativePre[i-1]+Npre[i-1]; //position of last pointer
#if COMPACTION_ALIGNMENT_POST
lastCnt_post= lastCnt_post + COMPACTION_ALIGNMENT_POST-lastCnt_post%COMPACTION_ALIGNMENT_POST;
lastCnt_pre = lastCnt_pre + COMPACTION_ALIGNMENT_PRE- lastCnt_pre%COMPACTION_ALIGNMENT_PRE;
#endif
tmp_cumulativePost[i] = lastCnt_post;
tmp_cumulativePre[i] = lastCnt_pre;
assert(tmp_cumulativePost[i] <= cumulativePost[i]);
assert(tmp_cumulativePre[i] <= cumulativePre[i]);
}
// compress the post_synaptic array according to the new values of the tmp_cumulative counts....
unsigned int tmp_postSynCnt = tmp_cumulativePost[numN-1]+Npost[numN-1];
unsigned int tmp_preSynCnt = tmp_cumulativePre[numN-1]+Npre[numN-1];
assert(tmp_postSynCnt <= allocatedPost);
assert(tmp_preSynCnt <= allocatedPre);
assert(tmp_postSynCnt <= postSynCnt);
assert(tmp_preSynCnt <= preSynCnt);
fprintf(fpLog, "******************\n");
fprintf(fpLog, "CompactConnection: \n");
fprintf(fpLog, "******************\n");
fprintf(fpLog, "old_postCnt = %d, new_postCnt = %d\n", postSynCnt, tmp_postSynCnt);
fprintf(fpLog, "old_preCnt = %d, new_postCnt = %d\n", preSynCnt, tmp_preSynCnt);
// new buffer with required size + 100 bytes of additional space just to provide limited overflow
post_info_t* tmp_postSynapticIds = new post_info_t[tmp_postSynCnt+100];
// new buffer with required size + 100 bytes of additional space just to provide limited overflow
post_info_t* tmp_preSynapticIds = new post_info_t[tmp_preSynCnt+100];
float* tmp_wt = new float[tmp_preSynCnt+100];
float* tmp_maxSynWt = new float[tmp_preSynCnt+100];
for(int i=0; i < numN; i++) {
assert(tmp_cumulativePost[i] <= cumulativePost[i]);
assert(tmp_cumulativePre[i] <= cumulativePre[i]);
for( int j=0; j < Npost[i]; j++) {
unsigned int tmpPos = tmp_cumulativePost[i]+j;
unsigned int oldPos = cumulativePost[i]+j;
tmp_postSynapticIds[tmpPos] = postSynapticIds[oldPos];
tmp_SynapticDelay[tmpPos] = tmp_SynapticDelay[oldPos];
}
for( int j=0; j < Npre[i]; j++) {
unsigned int tmpPos = tmp_cumulativePre[i]+j;
unsigned int oldPos = cumulativePre[i]+j;
tmp_preSynapticIds[tmpPos] = preSynapticIds[oldPos];
tmp_maxSynWt[tmpPos] = maxSynWt[oldPos];
tmp_wt[tmpPos] = wt[oldPos];
}
}
// delete old buffer space
delete[] postSynapticIds;
postSynapticIds = tmp_postSynapticIds;
cpuSnnSz.networkInfoSize -= (sizeof(post_info_t)*postSynCnt);
cpuSnnSz.networkInfoSize += (sizeof(post_info_t)*(tmp_postSynCnt+100));
delete[] cumulativePost;
cumulativePost = tmp_cumulativePost;
delete[] cumulativePre;
cumulativePre = tmp_cumulativePre;
delete[] maxSynWt;
maxSynWt = tmp_maxSynWt;
cpuSnnSz.synapticInfoSize -= (sizeof(float)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(int)*(tmp_preSynCnt+100));
delete[] wt;
wt = tmp_wt;
cpuSnnSz.synapticInfoSize -= (sizeof(float)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(int)*(tmp_preSynCnt+100));
delete[] preSynapticIds;
preSynapticIds = tmp_preSynapticIds;
cpuSnnSz.synapticInfoSize -= (sizeof(post_info_t)*preSynCnt);
cpuSnnSz.synapticInfoSize += (sizeof(post_info_t)*(tmp_preSynCnt+100));
preSynCnt = tmp_preSynCnt;
postSynCnt = tmp_postSynCnt;
}
void CpuSNN::updateParameters(int* curN, int* numPostSynapses, int* numPreSynapses, int nConfig)
{
assert(nConfig > 0);
numNExcPois = 0; numNInhPois = 0; numNExcReg = 0; numNInhReg = 0;
*numPostSynapses = 0; *numPreSynapses = 0;
// scan all the groups and find the required information
// about the group (numN, numPostSynapses, numPreSynapses and others).
for(int g=0; g < numGrp; g++) {
if (grp_Info[g].Type==UNKNOWN_NEURON) {
fprintf(stderr, "Unknown group for %d (%s)\n", g, grp_Info2[g].Name.c_str());
exitSimulation(1);
}
if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON))
numNInhReg += grp_Info[g].SizeN;
else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && !(grp_Info[g].Type&POISSON_NEURON))
numNExcReg += grp_Info[g].SizeN;
else if (IS_EXCITATORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON))
numNExcPois += grp_Info[g].SizeN;
else if (IS_INHIBITORY_TYPE(grp_Info[g].Type) && (grp_Info[g].Type&POISSON_NEURON))
numNInhPois += grp_Info[g].SizeN;
// find the values for maximum postsynaptic length
// and maximum pre-synaptic length
if (grp_Info[g].numPostSynapses >= *numPostSynapses)
*numPostSynapses = grp_Info[g].numPostSynapses;
if (grp_Info[g].numPreSynapses >= *numPreSynapses)
*numPreSynapses = grp_Info[g].numPreSynapses;
}
*curN = numNExcReg + numNInhReg + numNExcPois + numNInhPois;
numNPois = numNExcPois + numNInhPois;
numNReg = numNExcReg +numNInhReg;
}
void CpuSNN::resetSynapticConnections(bool changeWeights)
{
int j;
// Reset wt,wtChange,pre-firingtime values to default values...
for(int destGrp=0; destGrp < numGrp; destGrp++) {
const char* updateStr = (grp_Info[destGrp].newUpdates == true)?"(**)":"";
fprintf(stdout, "Grp: %d:%s s=%d e=%d %s\n", destGrp, grp_Info2[destGrp].Name.c_str(), grp_Info[destGrp].StartN, grp_Info[destGrp].EndN, updateStr);
fprintf(fpLog, "Grp: %d:%s s=%d e=%d %s\n", destGrp, grp_Info2[destGrp].Name.c_str(), grp_Info[destGrp].StartN, grp_Info[destGrp].EndN, updateStr);
for(int nid=grp_Info[destGrp].StartN; nid <= grp_Info[destGrp].EndN; nid++) {
int offset = cumulativePre[nid];
for (j=0;j<Npre[nid]; j++) wtChange[offset+j] = 0.0; // synaptic derivatives is reset
for (j=0;j<Npre[nid]; j++) synSpikeTime[offset+j] = MAX_SIMULATION_TIME; // some large negative value..
post_info_t *preIdPtr = &preSynapticIds[cumulativePre[nid]];
float* synWtPtr = &wt[cumulativePre[nid]];
float* maxWtPtr = &maxSynWt[cumulativePre[nid]];
int prevPreGrp = -1;
/* MDR -- this code no longer works because grpConnInfo is no longer used/defined
for (j=0; j < Npre[nid]; j++,preIdPtr++, synWtPtr++, maxWtPtr++) {
int preId = GET_CONN_NEURON_ID((*preIdPtr));
assert(preId < numN);
int srcGrp = findGrpId(preId);
grpConnectInfo_t* connInfo = grpConnInfo[srcGrp][destGrp];
assert(connInfo != NULL);
int connProp = connInfo->connProp;
bool synWtType = GET_FIXED_PLASTIC(connProp);
if ( j >= Npre_plastic[nid] ) {
// if the j is greater than Npre_plastic it means the
// connection should be fixed type..
//MDR unfortunately, for user defined connections, this check is not valid if they have a mixture of fixed and plastic
//MDR assert(synWtType == SYN_FIXED);
}
// print debug information...
if( prevPreGrp != srcGrp) {
if(nid==grp_Info[destGrp].StartN) {
const char* updateStr = (connInfo->newUpdates==true)? "(**)":"";
fprintf(stdout, "\t%d (%s) start=%d, type=%s maxWts = %f %s\n", srcGrp,
grp_Info2[srcGrp].Name.c_str(), j, (j<Npre_plastic[nid]?"P":"F"), connInfo->maxWt, updateStr);
fprintf(fpLog, "\t%d (%s) start=%d, type=%s maxWts = %f %s\n", srcGrp,
grp_Info2[srcGrp].Name.c_str(), j, (j<Npre_plastic[nid]?"P":"F"), connInfo->maxWt, updateStr);
}
prevPreGrp = srcGrp;
}
if(!changeWeights)
continue;
// if connection was of plastic type or if the connection weights were updated we need to reset the weights..
// TODO: How to account for user-defined connection reset...
if ((synWtType == SYN_PLASTIC) || connInfo->newUpdates) {
*synWtPtr = getWeights(connInfo->connProp, connInfo->initWt, connInfo->maxWt, nid, srcGrp);
*maxWtPtr = connInfo->maxWt;
}
}
*/
}
grp_Info[destGrp].newUpdates = false;
}
grpConnectInfo_t* connInfo = connectBegin;
// clear all existing connection info...
while (connInfo) {
connInfo->newUpdates = false;
connInfo = connInfo->next;
}
}
void CpuSNN::resetGroups()
{
for(int g=0; (g < numGrp); g++) {
// reset spike generator group...
if (grp_Info[g].isSpikeGenerator) {
grp_Info[g].CurrTimeSlice = grp_Info[g].NewTimeSlice;
grp_Info[g].SliceUpdateTime = 0;
for(int nid=grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++)
resetPoissonNeuron(nid, g);
}
// reset regular neuron group...
else {
for(int nid=grp_Info[g].StartN; nid <= grp_Info[g].EndN; nid++)
resetNeuron(nid, g);
}
}
// reset the currents for each neuron
resetCurrent();
// reset the conductances...
resetConductances();
// reset various counters in the group...
resetCounters();
}
void CpuSNN::resetFiringInformation()
{
// Reset firing tables and time tables to default values..
// reset Various Times..
spikeCountAll = 0;
spikeCountAll1sec = 0;
spikeCountD2 = 0;
spikeCountD1 = 0;
secD1fireCnt = 0;
secD2fireCnt = 0;
for(int i=0; i < numGrp; i++) {
grp_Info[i].FiringCount1sec = 0;
}
// reset various times...
simTimeMs = 0;
simTimeSec = 0;
simTime = 0;
// reset the propogation Buffer.
resetPropogationBuffer();
// reset Timing Table..
resetTimingTable();
}
void CpuSNN::printTuningLog()
{
if (fpTuningLog) {
fprintf(fpTuningLog, "Generating Tuning log %d\n", cntTuning);
printParameters(fpTuningLog);
cntTuning++;
}
}
// after all the initalization. Its time to create the synaptic weights, weight change and also
// time of firing these are the mostly costly arrays so dense packing is essential to minimize wastage of space
void CpuSNN::reorganizeNetwork(bool removeTempMemory, int simType)
{
//Double check...sometimes by mistake we might call reorganize network again...
if(doneReorganization)
return;
fprintf(stdout, "Beginning reorganization of network....\n");
// time to build the complete network with relevant parameters..
buildNetwork();
//..minimize any other wastage in that array by compacting the store
compactConnections();
// The post synaptic connections are sorted based on delay here
reorganizeDelay();
// Print statistics of the memory used to stdout...
printMemoryInfo();
// Print the statistics again but dump the results to a file
printMemoryInfo(fpLog);
// initialize the synaptic weights accordingly..
initSynapticWeights();
//not of much use currently
// updateRandomProperty();
updateSpikeGeneratorsInit();
//ensure that we dont do all the above optimizations again
doneReorganization = true;
//printParameters(fpParam);
printParameters(fpLog);
printTuningLog();
makePtrInfo();
// if our initial operating mode is GPU_MODE, then it is time to
// allocate necessary data within the GPU
// assert(simType != GPU_MODE || cpu_gpuNetPtrs.allocated);
// if(netInitMode==GPU_MODE)
// allocateSNN_GPU();
if(simType==GPU_MODE)
fprintf(stdout, "Starting GPU-SNN Simulations ....\n");
else
fprintf(stdout, "Starting CPU-SNN Simulations ....\n");
FILE* fconn = NULL;
#if TESTING
if (simType == GPU_MODE)
fconn = fopen("gpu_conn.txt", "w");
else
fconn = fopen("conn.txt", "w");
//printCheckDetailedInfo(fconn);
#endif
#if 0
printPostConnection(fconn);
printPreConnection(fconn);
#endif
//printNetworkInfo();
printDotty();
#if TESTING
fclose(fconn);
#endif
if(removeTempMemory) {
memoryOptimized = true;
delete[] tmp_SynapticDelay;
tmp_SynapticDelay = NULL;
}
}
void CpuSNN::setDefaultParameters(float alpha_ltp, float tau_ltp, float alpha_ltd, float tau_ltd)
{
printf("Warning: setDefaultParameters() is deprecated and may be removed in the future.\nIt is recommended that you set the desired parameters explicitly.\n");
#define DEFAULT_COND_tAMPA 5.0
#define DEFAULT_COND_tNMDA 150.0
#define DEFAULT_COND_tGABAa 6.0
#define DEFAULT_COND_tGABAb 150.0
#define DEFAULT_STP_U_Inh 0.5
#define DEFAULT_STP_tD_Inh 800
#define DEFAULT_STP_tF_Inh 1000
#define DEFAULT_STP_U_Exc 0.2
#define DEFAULT_STP_tD_Exc 700
#define DEFAULT_STP_tF_Exc 20
// setup the conductance parameter for the given network
setConductances(ALL, true, DEFAULT_COND_tAMPA, DEFAULT_COND_tNMDA, DEFAULT_COND_tGABAa, DEFAULT_COND_tGABAb);
// setting the STP values for different groups...
for(int g=0; g < getNumGroups(); g++) {
// default STDP is set to false for all groups..
setSTDP(g, false);
// setup the excitatory group properties here..
if(isExcitatoryGroup(g)) {
setSTP(g, true, DEFAULT_STP_U_Exc, DEFAULT_STP_tD_Exc, DEFAULT_STP_tF_Exc);
if ((alpha_ltp!=0.0) && (!isPoissonGroup(g)))
setSTDP(g, true, alpha_ltp, tau_ltp, alpha_ltd, tau_ltd);
}
else {
setSTP(g, true, DEFAULT_STP_U_Inh, DEFAULT_STP_tD_Inh, DEFAULT_STP_tF_Inh);
}
}
}
#if ! (_WIN32 || _WIN64)
#include <string.h>
#define strcmpi(s1,s2) strcasecmp(s1,s2)
#endif
#define PROBE_CURRENT (1 << 1)
#define PROBE_VOLTAGE (1 << 2)
#define PROBE_FIRING_RATE (1 << 3)
void CpuSNN::setProbe(int g, const string& type, int startId, int cnt, uint32_t _printProbe)
{
int endId;
assert(startId >= 0);
assert(startId <= grp_Info[g].SizeN);
//assert(cnt!=0);
int i=grp_Info[g].StartN+startId;
if (cnt<=0)
endId = grp_Info[g].EndN;
else
endId = i + cnt - 1;
if(endId > grp_Info[g].EndN)
endId = grp_Info[g].EndN;
for(; i <= endId; i++) {
probeParam_t* n = new probeParam_t;
memset(n, 0, sizeof(probeParam_t));
n->next = neuronProbe;
if(type.find("current") != string::npos) {
n->type |= PROBE_CURRENT;
n->bufferI = new float[1000];
cpuSnnSz.probeInfoSize += sizeof(float)*1000;
}
if(type.find("voltage") != string::npos) {
n->type |= PROBE_VOLTAGE;
n->bufferV = new float[1000];
cpuSnnSz.probeInfoSize += sizeof(float)*1000;
}
if(type.find("firing-rate") != string::npos) {
n->type |= PROBE_FIRING_RATE;
n->spikeBins = new bool[1000];
n->bufferFRate = new float[1000];
cpuSnnSz.probeInfoSize += (sizeof(float)+sizeof(bool))*1000;
n->cumCount = 0;
}
n->vmax = 40.0; n->vmin = -80.0;
n->imax = 50.0; n->imin = -50.0;
n->debugCnt = 0;
n->printProbe = _printProbe;
n->nid = i;
neuronProbe = n;
numProbe++;
}
}
void CpuSNN::updateMonitors()
{
int cnt=0;
probeParam_t* n = neuronProbe;
while(n) {
int nid = n->nid;
if(n->printProbe) {
// if there is an input inhspike or excSpike or curSpike then display values..
//if( I[nid] != 0 ) {
/* FIXME
MDR I broke this because I removed inhSpikes and excSpikes because they are incorrectly named...
if (inhSpikes[nid] || excSpikes[nid] || curSpike[nid] || (n->debugCnt++ > n->printProbe)) {
fprintf(stderr, "[t=%d, n=%d] voltage=%3.3f current=%3.3f ", simTime, nid, voltage[nid], current[nid]);
//FIXME should check to see if conductances are enabled for this group
if (true) {
fprintf(stderr, " ampa=%3.4f nmda=%3.4f gabaA=%3.4f gabaB=%3.4f ",
gAMPA[nid], gNMDA[nid], gGABAa[nid], gGABAb[nid]);
}
fprintf(stderr, " +Spike=%d ", excSpikes[nid]);
if (inhSpikes[nid])
fprintf(stderr, " -Spike=%d ", inhSpikes[nid]);
if (curSpike[nid])
fprintf(stderr, " | ");
fprintf(stderr, "\n");
if(n->debugCnt > n->printProbe) {
n->debugCnt = 0;
}
}
*/
}
if (n->type & PROBE_CURRENT)
n->bufferI[simTimeMs] = current[nid];
if (n->type & PROBE_VOLTAGE)
n->bufferV[simTimeMs] = voltage[nid];
#define NUM_BIN 256
#define BIN_SIZE 0.001 /* 1ms bin size */
if (n->type & PROBE_FIRING_RATE) {
int oldSpike = 0;
if (simTime >= NUM_BIN)
oldSpike = n->spikeBins[simTimeMs%NUM_BIN];
int newSpike = (voltage[nid] >= 30.0 ) ? 1 : 0;
n->cumCount = n->cumCount - oldSpike + newSpike;
float frate = n->cumCount/(NUM_BIN*BIN_SIZE);
n->spikeBins[simTimeMs % NUM_BIN] = newSpike;
if (simTime >= NUM_BIN)
n->bufferFRate[(simTime-NUM_BIN)%1000] = frate;
}
n=n->next;
cnt++;
}
//fclose(fp);
// ensure that we checked all the nodes in the list
assert(cnt==numProbe);
}
class WriteSpikeToFile: public SpikeMonitor {
public:
WriteSpikeToFile(FILE* _fid) {
fid = _fid;
}
void update(CpuSNN* s, int grpId, unsigned int* Nids, unsigned int* timeCnts)
{
int pos = 0;
for (int t=0; t < 1000; t++) {
for(int i=0; i<timeCnts[t];i++,pos++) {
int time = t + s->getSimTime() - 1000;
int id = Nids[pos];
int cnt = fwrite(&time,sizeof(int),1,fid);
assert(cnt != 0);
cnt = fwrite(&id,sizeof(int),1,fid);
assert(cnt != 0);
}
}
fflush(fid);
}
FILE* fid;
};
void CpuSNN::setSpikeMonitor(int gid, const string& fname, int configId) {
FILE* fid = fopen(fname.c_str(),"wb");
assert(configId != ALL);
setSpikeMonitor(gid, new WriteSpikeToFile(fid), configId);
}
void CpuSNN::setSpikeMonitor(int grpId, SpikeMonitor* spikeMon, int configId)
{
if (configId == ALL) {
for(int c=0; c < numConfig; c++)
setSpikeMonitor(grpId, spikeMon,c);
} else {
int cGrpId = getGroupId(grpId, configId);
DBG(2, fpLog, AT, "spikeMonitor Added");
// store the gid for further reference
monGrpId[numSpikeMonitor] = cGrpId;
// also inform the grp that it is being monitored...
grp_Info[cGrpId].MonitorId = numSpikeMonitor;
float maxRate = grp_Info[cGrpId].MaxFiringRate;
// count the size of the buffer for storing 1 sec worth of info..
// only the last second is stored in this buffer...
int buffSize = (int)(maxRate*grp_Info[cGrpId].SizeN);
// store the size for future comparison etc.
monBufferSize[numSpikeMonitor] = buffSize;
// reset the position of the buffer pointer..
monBufferPos[numSpikeMonitor] = 0;
monBufferCallback[numSpikeMonitor] = spikeMon;
// create the new buffer for keeping track of all the spikes in the system
monBufferFiring[numSpikeMonitor] = new unsigned int[buffSize];
monBufferTimeCnt[numSpikeMonitor]= new unsigned int[1000];
memset(monBufferTimeCnt[numSpikeMonitor],0,sizeof(int)*(1000));
numSpikeMonitor++;
// oh. finally update the size info that will be useful to see
// how much memory are we eating...
cpuSnnSz.monitorInfoSize += sizeof(int)*buffSize;
cpuSnnSz.monitorInfoSize += sizeof(int)*(1000);
}
}
void CpuSNN::updateSpikeMonitor()
{
// dont continue if numSpikeMonitor is zero
if(numSpikeMonitor==0)
return;
bool bufferOverFlow[MAX_GRP_PER_SNN];
memset(bufferOverFlow,0,sizeof(bufferOverFlow));
/* Reset buffer time counter */
for(int i=0; i < numSpikeMonitor; i++)
memset(monBufferTimeCnt[i],0,sizeof(int)*(1000));
/* Reset buffer position */
memset(monBufferPos,0,sizeof(int)*numSpikeMonitor);
if(currentMode == GPU_MODE) {
updateSpikeMonitor_GPU();
}
/* Read one spike at a time from the buffer and
put the spikes to an appopriate monitor buffer.
Later the user may need need to dump these spikes
to an output file */
for(int k=0; k < 2; k++) {
unsigned int* timeTablePtr = (k==0)?timeTableD2:timeTableD1;
unsigned int* fireTablePtr = (k==0)?firingTableD2:firingTableD1;
for(int t=0; t < 1000; t++) {
for(int i=timeTablePtr[t+D]; i<timeTablePtr[t+D+1];i++) {
/* retrieve the neuron id */
int nid = fireTablePtr[i];
if (currentMode == GPU_MODE)
nid = GET_FIRING_TABLE_NID(nid);
//fprintf(fpLog, "%d %d \n", t, nid);
assert(nid < numN);
int grpId = findGrpId(nid);
int monitorId = grp_Info[grpId].MonitorId;
if(monitorId!= -1) {
assert(nid >= grp_Info[grpId].StartN);
assert(nid <= grp_Info[grpId].EndN);
int pos = monBufferPos[monitorId];
if((pos >= monBufferSize[monitorId]))
{
if(!bufferOverFlow[monitorId])
fprintf(stderr, "Buffer Monitor size (%d) is small. Increase buffer firing rate for %s\n", monBufferSize[monitorId], grp_Info2[grpId].Name.c_str());
bufferOverFlow[monitorId] = true;
}
else {
monBufferPos[monitorId]++;
monBufferFiring[monitorId][pos] = nid-grp_Info[grpId].StartN; // store the Neuron ID relative to the start of the group
// we store the total firing at time t...
monBufferTimeCnt[monitorId][t]++;
}
} /* if monitoring is enabled for this spike */
} /* for all spikes happening at time t */
} /* for all time t */
}
for (int grpId=0;grpId<numGrp;grpId++) {
int monitorId = grp_Info[grpId].MonitorId;
if(monitorId!= -1) {
fprintf(stderr, "Spike Monitor for Group %s has %d spikes (%f Hz)\n",grp_Info2[grpId].Name.c_str(),monBufferPos[monitorId],((float)monBufferPos[monitorId])/(grp_Info[grpId].SizeN));
// call the callback function
if (monBufferCallback[monitorId])
monBufferCallback[monitorId]->update(this,grpId,monBufferFiring[monitorId],monBufferTimeCnt[monitorId]);
}
}
}
/* MDR -- DEPRECATED
void CpuSNN::initThalInput()
{
DBG(2, fpLog, AT, "initThalInput()");
#define I_EXPONENTIAL_DECAY 5.0f
// reset thalamic currents here..
//KILLME NOW
//resetCurrent();
resetCounters();
// first we do the initial simulation corresponding to the random number generator
int randCnt=0;
//fprintf(stderr, "Thalamic inputs: ");
for (int i=0; i < numNoise; i++)
{
float currentStrength = noiseGenGroup[i].currentStrength;
int ncount = noiseGenGroup[i].ncount;
int nstart = noiseGenGroup[i].nstart;
int nrands = noiseGenGroup[i].rand_ncount;
assert(ncount > 0);
assert(nstart >= 0);
assert(nrands > 0);
for(int j=0; j < nrands; j++,randCnt++) {
int rneuron = nstart + (int)(ncount*getRand());
randNeuronId[randCnt]= rneuron;
// assuming there is only one driver at a time.
// More than one noise input is not correct...
current[rneuron] = currentStrength;
//fprintf(stderr, " %d ", rneuron);
}
}
//fprintf(stderr, "\n");
}
// This would supply the required random current to the specific percentage of neurons. If groupId=-1,
// then the neuron is picked from the full population.
// If the groupId=n, then only neurons are picked from selected group n.
void CpuSNN::randomNoiseCurrent(float neuronPercentage, float currentStrength, int groupId)
{
DBG(2, fpLog, AT, "randomNoiseCurrent() added");
int numNeuron = ((groupId==-1)? -1: grp_Info[groupId].SizeN);
int nstart = ((groupId==-1)? -1: grp_Info[groupId].StartN);
noiseGenGroup[numNoise].groupId = groupId;
noiseGenGroup[numNoise].currentStrength = currentStrength;
noiseGenGroup[numNoise].neuronPercentage = neuronPercentage;
noiseGenGroup[numNoise].ncount = numNeuron;
noiseGenGroup[numNoise].nstart = nstart;
noiseGenGroup[numNoise].rand_ncount = (int)(numNeuron*(neuronPercentage/100.0));
if(noiseGenGroup[numNoise].rand_ncount<=0)
noiseGenGroup[numNoise].rand_ncount = 1;
numNoise++;
// i have already reorganized the network. hence it is important to update the random neuron property..
if (doneReorganization == true)
updateRandomProperty();
}
// we calculate global properties like how many random number need to be generated
//each cycle, etc
void CpuSNN::updateRandomProperty()
{
numRandNeurons = 0;
for (int i=0; i < numNoise; i++) {
// paramters for few noise generator has not been updated...update now !!!
if(noiseGenGroup[i].groupId == -1) {
int numNeuron = numNReg;
int nstart = 0;
noiseGenGroup[i].groupId = -1;
int neuronPercentage = noiseGenGroup[i].neuronPercentage;
noiseGenGroup[i].ncount = numNeuron;
noiseGenGroup[i].nstart = nstart;
noiseGenGroup[i].rand_ncount = (int)(numNeuron*(neuronPercentage/100.0));
if(noiseGenGroup[i].rand_ncount<=0)
noiseGenGroup[i].rand_ncount = 1;
}
// update the number of random counts...
numRandNeurons += noiseGenGroup[i].rand_ncount;
}
assert(numRandNeurons>=0);
}
*/
|
#pragma once
#include "boost_defs.hpp"
#include "gcd_utility.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <boost/signals2.hpp>
#include <unordered_map>
namespace krbn {
class hid_manager final {
public:
boost::signals2::signal<void(human_interface_device&)> device_detected;
boost::signals2::signal<void(human_interface_device&)> device_removed;
hid_manager(const hid_manager&) = delete;
hid_manager(void) : manager_(nullptr) {
}
~hid_manager(void) {
stop();
}
void start(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) {
if (manager_) {
stop();
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
void stop(void) {
// Release manager_ in main thread to avoid callback invocations after object has been destroyed.
gcd_utility::dispatch_sync_in_main_queue(^{
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
});
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_matching_device(device);
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
auto it = hids_.find(*registry_entry_id);
if (it != std::end(hids_)) {
logger::get_logger().info("registry_entry_id:{0} already exists.", static_cast<uint64_t>(*registry_entry_id));
return;
}
auto hid = std::make_shared<human_interface_device>(device);
hids_[*registry_entry_id] = hid;
logger::get_logger().info("{0} is detected.", hid->get_name_for_log());
device_detected(*hid);
}
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(device);
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
auto it = hids_.find(*registry_entry_id);
if (it != hids_.end()) {
if (auto hid = it->second) {
logger::get_logger().info("{0} is removed.", hid->get_name_for_log());
hid->set_removed();
device_removed(*hid);
hids_.erase(it);
}
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else
std::advance(it, 1);
}
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
IOHIDManagerRef _Nullable manager_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
std::unordered_map<registry_entry_id, std::shared_ptr<human_interface_device>> hids_;
};
} // namespace krbn
add hid_manager::device_detecting
#pragma once
#include "boost_utility.hpp"
#include "gcd_utility.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <unordered_map>
namespace krbn {
class hid_manager final {
public:
// Return false to ignore device.
boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull),
boost_utility::signal2_combiner_call_while_true>
device_detecting;
boost::signals2::signal<void(human_interface_device&)> device_detected;
boost::signals2::signal<void(human_interface_device&)> device_removed;
hid_manager(const hid_manager&) = delete;
hid_manager(void) : manager_(nullptr) {
}
~hid_manager(void) {
stop();
}
const std::unordered_map<registry_entry_id, std::shared_ptr<human_interface_device>>& get_hids(void) const {
return hids_;
}
void start(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) {
if (manager_) {
stop();
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
void stop(void) {
// Release manager_ in main thread to avoid callback invocations after object has been destroyed.
gcd_utility::dispatch_sync_in_main_queue(^{
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
});
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
if (!device_detecting(device)) {
return;
}
iokit_utility::log_matching_device(device);
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
auto it = hids_.find(*registry_entry_id);
if (it != std::end(hids_)) {
logger::get_logger().info("registry_entry_id:{0} already exists.", static_cast<uint64_t>(*registry_entry_id));
return;
}
auto hid = std::make_shared<human_interface_device>(device);
hids_[*registry_entry_id] = hid;
logger::get_logger().info("{0} is detected.", hid->get_name_for_log());
device_detected(*hid);
}
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(device);
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
auto it = hids_.find(*registry_entry_id);
if (it != hids_.end()) {
if (auto hid = it->second) {
logger::get_logger().info("{0} is removed.", hid->get_name_for_log());
hids_.erase(it);
hid->set_removed();
device_removed(*hid);
}
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else
std::advance(it, 1);
}
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
IOHIDManagerRef _Nullable manager_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
std::unordered_map<registry_entry_id, std::shared_ptr<human_interface_device>> hids_;
};
} // namespace krbn
|
#pragma once
#include "boost_utility.hpp"
#include "cf_utility.hpp"
#include "device_detail.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <unordered_map>
namespace krbn {
class hid_manager final {
public:
// Return false to ignore device.
boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull),
boost_utility::signals2_combiner_call_while_true>
device_detecting;
boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_detected;
boost::signals2::signal<void(std::shared_ptr<human_interface_device>)>
device_removed;
hid_manager(const hid_manager&) = delete;
hid_manager(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : usage_pairs_(usage_pairs),
manager_(nullptr) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
}
~hid_manager(void) {
stop();
run_loop_thread_ = nullptr;
}
void start(void) {
run_loop_thread_->enqueue(^{
if (manager_) {
return;
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs_)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
refresh_timer_ = std::make_unique<thread_utility::timer>(
std::chrono::milliseconds(5000),
true,
[this] {
run_loop_thread_->enqueue(^{
refresh_if_needed();
});
});
logger::get_logger().info("hid_manager is started.");
});
}
void stop(void) {
run_loop_thread_->enqueue(^{
if (!manager_) {
return;
}
// refresh_timer_
refresh_timer_ = nullptr;
// manager_
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
// Other variables
registry_entry_ids_.clear();
{
std::lock_guard<std::mutex> lock(hids_mutex_);
hids_.clear();
}
logger::get_logger().info("hid_manager is stopped.");
});
}
std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {
std::lock_guard<std::mutex> lock(hids_mutex_);
return hids_;
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
if (!device_detecting(device)) {
return;
}
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
if (std::any_of(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
})) {
logger::get_logger().info("registry_entry_id:{0} already exists", static_cast<uint64_t>(*registry_entry_id));
return;
}
hid = std::make_shared<human_interface_device>(device, *registry_entry_id);
hids_.push_back(hid);
}
device_detected(hid);
}
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
auto it = std::find_if(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
});
if (it != hids_.end()) {
hid = *it;
hids_.erase(it);
}
}
if (hid) {
hid->set_removed();
device_removed(hid);
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else
std::advance(it, 1);
}
}
}
void refresh_if_needed(void) {
// `device_removal_callback` is sometimes missed
// and invalid human_interface_devices are remained into hids_.
// (The problem is likely occur just after wake up from sleep.)
//
// We validate the human_interface_device,
// and then reload devices if there is an invalid human_interface_device.
bool needs_refresh = false;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
for (const auto& hid : hids_) {
if (!hid->validate()) {
logger::get_logger().warn("Refreshing hid_manager since a dangling human_interface_device is found. ({0})",
hid->get_name_for_log());
needs_refresh = true;
break;
}
}
}
if (needs_refresh) {
stop();
start();
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<thread_utility::timer> refresh_timer_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
// We do not need to use registry_entry_ids_mutex_ since it is modified only in run_loop_thread_.
std::vector<std::shared_ptr<human_interface_device>> hids_;
mutable std::mutex hids_mutex_;
};
} // namespace krbn
remove a log message
#pragma once
#include "boost_utility.hpp"
#include "cf_utility.hpp"
#include "device_detail.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <unordered_map>
namespace krbn {
class hid_manager final {
public:
// Return false to ignore device.
boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull),
boost_utility::signals2_combiner_call_while_true>
device_detecting;
boost::signals2::signal<void(std::shared_ptr<human_interface_device>)> device_detected;
boost::signals2::signal<void(std::shared_ptr<human_interface_device>)>
device_removed;
hid_manager(const hid_manager&) = delete;
hid_manager(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : usage_pairs_(usage_pairs),
manager_(nullptr) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
}
~hid_manager(void) {
stop();
run_loop_thread_ = nullptr;
}
void start(void) {
run_loop_thread_->enqueue(^{
if (manager_) {
return;
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs_)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
refresh_timer_ = std::make_unique<thread_utility::timer>(
std::chrono::milliseconds(5000),
true,
[this] {
run_loop_thread_->enqueue(^{
refresh_if_needed();
});
});
logger::get_logger().info("hid_manager is started.");
});
}
void stop(void) {
run_loop_thread_->enqueue(^{
if (!manager_) {
return;
}
// refresh_timer_
refresh_timer_ = nullptr;
// manager_
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
// Other variables
registry_entry_ids_.clear();
{
std::lock_guard<std::mutex> lock(hids_mutex_);
hids_.clear();
}
logger::get_logger().info("hid_manager is stopped.");
});
}
std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {
std::lock_guard<std::mutex> lock(hids_mutex_);
return hids_;
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
if (!device_detecting(device)) {
return;
}
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
if (std::any_of(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
})) {
// logger::get_logger().info("registry_entry_id:{0} already exists", static_cast<uint64_t>(*registry_entry_id));
return;
}
hid = std::make_shared<human_interface_device>(device, *registry_entry_id);
hids_.push_back(hid);
}
device_detected(hid);
}
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
auto it = std::find_if(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
});
if (it != hids_.end()) {
hid = *it;
hids_.erase(it);
}
}
if (hid) {
hid->set_removed();
device_removed(hid);
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else
std::advance(it, 1);
}
}
}
void refresh_if_needed(void) {
// `device_removal_callback` is sometimes missed
// and invalid human_interface_devices are remained into hids_.
// (The problem is likely occur just after wake up from sleep.)
//
// We validate the human_interface_device,
// and then reload devices if there is an invalid human_interface_device.
bool needs_refresh = false;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
for (const auto& hid : hids_) {
if (!hid->validate()) {
logger::get_logger().warn("Refreshing hid_manager since a dangling human_interface_device is found. ({0})",
hid->get_name_for_log());
needs_refresh = true;
break;
}
}
}
if (needs_refresh) {
stop();
start();
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<thread_utility::timer> refresh_timer_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
// We do not need to use registry_entry_ids_mutex_ since it is modified only in run_loop_thread_.
std::vector<std::shared_ptr<human_interface_device>> hids_;
mutable std::mutex hids_mutex_;
};
} // namespace krbn
|
#pragma once
// `krbn::hid_manager` can be used safely in a multi-threaded environment.
#include "boost_utility.hpp"
#include "cf_utility.hpp"
#include "device_detail.hpp"
#include "dispatcher.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <unordered_map>
namespace krbn {
class hid_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
// Signals
// Return false to ignore device.
boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull), boost_utility::signals2_combiner_call_while_true> device_detecting;
boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_detected;
boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_removed;
// Methods
hid_manager(const hid_manager&) = delete;
hid_manager(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher,
const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : dispatcher_client(weak_dispatcher),
usage_pairs_(usage_pairs),
manager_(nullptr),
refresh_timer_(*this) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
}
~hid_manager(void) {
async_stop();
run_loop_thread_->terminate();
run_loop_thread_ = nullptr;
}
void async_start(void) {
run_loop_thread_->enqueue(^{
if (manager_) {
logger::get_logger().warn("hid_manager is already started.");
return;
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs_)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
refresh_timer_.start(
[this] {
run_loop_thread_->enqueue(^{
refresh_if_needed();
});
},
std::chrono::milliseconds(5000));
logger::get_logger().info("hid_manager is started.");
});
}
void async_stop(void) {
run_loop_thread_->enqueue(^{
if (!manager_) {
return;
}
// refresh_timer_
refresh_timer_.stop();
// manager_
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
// Other variables
registry_entry_ids_.clear();
{
std::lock_guard<std::mutex> lock(hids_mutex_);
hids_.clear();
}
logger::get_logger().info("hid_manager is stopped.");
});
}
std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {
std::lock_guard<std::mutex> lock(hids_mutex_);
return hids_;
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
// `static_device_matching_callback` is called by multiple threads.
// (It is not called from `run_loop_thread_`.)
// Thus, we have to synchronize by using `run_loop_thread_`.
run_loop_thread_->enqueue(^{
if (!device) {
return;
}
if (!device_detecting(device)) {
return;
}
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
if (std::any_of(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
})) {
// logger::get_logger().info("registry_entry_id:{0} already exists", static_cast<uint64_t>(*registry_entry_id));
return;
}
hid = std::make_shared<human_interface_device>(device, *registry_entry_id);
hids_.push_back(hid);
}
device_detected(hid);
}
});
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
// `static_device_removal_callback` is called by multiple threads.
// (It is not called from `run_loop_thread_`.)
// Thus, we have to synchronize by using `run_loop_thread_`.
run_loop_thread_->enqueue(^{
if (!device) {
return;
}
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
auto it = std::find_if(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
});
if (it != hids_.end()) {
hid = *it;
hids_.erase(it);
}
}
if (hid) {
hid->set_removed();
device_removed(hid);
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else {
std::advance(it, 1);
}
}
}
});
}
void refresh_if_needed(void) {
// `device_removal_callback` is sometimes missed
// and invalid human_interface_devices are remained into hids_.
// (The problem is likely occur just after wake up from sleep.)
//
// We validate the human_interface_device,
// and then reload devices if there is an invalid human_interface_device.
bool needs_refresh = false;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
for (const auto& hid : hids_) {
if (!hid->validate()) {
logger::get_logger().warn("Refreshing hid_manager since a dangling human_interface_device is found. ({0})",
hid->get_name_for_log());
needs_refresh = true;
break;
}
}
}
if (needs_refresh) {
async_stop();
async_start();
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;
IOHIDManagerRef _Nullable manager_;
pqrs::dispatcher::extra::timer refresh_timer_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
// We do not need to use registry_entry_ids_mutex_ since it is modified only in run_loop_thread_.
std::vector<std::shared_ptr<human_interface_device>> hids_;
mutable std::mutex hids_mutex_;
};
} // namespace krbn
update hid_manager
#pragma once
// `krbn::hid_manager` can be used safely in a multi-threaded environment.
#include "boost_utility.hpp"
#include "cf_utility.hpp"
#include "device_detail.hpp"
#include "dispatcher.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <unordered_map>
namespace krbn {
class hid_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
// Signals
// Return false to ignore device.
boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull), boost_utility::signals2_combiner_call_while_true> device_detecting;
boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_detected;
boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_removed;
// Methods
hid_manager(const hid_manager&) = delete;
hid_manager(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher,
const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : dispatcher_client(weak_dispatcher),
usage_pairs_(usage_pairs),
manager_(nullptr),
refresh_timer_(*this) {
run_loop_thread_ = std::make_shared<cf_utility::run_loop_thread>();
}
virtual ~hid_manager(void) {
async_stop();
run_loop_thread_->terminate();
run_loop_thread_ = nullptr;
detach_from_dispatcher([] {
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
if (manager_) {
logger::get_logger().warn("hid_manager is already started.");
return;
}
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs_)) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
}
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
refresh_timer_.start(
[this] {
refresh_if_needed();
},
std::chrono::milliseconds(5000));
logger::get_logger().info("hid_manager is started.");
});
}
void async_stop(void) {
enqueue_to_dispatcher([this] {
if (!manager_) {
return;
}
// refresh_timer_
refresh_timer_.stop();
// manager_
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_,
run_loop_thread_->get_run_loop(),
kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
// Other variables
registry_entry_ids_.clear();
{
std::lock_guard<std::mutex> lock(hids_mutex_);
hids_.clear();
}
logger::get_logger().info("hid_manager is stopped.");
});
}
std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {
std::lock_guard<std::mutex> lock(hids_mutex_);
return hids_;
}
private:
static void static_device_matching_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
// `static_device_matching_callback` is called by multiple threads.
// (It is not called from `run_loop_thread_`.)
// Thus, we have to synchronize by using `dispatcher`.
enqueue_to_dispatcher([this, device] {
if (!device) {
return;
}
if (!device_detecting(device)) {
return;
}
if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {
// iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.
// Thus, we have to memory device and registry_entry_id correspondence by myself.
registry_entry_ids_[device] = *registry_entry_id;
// Skip if same device is already matched.
// (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
if (std::any_of(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
})) {
// logger::get_logger().info("registry_entry_id:{0} already exists", static_cast<uint64_t>(*registry_entry_id));
return;
}
hid = std::make_shared<human_interface_device>(device, *registry_entry_id);
hids_.push_back(hid);
}
device_detected(hid);
}
});
}
static void static_device_removal_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<hid_manager*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
// `static_device_removal_callback` is called by multiple threads.
// (It is not called from `run_loop_thread_`.)
// Thus, we have to synchronize by using `dispatcher`.
enqueue_to_dispatcher([this, device] {
if (!device) {
return;
}
// ----------------------------------------
if (auto registry_entry_id = find_registry_entry_id(device)) {
std::shared_ptr<human_interface_device> hid;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
auto it = std::find_if(std::begin(hids_),
std::end(hids_),
[&](auto&& h) {
return *registry_entry_id == h->get_registry_entry_id();
});
if (it != hids_.end()) {
hid = *it;
hids_.erase(it);
}
}
if (hid) {
hid->set_removed();
device_removed(hid);
}
// There might be multiple devices for one registry_entry_id.
// (For example, keyboard and mouse combined device.)
// And there is possibility that removal callback is not called with some device.
//
// For example, there are 3 devices for 1 registry_entry_id (4294974284).
// - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }
// - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }
// - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }
// And device_removal_callback are called only with device1 and device2.
//
// We should remove device1, device2 and device3 at the same time in order to deal with this case.
for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {
if (it->second == *registry_entry_id) {
it = registry_entry_ids_.erase(it);
} else {
std::advance(it, 1);
}
}
}
});
}
void refresh_if_needed(void) {
// `device_removal_callback` is sometimes missed
// and invalid human_interface_devices are remained into hids_.
// (The problem is likely occur just after wake up from sleep.)
//
// We validate the human_interface_device,
// and then reload devices if there is an invalid human_interface_device.
bool needs_refresh = false;
{
std::lock_guard<std::mutex> lock(hids_mutex_);
for (const auto& hid : hids_) {
if (!hid->validate()) {
logger::get_logger().warn("Refreshing hid_manager since a dangling human_interface_device is found. ({0})",
hid->get_name_for_log());
needs_refresh = true;
break;
}
}
}
if (needs_refresh) {
async_stop();
async_start();
}
}
boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {
auto it = registry_entry_ids_.find(device);
if (it != std::end(registry_entry_ids_)) {
return it->second;
}
return boost::none;
}
std::shared_ptr<cf_utility::run_loop_thread> run_loop_thread_;
std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;
IOHIDManagerRef _Nullable manager_;
pqrs::dispatcher::extra::timer refresh_timer_;
std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;
std::vector<std::shared_ptr<human_interface_device>> hids_;
mutable std::mutex hids_mutex_;
};
} // namespace krbn
|
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "jml/arch/exception.h"
#include "soa/types/date.h"
#include "soa/types/value_description.h"
#include "soa/service/http_client.h"
#include "soa/service/http_endpoint.h"
#include "soa/service/named_endpoint.h"
#include "soa/service/message_loop.h"
#include "soa/service/rest_proxy.h"
#include "soa/service/rest_service_endpoint.h"
#include "soa/service/runner.h"
#include "test_http_services.h"
using namespace std;
using namespace Datacratic;
/* bench methods */
void
AsyncModelBench(const string & baseUrl, int maxReqs, int concurrency,
Date & start, Date & end)
{
int numReqs, numResponses(0), numMissed(0);
MessageLoop loop(1, 0, -1);
loop.start();
auto client = make_shared<HttpClient>(baseUrl, concurrency);
loop.addSource("httpClient", client);
auto onResponse = [&] (const HttpRequest & rq, HttpClientError errorCode_,
int status, string && headers, string && body) {
numResponses++;
// if (numResponses % 1000) {
// cerr << "resps: " + to_string(numResponses) + "\n";
// }
if (numResponses == maxReqs) {
// cerr << "received all responses\n";
ML::futex_wake(numResponses);
}
};
auto cbs = make_shared<HttpClientSimpleCallbacks>(onResponse);
auto & clientRef = *client.get();
string url("/");
start = Date::now();
for (numReqs = 0; numReqs < maxReqs;) {
if (clientRef.get(url, cbs)) {
numReqs++;
// if (numReqs % 1000) {
// cerr << "reqs: " + to_string(numReqs) + "\n";
// }
}
else {
numMissed++;
}
}
while (numResponses < maxReqs) {
// cerr << (" num Responses: " + to_string(numResponses)
// + "; max reqs: " + to_string(maxReqs)
// + "\n");
int old(numResponses);
ML::futex_wait(numResponses, old);
}
end = Date::now();
loop.removeSource(client.get());
client->waitConnectionState(AsyncEventSource::DISCONNECTED);
cerr << "num misses: " + to_string(numMissed) + "\n";
}
void
ThreadedModelBench(const string & baseUrl, int maxReqs, int concurrency,
Date & start, Date & end)
{
vector<thread> threads;
auto threadFn = [&] (int num, int nReqs) {
int i;
HttpRestProxy client(baseUrl);
for (i = 0; i < nReqs; i++) {
auto response = client.get("/");
}
};
start = Date::now();
int slice(maxReqs / concurrency);
for (int i = 0; i < concurrency; i++) {
// cerr << "doing slice: " + to_string(slice) + "\n";
threads.emplace_back(threadFn, i, slice);
}
for (int i = 0; i < concurrency; i++) {
threads[i].join();
}
end = Date::now();
}
int main(int argc, char *argv[])
{
using namespace boost::program_options;
size_t concurrency(0);
int model(0);
size_t maxReqs(0);
size_t payloadSize(0);
string serveriface("127.0.0.1");
string clientiface(serveriface);
options_description all_opt;
all_opt.add_options()
("client-iface,C", value(&clientiface),
"address:port to connect to (\"none\" for no client)")
("concurrency,c", value(&concurrency),
"Number of concurrent requests")
("model,m", value(&model),
"Type of concurrency model (1 for async, 2 for threaded))")
("requests,r", value(&maxReqs),
"total of number of requests to perform")
("payload-size,s", value(&payloadSize),
"size of the response body")
("server-iface,S", value(&serveriface),
"server address (\"none\" for no server)")
("help,H", "show help");
if (argc == 1) {
return 0;
}
variables_map vm;
store(command_line_parser(argc, argv)
.options(all_opt)
.run(),
vm);
notify(vm);
if (vm.count("help")) {
cerr << all_opt << endl;
return 1;
}
/* service setup */
auto proxies = make_shared<ServiceProxies>();
HttpGetService service(proxies);
if (concurrency == 0) {
throw ML::Exception("'concurrency' must be specified");
}
if (payloadSize == 0) {
throw ML::Exception("'payload-size' must be specified");
}
string payload;
while (payload.size() < payloadSize) {
payload += "aaaaaaaa";
}
if (serveriface != "none") {
cerr << "launching server\n";
service.portToUse = 20000;
service.addResponse("GET", "/", 200, payload);
service.start(serveriface, concurrency);
}
if (clientiface != "none") {
cerr << "launching client\n";
if (maxReqs == 0) {
throw ML::Exception("'max-reqs' must be specified");
}
string baseUrl;
if (serveriface != "none") {
baseUrl = ("http://" + serveriface
+ ":" + to_string(service.port()));
}
else {
baseUrl = "http://" + clientiface;
}
::printf("model\tconc.\treqs\tsize\ttime_secs\tqps\n");
Date start, end;
if (model == 1) {
AsyncModelBench(baseUrl, maxReqs, concurrency, start, end);
}
else if (model == 2) {
ThreadedModelBench(baseUrl, maxReqs, concurrency, start, end);
}
else {
throw ML::Exception("invalid 'model'");
}
double delta = end - start;
double qps = maxReqs / delta;
::printf("%d\t%lu\t%lu\t%lu\t%f\t%f\n",
model, concurrency, maxReqs, payloadSize, delta, qps);
}
else {
while (1) {
sleep(100);
}
}
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
Json::Value jsonUsage = jsonEncode(usage);
cerr << "rusage:\n" << jsonUsage.toStyledString() << endl;
return 0;
}
http_client_bench: added the ability to specify the http method to benchmark (TRIVIAL: enhancement, affects only the http_client_bench tool)
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "jml/arch/exception.h"
#include "soa/types/date.h"
#include "soa/types/value_description.h"
#include "soa/utils/print_utils.h"
#include "soa/service/http_client.h"
#include "soa/service/http_endpoint.h"
#include "soa/service/named_endpoint.h"
#include "soa/service/message_loop.h"
#include "soa/service/rest_proxy.h"
#include "soa/service/rest_service_endpoint.h"
#include "soa/service/runner.h"
#include "test_http_services.h"
using namespace std;
using namespace Datacratic;
enum HttpMethod {
GET,
POST,
PUT
};
/* bench methods */
double
AsyncModelBench(HttpMethod method,
const string & baseUrl, const string & payload,
int maxReqs, int concurrency)
{
int numReqs, numResponses(0), numMissed(0);
MessageLoop loop(1, 0, -1);
loop.start();
auto client = make_shared<HttpClient>(baseUrl, concurrency);
loop.addSource("httpClient", client);
auto onResponse = [&] (const HttpRequest & rq, HttpClientError errorCode_,
int status, string && headers, string && body) {
numResponses++;
// if (numResponses % 1000) {
// cerr << "resps: " + to_string(numResponses) + "\n";
// }
if (numResponses == maxReqs) {
// cerr << "received all responses\n";
ML::futex_wake(numResponses);
}
};
auto cbs = make_shared<HttpClientSimpleCallbacks>(onResponse);
HttpRequest::Content content(payload, "application/binary");
auto & clientRef = *client.get();
string url("/");
Date start = Date::now();
for (numReqs = 0; numReqs < maxReqs;) {
bool result;
if (method == GET) {
result = clientRef.get(url, cbs);
}
else if (method == POST) {
result = clientRef.post(url, cbs, content);
}
else if (method == PUT) {
result = clientRef.put(url, cbs, content);
}
else {
result = true;
}
if (result) {
numReqs++;
// if (numReqs % 1000) {
// cerr << "reqs: " + to_string(numReqs) + "\n";
// }
}
else {
numMissed++;
}
}
while (numResponses < maxReqs) {
// cerr << (" num Responses: " + to_string(numResponses)
// + "; max reqs: " + to_string(maxReqs)
// + "\n");
int old(numResponses);
ML::futex_wait(numResponses, old);
}
Date end = Date::now();
loop.removeSource(client.get());
client->waitConnectionState(AsyncEventSource::DISCONNECTED);
cerr << "num misses: " + to_string(numMissed) + "\n";
return end - start;
}
double
ThreadedModelBench(HttpMethod method,
const string & baseUrl, const string & payload,
int maxReqs, int concurrency)
{
vector<thread> threads;
HttpRestProxy::Content content(payload, "application/binary");
auto threadFn = [&] (int num, int nReqs) {
int i;
HttpRestProxy client(baseUrl);
for (i = 0; i < nReqs; i++) {
if (method == GET) {
auto response = client.get("/");
}
else if (method == POST) {
auto response = client.post("/", content);
}
else if (method == PUT) {
auto response = client.put("/", content);
}
}
};
Date start = Date::now();
int slice(maxReqs / concurrency);
for (int i = 0; i < concurrency; i++) {
// cerr << "doing slice: " + to_string(slice) + "\n";
threads.emplace_back(threadFn, i, slice);
}
for (int i = 0; i < concurrency; i++) {
threads[i].join();
}
return Date::now() - start;
}
int main(int argc, char *argv[])
{
using namespace boost::program_options;
size_t concurrency(0);
int model(0);
size_t maxReqs(0);
string method("GET");
size_t payloadSize(0);
string serveriface("127.0.0.1");
string clientiface(serveriface);
options_description all_opt;
all_opt.add_options()
("client-iface,C", value(&clientiface),
"address:port to connect to (\"none\" for no client)")
("concurrency,c", value(&concurrency),
"Number of concurrent requests")
("method,M", value(&method),
"Method to use (\"GET\"*, \"PUT\", \"POST\")")
("model,m", value(&model),
"Type of concurrency model (1 for async, 2 for threaded))")
("requests,r", value(&maxReqs),
"total of number of requests to perform")
("payload-size,s", value(&payloadSize),
"size of the response body")
("server-iface,S", value(&serveriface),
"server address (\"none\" for no server)")
("help,H", "show help");
if (argc == 1) {
return 0;
}
variables_map vm;
store(command_line_parser(argc, argv)
.options(all_opt)
.run(),
vm);
notify(vm);
if (vm.count("help")) {
cerr << all_opt << endl;
return 1;
}
/* service setup */
auto proxies = make_shared<ServiceProxies>();
HttpGetService service(proxies);
if (concurrency == 0) {
throw ML::Exception("'concurrency' must be specified");
}
if (payloadSize == 0) {
throw ML::Exception("'payload-size' must be specified");
}
string payload;
while (payload.size() < payloadSize) {
payload += randomString(128);
}
if (serveriface != "none") {
cerr << "launching server\n";
service.portToUse = 20000;
service.addResponse("GET", "/", 200, payload);
service.addResponse("PUT", "/", 200, "");
service.addResponse("POST", "/", 200, "");
service.start(serveriface, concurrency);
}
if (clientiface != "none") {
cerr << "launching client\n";
if (maxReqs == 0) {
throw ML::Exception("'max-reqs' must be specified");
}
if (!(method == "GET" || method == "POST" || method == "PUT")) {
throw ML::Exception("invalid method:" + method);
}
string baseUrl;
if (serveriface != "none") {
baseUrl = ("http://" + serveriface
+ ":" + to_string(service.port()));
}
else {
baseUrl = "http://" + clientiface;
}
::printf("model\tconc.\treqs\tsize\ttime_secs\tqps\n");
HttpMethod httpMethod;
if (method == "GET") {
httpMethod = GET;
}
else if (method == "POST") {
httpMethod = POST;
}
else if (method == "PUT") {
httpMethod = PUT;
}
else {
throw ML::Exception("unknown method: " + method);
}
double delta;
if (model == 1) {
delta = AsyncModelBench(httpMethod, baseUrl, payload, maxReqs, concurrency);
}
else if (model == 2) {
delta = ThreadedModelBench(httpMethod, baseUrl, payload, maxReqs, concurrency);
}
else {
throw ML::Exception("invalid 'model'");
}
double qps = maxReqs / delta;
::printf("%d\t%lu\t%lu\t%lu\t%f\t%f\n",
model, concurrency, maxReqs, payloadSize, delta, qps);
}
else {
while (1) {
sleep(100);
}
}
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
Json::Value jsonUsage = jsonEncode(usage);
cerr << "rusage:\n" << jsonUsage.toStyledString() << endl;
return 0;
}
|
// @(#)root/sessionviewer:$Name: $:$Id: TSessionViewer.cxx,v 1.12 2007/03/17 18:02:24 rdm Exp $
// Author: Marek Biskup, Jakub Madejczyk, Bertrand Bellenot 10/08/2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TSessionViewer //
// //
// Widget used to manage PROOF or local sessions, PROOF connections, //
// queries construction and results handling. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TApplication.h"
#include "TROOT.h"
#include "THashList.h"
#include "TClass.h"
#include "TSystem.h"
#include "TGFileDialog.h"
#include "TBrowser.h"
#include "TGButton.h"
#include "TGLayout.h"
#include "TGListTree.h"
#include "TGCanvas.h"
#include "TGLabel.h"
#include "TGTextEntry.h"
#include "TGNumberEntry.h"
#include "TGTableLayout.h"
#include "TGComboBox.h"
#include "TGSplitter.h"
#include "TGProgressBar.h"
#include "TGListView.h"
#include "TGMsgBox.h"
#include "TGMenu.h"
#include "TGStatusBar.h"
#include "TGIcon.h"
#include "TChain.h"
#include "TDSet.h"
#include "TFileInfo.h"
#include "TProof.h"
#include "TRandom.h"
#include "TSessionViewer.h"
#include "TSessionLogView.h"
#include "TQueryResult.h"
#include "TGTextView.h"
#include "TGMenu.h"
#include "TGToolBar.h"
#include "TGTab.h"
#include "TRootEmbeddedCanvas.h"
#include "TCanvas.h"
#include "TGMimeTypes.h"
#include "TInterpreter.h"
#include "TContextMenu.h"
#include "TG3DLine.h"
#include "TSessionDialogs.h"
#include "TEnv.h"
#include "TH2.h"
#include "TTreePlayer.h"
#ifdef WIN32
#include "TWin32SplashThread.h"
#endif
TSessionViewer *gSessionViewer = 0;
const char *kConfigFile = ".proofgui.conf";
ClassImp(TQueryDescription)
ClassImp(TSessionDescription)
ClassImp(TSessionServerFrame)
ClassImp(TSessionFrame)
ClassImp(TSessionQueryFrame)
ClassImp(TSessionOutputFrame)
ClassImp(TSessionInputFrame)
ClassImp(TSessionViewer)
const char *xpm_names[] = {
"monitor01.xpm",
"monitor02.xpm",
"monitor03.xpm",
"monitor04.xpm",
0
};
const char *conftypes[] = {
"Config files", "*.conf",
"All files", "*.*",
0, 0
};
const char *pkgtypes[] = {
"Package files", "*.par",
"All files", "*.*",
0, 0
};
const char *macrotypes[] = {
"C files", "*.[C|c]*",
"All files", "*",
0, 0
};
const char *kFeedbackHistos[] = {
"PROOF_PacketsHist",
"PROOF_EventsHist",
"PROOF_NodeHist",
"PROOF_LatencyHist",
"PROOF_ProcTimeHist",
"PROOF_CpuTimeHist",
0
};
const char* const kSession_RedirectFile = ".templog";
const char* const kSession_RedirectCmd = ".tempcmd";
// Menu command id's
enum ESessionViewerCommands {
kFileLoadConfig,
kFileSaveConfig,
kFileCloseViewer,
kFileQuit,
kSessionNew,
kSessionAdd,
kSessionDelete,
kSessionGetQueries,
kSessionConnect,
kSessionDisconnect,
kSessionShutdown,
kSessionCleanup,
kSessionBrowse,
kSessionShowStatus,
kSessionReset,
kQueryNew,
kQueryEdit,
kQueryDelete,
kQuerySubmit,
kQueryStartViewer,
kOptionsAutoSave,
kOptionsStatsHist,
kOptionsStatsTrace,
kOptionsSlaveStatsTrace,
kOptionsFeedback,
kHelpAbout
};
const char *xpm_toolbar[] = {
"fileopen.xpm",
"filesaveas.xpm",
"",
"connect.xpm",
"disconnect.xpm",
"",
"query_new.xpm",
"query_submit.xpm",
"",
"about.xpm",
"",
"quit.xpm",
0
};
ToolBarData_t tb_data[] = {
{ "", "Open Config File", kFALSE, kFileLoadConfig, 0 },
{ "", "Save Config File", kFALSE, kFileSaveConfig, 0 },
{ "", 0, 0, -1, 0 },
{ "", "Connect", kFALSE, kSessionConnect, 0 },
{ "", "Disconnect", kFALSE, kSessionDisconnect, 0 },
{ "", 0, 0, -1, 0 },
{ "", "New Query", kFALSE, kQueryNew, 0 },
{ "", "Submit Query", kFALSE, kQuerySubmit, 0 },
{ "", 0, 0, -1, 0 },
{ "", "About Root", kFALSE, kHelpAbout, 0 },
{ "", 0, 0, -1, 0 },
{ "", "Exit Root", kFALSE, kFileQuit, 0 },
{ 0, 0, 0, 0, 0 }
};
////////////////////////////////////////////////////////////////////////////////
// Server Frame
//______________________________________________________________________________
TSessionServerFrame::TSessionServerFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fFrmNewServer(0), fTxtName(0), fTxtAddress(0),
fTxtConfig(0), fTxtUsrName(0), fViewer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionServerFrame::~TSessionServerFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionServerFrame::Build(TSessionViewer *gui)
{
// Build server configuration frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fViewer = gui;
fFrmNewServer = new TGGroupFrame(this, "New Session");
fFrmNewServer->SetCleanup(kDeepCleanup);
AddFrame(fFrmNewServer, new TGLayoutHints(kLHintsExpandX, 2, 2, 2, 2));
fFrmNewServer->SetLayoutManager(new TGMatrixLayout(fFrmNewServer, 0, 2, 8));
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Session Name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtName = new TGTextEntry(fFrmNewServer,
(const char *)0, 1), new TGLayoutHints());
fTxtName->Resize(156, fTxtName->GetDefaultHeight());
fTxtName->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Server name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtAddress = new TGTextEntry(fFrmNewServer,
(const char *)0, 2), new TGLayoutHints());
fTxtAddress->Resize(156, fTxtAddress->GetDefaultHeight());
fTxtAddress->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Port (default: 1093):"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fNumPort = new TGNumberEntry(fFrmNewServer, 1093, 5,
3, TGNumberFormat::kNESInteger,TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0, 65535),new TGLayoutHints());
fNumPort->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Configuration File:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtConfig = new TGTextEntry(fFrmNewServer,
(const char *)0, 4), new TGLayoutHints());
fTxtConfig->Resize(156, fTxtConfig->GetDefaultHeight());
fTxtConfig->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Log Level:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fLogLevel = new TGNumberEntry(fFrmNewServer, 0, 5, 5,
TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0, 5),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fLogLevel->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "User Name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtUsrName = new TGTextEntry(fFrmNewServer,
(const char *)0, 6), new TGLayoutHints());
fTxtUsrName->Resize(156, fTxtUsrName->GetDefaultHeight());
fTxtUsrName->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Process mode :"),
new TGLayoutHints(kLHintsLeft | kLHintsBottom | kLHintsExpandX,
3, 3, 3, 3));
fFrmNewServer->AddFrame(fSync = new TGCheckButton(fFrmNewServer,
"&Synchronous"), new TGLayoutHints(kLHintsLeft | kLHintsBottom |
kLHintsExpandX, 3, 3, 3, 3));
fSync->SetToolTipText("Default Process Mode");
fSync->SetState(kButtonDown);
AddFrame(fBtnAdd = new TGTextButton(this, " Save "),
new TGLayoutHints(kLHintsTop | kLHintsCenterX, 5, 5, 15, 5));
fBtnAdd->SetToolTipText("Add server to the list");
fBtnAdd->Connect("Clicked()", "TSessionServerFrame", this,
"OnBtnAddClicked()");
AddFrame(fBtnConnect = new TGTextButton(this, " Connect "),
new TGLayoutHints(kLHintsTop | kLHintsCenterX, 5, 5, 15, 5));
fBtnConnect->Connect("Clicked()", "TSessionServerFrame", this,
"OnBtnConnectClicked()");
fBtnConnect->SetToolTipText("Connect to the selected server");
fTxtConfig->Connect("DoubleClicked()", "TSessionServerFrame", this,
"OnConfigFileClicked()");
fTxtName->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtAddress->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtConfig->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtUsrName->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fSync->Connect("Clicked()", "TSessionServerFrame", this,
"SettingsChanged()");
fLogLevel->Connect("ValueChanged(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fLogLevel->Connect("ValueSet(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fNumPort->Connect("ValueChanged(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fNumPort->Connect("ValueSet(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
}
//______________________________________________________________________________
void TSessionServerFrame::SettingsChanged()
{
// Settings have changed, update GUI accordingly.
TGTextEntry *sender = dynamic_cast<TGTextEntry*>((TQObject*)gTQSender);
Bool_t issync = (fSync->GetState() == kButtonDown);
if ((fViewer->GetActDesc()->fLocal) ||
(strcmp(fViewer->GetActDesc()->GetName(), fTxtName->GetText())) ||
(strcmp(fViewer->GetActDesc()->fAddress.Data(), fTxtAddress->GetText())) ||
(strcmp(fViewer->GetActDesc()->fConfigFile.Data(), fTxtConfig->GetText())) ||
(strcmp(fViewer->GetActDesc()->fUserName.Data(), fTxtUsrName->GetText())) ||
(fViewer->GetActDesc()->fLogLevel != fLogLevel->GetIntNumber()) ||
(fViewer->GetActDesc()->fPort != fNumPort->GetIntNumber()) ||
(fViewer->GetActDesc()->fSync != issync)) {
ShowFrame(fBtnAdd);
HideFrame(fBtnConnect);
}
else {
HideFrame(fBtnAdd);
ShowFrame(fBtnConnect);
}
if (sender) {
sender->SetFocus();
}
}
//______________________________________________________________________________
Bool_t TSessionServerFrame::HandleExpose(Event_t * /*event*/)
{
// Handle expose event in server frame.
//fTxtName->SelectAll();
//fTxtName->SetFocus();
return kTRUE;
}
//______________________________________________________________________________
void TSessionServerFrame::OnConfigFileClicked()
{
// Browse configuration files.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
TGFileInfo fi;
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), fViewer, kFDOpen, &fi);
if (!fi.fFilename) return;
fTxtConfig->SetText(gSystem->BaseName(fi.fFilename));
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnDeleteClicked()
{
// Delete selected session configuration (remove it from the list).
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
TString name(fTxtName->GetText());
TIter next(fViewer->GetSessions());
TSessionDescription *desc = fViewer->GetActDesc();
if (desc->fLocal) {
Int_t retval;
new TGMsgBox(fClient->GetRoot(), this, "Error Deleting Session",
"Deleting Local Sessions is not allowed !",
kMBIconExclamation,kMBOk,&retval);
return;
}
// ask for confirmation
TString m;
m.Form("Are you sure to delete the server \"%s\"",
desc->fName.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBOk | kMBCancel, &result);
// if confirmed, delete it
if (result == kMBOk) {
// remove the Proof session from gROOT list of Proofs
if (desc->fConnected && desc->fAttached && desc->fProof) {
desc->fProof->Detach("S");
}
// remove it from our sessions list
fViewer->GetSessions()->Remove((TObject *)desc);
// update configuration file
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
fViewer->GetSessionHierarchy()->DeleteItem(item);
TObject *obj = fViewer->GetSessions()->Last();
item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), (void *)obj);
if (item) {
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(item);
fViewer->GetSessionHierarchy()->HighlightItem(item);
fViewer->GetSessionHierarchy()->SetSelected(item);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->OnListTreeClicked(item, 1, 0, 0);
}
}
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnConnectClicked()
{
// Connect to selected server.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if (!fViewer->GetSessions()->FindObject(fTxtName->GetText())) {
OnBtnAddClicked();
}
else {
fViewer->GetActDesc()->fAddress = fTxtAddress->GetText();
fViewer->GetActDesc()->fPort = fNumPort->GetIntNumber();
if (strlen(fTxtConfig->GetText()) > 1)
fViewer->GetActDesc()->fConfigFile = TString(fTxtConfig->GetText());
else
fViewer->GetActDesc()->fConfigFile = "";
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fUserName = fTxtUsrName->GetText();
fViewer->GetActDesc()->fSync = (fSync->GetState() == kButtonDown);
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
// set flag busy
fViewer->SetBusy();
// avoid input events in list tree while connecting
fViewer->GetSessionHierarchy()->RemoveInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone, kFALSE);
// set watch cursor to indicate connection in progress
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(),
gVirtualX->CreateCursor(kWatch));
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
// display connection progress bar in first part of status bar
fViewer->GetStatusBar()->GetBarPart(0)->ShowFrame(fViewer->GetConnectProg());
// connect to proof startup message (to update progress bar)
TQObject::Connect("TProof", "StartupMessage(char *,Bool_t,Int_t,Int_t)",
"TSessionViewer", fViewer, "StartupMessage(char *,Bool_t,Int_t,Int_t)");
// collect and set-up configuration
TString url = fTxtUsrName->GetText();
url += "@"; url += fTxtAddress->GetText();
if (fNumPort->GetIntNumber() > 0) {
url += ":";
url += fNumPort->GetIntNumber();
}
TProofDesc *desc;
fViewer->GetActDesc()->fProofMgr = TProofMgr::Create(url);
if (!fViewer->GetActDesc()->fProofMgr->IsValid()) {
// hide connection progress bar from status bar
fViewer->GetStatusBar()->GetBarPart(0)->HideFrame(fViewer->GetConnectProg());
// release busy flag
fViewer->SetBusy(kFALSE);
// restore cursors and input
gVirtualX->SetCursor(GetId(), 0);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone);
fViewer->GetSessionHierarchy()->AddInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(), 0);
return;
}
fViewer->UpdateListOfSessions();
// check if the session already exist before to recreate it
TList *sessions = fViewer->GetActDesc()->fProofMgr->QuerySessions("");
if (sessions) {
TIter nextp(sessions);
// loop over existing Proof sessions
while ((desc = (TProofDesc *)nextp())) {
if ((desc->GetName() == fViewer->GetActDesc()->fTag) ||
(desc->GetTitle() == fViewer->GetActDesc()->fName)) {
fViewer->GetActDesc()->fProof =
fViewer->GetActDesc()->fProofMgr->AttachSession(desc->GetLocalId(), kTRUE);
fViewer->GetActDesc()->fTag = desc->GetName();
fViewer->GetActDesc()->fProof->SetAlias(fViewer->GetActDesc()->fName);
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fAttached = kTRUE;
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fProof->AddFeedback(kFeedbackHistos[i]);
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
// connect feedback signal
fViewer->GetActDesc()->fProof->Connect("Feedback(TList *objs)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Feedback(TList *objs)");
gROOT->Time();
}
else {
// if feedback option not selected, clear Proof's feedback option
fViewer->GetActDesc()->fProof->ClearFeedback();
}
break;
}
}
}
if (fViewer->GetActDesc()->fProof == 0) {
if (fViewer->GetActDesc()->fProofMgr->IsValid()) {
fViewer->GetActDesc()->fProof = fViewer->GetActDesc()->fProofMgr->CreateSession(
fViewer->GetActDesc()->fConfigFile);
sessions = fViewer->GetActDesc()->fProofMgr->QuerySessions("");
desc = (TProofDesc *)sessions->Last();
if (desc) {
fViewer->GetActDesc()->fProof->SetAlias(fViewer->GetActDesc()->fName);
fViewer->GetActDesc()->fTag = desc->GetName();
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fAttached = kTRUE;
}
}
}
if (fViewer->GetActDesc()->fProof) {
fViewer->GetActDesc()->fConfigFile = fViewer->GetActDesc()->fProof->GetConfFile();
fViewer->GetActDesc()->fUserName = fViewer->GetActDesc()->fProof->GetUser();
fViewer->GetActDesc()->fPort = fViewer->GetActDesc()->fProof->GetPort();
fViewer->GetActDesc()->fLogLevel = fViewer->GetActDesc()->fProof->GetLogLevel();
if (fViewer->GetActDesc()->fLogLevel < 0)
fViewer->GetActDesc()->fLogLevel = 0;
fViewer->GetActDesc()->fAddress = fViewer->GetActDesc()->fProof->GetMaster();
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fProof->SetBit(TProof::kUsingSessionGui);
}
fViewer->UpdateListOfSessions();
// check if connected and valid
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
// set log level
fViewer->GetActDesc()->fProof->SetLogLevel(fViewer->GetActDesc()->fLogLevel);
// set query type (synch / asynch)
fViewer->GetActDesc()->fProof->SetQueryMode(fViewer->GetActDesc()->fSync ?
TProof::kSync : TProof::kAsync);
// set connected flag
fViewer->GetActDesc()->fConnected = kTRUE;
// change list tree item picture to connected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(),fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofConPict(), fViewer->GetProofConPict());
// update viewer
fViewer->OnListTreeClicked(item, 1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
// connect to progress related signals
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"IndicateStop(Bool_t)");
fViewer->GetActDesc()->fProof->Connect(
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
fViewer->EnableTimer();
// change status bar right icon to connected pixmap
fViewer->ChangeRightLogo("monitor01.xpm");
// do not animate yet
fViewer->SetChangePic(kFALSE);
// connect to signal "query result ready"
fViewer->GetActDesc()->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", fViewer, "QueryResultReady(char *)");
// display connection information on status bar
TString msg;
msg.Form("PROOF Cluster %s ready", fViewer->GetActDesc()->fName.Data());
fViewer->GetStatusBar()->SetText(msg.Data(), 1);
fViewer->GetSessionFrame()->ProofInfos();
fViewer->UpdateListOfPackages();
fViewer->GetSessionFrame()->UpdateListOfDataSets();
// Enable previously uploaded packages if in auto-enable mode
if (fViewer->GetActDesc()->fAutoEnable) {
TPackageDescription *package;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
if (!package->fEnabled) {
if (fViewer->GetActDesc()->fProof->EnablePackage(package->fName) != 0)
Error("Submit", "Enable package failed");
else {
package->fEnabled = kTRUE;
fViewer->GetSessionFrame()->UpdatePackages();
}
}
}
}
}
// hide connection progress bar from status bar
fViewer->GetStatusBar()->GetBarPart(0)->HideFrame(fViewer->GetConnectProg());
// release busy flag
fViewer->SetBusy(kFALSE);
// restore cursors and input
gVirtualX->SetCursor(GetId(), 0);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone);
fViewer->GetSessionHierarchy()->AddInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(), 0);
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnNewServerClicked()
{
// Reset server configuration fields.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->HighlightItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->SetSelected(fViewer->GetSessionItem());
fViewer->OnListTreeClicked(fViewer->GetSessionItem(), 1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fTxtName->SetText("");
fTxtAddress->SetText("");
fTxtConfig->SetText("");
fNumPort->SetIntNumber(1093);
fLogLevel->SetIntNumber(0);
fTxtUsrName->SetText("");
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnAddClicked()
{
// Add newly created session configuration in the list of sessions.
Int_t retval;
Bool_t newSession = kTRUE;
TSessionDescription* desc = 0;
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if ((!fTxtName->GetBuffer()->GetTextLength()) ||
(!fTxtAddress->GetBuffer()->GetTextLength()) ||
(!fTxtUsrName->GetBuffer()->GetTextLength())) {
new TGMsgBox(fClient->GetRoot(), fViewer, "Error Adding Session",
"At least one required field is empty !",
kMBIconExclamation, kMBOk, &retval);
return;
}
TObject *obj = fViewer->GetSessions()->FindObject(fTxtName->GetText());
if (obj)
desc = dynamic_cast<TSessionDescription*>(obj);
if (desc) {
new TGMsgBox(fClient->GetRoot(), fViewer, "Adding Session",
Form("The session \"%s\" already exists ! Overwrite ?",
fTxtName->GetText()), kMBIconQuestion, kMBYes | kMBNo |
kMBCancel, &retval);
if (retval != kMBYes)
return;
newSession = kFALSE;
}
if (newSession) {
desc = new TSessionDescription();
desc->fName = fTxtName->GetText();
desc->fTag = "";
desc->fQueries = new TList();
desc->fPackages = new TList();
desc->fActQuery = 0;
desc->fProof = 0;
desc->fProofMgr = 0;
desc->fAutoEnable = kFALSE;
desc->fAddress = fTxtAddress->GetText();
desc->fPort = fNumPort->GetIntNumber();
desc->fConnected = kFALSE;
desc->fAttached = kFALSE;
desc->fLocal = kFALSE;
if (strlen(fTxtConfig->GetText()) > 1)
desc->fConfigFile = TString(fTxtConfig->GetText());
else
desc->fConfigFile = "";
desc->fLogLevel = fLogLevel->GetIntNumber();
desc->fUserName = fTxtUsrName->GetText();
desc->fSync = (fSync->GetState() == kButtonDown);
// add newly created session config to our session list
fViewer->GetSessions()->Add((TObject *)desc);
// save into configuration file
TGListTreeItem *item = fViewer->GetSessionHierarchy()->AddItem(
fViewer->GetSessionItem(), desc->fName.Data(),
fViewer->GetProofDisconPict(), fViewer->GetProofDisconPict());
fViewer->GetSessionHierarchy()->SetToolTipItem(item, "Proof Session");
item->SetUserData(desc);
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->OpenItem(item);
fViewer->GetSessionHierarchy()->HighlightItem(item);
fViewer->GetSessionHierarchy()->SetSelected(item);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->OnListTreeClicked(item, 1, 0, 0);
}
else {
fViewer->GetActDesc()->fName = fTxtName->GetText();
fViewer->GetActDesc()->fAddress = fTxtAddress->GetText();
fViewer->GetActDesc()->fPort = fNumPort->GetIntNumber();
if (strlen(fTxtConfig->GetText()) > 1)
fViewer->GetActDesc()->fConfigFile = TString(fTxtConfig->GetText());
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fUserName = fTxtUsrName->GetText();
fViewer->GetActDesc()->fSync = (fSync->GetState() == kButtonDown);
TGListTreeItem *item2 = fViewer->GetSessionHierarchy()->GetSelected();
item2->SetUserData(fViewer->GetActDesc());
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
}
HideFrame(fBtnAdd);
ShowFrame(fBtnConnect);
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
//______________________________________________________________________________
void TSessionServerFrame::Update(TSessionDescription* desc)
{
// Update fields with values from session description desc.
if (desc->fLocal) {
fTxtName->SetText("");
fTxtAddress->SetText("");
fNumPort->SetIntNumber(1093);
fTxtConfig->SetText("");
fTxtUsrName->SetText("");
fLogLevel->SetIntNumber(0);
return;
}
fTxtName->SetText(desc->fName);
fTxtAddress->SetText(desc->fAddress);
fNumPort->SetIntNumber(desc->fPort);
fLogLevel->SetIntNumber(desc->fLogLevel);
if (desc->fConfigFile.Length() > 1) {
fTxtConfig->SetText(desc->fConfigFile);
}
else {
fTxtConfig->SetText("");
}
fTxtUsrName->SetText(desc->fUserName);
}
//______________________________________________________________________________
Bool_t TSessionServerFrame::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
// Process messages for session server frame.
// Used to navigate between text entry fields.
switch (GET_MSG(msg)) {
case kC_TEXTENTRY:
switch (GET_SUBMSG(msg)) {
case kTE_ENTER:
case kTE_TAB:
switch (parm1) {
case 1: // session name
fTxtAddress->SelectAll();
fTxtAddress->SetFocus();
break;
case 2: // server address
fNumPort->GetNumberEntry()->SelectAll();
fNumPort->GetNumberEntry()->SetFocus();
break;
case 3: // port number
fTxtConfig->SelectAll();
fTxtConfig->SetFocus();
break;
case 4: // configuration file
fLogLevel->GetNumberEntry()->SelectAll();
fLogLevel->GetNumberEntry()->SetFocus();
break;
case 5: // log level
fTxtUsrName->SelectAll();
fTxtUsrName->SetFocus();
break;
case 6: // user name
fTxtName->SelectAll();
fTxtName->SetFocus();
break;
}
break;
default:
break;
}
break;
default:
break;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
// Session Frame
//______________________________________________________________________________
TSessionFrame::TSessionFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h)
{
// Constructor.
}
//______________________________________________________________________________
TSessionFrame::~TSessionFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionFrame::Build(TSessionViewer *gui)
{
// Build session frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fViewer = gui;
Int_t i,j;
// main session tab
fTab = new TGTab(this, 200, 200);
AddFrame(fTab, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 2, 2, 2));
// add "Status" tab element
TGCompositeFrame *tf = fTab->AddTab("Status");
fFA = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFA, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add first session information line
fInfoLine[0] = new TGLabel(fFA, " ");
fFA->AddFrame(fInfoLine[0], new TGLayoutHints(kLHintsCenterX |
kLHintsExpandX, 5, 5, 15, 5));
TGCompositeFrame* frmInfos = new TGHorizontalFrame(fFA, 350, 100);
frmInfos->SetLayoutManager(new TGTableLayout(frmInfos, 9, 2));
// add session information lines
j = 0;
for (i=0;i<17;i+=2) {
fInfoLine[i+1] = new TGLabel(frmInfos, " ");
frmInfos->AddFrame(fInfoLine[i+1], new TGTableLayoutHints(0, 1, j, j+1,
kLHintsLeft | kLHintsCenterY, 5, 5, 2, 2));
fInfoLine[i+2] = new TGLabel(frmInfos, " ");
frmInfos->AddFrame(fInfoLine[i+2], new TGTableLayoutHints(1, 2, j, j+1,
kLHintsLeft | kLHintsCenterY, 5, 5, 2, 2));
j++;
}
fFA->AddFrame(frmInfos, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY, 5, 5, 5, 5));
// add "new query" and "get queries" buttons
TGCompositeFrame* frmBut1 = new TGHorizontalFrame(fFA, 350, 100);
frmBut1->SetCleanup(kDeepCleanup);
frmBut1->AddFrame(fBtnNewQuery = new TGTextButton(frmBut1, "New Query..."),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5));
fBtnNewQuery->SetToolTipText("Open New Query Dialog");
frmBut1->AddFrame(fBtnGetQueries = new TGTextButton(frmBut1, " Get Queries "),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5));
fBtnGetQueries->SetToolTipText("Get List of Queries from the server");
fBtnShowLog = new TGTextButton(frmBut1, "Show log...");
fBtnShowLog->SetToolTipText("Show Session log (opens log window)");
frmBut1->AddFrame(fBtnShowLog, new TGLayoutHints(kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fFA->AddFrame(frmBut1, new TGLayoutHints(kLHintsLeft | kLHintsBottom |
kLHintsExpandX));
// add "Commands" tab element
tf = fTab->AddTab("Commands");
fFC = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFC, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add comand line label and text entry
TGCompositeFrame* frmCmd = new TGHorizontalFrame(fFC, 350, 100);
frmCmd->SetCleanup(kDeepCleanup);
frmCmd->AddFrame(new TGLabel(frmCmd, "Command Line :"),
new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 5, 5, 15, 5));
fCommandBuf = new TGTextBuffer(120);
frmCmd->AddFrame(fCommandTxt = new TGTextEntry(frmCmd,
fCommandBuf ),new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandX, 5, 5, 15, 5));
fFC->AddFrame(frmCmd, new TGLayoutHints(kLHintsExpandX, 5, 5, 10, 5));
// connect command line text entry to "return pressed" signal
fCommandTxt->Connect("ReturnPressed()", "TSessionFrame", this,
"OnCommandLine()");
// check box for option "clear view"
fClearCheck = new TGCheckButton(fFC, "Clear view after each command");
fFC->AddFrame(fClearCheck,new TGLayoutHints(kLHintsLeft | kLHintsTop,
10, 5, 5, 5));
fClearCheck->SetState(kButtonUp);
// add text view for redirected output
fFC->AddFrame(new TGLabel(fFC, "Output :"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 10, 5, 5, 5));
fInfoTextView = new TGTextView(fFC, 330, 150, "", kSunkenFrame |
kDoubleBorder);
fFC->AddFrame(fInfoTextView, new TGLayoutHints(kLHintsLeft |
kLHintsTop | kLHintsExpandX | kLHintsExpandY, 10, 10, 5, 5));
// add "Packages" tab element
tf = fTab->AddTab("Packages");
fFB = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFB, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing packages listbox and control buttons
TGCompositeFrame* frmcanvas = new TGHorizontalFrame(fFB, 350, 100);
// packages listbox
fLBPackages = new TGListBox(frmcanvas);
fLBPackages->Resize(80,150);
fLBPackages->SetMultipleSelections(kFALSE);
frmcanvas->AddFrame(fLBPackages, new TGLayoutHints(kLHintsExpandX |
kLHintsExpandY, 5, 5, 5, 5));
// control buttons frame
TGCompositeFrame* frmBut2 = new TGVerticalFrame(frmcanvas, 150, 100);
fChkMulti = new TGCheckButton(frmBut2, "Multiple Selection");
fChkMulti->SetToolTipText("Enable multiple selection in the package list");
frmBut2->AddFrame(fChkMulti, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
fBtnAdd = new TGTextButton(frmBut2, " Add... ");
fBtnAdd->SetToolTipText("Add a package to the list");
frmBut2->AddFrame(fBtnAdd,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRemove = new TGTextButton(frmBut2, "Remove");
fBtnRemove->SetToolTipText("Remove package from the list");
frmBut2->AddFrame(fBtnRemove,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnUp = new TGTextButton(frmBut2, "Move Up");
fBtnUp->SetToolTipText("Move package one step upward in the list");
frmBut2->AddFrame(fBtnUp,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnDown = new TGTextButton(frmBut2, "Move Down");
fBtnDown->SetToolTipText("Move package one step downward in the list");
frmBut2->AddFrame(fBtnDown,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
frmcanvas->AddFrame(frmBut2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY));
fFB->AddFrame(frmcanvas, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
TGCompositeFrame* frmLeg = new TGHorizontalFrame(fFB, 300, 100);
frmLeg->SetCleanup(kDeepCleanup);
TGPicture *pic1 = (TGPicture *)fClient->GetPicture("package.xpm");
TGIcon *icn1 = new TGIcon(frmLeg, pic1, pic1->GetWidth(), pic1->GetHeight());
frmLeg->AddFrame(icn1, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Local"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
TGPicture *pic2 = (TGPicture *)fClient->GetPicture("package_delete.xpm");
TGIcon *icn2 = new TGIcon(frmLeg, pic2, pic2->GetWidth(), pic2->GetHeight());
frmLeg->AddFrame(icn2, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Uploaded"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
TGPicture *pic3 = (TGPicture *)fClient->GetPicture("package_add.xpm");
TGIcon *icn3 = new TGIcon(frmLeg, pic3, pic3->GetWidth(), pic3->GetHeight());
frmLeg->AddFrame(icn3, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Enabled"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
fFB->AddFrame(frmLeg, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX, 0, 0, 0, 0));
TGCompositeFrame* frmBtn = new TGHorizontalFrame(fFB, 300, 100);
frmBtn->SetCleanup(kDeepCleanup);
frmBtn->AddFrame(fBtnUpload = new TGTextButton(frmBtn,
" Upload "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnUpload->SetToolTipText("Upload selected package(s) to the server");
frmBtn->AddFrame(fBtnEnable = new TGTextButton(frmBtn,
" Enable "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnEnable->SetToolTipText("Enable selected package(s) on the server");
frmBtn->AddFrame(fBtnDisable = new TGTextButton(frmBtn,
" Disable "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnDisable->SetToolTipText("Disable selected package(s) on the server");
frmBtn->AddFrame(fBtnClear = new TGTextButton(frmBtn,
" Clear "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnClear->SetToolTipText("Clear all packages on the server");
fFB->AddFrame(frmBtn, new TGLayoutHints(kLHintsExpandX, 0, 0, 0, 0));
fBtnClear->SetEnabled(kFALSE);
TGCompositeFrame* frmBtn3 = new TGHorizontalFrame(fFB, 300, 100);
frmBtn3->SetCleanup(kDeepCleanup);
fBtnShow = new TGTextButton(frmBtn3, "Show packages");
fBtnShow->SetToolTipText("Show (list) available packages on the server");
frmBtn3->AddFrame(fBtnShow,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnShowEnabled = new TGTextButton(frmBtn3, "Show Enabled");
fBtnShowEnabled->SetToolTipText("Show (list) enabled packages on the server");
frmBtn3->AddFrame(fBtnShowEnabled,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fFB->AddFrame(frmBtn3, new TGLayoutHints(kLHintsExpandX, 0, 0, 0, 0));
fChkEnable = new TGCheckButton(fFB, "Enable at session startup");
fChkEnable->SetToolTipText("Enable packages on the server at startup time");
fFB->AddFrame(fChkEnable, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// add "DataSets" tab element
tf = fTab->AddTab("DataSets");
fFE = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFE, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing datasets treeview and control buttons
TGCompositeFrame* frmdataset = new TGHorizontalFrame(fFE, 350, 100);
// datasets list tree
fDSetView = new TGCanvas(frmdataset, 200, 200, kSunkenFrame | kDoubleBorder);
frmdataset->AddFrame(fDSetView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
5, 5, 5, 5));
fDataSetTree = new TGListTree(fDSetView, kHorizontalFrame);
fDataSetTree->AddItem(0, "DataSets");
// control buttons frame
TGCompositeFrame* frmBut3 = new TGVerticalFrame(frmdataset, 150, 100);
fBtnUploadDSet = new TGTextButton(frmBut3, " Upload... ");
fBtnUploadDSet->SetToolTipText("Upload a dataset to the cluster");
frmBut3->AddFrame(fBtnUploadDSet, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRemoveDSet = new TGTextButton(frmBut3, "Remove");
fBtnRemoveDSet->SetToolTipText("Remove dataset from the cluster");
frmBut3->AddFrame(fBtnRemoveDSet,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnVerifyDSet = new TGTextButton(frmBut3, "Verify");
fBtnVerifyDSet->SetToolTipText("Verify dataset on the cluster");
frmBut3->AddFrame(fBtnVerifyDSet,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRefresh = new TGTextButton(frmBut3, "Refresh List");
fBtnRefresh->SetToolTipText("Refresh List of DataSet/Files present on the cluster");
frmBut3->AddFrame(fBtnRefresh,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 15, 5));
frmdataset->AddFrame(frmBut3, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY, 5, 5, 5, 0));
fFE->AddFrame(frmdataset, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
// add "Options" tab element
tf = fTab->AddTab("Options");
fFD = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFD, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add Log Level label and text entry
TGCompositeFrame* frmLog = new TGHorizontalFrame(fFD, 310, 100, kFixedWidth);
frmLog->SetCleanup(kDeepCleanup);
frmLog->AddFrame(fApplyLogLevel = new TGTextButton(frmLog,
" Apply "), new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 10, 5, 5, 5));
fApplyLogLevel->SetToolTipText("Apply currently selected log level");
fLogLevel = new TGNumberEntry(frmLog, 0, 5, 5, TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0, 5);
frmLog->AddFrame(fLogLevel, new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 5, 5, 5, 5));
frmLog->AddFrame(new TGLabel(frmLog, "Log Level :"),
new TGLayoutHints(kLHintsRight | kLHintsCenterY, 5, 5, 5, 5));
fFD->AddFrame(frmLog, new TGLayoutHints(kLHintsLeft, 5, 5, 15, 5));
// add Parallel Nodes label and text entry
TGCompositeFrame* frmPar = new TGHorizontalFrame(fFD, 310, 100, kFixedWidth);
frmPar->SetCleanup(kDeepCleanup);
frmPar->AddFrame(fApplyParallel = new TGTextButton(frmPar,
" Apply "), new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 10, 5, 5, 5));
fApplyParallel->SetToolTipText("Apply currently selected parallel nodes");
fTxtParallel = new TGTextEntry(frmPar);
fTxtParallel->SetAlignment(kTextRight);
fTxtParallel->SetText("99999");
fTxtParallel->Resize(fLogLevel->GetDefaultWidth(), fTxtParallel->GetDefaultHeight());
frmPar->AddFrame(fTxtParallel, new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 5, 5, 5, 5));
frmPar->AddFrame(new TGLabel(frmPar, "Set Parallel Nodes :"),
new TGLayoutHints(kLHintsRight | kLHintsCenterY, 5, 5, 5, 5));
fFD->AddFrame(frmPar, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// connect button actions to functions
fBtnShowLog->Connect("Clicked()", "TSessionFrame", this,
"OnBtnShowLogClicked()");
fBtnNewQuery->Connect("Clicked()", "TSessionFrame", this,
"OnBtnNewQueryClicked()");
fBtnGetQueries->Connect("Clicked()", "TSessionFrame", this,
"OnBtnGetQueriesClicked()");
fChkEnable->Connect("Toggled(Bool_t)", "TSessionFrame", this,
"OnStartupEnable(Bool_t)");
fChkMulti->Connect("Toggled(Bool_t)", "TSessionFrame", this,
"OnMultipleSelection(Bool_t)");
fBtnAdd->Connect("Clicked()", "TSessionFrame", this,
"OnBtnAddClicked()");
fBtnRemove->Connect("Clicked()", "TSessionFrame", this,
"OnBtnRemoveClicked()");
fBtnUp->Connect("Clicked()", "TSessionFrame", this,
"OnBtnUpClicked()");
fBtnDown->Connect("Clicked()", "TSessionFrame", this,
"OnBtnDownClicked()");
fApplyLogLevel->Connect("Clicked()", "TSessionFrame", this,
"OnApplyLogLevel()");
fApplyParallel->Connect("Clicked()", "TSessionFrame", this,
"OnApplyParallel()");
fBtnUpload->Connect("Clicked()", "TSessionFrame", this,
"OnUploadPackages()");
fBtnEnable->Connect("Clicked()", "TSessionFrame", this,
"OnEnablePackages()");
fBtnDisable->Connect("Clicked()", "TSessionFrame", this,
"OnDisablePackages()");
fBtnClear->Connect("Clicked()", "TSessionFrame", this,
"OnClearPackages()");
fBtnShowEnabled->Connect("Clicked()", "TSessionViewer", fViewer,
"ShowEnabledPackages()");
fBtnShow->Connect("Clicked()", "TSessionViewer", fViewer,
"ShowPackages()");
fBtnUploadDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnUploadDSet()");
fBtnRemoveDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnRemoveDSet()");
fBtnVerifyDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnVerifyDSet()");
fBtnRefresh->Connect("Clicked()", "TSessionFrame", this,
"UpdateListOfDataSets()");
}
//______________________________________________________________________________
void TSessionFrame::ProofInfos()
{
// Display informations on current session.
char buf[256];
// if local session
if (fViewer->GetActDesc()->fLocal) {
sprintf(buf, "*** Local Session on %s ***", gSystem->HostName());
fInfoLine[0]->SetText(buf);
UserGroup_t *userGroup = gSystem->GetUserInfo();
fInfoLine[1]->SetText("User :");
sprintf(buf, "%s", userGroup->fRealName.Data());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("Working directory :");
sprintf(buf, "%s", gSystem->WorkingDirectory());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText(" ");
fInfoLine[6]->SetText(" ");
fInfoLine[7]->SetText(" ");
fInfoLine[8]->SetText(" ");
fInfoLine[9]->SetText(" ");
fInfoLine[10]->SetText(" ");
fInfoLine[11]->SetText(" ");
fInfoLine[12]->SetText(" ");
fInfoLine[13]->SetText(" ");
fInfoLine[14]->SetText(" ");
fInfoLine[15]->SetText(" ");
fInfoLine[16]->SetText(" ");
fInfoLine[17]->SetText(" ");
fInfoLine[18]->SetText(" ");
delete userGroup;
Layout();
Resize(GetDefaultSize());
return;
}
// return if not a valid Proof session
if (!fViewer->GetActDesc()->fConnected ||
!fViewer->GetActDesc()->fAttached ||
!fViewer->GetActDesc()->fProof ||
!fViewer->GetActDesc()->fProof->IsValid())
return;
if (!fViewer->GetActDesc()->fProof->IsMaster()) {
if (fViewer->GetActDesc()->fProof->IsParallel())
sprintf(buf,"*** Connected to %s (parallel mode, %d workers) ***",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
else
sprintf(buf, "*** Connected to %s (sequential mode) ***",
fViewer->GetActDesc()->fProof->GetMaster());
fInfoLine[0]->SetText(buf);
fInfoLine[1]->SetText("Port number : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetPort());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("User : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetUser());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText("Client protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetClientProtocol());
fInfoLine[6]->SetText(buf);
fInfoLine[7]->SetText("Remote protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetRemoteProtocol());
fInfoLine[8]->SetText(buf);
fInfoLine[9]->SetText("Log level : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetLogLevel());
fInfoLine[10]->SetText(buf);
fInfoLine[11]->SetText("Session unique tag : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->IsValid() ?
fViewer->GetActDesc()->fProof->GetSessionTag() : " ");
fInfoLine[12]->SetText(buf);
fInfoLine[13]->SetText("Total MB's processed :");
sprintf(buf, "%.2f", float(fViewer->GetActDesc()->fProof->GetBytesRead())/(1024*1024));
fInfoLine[14]->SetText(buf);
fInfoLine[15]->SetText("Total real time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetRealTime());
fInfoLine[16]->SetText(buf);
fInfoLine[17]->SetText("Total CPU time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetCpuTime());
fInfoLine[18]->SetText(buf);
}
else {
if (fViewer->GetActDesc()->fProof->IsParallel())
sprintf(buf,"*** Master server %s (parallel mode, %d workers) ***",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
else
sprintf(buf, "*** Master server %s (sequential mode) ***",
fViewer->GetActDesc()->fProof->GetMaster());
fInfoLine[0]->SetText(buf);
fInfoLine[1]->SetText("Port number : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetPort());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("User : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetUser());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText("Protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetClientProtocol());
fInfoLine[6]->SetText(buf);
fInfoLine[7]->SetText("Image name : ");
sprintf(buf, "%s",fViewer->GetActDesc()->fProof->GetImage());
fInfoLine[8]->SetText(buf);
fInfoLine[9]->SetText("Config directory : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetConfDir());
fInfoLine[10]->SetText(buf);
fInfoLine[11]->SetText("Config file : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetConfFile());
fInfoLine[12]->SetText(buf);
fInfoLine[13]->SetText("Total MB's processed :");
sprintf(buf, "%.2f", float(fViewer->GetActDesc()->fProof->GetBytesRead())/(1024*1024));
fInfoLine[14]->SetText(buf);
fInfoLine[15]->SetText("Total real time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetRealTime());
fInfoLine[16]->SetText(buf);
fInfoLine[17]->SetText("Total CPU time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetCpuTime());
fInfoLine[18]->SetText(buf);
}
Layout();
Resize(GetDefaultSize());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnUploadDSet()
{
// Open Upload Dataset dialog.
if (fViewer->IsBusy())
return;
if (fViewer->GetActDesc()->fLocal) return;
new TUploadDataSetDlg(fViewer, 450, 360);
}
//______________________________________________________________________________
void TSessionFrame::UpdateListOfDataSets()
{
// Update list of dataset present on the cluster.
TObjString *dsetname;
TFileInfo *dsetfilename;
// cleanup the list
fDataSetTree->DeleteChildren(fDataSetTree->GetFirstItem());
if (fViewer->GetActDesc()->fConnected && fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof && fViewer->GetActDesc()->fProof->IsValid() &&
fViewer->GetActDesc()->fProof->IsParallel()) {
const TGPicture *dseticon = fClient->GetPicture("rootdb_t.xpm");
// ask for the list of datasets
TList *dsetlist = fViewer->GetActDesc()->fProof->GetDataSets();
if(dsetlist) {
TGListTreeItem *dsetitem;
fDataSetTree->OpenItem(fDataSetTree->GetFirstItem());
TIter nextdset(dsetlist);
while ((dsetname = (TObjString *)nextdset())) {
if (!fDataSetTree->FindItemByObj(fDataSetTree->GetFirstItem(), dsetname)) {
// add the dataset in the tree
dsetitem = fDataSetTree->AddItem(fDataSetTree->GetFirstItem(),
dsetname->GetName(), dsetname);
// ask for the list of files in the dataset
TList *dsetfilelist = fViewer->GetActDesc()->fProof->GetDataSet(
dsetname->GetName());
if(dsetfilelist) {
TIter nextdsetfile(dsetfilelist);
while ((dsetfilename = (TFileInfo *)nextdsetfile())) {
if (! fDataSetTree->FindItemByObj(dsetitem, dsetfilename)) {
// if not already in, add the file name in the tree
fDataSetTree->AddItem(dsetitem,
dsetfilename->GetFirstUrl()->GetUrl(),
dsetfilename, dseticon, dseticon);
}
}
// open the dataset item in order to show the files
fDataSetTree->OpenItem(dsetitem);
}
}
}
}
}
// refresh list tree
fClient->NeedRedraw(fDataSetTree);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnRemoveDSet()
{
// Remove dataset from the list and from the cluster.
TGListTreeItem *item;
TObjString *obj = 0;
if (fViewer->GetActDesc()->fLocal) return;
item = fDataSetTree->GetSelected();
if (!item) return;
if (item->GetParent() == 0) return;
if (item->GetParent() == fDataSetTree->GetFirstItem()) {
// Dataset itself
obj = (TObjString *)item->GetUserData();
}
else if (item->GetParent()->GetParent() == fDataSetTree->GetFirstItem()) {
// One file of the dataset
obj = (TObjString *)item->GetParent()->GetUserData();
}
// if valid Proof session, set parallel slaves
if (obj && fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->RemoveDataSet(obj->GetName());
UpdateListOfDataSets();
}
}
//______________________________________________________________________________
void TSessionFrame::OnBtnVerifyDSet()
{
// Verify that the files in the selected dataset are present on the cluster.
TGListTreeItem *item;
TObjString *obj = 0;
if (fViewer->GetActDesc()->fLocal) return;
item = fDataSetTree->GetSelected();
if (!item) return;
if (item->GetParent() == 0) return;
if (item->GetParent() == fDataSetTree->GetFirstItem()) {
// Dataset itself
obj = (TObjString *)item->GetUserData();
}
else if (item->GetParent()->GetParent() == fDataSetTree->GetFirstItem()) {
// One file of the dataset
obj = (TObjString *)item->GetParent()->GetUserData();
}
// if valid Proof session, set parallel slaves
if (obj && fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->VerifyDataSet(obj->GetName());
}
}
//______________________________________________________________________________
void TSessionFrame::OnApplyLogLevel()
{
// Apply selected log level on current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, set log level
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fProof->SetLogLevel(fViewer->GetActDesc()->fLogLevel);
}
fViewer->GetSessionFrame()->ProofInfos();
}
//______________________________________________________________________________
void TSessionFrame::OnApplyParallel()
{
// Apply selected number of workers on current Proof session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, set parallel slaves
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
Int_t nodes = atoi(fTxtParallel->GetText());
fViewer->GetActDesc()->fProof->SetParallel(nodes);
}
fViewer->GetSessionFrame()->ProofInfos();
}
//______________________________________________________________________________
void TSessionFrame::OnMultipleSelection(Bool_t on)
{
// Handle multiple selection check button.
fLBPackages->SetMultipleSelections(on);
}
//______________________________________________________________________________
void TSessionFrame::OnStartupEnable(Bool_t on)
{
// Handle multiple selection check button.
if (fViewer->GetActDesc())
fViewer->GetActDesc()->fAutoEnable = on;
}
//______________________________________________________________________________
void TSessionFrame::UpdatePackages()
{
// Update list of packages.
TPackageDescription *package;
const TGPicture *pict;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnUploadPackages()
{
// Upload selected package(s) to the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, upload packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
if (fViewer->GetActDesc()->fProof->UploadPackage(name.Data()) != 0)
Error("Submit", "Upload package failed");
else {
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
package->fUploaded = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(
fClient->GetPicture("package_delete.xpm"));
}
}
}
UpdatePackages();
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnEnablePackages()
{
// Enable selected package(s) in the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, enable packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fBtnEnable->SetState(kButtonDisabled);
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
if (!package->fUploaded) {
if (fViewer->GetActDesc()->fProof->UploadPackage(name.Data()) != 0)
Error("Submit", "Upload package failed");
else {
package->fUploaded = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(
fClient->GetPicture("package_delete.xpm"));
}
}
}
if (fViewer->GetActDesc()->fProof->EnablePackage(name) != 0)
Error("Submit", "Enable package failed");
else {
package->fEnabled = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(fClient->GetPicture("package_add.xpm"));
}
}
UpdatePackages();
fBtnEnable->SetState(kButtonUp);
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnDisablePackages()
{
// Disable selected package(s) in the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, disable (clear) packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
if (fViewer->GetActDesc()->fProof->ClearPackage(name) != 0)
Error("Submit", "Clear package failed");
else {
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
package->fEnabled = kFALSE;
package->fUploaded = kFALSE;
((TGIconLBEntry *)obj)->SetPicture(fClient->GetPicture("package.xpm"));
}
}
}
UpdatePackages();
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnClearPackages()
{
// Clear (disable) all packages in the current session.
TPackageDescription *package;
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, clear packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
if (fViewer->GetActDesc()->fProof->ClearPackages() != 0)
Error("Submit", "Clear packages failed");
else {
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fEnabled = kFALSE;
}
}
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnAddClicked()
{
// Open file dialog and add selected package file to the list.
if (fViewer->IsBusy())
return;
TGFileInfo fi;
TPackageDescription *package;
TGIconLBEntry *entry;
fi.fFileTypes = pkgtypes;
new TGFileDialog(fClient->GetRoot(), fViewer, kFDOpen, &fi);
if (fi.fMultipleSelection && fi.fFileNamesList) {
TObjString *el;
TIter next(fi.fFileNamesList);
while ((el = (TObjString *) next())) {
package = new TPackageDescription;
package->fName = gSystem->BaseName(gSystem->UnixPathName(el->GetString()));
package->fPathName = gSystem->UnixPathName(el->GetString());
package->fId = fViewer->GetActDesc()->fPackages->GetEntries();
package->fUploaded = kFALSE;
package->fEnabled = kFALSE;
fViewer->GetActDesc()->fPackages->Add((TObject *)package);
entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName,
fClient->GetPicture("package.xpm"));
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
}
else if (fi.fFilename) {
package = new TPackageDescription;
package->fName = gSystem->BaseName(gSystem->UnixPathName(fi.fFilename));
package->fPathName = gSystem->UnixPathName(fi.fFilename);
package->fId = fViewer->GetActDesc()->fPackages->GetEntries();
package->fUploaded = kFALSE;
package->fEnabled = kFALSE;
fViewer->GetActDesc()->fPackages->Add((TObject *)package);
entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName,
fClient->GetPicture("package.xpm"));
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnRemoveClicked()
{
// Remove selected package from the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnUpClicked()
{
// Move selected package entry one position up in the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
if (pos <= 0) return;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
package = (TPackageDescription *)fViewer->GetActDesc()->fPackages->At(pos);
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
package->fId -= 1;
fViewer->GetActDesc()->fPackages->AddAt(package, package->fId);
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Select(pos-1);
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnDownClicked()
{
// Move selected package entry one position down in the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
if (pos == -1 || pos == fViewer->GetActDesc()->fPackages->GetEntries()-1)
return;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
package = (TPackageDescription *)fViewer->GetActDesc()->fPackages->At(pos);
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
package->fId += 1;
fViewer->GetActDesc()->fPackages->AddAt(package, package->fId);
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Select(pos+1);
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnDisconnectClicked()
{
// Disconnect from current Proof session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, disconnect (close)
if (fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Detach();
}
// reset connected flag
fViewer->GetActDesc()->fAttached = kFALSE;
fViewer->GetActDesc()->fProof = 0;
// disable animation timer
fViewer->DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofDisconPict(),
fViewer->GetProofDisconPict());
// update viewer
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->GetStatusBar()->SetText("", 1);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnShowLogClicked()
{
// Show session log.
fViewer->ShowLog(0);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnNewQueryClicked()
{
// Call "New Query" Dialog.
TNewQueryDlg *dlg = new TNewQueryDlg(fViewer, 350, 310);
dlg->Popup();
}
//______________________________________________________________________________
void TSessionFrame::OnBtnGetQueriesClicked()
{
// Get list of queries from current Proof server and populate the list tree.
TList *lqueries = 0;
TQueryResult *query = 0;
TQueryDescription *newquery = 0, *lquery = 0;
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
lqueries = fViewer->GetActDesc()->fProof->GetListOfQueries();
}
if (lqueries) {
TIter nextp(lqueries);
// loop over list of queries received from Proof server
while ((query = (TQueryResult *)nextp())) {
// create new query description
newquery = new TQueryDescription();
newquery->fReference = Form("%s:%s", query->GetTitle(),
query->GetName());
// check in our tree if it is already there
TGListTreeItem *item =
fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
// if already there, skip
if (fViewer->GetSessionHierarchy()->FindChildByName(item,
newquery->fReference.Data()))
continue;
// check also in our query description list
Bool_t found = kFALSE;
TIter nextp(fViewer->GetActDesc()->fQueries);
while ((lquery = (TQueryDescription *)nextp())) {
if (lquery->fReference.CompareTo(newquery->fReference) == 0) {
found = kTRUE;
break;
}
}
if (found) continue;
// build new query description with infos from Proof
newquery->fStatus = query->IsFinalized() ?
TQueryDescription::kSessionQueryFinalized :
(TQueryDescription::ESessionQueryStatus)query->GetStatus();
newquery->fSelectorString = query->GetSelecImp()->GetName();
newquery->fQueryName = Form("%s:%s", query->GetTitle(),
query->GetName());
newquery->fOptions = query->GetOptions();
newquery->fEventList = "";
newquery->fNbFiles = 0;
newquery->fNoEntries = query->GetEntries();
newquery->fFirstEntry = query->GetFirst();
newquery->fResult = query;
newquery->fChain = 0;
fViewer->GetActDesc()->fQueries->Add((TObject *)newquery);
TGListTreeItem *item2 = fViewer->GetSessionHierarchy()->AddItem(item,
newquery->fQueryName, fViewer->GetQueryConPict(),
fViewer->GetQueryConPict());
item2->SetUserData(newquery);
if (query->GetInputList())
fViewer->GetSessionHierarchy()->AddItem(item2, "InputList");
if (query->GetOutputList())
fViewer->GetSessionHierarchy()->AddItem(item2, "OutputList");
}
}
// at the end, update list tree
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
}
//______________________________________________________________________________
void TSessionFrame::OnCommandLine()
{
// Command line handling.
// get command string
const char *cmd = fCommandTxt->GetText();
char opt[2];
// form temporary file path
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectCmd);
// if check box "clear view" is checked, open temp file in write mode
// (overwrite), in append mode otherwise.
if (fClearCheck->IsOn())
sprintf(opt, "w");
else
sprintf(opt, "a");
// if valid Proof session, pass the command to Proof
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), opt) != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
// execute command line
fViewer->GetActDesc()->fProof->Exec(cmd);
// restore back stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
// if check box "clear view" is checked, clear text view
if (fClearCheck->IsOn())
fInfoTextView->Clear();
// load (display) temp file in text view
fInfoTextView->LoadFile(pathtmp.Data());
// set focus to "command line" text entry
fCommandTxt->SetFocus();
}
else {
// if no Proof session, or Proof session not valid,
// lets execute command line by TApplication
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), opt) != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
}
// execute command line
gApplication->ProcessLine(cmd);
// restore back stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
}
// if check box "clear view" is checked, clear text view
if (fClearCheck->IsOn())
fInfoTextView->Clear();
// load (display) temp file in text view
fInfoTextView->LoadFile(pathtmp.Data());
// set focus to "command line" text entry
fCommandTxt->SetFocus();
}
// display bottom of text view
fInfoTextView->ShowBottom();
}
//______________________________________________________________________________
void TSessionFrame::SetLocal(Bool_t local)
{
// Switch widgets status/visibility for local/remote sessions.
if (local) {
fBtnGetQueries->SetState(kButtonDisabled);
fBtnShowLog->SetState(kButtonDisabled);
fTab->HideFrame(fTab->GetTabTab("Options"));
fTab->HideFrame(fTab->GetTabTab("Packages"));
fTab->HideFrame(fTab->GetTabTab("DataSets"));
}
else {
fBtnGetQueries->SetState(kButtonUp);
fBtnShowLog->SetState(kButtonUp);
fTab->ShowFrame(fTab->GetTabTab("Options"));
fTab->ShowFrame(fTab->GetTabTab("Packages"));
fTab->ShowFrame(fTab->GetTabTab("DataSets"));
}
}
//______________________________________________________________________________
void TSessionFrame::ShutdownSession()
{
// Shutdown current session.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if (fViewer->GetActDesc()->fLocal) {
Int_t retval;
new TGMsgBox(fClient->GetRoot(), this, "Error Shutting down Session",
"Shutting down Local Sessions is not allowed !",
kMBIconExclamation,kMBOk,&retval);
return;
}
if (!fViewer->GetActDesc()->fAttached ||
!fViewer->GetActDesc()->fProof ||
!fViewer->GetActDesc()->fProof->IsValid())
return;
// ask for confirmation
TString m;
m.Form("Are you sure to shutdown the session \"%s\"",
fViewer->GetActDesc()->fName.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBOk | kMBCancel, &result);
// if confirmed, delete it
if (result != kMBOk)
return;
// remove the Proof session from gROOT list of Proofs
fViewer->GetActDesc()->fProof->Detach("S");
// reset connected flag
fViewer->GetActDesc()->fAttached = kFALSE;
fViewer->GetActDesc()->fProof = 0;
// disable animation timer
fViewer->DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofDisconPict(),
fViewer->GetProofDisconPict());
// update viewer
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->GetStatusBar()->SetText("", 1);
}
//////////////////////////////////////////////////////////////////////////
// Edit Query Frame
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TEditQueryFrame::TEditQueryFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h, kVerticalFrame)
{
// Create a new Query dialog, used by the Session Viewer, to Edit a Query if
// the editmode flag is set, or to create a new one if not set.
}
//______________________________________________________________________________
TEditQueryFrame::~TEditQueryFrame()
{
// Delete query dialog.
Cleanup();
}
//______________________________________________________________________________
void TEditQueryFrame::Build(TSessionViewer *gui)
{
// Build the "new query" dialog.
TGButton *btnTmp;
fViewer = gui;
SetCleanup(kDeepCleanup);
SetLayoutManager(new TGTableLayout(this, 6, 5));
// add "Query Name" label and text entry
AddFrame(new TGLabel(this, "Query Name :"),
new TGTableLayoutHints(0, 1, 0, 1, kLHintsCenterY, 5, 5, 4, 0));
AddFrame(fTxtQueryName = new TGTextEntry(this,
(const char *)0, 1), new TGTableLayoutHints(1, 2, 0, 1,
kLHintsCenterY, 5, 5, 4, 0));
// add "TChain" label and text entry
AddFrame(new TGLabel(this, "TChain :"),
new TGTableLayoutHints(0, 1, 1, 2, kLHintsCenterY, 5, 5, 4, 0));
AddFrame(fTxtChain = new TGTextEntry(this,
(const char *)0, 2), new TGTableLayoutHints(1, 2, 1, 2,
kLHintsCenterY, 5, 5, 4, 0));
fTxtChain->SetToolTipText("Specify TChain or TDSet from memory or file");
fTxtChain->SetEnabled(kFALSE);
// add "Browse" button
AddFrame(btnTmp = new TGTextButton(this, "Browse..."),
new TGTableLayoutHints(2, 3, 1, 2, kLHintsCenterY, 5, 0, 4, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseChain()");
// add "Selector" label and text entry
AddFrame(new TGLabel(this, "Selector :"),
new TGTableLayoutHints(0, 1, 2, 3, kLHintsCenterY, 5, 5, 0, 0));
AddFrame(fTxtSelector = new TGTextEntry(this,
(const char *)0, 3), new TGTableLayoutHints(1, 2, 2, 3,
kLHintsCenterY, 5, 5, 0, 0));
// add "Browse" button
AddFrame(btnTmp = new TGTextButton(this, "Browse..."),
new TGTableLayoutHints(2, 3, 2, 3, kLHintsCenterY, 5, 0, 0, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseSelector()");
// add "Less <<" ("More >>") button
AddFrame(fBtnMore = new TGTextButton(this, " Less << "),
new TGTableLayoutHints(2, 3, 4, 5, kLHintsCenterY, 5, 5, 4, 0));
fBtnMore->Connect("Clicked()", "TEditQueryFrame", this, "OnNewQueryMore()");
// add (initially hidden) options frame
fFrmMore = new TGCompositeFrame(this, 200, 200);
fFrmMore->SetCleanup(kDeepCleanup);
AddFrame(fFrmMore, new TGTableLayoutHints(0, 3, 5, 6,
kLHintsExpandX | kLHintsExpandY));
fFrmMore->SetLayoutManager(new TGTableLayout(fFrmMore, 4, 3));
// add "Options" label and text entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Options :"),
new TGTableLayoutHints(0, 1, 0, 1, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fTxtOptions = new TGTextEntry(fFrmMore,
(const char *)0, 4), new TGTableLayoutHints(1, 2, 0, 1, 0, 17,
0, 0, 8));
fTxtOptions->SetText("ASYN");
// add "Nb Entries" label and number entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Nb Entries :"),
new TGTableLayoutHints(0, 1, 1, 2, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fNumEntries = new TGNumberEntry(fFrmMore, 0, 5, -1,
TGNumberFormat::kNESInteger, TGNumberFormat::kNEAAnyNumber,
TGNumberFormat::kNELNoLimits), new TGTableLayoutHints(1, 2, 1, 2,
0, 17, 0, 0, 8));
fNumEntries->SetIntNumber(-1);
// add "First Entry" label and number entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "First entry :"),
new TGTableLayoutHints(0, 1, 2, 3, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fNumFirstEntry = new TGNumberEntry(fFrmMore, 0, 5, -1,
TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits), new TGTableLayoutHints(1, 2, 2, 3, 0,
17, 0, 0, 8));
// add "Event list" label and text entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Event list :"),
new TGTableLayoutHints(0, 1, 3, 4, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fTxtEventList = new TGTextEntry(fFrmMore,
(const char *)0, 6), new TGTableLayoutHints(1, 2, 3, 4, 0, 17,
5, 0, 0));
// add "Browse" button
fFrmMore->AddFrame(btnTmp = new TGTextButton(fFrmMore, "Browse..."),
new TGTableLayoutHints(2, 3, 3, 4, 0, 6, 0, 0, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseEventList()");
fTxtQueryName->Associate(this);
fTxtChain->Associate(this);
fTxtSelector->Associate(this);
fTxtOptions->Associate(this);
fNumEntries->Associate(this);
fNumFirstEntry->Associate(this);
fTxtEventList->Associate(this);
fTxtQueryName->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtChain->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtSelector->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtOptions->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fNumEntries->Connect("ValueChanged(Long_t)", "TEditQueryFrame", this,
"SettingsChanged()");
fNumFirstEntry->Connect("ValueChanged(Long_t)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtEventList->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
}
//______________________________________________________________________________
void TEditQueryFrame::OnNewQueryMore()
{
// Show/hide options frame and update button text accordingly.
if (IsVisible(fFrmMore)) {
HideFrame(fFrmMore);
fBtnMore->SetText(" More >> ");
}
else {
ShowFrame(fFrmMore);
fBtnMore->SetText(" Less << ");
}
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseChain()
{
// Call new chain dialog.
TNewChainDlg *dlg = new TNewChainDlg(fClient->GetRoot(), this);
dlg->Connect("OnElementSelected(TObject *)", "TEditQueryFrame",
this, "OnElementSelected(TObject *)");
}
//____________________________________________________________________________
void TEditQueryFrame::OnElementSelected(TObject *obj)
{
// Handle OnElementSelected signal coming from new chain dialog.
if (obj) {
fChain = obj;
if (obj->IsA() == TChain::Class())
fTxtChain->SetText(((TChain *)fChain)->GetName());
else if (obj->IsA() == TDSet::Class())
fTxtChain->SetText(((TDSet *)fChain)->GetObjName());
}
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseSelector()
{
// Open file browser to choose selector macro.
TGFileInfo fi;
fi.fFileTypes = macrotypes;
new TGFileDialog(fClient->GetRoot(), this, kFDOpen, &fi);
if (!fi.fFilename) return;
fTxtSelector->SetText(gSystem->UnixPathName(fi.fFilename));
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseEventList()
{
//Browse event list
}
//______________________________________________________________________________
void TEditQueryFrame::OnBtnSave()
{
// Save current settings in main session viewer.
// if we are in edition mode and query description is valid,
// use it, otherwise create a new one
TQueryDescription *newquery;
if (fQuery)
newquery = fQuery;
else
newquery = new TQueryDescription();
// update query description fields
newquery->fSelectorString = fTxtSelector->GetText();
if (fChain) {
newquery->fTDSetString = fChain->GetName();
newquery->fChain = fChain;
}
else {
newquery->fTDSetString = "";
newquery->fChain = 0;
}
newquery->fQueryName = fTxtQueryName->GetText();
newquery->fOptions = fTxtOptions->GetText();
newquery->fNoEntries = fNumEntries->GetIntNumber();
newquery->fFirstEntry = fNumFirstEntry->GetIntNumber();
newquery->fNbFiles = 0;
newquery->fResult = 0;
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class())
newquery->fNbFiles = ((TChain *)newquery->fChain)->GetListOfFiles()->GetEntriesFast();
else if (newquery->fChain->IsA() == TDSet::Class())
newquery->fNbFiles = ((TDSet *)newquery->fChain)->GetListOfElements()->GetSize();
}
// update user data with modified query description
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
fViewer->GetSessionHierarchy()->RenameItem(item, newquery->fQueryName);
item->SetUserData(newquery);
// update list tree
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fTxtQueryName->SelectAll();
fTxtQueryName->SetFocus();
fViewer->WriteConfiguration();
fViewer->GetQueryFrame()->Modified(kFALSE);
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fConnected &&
fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
fViewer->GetQueryFrame()->GetTab()->SetTab("Status");
fViewer->GetQueryFrame()->OnBtnSubmit();
}
}
//______________________________________________________________________________
void TEditQueryFrame::SettingsChanged()
{
// Settings have changed, update GUI accordingly.
if (fQuery) {
if ((strcmp(fQuery->fSelectorString.Data(), fTxtSelector->GetText())) ||
(strcmp(fQuery->fQueryName.Data(), fTxtQueryName->GetText())) ||
(strcmp(fQuery->fOptions.Data(), fTxtOptions->GetText())) ||
(fQuery->fNoEntries != fNumEntries->GetIntNumber()) ||
(fQuery->fFirstEntry != fNumFirstEntry->GetIntNumber()) ||
(fQuery->fChain != fChain)) {
fViewer->GetQueryFrame()->Modified(kTRUE);
}
else {
fViewer->GetQueryFrame()->Modified(kFALSE);
}
}
else {
if ((fTxtQueryName->GetText()) &&
((fTxtQueryName->GetText()) ||
(fTxtChain->GetText())))
fViewer->GetQueryFrame()->Modified(kTRUE);
else
fViewer->GetQueryFrame()->Modified(kFALSE);
}
}
//______________________________________________________________________________
void TEditQueryFrame::UpdateFields(TQueryDescription *desc)
{
// Update entry fields with query description values.
fChain = 0;
fQuery = desc;
fTxtChain->SetText("");
if (desc->fChain) {
fChain = desc->fChain;
fTxtChain->SetText(desc->fTDSetString);
}
fTxtQueryName->SetText(desc->fQueryName);
fTxtSelector->SetText(desc->fSelectorString);
fTxtOptions->SetText(desc->fOptions);
fNumEntries->SetIntNumber(desc->fNoEntries);
fNumFirstEntry->SetIntNumber(desc->fFirstEntry);
fTxtEventList->SetText(desc->fEventList);
}
////////////////////////////////////////////////////////////////////////////////
// Query Frame
//______________________________________________________________________________
TSessionQueryFrame::TSessionQueryFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h)
{
// Constructor
}
//______________________________________________________________________________
TSessionQueryFrame::~TSessionQueryFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionQueryFrame::Build(TSessionViewer *gui)
{
// Build query informations frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fFirst = fEntries = fPrevTotal = 0;
fPrevProcessed = 0;
fViewer = gui;
fModified = kFALSE;
// main query tab
fTab = new TGTab(this, 200, 200);
AddFrame(fTab, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 2, 2, 2));
// add "Status" tab element
TGCompositeFrame *tf = fTab->AddTab("Status");
fFB = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFB, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing control buttons and feedback histos canvas
TGCompositeFrame* frmcanvas = new TGHorizontalFrame(fFB, 350, 100);
// control buttons frame
TGCompositeFrame* frmBut2 = new TGVerticalFrame(frmcanvas, 150, 100);
fBtnSubmit = new TGTextButton(frmBut2, " Submit ");
fBtnSubmit->SetToolTipText("Submit (process) selected query");
frmBut2->AddFrame(fBtnSubmit,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnStop = new TGTextButton(frmBut2, "Stop");
fBtnStop->SetToolTipText("Stop processing query");
frmBut2->AddFrame(fBtnStop,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnAbort = new TGTextButton(frmBut2, "Abort");
fBtnAbort->SetToolTipText("Abort processing query");
frmBut2->AddFrame(fBtnAbort,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
frmcanvas->AddFrame(frmBut2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY));
// feedback histos embedded canvas
fECanvas = new TRootEmbeddedCanvas("fECanvas", frmcanvas, 400, 150);
fStatsCanvas = fECanvas->GetCanvas();
fStatsCanvas->SetFillColor(10);
fStatsCanvas->SetBorderMode(0);
frmcanvas->AddFrame(fECanvas, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
fFB->AddFrame(frmcanvas, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
// progress infos label
fLabInfos = new TGLabel(fFB, " ");
fFB->AddFrame(fLabInfos, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// progress status label
fLabStatus = new TGLabel(fFB, " ");
fFB->AddFrame(fLabStatus, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
//progress bar
frmProg = new TGHProgressBar(fFB, TGProgressBar::kFancy, 350 - 20);
frmProg->ShowPosition();
frmProg->SetBarColor("green");
fFB->AddFrame(frmProg, new TGLayoutHints(kLHintsExpandX, 5, 5, 5, 5));
// total progress infos
fFB->AddFrame(fTotal = new TGLabel(fFB,
" Estimated time left : 00:00:00 (--- events of --- processed) "),
new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// progress rate infos
fFB->AddFrame(fRate = new TGLabel(fFB,
" Processing Rate : -- events/sec "),
new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// add "Results" tab element
tf = fTab->AddTab("Results");
fFC = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFC, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// query result (header) information text view
fInfoTextView = new TGTextView(fFC, 330, 185, "", kSunkenFrame |
kDoubleBorder);
fFC->AddFrame(fInfoTextView, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandY | kLHintsExpandX, 5, 5, 10, 10));
// add "Retrieve", "Finalize" and "Show Log" buttons
TGCompositeFrame* frmBut3 = new TGHorizontalFrame(fFC, 350, 100);
fBtnRetrieve = new TGTextButton(frmBut3, "Retrieve");
fBtnRetrieve->SetToolTipText("Retrieve query results");
frmBut3->AddFrame(fBtnRetrieve,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fBtnFinalize = new TGTextButton(frmBut3, "Finalize");
fBtnFinalize->SetToolTipText("Finalize query");
frmBut3->AddFrame(fBtnFinalize,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fBtnShowLog = new TGTextButton(frmBut3, "Show Log");
fBtnShowLog->SetToolTipText("Show query log (open log window)");
frmBut3->AddFrame(fBtnShowLog,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fFC->AddFrame(frmBut3, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandX));
// add "Results" tab element
tf = fTab->AddTab("Edit Query");
fFD = new TEditQueryFrame(tf, 100, 100);
fFD->Build(fViewer);
tf->AddFrame(fFD, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 10, 0));
TString btntxt;
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
btntxt = " Submit ";
}
else {
btntxt = " Apply changes ";
}
tf->AddFrame(fBtnSave = new TGTextButton(tf, btntxt),
new TGLayoutHints(kLHintsTop | kLHintsLeft, 10, 5, 25, 5));
// connect button actions to functions
fBtnSave->Connect("Clicked()", "TEditQueryFrame", fFD,
"OnBtnSave()");
fBtnSubmit->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnSubmit()");
fBtnFinalize->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnFinalize()");
fBtnStop->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnStop()");
fBtnAbort->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnAbort()");
fBtnShowLog->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnShowLog()");
fBtnRetrieve->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnRetrieve()");
// fBtnSave->SetState(kButtonDisabled);
Resize(350, 310);
}
//______________________________________________________________________________
void TSessionQueryFrame::Modified(Bool_t mod)
{
// Notify changes in query editor settings.
fModified = mod;
if (fModified) {
fBtnSave->SetState(kButtonUp);
}
else {
fBtnSave->SetState(kButtonDisabled);
}
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()))
fBtnSave->SetState(kButtonUp);
}
//______________________________________________________________________________
void TSessionQueryFrame::Feedback(TList *objs)
{
// Feedback function connected to Feedback signal.
// Used to update feedback histograms.
// if no actual session, just return
if (!fViewer->GetActDesc()->fAttached)
return;
if (!fViewer->GetActDesc()->fProof)
return;
if ((fViewer->GetActDesc()->fActQuery) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQuerySubmitted) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQueryRunning) )
return;
TProof *sender = dynamic_cast<TProof*>((TQObject*)gTQSender);
// if Proof sender match actual session one, update feedback histos
if (sender && (sender == fViewer->GetActDesc()->fProof))
UpdateHistos(objs);
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateHistos(TList *objs)
{
// Update feedback histograms.
TVirtualPad *save = gPad;
TObject *o;
Int_t pos = 1;
Int_t i = 0;
while (kFeedbackHistos[i]) {
// check if user has selected this histogram in the option menu
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
if ( (o = objs->FindObject(kFeedbackHistos[i]))) {
fStatsCanvas->cd(pos);
gPad->SetEditable(kTRUE);
if (TH1 *h = dynamic_cast<TH1*>(o)) {
h->SetStats(0);
h->SetBarWidth(0.75);
h->SetBarOffset(0.125);
h->SetFillColor(9);
h->Draw("bar");
pos++;
}
else if (TH2 *h2 = dynamic_cast<TH2*>(o)) {
h2->Draw();
pos++;
}
gPad->Modified();
}
}
i++;
}
// update canvas
fStatsCanvas->cd();
fStatsCanvas->Modified();
fStatsCanvas->Update();
if (save != 0) {
save->cd();
} else {
gPad = 0;
}
}
//______________________________________________________________________________
void TSessionQueryFrame::Progress(Long64_t total, Long64_t processed)
{
// Update progress bar and status labels.
// if no actual session, just return
if (!fViewer->GetActDesc()->fProof)
return;
// if Proof sender does't match actual session one, return
TProof *sender = dynamic_cast<TProof*>((TQObject*)gTQSender);
if (!sender || (sender != fViewer->GetActDesc()->fProof))
return;
if ((fViewer->GetActDesc()->fActQuery) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQuerySubmitted) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQueryRunning) ) {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
return;
}
if (total < 0)
total = fPrevTotal;
else
fPrevTotal = total;
// if no change since last call, just return
if (fPrevProcessed == processed)
return;
char *buf;
// Update informations at first call
if (fEntries != total) {
buf = Form("PROOF cluster : \"%s\" - %d worker nodes",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
fLabInfos->SetText(buf);
fEntries = total;
buf = Form(" %d files, %lld events, starting event %lld",
fFiles, fEntries, fFirst);
fLabStatus->SetText(buf);
}
// compute progress bar position and update
Float_t pos = (Float_t)((Double_t)(processed * 100)/(Double_t)total);
frmProg->SetPosition(pos);
// if 100%, stop animation and set icon to "connected"
if (pos >= 100.0) {
fViewer->SetChangePic(kFALSE);
fViewer->ChangeRightLogo("monitor01.xpm");
}
// get current time
if ((fViewer->GetActDesc()->fActQuery->fStatus ==
TQueryDescription::kSessionQueryRunning) ||
(fViewer->GetActDesc()->fActQuery->fStatus ==
TQueryDescription::kSessionQuerySubmitted))
fViewer->GetActDesc()->fActQuery->fEndTime = gSystem->Now();
TTime tdiff = fViewer->GetActDesc()->fActQuery->fEndTime -
fViewer->GetActDesc()->fActQuery->fStartTime;
Float_t eta = 0;
if (processed)
eta = ((Float_t)((Long_t)tdiff)*total/Float_t(processed) -
Long_t(tdiff))/1000.;
if (processed == total) {
// finished
buf = Form(" Processed : %lld events in %.1f sec", total, Long_t(tdiff)/1000.);
fTotal->SetText(buf);
} else {
// update status infos
buf = Form(" Estimated time left : %.1f sec (%lld events of %lld processed) ",
eta, processed, total);
fTotal->SetText(buf);
}
if (processed > 0 && (Long_t)tdiff > 0) {
buf = Form(" Processing Rate : %.1f events/sec ",
(Float_t)processed/(Long_t)tdiff*1000.);
fRate->SetText(buf);
}
fPrevProcessed = processed;
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::Progress(Long64_t total, Long64_t processed,
Long64_t /*bytesread*/ , Float_t /*initTime*/,
Float_t /*procTime*/, Float_t /*evtrti*/,
Float_t /*mbrti*/)
{
// New version of Progress (just forward to the old version
// for the time being).
Progress(total, processed);
}
//______________________________________________________________________________
void TSessionQueryFrame::ProgressLocal(Long64_t total, Long64_t processed)
{
// Update progress bar and status labels.
char cproc[80];
Int_t status;
switch (fViewer->GetActDesc()->fActQuery->fStatus) {
case TQueryDescription::kSessionQueryAborted:
strcpy(cproc, " - ABORTED");
status = kAborted;
break;
case TQueryDescription::kSessionQueryStopped:
strcpy(cproc, " - STOPPED");
status = kStopped;
break;
case TQueryDescription::kSessionQueryRunning:
strcpy(cproc, " ");
status = kRunning;
break;
case TQueryDescription::kSessionQueryCompleted:
case TQueryDescription::kSessionQueryFinalized:
strcpy(cproc, " ");
status = kDone;
break;
default:
status = -1;
break;
}
if (processed < 0) processed = 0;
frmProg->SetBarColor("green");
if (status == kAborted)
frmProg->SetBarColor("red");
else if (status == kStopped)
frmProg->SetBarColor("yellow");
else if (status == -1 ) {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
return;
}
if (total < 0)
total = fPrevTotal;
else
fPrevTotal = total;
// if no change since last call, just return
char *buf;
// Update informations at first call
if (fEntries != total) {
fLabInfos->SetText("Local Session");
fEntries = total;
buf = Form(" %d files, %lld events, starting event %lld",
fFiles, fEntries, fFirst);
fLabStatus->SetText(buf);
}
// compute progress bar position and update
Float_t pos = 0.0;
if (processed > 0 && total > 0)
pos = (Float_t)((Double_t)(processed * 100)/(Double_t)total);
frmProg->SetPosition(pos);
// if 100%, stop animation and set icon to "connected"
if (pos >= 100.0) {
fViewer->SetChangePic(kFALSE);
fViewer->ChangeRightLogo("monitor01.xpm");
}
// get current time
if (status == kRunning)
fViewer->GetActDesc()->fActQuery->fEndTime = gSystem->Now();
TTime tdiff = fViewer->GetActDesc()->fActQuery->fEndTime -
fViewer->GetActDesc()->fActQuery->fStartTime;
Float_t eta = 0;
if (processed)
eta = ((Float_t)((Long_t)tdiff)*total/(Float_t)(processed) -
(Long_t)(tdiff))/1000.;
if ((processed != total) && (status == kRunning)) {
// update status infos
buf = Form(" Estimated time left : %.1f sec (%lld events of %lld processed) ",
eta, processed, total);
fTotal->SetText(buf);
} else {
buf = Form(" Processed : %ld events in %.1f sec", (Long_t)processed,
(Long_t)tdiff/1000.0);
strcat(buf, cproc);
fTotal->SetText(buf);
}
if (processed > 0 && (Long_t)tdiff > 0) {
buf = Form(" Processing Rate : %.1f events/sec ",
(Float_t)processed/(Long_t)tdiff*1000.);
fRate->SetText(buf);
}
fPrevProcessed = processed;
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::IndicateStop(Bool_t aborted)
{
// Indicate that Cancel or Stop was clicked.
if (aborted == kTRUE) {
// Aborted
frmProg->SetBarColor("red");
}
else {
// Stopped
frmProg->SetBarColor("yellow");
}
// disconnect progress related signals
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Disconnect("Progress(Long64_t,Long64_t)",
this, "Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Disconnect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
this, "Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Disconnect("StopProcess(Bool_t)", this,
"IndicateStop(Bool_t)");
}
}
//______________________________________________________________________________
void TSessionQueryFrame::ResetProgressDialog(const char * /*selector*/, Int_t files,
Long64_t first, Long64_t entries)
{
// Reset progress frame information fields.
char *buf;
fFiles = files > 0 ? files : 0;
fFirst = first;
fEntries = entries;
fPrevProcessed = 0;
fPrevTotal = 0;
if (!fViewer->GetActDesc()->fLocal) {
frmProg->SetBarColor("green");
frmProg->Reset();
}
buf = Form("%0d files, %0lld events, starting event %0lld",
fFiles > 0 ? fFiles : 0, fEntries > 0 ? fEntries : 0,
fFirst >= 0 ? fFirst : 0);
fLabStatus->SetText(buf);
// Reconnect the slots
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", this, "Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", this,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", this, "IndicateStop(Bool_t)");
sprintf(buf, "PROOF cluster : \"%s\" - %d worker nodes",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
fLabInfos->SetText(buf);
}
else if (fViewer->GetActDesc()->fLocal) {
fStatsCanvas->Clear();
fLabInfos->SetText("Local Session");
fLabStatus->SetText(" ");
}
else {
fLabInfos->SetText(" ");
fLabStatus->SetText(" ");
}
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnFinalize()
{
// Finalize query.
// check if Proof is valid
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
gPad->SetEditable(kFALSE);
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
// as it can take time, set watch cursor
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
TQueryDescription *query = (TQueryDescription *)obj;
fViewer->GetActDesc()->fProof->Finalize(query->fReference);
UpdateButtons(query);
// restore cursor
gVirtualX->SetCursor(GetId(), 0);
}
}
if (fViewer->GetActDesc()->fLocal) {
gPad->SetEditable(kFALSE);
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain)
((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile()->Terminate();
}
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnStop()
{
// Stop processing query.
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->StopProcess(kFALSE);
}
if (fViewer->GetActDesc()->fLocal) {
gROOT->SetInterrupt();
fViewer->GetActDesc()->fActQuery->fStatus =
TQueryDescription::kSessionQueryStopped;
}
// stop icon animation and set connected icon
fViewer->ChangeRightLogo("monitor01.xpm");
fViewer->SetChangePic(kFALSE);
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnShowLog()
{
// Show query log.
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *query = (TQueryDescription *)obj;
fViewer->ShowLog(query->fReference.Data());
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnRetrieve()
{
// Retrieve query.
// check for proof validity
if (fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
// as it can take time, set watch cursor
gVirtualX->SetCursor(GetId(), gVirtualX->CreateCursor(kWatch));
TQueryDescription *query = (TQueryDescription *)obj;
Int_t rc = fViewer->GetActDesc()->fProof->Retrieve(query->fReference);
if (rc == 0)
fViewer->OnCascadeMenu();
// restore cursor
gVirtualX->SetCursor(GetId(), 0);
}
}
if (fViewer->GetActDesc()->fLocal) {
TGListTreeItem *item=0, *item2=0;
item = fViewer->GetSessionHierarchy()->FindItemByObj(fViewer->GetSessionItem(),
fViewer->GetActDesc());
if (item) {
item2 = fViewer->GetSessionHierarchy()->FindItemByObj(item,
fViewer->GetActDesc()->fActQuery);
}
if (item2) {
// add input and output list entries
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain) {
TSelector *selector = ((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile();
if (selector) {
TList *objlist = selector->GetOutputList();
if (objlist)
if (!fViewer->GetSessionHierarchy()->FindChildByName(item2, "OutputList"))
fViewer->GetSessionHierarchy()->AddItem(item2, "OutputList");
}
}
}
// update list tree, query frame informations, and buttons state
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
UpdateInfos();
UpdateButtons(fViewer->GetActDesc()->fActQuery);
}
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnAbort()
{
// Abort processing query.
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->StopProcess(kTRUE);
}
if (fViewer->GetActDesc()->fLocal) {
gROOT->SetInterrupt();
fViewer->GetActDesc()->fActQuery->fStatus =
TQueryDescription::kSessionQueryAborted;
}
// stop icon animation and set connected icon
fViewer->ChangeRightLogo("monitor01.xpm");
fViewer->SetChangePic(kFALSE);
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnSubmit()
{
// Submit query.
Int_t retval;
Long64_t id = 0;
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
// retrieve query description attached to list tree item
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *newquery = (TQueryDescription *)obj;
// reset progress informations
ResetProgressDialog(newquery->fSelectorString,
newquery->fNbFiles, newquery->fFirstEntry, newquery->fNoEntries);
// set query start time
newquery->fStartTime = gSystem->Now();
fViewer->GetActDesc()->fNbHistos = 0;
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->SetBit(TProof::kUsingSessionGui);
// set query description status to submitted
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
// if feedback option selected
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fProof->AddFeedback(kFeedbackHistos[i]);
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
// connect feedback signal
fViewer->GetActDesc()->fProof->Connect("Feedback(TList *objs)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Feedback(TList *objs)");
gROOT->Time();
}
else {
// if feedback option not selected, clear Proof's feedback option
fViewer->GetActDesc()->fProof->ClearFeedback();
}
// set current proof session
fViewer->GetActDesc()->fProof->cd();
// check if parameter file has been specified
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class()) {
// TChain case
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
((TChain *)newquery->fChain)->SetProof(fViewer->GetActDesc()->fProof);
id = ((TChain *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries > 0 ? newquery->fNoEntries : 1234567890,
newquery->fFirstEntry);
}
else if (newquery->fChain->IsA() == TDSet::Class()) {
// TDSet case
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
id = ((TDSet *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries,
newquery->fFirstEntry);
}
}
else {
Error("Submit", "No TChain defined; skipping");
newquery->fStatus = TQueryDescription::kSessionQueryCreated;
return;
}
// set query reference id to unique identifier
newquery->fReference= Form("session-%s:q%lld",
fViewer->GetActDesc()->fProof->GetSessionTag(), id);
// start icon animation
fViewer->SetChangePic(kTRUE);
}
else if (fViewer->GetActDesc()->fLocal) { // local session case
// if feedback option selected
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
}
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class()) {
// TChain case
newquery->fStatus = TQueryDescription::kSessionQueryRunning;
fViewer->EnableTimer();
UpdateButtons(newquery);
gPad->SetEditable(kFALSE);
((TChain *)newquery->fChain)->SetTimerInterval(100);
id = ((TChain *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries > 0 ? newquery->fNoEntries : 1234567890,
newquery->fFirstEntry);
((TChain *)newquery->fChain)->SetTimerInterval(0);
OnBtnRetrieve();
TChain *chain = (TChain *)newquery->fChain;
ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
if ((newquery->fStatus != TQueryDescription::kSessionQueryAborted) &&
(newquery->fStatus != TQueryDescription::kSessionQueryStopped))
newquery->fStatus = TQueryDescription::kSessionQueryCompleted;
UpdateButtons(newquery);
}
else {
new TGMsgBox(fClient->GetRoot(), this, "Error Submitting Query",
"Only TChains are allowed in Local Session (no TDSet) !",
kMBIconExclamation,kMBOk,&retval);
}
}
else {
Error("Submit", "No TChain defined; skipping");
newquery->fStatus = TQueryDescription::kSessionQueryCreated;
return;
}
// set query reference id to unique identifier
newquery->fReference = Form("local-session-%s:q%lld", newquery->fQueryName.Data(), id);
}
// update buttons state
UpdateButtons(newquery);
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateButtons(TQueryDescription *desc)
{
// Update buttons state for the current query status.
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
// retrieve query description attached to list tree item
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *query = (TQueryDescription *)obj;
if (desc != query) return;
Bool_t submit_en = kFALSE;
if ((fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) ||
fViewer->GetActDesc()->fLocal)
submit_en = kTRUE;
switch (desc->fStatus) {
case TQueryDescription::kSessionQueryFromProof:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryCompleted:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
if (((desc->fResult == 0) || (desc->fResult &&
(desc->fResult->IsFinalized() ||
(desc->fResult->GetInputObject("TDSet") == 0)))) &&
!(fViewer->GetActDesc()->fLocal))
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryCreated:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQuerySubmitted:
fBtnSubmit->SetEnabled(kFALSE);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kTRUE);
fBtnAbort->SetEnabled(kTRUE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryRunning:
fBtnSubmit->SetEnabled(kFALSE);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kTRUE);
fBtnAbort->SetEnabled(kTRUE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryStopped:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryAborted:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryFinalized:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
default:
break;
}
if (fViewer->GetActDesc()->fLocal &&
!(fViewer->GetActDesc()->fActQuery->fChain)) {
fBtnFinalize->SetEnabled(kFALSE);
fBtnRetrieve->SetEnabled(kFALSE);
}
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateInfos()
{
// Update query information (header) text view.
char *buffer;
const char *qst[] = {"aborted ", "submitted", "running ",
"stopped ", "completed"};
if (fViewer->GetActDesc()->fActQuery)
fFD->UpdateFields(fViewer->GetActDesc()->fActQuery);
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fConnected &&
fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
fBtnSave->SetText(" Submit ");
}
else {
fBtnSave->SetText(" Apply changes ");
}
fClient->NeedRedraw(fBtnSave);
fInfoTextView->Clear();
if (!fViewer->GetActDesc()->fActQuery ||
!fViewer->GetActDesc()->fActQuery->fResult) {
ResetProgressDialog("", 0, 0, 0);
if (fViewer->GetActDesc()->fLocal) {
if (fViewer->GetActDesc()->fActQuery) {
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain) {
ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
}
else {
ProgressLocal(0, 0);
}
UpdateButtons(fViewer->GetActDesc()->fActQuery);
}
}
else {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
}
return;
}
TQueryResult *result = fViewer->GetActDesc()->fActQuery->fResult;
// Status label
Int_t st = (result->GetStatus() > 0 && result->GetStatus() <=
TQueryResult::kCompleted) ? result->GetStatus() : 0;
Int_t qry = result->GetSeqNum();
buffer = Form("------------------------------------------------------\n");
// Print header
if (!result->IsDraw()) {
const char *fin = result->IsFinalized() ? "finalized" : qst[st];
const char *arc = result->IsArchived() ? "(A)" : "";
buffer = Form("%s Query No : %d\n", buffer, qry);
buffer = Form("%s Ref : \"%s:%s\"\n", buffer, result->GetTitle(),
result->GetName());
buffer = Form("%s Selector : %s\n", buffer,
result->GetSelecImp()->GetTitle());
buffer = Form("%s Status : %9s%s\n", buffer, fin, arc);
buffer = Form("%s------------------------------------------------------\n",
buffer);
} else {
buffer = Form("%s Query No : %d\n", buffer, qry);
buffer = Form("%s Ref : \"%s:%s\"\n", buffer, result->GetTitle(),
result->GetName());
buffer = Form("%s Selector : %s\n", buffer,
result->GetSelecImp()->GetTitle());
buffer = Form("%s------------------------------------------------------\n",
buffer);
}
// Time information
Int_t elapsed = (Int_t)(result->GetEndTime().Convert() -
result->GetStartTime().Convert());
buffer = Form("%s Started : %s\n",buffer,
result->GetStartTime().AsString());
buffer = Form("%s Real time : %d sec (CPU time: %.1f sec)\n", buffer, elapsed,
result->GetUsedCPU());
// Number of events processed, rate, size
Double_t rate = 0.0;
if (result->GetEntries() > -1 && elapsed > 0)
rate = result->GetEntries() / (Double_t)elapsed ;
Float_t size = ((Float_t)result->GetBytes())/(1024*1024);
buffer = Form("%s Processed : %lld events (size: %.3f MBs)\n",buffer,
result->GetEntries(), size);
buffer = Form("%s Rate : %.1f evts/sec\n",buffer, rate);
// Package information
if (strlen(result->GetParList()) > 1) {
buffer = Form("%s Packages : %s\n",buffer, result->GetParList());
}
// Result information
TString res = result->GetResultFile();
if (!result->IsArchived()) {
Int_t dq = res.Index("queries");
if (dq > -1) {
res.Remove(0,res.Index("queries"));
res.Insert(0,"<PROOF_SandBox>/");
}
if (res.BeginsWith("-")) {
res = (result->GetStatus() == TQueryResult::kAborted) ?
"not available" : "sent to client";
}
}
if (res.Length() > 1) {
buffer = Form("%s------------------------------------------------------\n",
buffer);
buffer = Form("%s Results : %s\n",buffer, res.Data());
}
if (result->GetOutputList() && result->GetOutputList()->GetSize() > 0) {
buffer = Form("%s Outlist : %d objects\n",buffer,
result->GetOutputList()->GetSize());
buffer = Form("%s------------------------------------------------------\n",
buffer);
}
fInfoTextView->LoadBuffer(buffer);
//Float_t pos = Float_t((Double_t)(result->GetEntries() * 100)/(Double_t)total);
if (result->GetStatus() == TQueryResult::kAborted)
frmProg->SetBarColor("red");
else if (result->GetStatus() == TQueryResult::kStopped)
frmProg->SetBarColor("yellow");
else
frmProg->SetBarColor("green");
frmProg->SetPosition(100.0);
buffer = Form(" Processed : %lld events in %.1f sec", result->GetEntries(),
(Float_t)elapsed);
fTotal->SetText(buffer);
buffer = Form(" Processing Rate : %.1f events/sec ", rate);
fRate->SetText(buffer);
fFB->Layout();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Output frame
//______________________________________________________________________________
TSessionOutputFrame::TSessionOutputFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fLVContainer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionOutputFrame::~TSessionOutputFrame()
{
// Destructor.
delete fLVContainer; // this container is inside the TGListView and is not
// deleted automatically
Cleanup();
}
//______________________________________________________________________________
void TSessionOutputFrame::Build(TSessionViewer *gui)
{
// Build query output information frame.
fViewer = gui;
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
// Container of object TGListView
TGListView *frmListView = new TGListView(this, 340, 190);
fLVContainer = new TGLVContainer(frmListView, kSunkenFrame, GetWhitePixel());
fLVContainer->Associate(frmListView);
fLVContainer->SetCleanup(kDeepCleanup);
AddFrame(frmListView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
frmListView->Connect("Clicked(TGLVEntry*, Int_t, Int_t, Int_t)",
"TSessionOutputFrame", this,
"OnElementClicked(TGLVEntry* ,Int_t, Int_t, Int_t)");
frmListView->Connect("DoubleClicked(TGLVEntry*, Int_t, Int_t, Int_t)",
"TSessionOutputFrame", this,
"OnElementDblClicked(TGLVEntry* ,Int_t, Int_t, Int_t)");
}
//______________________________________________________________________________
void TSessionOutputFrame::OnElementClicked(TGLVEntry* entry, Int_t btn, Int_t x,
Int_t y)
{
// Handle mouse clicks on list view items.
TObject *obj = (TObject *)entry->GetUserData();
if ((obj) && (btn ==3)) {
// if right button, popup context menu
fViewer->GetContextMenu()->Popup(x, y, obj, (TBrowser *)0);
}
}
//______________________________________________________________________________
void TSessionOutputFrame::OnElementDblClicked(TGLVEntry* entry, Int_t , Int_t, Int_t)
{
// Handle double-clicks on list view items.
char action[512];
TString act;
TObject *obj = (TObject *)entry->GetUserData();
TString ext = obj->GetName();
gPad->SetEditable(kFALSE);
// check default action from root.mimes
if (fClient->GetMimeTypeList()->GetAction(obj->IsA()->GetName(), action)) {
act = Form("((%s*)0x%lx)%s", obj->IsA()->GetName(), (Long_t)obj, action);
if (act[0] == '!') {
act.Remove(0, 1);
gSystem->Exec(act.Data());
} else {
// do not allow browse
if (!act.Contains("Browse"))
gROOT->ProcessLine(act.Data());
}
}
}
//______________________________________________________________________________
void TSessionOutputFrame::AddObject(TObject *obj)
{
// Add object to output list view.
TGLVEntry *item;
if (obj) {
item = new TGLVEntry(fLVContainer, obj->GetName(), obj->IsA()->GetName());
item->SetUserData(obj);
fLVContainer->AddItem(item);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Input Frame
//______________________________________________________________________________
TSessionInputFrame::TSessionInputFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fLVContainer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionInputFrame::~TSessionInputFrame()
{
// Destructor.
delete fLVContainer; // this container is inside the TGListView and is not
// deleted automatically
Cleanup();
}
//______________________________________________________________________________
void TSessionInputFrame::Build(TSessionViewer *gui)
{
// Build query input informations frame.
fViewer = gui;
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
// Container of object TGListView
TGListView *frmListView = new TGListView(this, 340, 190);
fLVContainer = new TGLVContainer(frmListView, kSunkenFrame, GetWhitePixel());
fLVContainer->Associate(frmListView);
fLVContainer->SetCleanup(kDeepCleanup);
AddFrame(frmListView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
}
//______________________________________________________________________________
void TSessionInputFrame::AddObject(TObject *obj)
{
// Add object to input list view.
TGLVEntry *item;
if (obj) {
item = new TGLVEntry(fLVContainer, obj->GetName(), obj->IsA()->GetName());
item->SetUserData(obj);
fLVContainer->AddItem(item);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Session Viewer Main Frame
//______________________________________________________________________________
TSessionViewer::TSessionViewer(const char *name, UInt_t w, UInt_t h) :
TGMainFrame(0, w, h), fSessionHierarchy(0), fSessionItem(0)
{
// Main Session viewer constructor.
// only one session viewer allowed
if (gSessionViewer)
return;
Build();
SetWindowName(name);
Resize(w, h);
gSessionViewer = this;
}
//______________________________________________________________________________
TSessionViewer::TSessionViewer(const char *name, Int_t x, Int_t y, UInt_t w,
UInt_t h) : TGMainFrame(0, w, h),
fSessionHierarchy(0), fSessionItem(0)
{
// Main Session viewer constructor.
// only one session viewer allowed
if (gSessionViewer)
return;
Build();
SetWindowName(name);
Move(x, y);
Resize(w, h);
gSessionViewer = this;
}
//______________________________________________________________________________
void TSessionViewer::ReadConfiguration(const char *filename)
{
// Read configuration file and populate list of sessions
// list of queries and list of packages.
// Read and set also global options as feedback histos.
if (fViewerEnv)
delete fViewerEnv;
fViewerEnv = new TEnv();
const char *fn = (filename && strlen(filename)) ? filename : fConfigFile.Data();
fViewerEnv->ReadFile(fn, kEnvUser);
Bool_t bval = (Bool_t)fViewerEnv->GetValue("Option.Feedback", 1);
if (bval)
fOptionsMenu->CheckEntry(kOptionsFeedback);
else
fOptionsMenu->UnCheckEntry(kOptionsFeedback);
bval = (Bool_t)fViewerEnv->GetValue("Option.MasterHistos", 1);
if (bval) {
fOptionsMenu->CheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 1);
}
else {
fOptionsMenu->UnCheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 0);
}
bval = (Bool_t)fViewerEnv->GetValue("Option.MasterEvents", 0);
if (bval)
fOptionsMenu->CheckEntry(kOptionsStatsTrace);
else
fOptionsMenu->UnCheckEntry(kOptionsStatsTrace);
bval = (Bool_t)fViewerEnv->GetValue("Option.WorkerEvents", 0);
if (bval)
fOptionsMenu->CheckEntry(kOptionsSlaveStatsTrace);
else
fOptionsMenu->UnCheckEntry(kOptionsSlaveStatsTrace);
Int_t i = 0;
while (kFeedbackHistos[i]) {
bval = (Bool_t)fViewerEnv->GetValue(Form("Option.%s",kFeedbackHistos[i]),
i == 1 ? 1 : 0);
if (bval)
fCascadeMenu->CheckEntry(41+i);
else
fCascadeMenu->UnCheckEntry(41+i);
i++;
}
TSessionDescription *proofDesc;
fSessions->Delete();
if (fSessionItem)
fSessionHierarchy->DeleteChildren(fSessionItem);
else
fSessionItem = fSessionHierarchy->AddItem(0, "Sessions", fBaseIcon,
fBaseIcon);
// add local session description
TGListTreeItem *item = fSessionHierarchy->AddItem(fSessionItem, "Local",
fLocal, fLocal);
fSessionHierarchy->SetToolTipItem(item, "Local Session");
TSessionDescription *localdesc = new TSessionDescription();
localdesc->fTag = "";
localdesc->fName = "Local";
localdesc->fAddress = "Local";
localdesc->fPort = 0;
localdesc->fConfigFile = "";
localdesc->fLogLevel = 0;
localdesc->fUserName = "";
localdesc->fQueries = new TList();
localdesc->fPackages = new TList();
localdesc->fActQuery = 0;
localdesc->fProof = 0;
localdesc->fProofMgr = 0;
localdesc->fLocal = kTRUE;
localdesc->fSync = kTRUE;
localdesc->fAutoEnable = kFALSE;
localdesc->fNbHistos = 0;
item->SetUserData(localdesc);
fSessions->Add((TObject *)localdesc);
fActDesc = localdesc;
TIter next(fViewerEnv->GetTable());
TEnvRec *er;
while ((er = (TEnvRec*) next())) {
const char *s;
if ((s = strstr(er->GetName(), "SessionDescription."))) {
const char *val = fViewerEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
char *v = StrDup(val);
s += 7;
while (1) {
TString name = strtok(!cnt ? v : 0, ";");
if (name.IsNull()) break;
TString sessiontag = strtok(0, ";");
TString address = strtok(0, ";");
if (address.IsNull()) break;
TString port = strtok(0, ";");
if (port.IsNull()) break;
TString loglevel = strtok(0, ";");
if (loglevel.IsNull()) break;
TString configfile = strtok(0, ";");
TString user = strtok(0, ";");
if (user.IsNull()) break;
TString sync = strtok(0, ";");
TString autoen = strtok(0, ";");
// build session description
proofDesc = new TSessionDescription();
proofDesc->fTag = sessiontag.Length() > 2 ? sessiontag.Data() : "";
proofDesc->fName = name;
proofDesc->fAddress = address;
proofDesc->fPort = atoi(port);
proofDesc->fConfigFile = configfile.Length() > 2 ? configfile.Data() : "";
proofDesc->fLogLevel = atoi(loglevel);
proofDesc->fConnected = kFALSE;
proofDesc->fAttached = kFALSE;
proofDesc->fLocal = kFALSE;
proofDesc->fQueries = new TList();
proofDesc->fPackages = new TList();
proofDesc->fActQuery = 0;
proofDesc->fProof = 0;
proofDesc->fProofMgr = 0;
proofDesc->fSync = (Bool_t)(atoi(sync));
proofDesc->fAutoEnable = (Bool_t)(atoi(autoen));
proofDesc->fUserName = user;
fSessions->Add((TObject *)proofDesc);
item = fSessionHierarchy->AddItem(
fSessionItem, proofDesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item->SetUserData(proofDesc);
fActDesc = proofDesc;
cnt++;
}
delete [] v;
}
}
if ((s = strstr(er->GetName(), "QueryDescription."))) {
const char *val = fViewerEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
char *v = StrDup(val);
s += 7;
while (1) {
TString status = strtok(!cnt ? v : 0, ";");
if (status.IsNull()) break;
TString reference = strtok(0, ";");
if (reference.IsNull()) break;
TString queryname = strtok(0, ";");
if (queryname.IsNull()) break;
TString selector = strtok(0, ";");
if (selector.IsNull()) break;
TString dset = strtok(0, ";");
TString options = strtok(0, ";");
TString eventlist = strtok(0, ";");
TString nbfiles = strtok(0, ";");
TString nbentries = strtok(0, ";");
TString firstentry = strtok(0, ";");
TQueryDescription *newquery = new TQueryDescription();
newquery->fStatus =
(TQueryDescription::ESessionQueryStatus)(atoi(status));
newquery->fSelectorString = selector.Length() > 2 ? selector.Data() : "";
newquery->fReference = reference.Length() > 2 ? reference.Data() : "";
newquery->fTDSetString = dset.Length() > 2 ? dset.Data() : "";
newquery->fQueryName = queryname.Length() > 2 ? queryname.Data() : "";
newquery->fOptions = options.Length() > 2 ? options.Data() : "";
newquery->fEventList = eventlist.Length() > 2 ? eventlist.Data() : "";
newquery->fNbFiles = atoi(nbfiles);
newquery->fNoEntries = atoi(nbentries);
newquery->fFirstEntry = atoi(firstentry);
newquery->fResult = 0;
newquery->fChain = 0;
fActDesc->fQueries->Add((TObject *)newquery);
cnt++;
TGListTreeItem *item1 = fSessionHierarchy->FindChildByData(
fSessionItem, fActDesc);
TGListTreeItem *item2 = fSessionHierarchy->AddItem(
item1, newquery->fQueryName, fQueryCon, fQueryCon);
item2->SetUserData(newquery);
}
delete [] v;
}
}
}
fSessionHierarchy->ClearHighlighted();
fSessionHierarchy->OpenItem(fSessionItem);
if (fActDesc == localdesc) {
fSessionHierarchy->HighlightItem(fSessionItem);
fSessionHierarchy->SetSelected(fSessionItem);
}
else {
fSessionHierarchy->OpenItem(item);
fSessionHierarchy->HighlightItem(item);
fSessionHierarchy->SetSelected(item);
}
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfProofs()
{
// Update list of existing Proof sessions.
// get list of proof sessions
Bool_t found = kFALSE;
Bool_t exists = kFALSE;
TGListTreeItem *item = 0;
TSeqCollection *proofs = gROOT->GetListOfProofs();
TSessionDescription *desc = 0;
TSessionDescription *newdesc;
if (proofs) {
TObject *o = proofs->First();
if (o && dynamic_cast<TProofMgr *>(o)) {
TProofMgr *mgr = dynamic_cast<TProofMgr *>(o);
if (mgr->QuerySessions("L")) {
TIter nxd(mgr->QuerySessions("L"));
TProofDesc *d = 0;
TProof *p = 0;
while ((d = (TProofDesc *)nxd())) {
TIter nextfs(fSessions);
// check if session exists in the list
while ((desc = (TSessionDescription *)nextfs())) {
if ((desc->fTag == d->GetName()) ||
(desc->fName == d->GetTitle())) {
exists = kTRUE;
break;
}
}
TIter nexts(fSessions);
found = kFALSE;
p = d->GetProof();
while ((desc = (TSessionDescription *)nexts())) {
if (desc->fConnected && desc->fAttached)
continue;
if (p && (exists && ((desc->fTag == d->GetName()) ||
(desc->fName == d->GetTitle())) ||
(!exists && (desc->fAddress == p->GetMaster())))) {
desc->fConnected = kTRUE;
desc->fAttached = kTRUE;
desc->fProof = p;
desc->fProofMgr = mgr;
desc->fTag = d->GetName();
item = fSessionHierarchy->FindChildByData(fSessionItem,
desc);
if (item) {
item->SetPictures(fProofCon, fProofCon);
if (item == fSessionHierarchy->GetSelected()) {
fActDesc->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t)");
fActDesc->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fActDesc->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fQueryFrame,
"IndicateStop(Bool_t)");
fActDesc->fProof->Connect(
"ResetProgressDialog(const char*, Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
EnableTimer();
// change status bar right icon to connected pixmap
ChangeRightLogo("monitor01.xpm");
// do not animate yet
SetChangePic(kFALSE);
// connect to signal "query result ready"
fActDesc->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", this, "QueryResultReady(char *)");
// display connection information on status bar
TString msg;
msg.Form("PROOF Cluster %s ready", fActDesc->fName.Data());
fStatusBar->SetText(msg.Data(), 1);
UpdateListOfPackages();
fSessionFrame->UpdatePackages();
fSessionFrame->UpdateListOfDataSets();
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fPopupSrv->EnableEntry(kSessionDisconnect);
fSessionMenu->EnableEntry(kSessionDisconnect);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonUp);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
fSessionFrame->SetLogLevel(fActDesc->fLogLevel);
// update session information frame
fSessionFrame->ProofInfos();
fSessionFrame->SetLocal(kFALSE);
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
}
}
}
if (desc->fLogLevel < 0)
desc->fLogLevel = 0;
found = kTRUE;
break;
}
}
if (found) continue;
p = d->GetProof();
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fTag = d->GetName();
newdesc->fName = d->GetTitle();
newdesc->fAddress = d->GetTitle();
newdesc->fConnected = kFALSE;
newdesc->fAttached = kFALSE;
newdesc->fProofMgr = mgr;
p = d->GetProof();
if (p) {
newdesc->fConnected = kTRUE;
newdesc->fAttached = kTRUE;
newdesc->fAddress = p->GetMaster();
newdesc->fConfigFile = p->GetConfFile();
newdesc->fUserName = p->GetUser();
newdesc->fPort = p->GetPort();
newdesc->fLogLevel = p->GetLogLevel();
newdesc->fProof = p;
newdesc->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t)");
newdesc->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
newdesc->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fQueryFrame,
"IndicateStop(Bool_t)");
newdesc->fProof->Connect(
"ResetProgressDialog(const char*, Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
EnableTimer();
// change status bar right icon to connected pixmap
ChangeRightLogo("monitor01.xpm");
// do not animate yet
SetChangePic(kFALSE);
// connect to signal "query result ready"
newdesc->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", this, "QueryResultReady(char *)");
}
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fActQuery = 0;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
if (p)
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofCon, fProofCon);
else
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
}
}
return;
}
TIter nextp(proofs);
TProof *proof;
// loop over existing Proof sessions
while ((proof = (TProof *)nextp())) {
TIter nexts(fSessions);
found = kFALSE;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if (desc->fProof == proof) {
desc->fConnected = kTRUE;
desc->fAttached = kTRUE;
found = kTRUE;
break;
}
}
if (found) continue;
// create new session description
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fName = proof->GetMaster();
newdesc->fConfigFile = proof->GetConfFile();
newdesc->fUserName = proof->GetUser();
newdesc->fPort = proof->GetPort();
newdesc->fLogLevel = proof->GetLogLevel();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fAddress = proof->GetMaster();
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
newdesc->fProof = proof;
newdesc->fActQuery = 0;
newdesc->fConnected = kTRUE;
newdesc->fAttached = kTRUE;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofCon, fProofCon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
}
}
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfSessions()
{
// Update list of existing Proof sessions.
// get list of proof sessions
TGListTreeItem *item;
TList *sessions = fActDesc->fProofMgr->QuerySessions("");
if (sessions) {
TIter nextp(sessions);
TProofDesc *pdesc;
TProof *proof;
TSessionDescription *newdesc;
// loop over existing Proof sessions
while ((pdesc = (TProofDesc *)nextp())) {
TIter nexts(fSessions);
TSessionDescription *desc = 0;
Bool_t found = kFALSE;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if ((desc->fTag == pdesc->GetName()) ||
(desc->fName == pdesc->GetTitle())) {
desc->fConnected = kTRUE;
found = kTRUE;
break;
}
}
if (found) continue;
// create new session description
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fTag = pdesc->GetName();
newdesc->fName = pdesc->GetTitle();
proof = pdesc->GetProof();
if (proof) {
newdesc->fConfigFile = proof->GetConfFile();
newdesc->fUserName = proof->GetUser();
newdesc->fPort = proof->GetPort();
newdesc->fLogLevel = proof->GetLogLevel();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fAddress = proof->GetMaster();
newdesc->fProof = proof;
}
else {
newdesc->fProof = 0;
newdesc->fConfigFile = "";
newdesc->fUserName = fActDesc->fUserName;
newdesc->fPort = fActDesc->fPort;
newdesc->fLogLevel = 0;
newdesc->fAddress = fActDesc->fAddress;
}
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
newdesc->fProofMgr = fActDesc->fProofMgr;
newdesc->fActQuery = 0;
newdesc->fConnected = kTRUE;
newdesc->fAttached = kFALSE;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
// set actual description to the last one
}
}
}
//______________________________________________________________________________
void TSessionViewer::WriteConfiguration(const char *filename)
{
// Save actual configuration in config file "filename".
TSessionDescription *session;
TQueryDescription *query;
Int_t scnt = 0, qcnt = 1;
const char *fname = filename ? filename : fConfigFile.Data();
delete fViewerEnv;
gSystem->Unlink(fname);
fViewerEnv = new TEnv();
fViewerEnv->SetValue("Option.Feedback",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsFeedback));
fViewerEnv->SetValue("Option.MasterHistos",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsStatsHist));
fViewerEnv->SetValue("Option.MasterEvents",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsStatsTrace));
fViewerEnv->SetValue("Option.WorkerEvents",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsSlaveStatsTrace));
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
fViewerEnv->SetValue(Form("Option.%s",kFeedbackHistos[i]),
(Int_t)fCascadeMenu->IsEntryChecked(41+i));
i++;
}
TIter snext(fSessions);
while ((session = (TSessionDescription *) snext())) {
if ((scnt > 0) && ((session->fAddress.Length() < 3) ||
session->fUserName.Length() < 2)) {
// skip gROOT's list of sessions
continue;
}
if ((scnt > 0) && (session->fName == session->fAddress)) {
// skip gROOT's list of proofs
continue;
}
TString sessionstring;
sessionstring += session->fName;
sessionstring += ";";
sessionstring += session->fTag.Length() > 1 ? session->fTag.Data() : " ";
sessionstring += ";";
sessionstring += session->fAddress;
sessionstring += ";";
sessionstring += Form("%d", session->fPort);
sessionstring += ";";
sessionstring += Form("%d", session->fLogLevel);
sessionstring += ";";
sessionstring += session->fConfigFile.Length() > 1 ? session->fConfigFile.Data() : " ";
sessionstring += ";";
sessionstring += session->fUserName;
sessionstring += ";";
sessionstring += Form("%d", session->fSync);
sessionstring += ";";
sessionstring += Form("%d", session->fAutoEnable);
if (scnt > 0) // skip local session
fViewerEnv->SetValue(Form("SessionDescription.%d",scnt), sessionstring);
scnt++;
TIter qnext(session->fQueries);
while ((query = (TQueryDescription *) qnext())) {
TString querystring;
querystring += Form("%d", query->fStatus);
querystring += ";";
querystring += query->fReference.Length() > 1 ? query->fReference.Data() : " ";
querystring += ";";
querystring += query->fQueryName;
querystring += ";";
querystring += query->fSelectorString.Length() > 1 ? query->fSelectorString.Data() : " ";
querystring += ";";
querystring += query->fTDSetString.Length() > 1 ? query->fTDSetString.Data() : " ";
querystring += ";";
querystring += query->fOptions.Length() > 1 ? query->fOptions.Data() : " ";
querystring += ";";
querystring += query->fEventList.Length() > 1 ? query->fEventList.Data() : " ";
querystring += ";";
querystring += Form("%d",query->fNbFiles);
querystring += ";";
querystring += Form("%d",query->fNoEntries);
querystring += ";";
querystring += Form("%d",query->fFirstEntry);
fViewerEnv->SetValue(Form("QueryDescription.%d",qcnt), querystring);
qcnt++;
}
}
fViewerEnv->WriteFile(fname);
}
//______________________________________________________________________________
void TSessionViewer::Build()
{
// Build main session viewer frame and subframes.
char line[120];
fActDesc = 0;
fActFrame = 0;
fLogWindow = 0;
fBusy = kFALSE;
fAutoSave = kTRUE;
SetCleanup(kDeepCleanup);
// set minimun size
SetWMSizeHints(400 + 200, 370+50, 2000, 1000, 1, 1);
// collect icons
fLocal = fClient->GetPicture("local_session.xpm");
fProofCon = fClient->GetPicture("proof_connected.xpm");
fProofDiscon = fClient->GetPicture("proof_disconnected.xpm");
fQueryCon = fClient->GetPicture("query_connected.xpm");
fQueryDiscon = fClient->GetPicture("query_disconnected.xpm");
fBaseIcon = fClient->GetPicture("proof_base.xpm");
//--- File menu
fFileMenu = new TGPopupMenu(fClient->GetRoot());
fFileMenu->AddEntry("&Load Config...", kFileLoadConfig);
fFileMenu->AddEntry("&Save Config...", kFileSaveConfig);
fFileMenu->AddSeparator();
fFileMenu->AddEntry("&Close Viewer", kFileCloseViewer);
fFileMenu->AddSeparator();
fFileMenu->AddEntry("&Quit ROOT", kFileQuit);
//--- Session menu
fSessionMenu = new TGPopupMenu(gClient->GetRoot());
fSessionMenu->AddLabel("Session Management");
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&New Session", kSessionNew);
fSessionMenu->AddEntry("&Add to the list", kSessionAdd);
fSessionMenu->AddEntry("De&lete", kSessionDelete);
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&Connect...", kSessionConnect);
fSessionMenu->AddEntry("&Disconnect", kSessionDisconnect);
fSessionMenu->AddEntry("Shutdo&wn", kSessionShutdown);
fSessionMenu->AddEntry("&Show status",kSessionShowStatus);
fSessionMenu->AddEntry("&Get Queries",kSessionGetQueries);
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&Cleanup", kSessionCleanup);
fSessionMenu->AddEntry("&Reset",kSessionReset);
fSessionMenu->DisableEntry(kSessionAdd);
//--- Query menu
fQueryMenu = new TGPopupMenu(gClient->GetRoot());
fQueryMenu->AddLabel("Query Management");
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("&New...", kQueryNew);
fQueryMenu->AddEntry("&Edit", kQueryEdit);
fQueryMenu->AddEntry("&Submit", kQuerySubmit);
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("Start &Viewer", kQueryStartViewer);
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("&Delete", kQueryDelete);
fViewerEnv = 0;
#ifdef WIN32
fConfigFile = Form("%s\\%s", gSystem->HomeDirectory(), kConfigFile);
#else
fConfigFile = Form("%s/%s", gSystem->HomeDirectory(), kConfigFile);
#endif
fCascadeMenu = new TGPopupMenu(fClient->GetRoot());
Int_t i = 0;
while (kFeedbackHistos[i]) {
fCascadeMenu->AddEntry(kFeedbackHistos[i], 41+i);
i++;
}
fCascadeMenu->AddEntry("User defined...", 50);
// disable it for now (until implemented)
fCascadeMenu->DisableEntry(50);
//--- Options menu
fOptionsMenu = new TGPopupMenu(fClient->GetRoot());
fOptionsMenu->AddLabel("Global Options");
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("&Autosave Config", kOptionsAutoSave);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("Master &Histos", kOptionsStatsHist);
fOptionsMenu->AddEntry("&Master Events", kOptionsStatsTrace);
fOptionsMenu->AddEntry("&Worker Events", kOptionsSlaveStatsTrace);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("Feedback &Active", kOptionsFeedback);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddPopup("&Feedback Histos", fCascadeMenu);
fOptionsMenu->CheckEntry(kOptionsAutoSave);
//--- Help menu
fHelpMenu = new TGPopupMenu(gClient->GetRoot());
fHelpMenu->AddEntry("&About ROOT...", kHelpAbout);
fFileMenu->Associate(this);
fSessionMenu->Associate(this);
fQueryMenu->Associate(this);
fOptionsMenu->Associate(this);
fCascadeMenu->Associate(this);
fHelpMenu->Associate(this);
//--- create menubar and add popup menus
fMenuBar = new TGMenuBar(this, 1, 1, kHorizontalFrame);
fMenuBar->AddPopup("&File", fFileMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Session", fSessionMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Query", fQueryMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Options", fOptionsMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Help", fHelpMenu, new TGLayoutHints(kLHintsTop |
kLHintsRight));
TGHorizontal3DLine *toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
AddFrame(fMenuBar, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 0, 0, 1, 1));
toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
//---- toolbar
int spacing = 8;
fToolBar = new TGToolBar(this, 60, 20, kHorizontalFrame);
for (int i = 0; xpm_toolbar[i]; i++) {
tb_data[i].fPixmap = xpm_toolbar[i];
if (strlen(xpm_toolbar[i]) == 0) {
spacing = 8;
continue;
}
fToolBar->AddButton(this, &tb_data[i], spacing);
spacing = 0;
}
AddFrame(fToolBar, new TGLayoutHints(kLHintsTop | kLHintsExpandX, 0, 0, 0, 0));
toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonDisabled);
fPopupSrv = new TGPopupMenu(fClient->GetRoot());
fPopupSrv->AddEntry("Connect",kSessionConnect);
fPopupSrv->AddEntry("Disconnect",kSessionDisconnect);
fPopupSrv->AddEntry("Shutdown",kSessionShutdown);
fPopupSrv->AddEntry("Browse",kSessionBrowse);
fPopupSrv->AddEntry("Show status",kSessionShowStatus);
fPopupSrv->AddEntry("Delete", kSessionDelete);
fPopupSrv->AddEntry("Get Queries",kSessionGetQueries);
fPopupSrv->AddSeparator();
fPopupSrv->AddEntry("Cleanup", kSessionCleanup);
fPopupSrv->AddEntry("Reset",kSessionReset);
fPopupSrv->Connect("Activated(Int_t)","TSessionViewer", this,
"MyHandleMenu(Int_t)");
fPopupQry = new TGPopupMenu(fClient->GetRoot());
fPopupQry->AddEntry("Edit",kQueryEdit);
fPopupQry->AddEntry("Submit",kQuerySubmit);
fPopupQry->AddSeparator();
fPopupQry->AddEntry("Start &Viewer", kQueryStartViewer);
fPopupQry->AddSeparator();
fPopupQry->AddEntry("Delete",kQueryDelete);
fPopupQry->Connect("Activated(Int_t)","TSessionViewer", this,
"MyHandleMenu(Int_t)");
fSessionMenu->DisableEntry(kSessionGetQueries);
fSessionMenu->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionGetQueries);
fPopupSrv->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionDisconnect);
fPopupSrv->DisableEntry(kSessionShutdown);
fPopupSrv->DisableEntry(kSessionCleanup);
fPopupSrv->DisableEntry(kSessionReset);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
//--- Horizontal mother frame -----------------------------------------------
fHf = new TGHorizontalFrame(this, 10, 10);
fHf->SetCleanup(kDeepCleanup);
//--- fV1 -------------------------------------------------------------------
fV1 = new TGVerticalFrame(fHf, 100, 100, kFixedWidth);
fV1->SetCleanup(kDeepCleanup);
fTreeView = new TGCanvas(fV1, 100, 200, kSunkenFrame | kDoubleBorder);
fV1->AddFrame(fTreeView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
2, 0, 0, 0));
fSessionHierarchy = new TGListTree(fTreeView, kHorizontalFrame);
fSessionHierarchy->DisableOpen();
fSessionHierarchy->Connect("Clicked(TGListTreeItem*,Int_t,Int_t,Int_t)",
"TSessionViewer", this,
"OnListTreeClicked(TGListTreeItem*, Int_t, Int_t, Int_t)");
fSessionHierarchy->Connect("DoubleClicked(TGListTreeItem*,Int_t)",
"TSessionViewer", this,
"OnListTreeDoubleClicked(TGListTreeItem*, Int_t)");
fV1->Resize(fTreeView->GetDefaultWidth()+100, fV1->GetDefaultHeight());
//--- fV2 -------------------------------------------------------------------
fV2 = new TGVerticalFrame(fHf, 350, 310);
fV2->SetCleanup(kDeepCleanup);
//--- Server Frame ----------------------------------------------------------
fServerFrame = new TSessionServerFrame(fV2, 350, 310);
fSessions = new TList;
ReadConfiguration();
fServerFrame->Build(this);
fV2->AddFrame(fServerFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Session Frame ---------------------------------------------------------
fSessionFrame = new TSessionFrame(fV2, 350, 310);
fSessionFrame->Build(this);
fV2->AddFrame(fSessionFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Query Frame -----------------------------------------------------------
fQueryFrame = new TSessionQueryFrame(fV2, 350, 310);
fQueryFrame->Build(this);
fV2->AddFrame(fQueryFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Output Frame ----------------------------------------------------------
fOutputFrame = new TSessionOutputFrame(fV2, 350, 310);
fOutputFrame->Build(this);
fV2->AddFrame(fOutputFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Input Frame -----------------------------------------------------------
fInputFrame = new TSessionInputFrame(fV2, 350, 310);
fInputFrame->Build(this);
fV2->AddFrame(fInputFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
fHf->AddFrame(fV1, new TGLayoutHints(kLHintsLeft | kLHintsExpandY));
// add vertical splitter between list tree and frames
TGVSplitter *splitter = new TGVSplitter(fHf, 4);
splitter->SetFrame(fV1, kTRUE);
fHf->AddFrame(splitter,new TGLayoutHints(kLHintsLeft | kLHintsExpandY));
fHf->AddFrame(new TGVertical3DLine(fHf), new TGLayoutHints(kLHintsLeft |
kLHintsExpandY));
fHf->AddFrame(fV2, new TGLayoutHints(kLHintsRight | kLHintsExpandX |
kLHintsExpandY));
AddFrame(fHf, new TGLayoutHints(kLHintsRight | kLHintsExpandX |
kLHintsExpandY));
// if description available, update server infos frame
if (fActDesc) {
if (!fActDesc->fLocal) {
fServerFrame->Update(fActDesc);
}
else {
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
}
}
//--- Status Bar ------------------------------------------------------------
int parts[] = { 36, 49, 15 };
fStatusBar = new TGStatusBar(this, 10, 10);
fStatusBar->SetCleanup(kDeepCleanup);
fStatusBar->SetParts(parts, 3);
for (int p = 0; p < 3; ++p)
fStatusBar->GetBarPart(p)->SetCleanup(kDeepCleanup);
AddFrame(fStatusBar, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 0, 0, 1, 1));
// connection icon (animation) and time info
fStatusBar->SetText(" 00:00:00", 2);
TGCompositeFrame *leftpart = fStatusBar->GetBarPart(2);
fRightIconPicture = (TGPicture *)fClient->GetPicture("proof_disconnected.xpm");
fRightIcon = new TGIcon(leftpart, fRightIconPicture,
fRightIconPicture->GetWidth(),fRightIconPicture->GetHeight());
leftpart->AddFrame(fRightIcon, new TGLayoutHints(kLHintsLeft, 2, 0, 0, 0));
// connection progress bar
TGCompositeFrame *rightpart = fStatusBar->GetBarPart(0);
fConnectProg = new TGHProgressBar(rightpart, TGProgressBar::kStandard, 100);
fConnectProg->ShowPosition();
fConnectProg->SetBarColor("green");
rightpart->AddFrame(fConnectProg, new TGLayoutHints(kLHintsExpandX, 1, 1, 1, 1));
// add user info
fUserGroup = gSystem->GetUserInfo();
sprintf(line,"User : %s - %s", fUserGroup->fRealName.Data(),
fUserGroup->fGroup.Data());
fStatusBar->SetText(line, 1);
fTimer = 0;
// create context menu
fContextMenu = new TContextMenu("SessionViewerContextMenu") ;
SetWindowName("ROOT Session Viewer");
MapSubwindows();
MapWindow();
// hide frames
fServerFrame->SetAddEnabled(kFALSE);
fStatusBar->GetBarPart(0)->HideFrame(fConnectProg);
fV2->HideFrame(fSessionFrame);
fV2->HideFrame(fQueryFrame);
fV2->HideFrame(fOutputFrame);
fV2->HideFrame(fInputFrame);
fQueryFrame->GetQueryEditFrame()->OnNewQueryMore();
fActFrame = fServerFrame;
UpdateListOfProofs();
Resize(610, 420);
}
//______________________________________________________________________________
TSessionViewer::~TSessionViewer()
{
// Destructor.
Cleanup();
delete fUserGroup;
if (gSessionViewer == this)
gSessionViewer = 0;
}
//______________________________________________________________________________
void TSessionViewer::OnListTreeClicked(TGListTreeItem *entry, Int_t btn,
Int_t x, Int_t y)
{
// Handle mouse clicks in list tree.
TList *objlist;
TObject *obj;
TString msg;
fSessionMenu->DisableEntry(kSessionAdd);
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonDisabled);
if (entry->GetParent() == 0) { // PROOF
// switch frames only if actual one doesn't match
if (fActFrame != fServerFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fServerFrame);
fActFrame = fServerFrame;
}
fSessionMenu->DisableEntry(kSessionDelete);
fSessionMenu->EnableEntry(kSessionAdd);
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
}
else if (entry->GetParent()->GetParent() == 0) { // Server
if (entry->GetUserData()) {
obj = (TObject *)entry->GetUserData();
if (obj->IsA() != TSessionDescription::Class())
return;
// update server frame informations
fServerFrame->Update((TSessionDescription *)obj);
fActDesc = (TSessionDescription*)obj;
// if Proof valid, update connection infos
if (fActDesc->fConnected && fActDesc->fAttached &&
fActDesc->fProof && fActDesc->fProof->IsValid()) {
fActDesc->fProof->cd();
msg.Form("PROOF Cluster %s ready", fActDesc->fName.Data());
}
else {
msg.Form("PROOF Cluster %s not connected", fActDesc->fName.Data());
}
fStatusBar->SetText(msg.Data(), 1);
}
if ((fActDesc->fConnected) && (fActDesc->fAttached)) {
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
UpdateListOfPackages();
fSessionFrame->UpdateListOfDataSets();
}
else {
fPopupSrv->EnableEntry(kSessionConnect);
fSessionMenu->EnableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonUp);
}
// local session
if (fActDesc->fLocal) {
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
UpdateListOfPackages();
fSessionFrame->UpdateListOfDataSets();
}
fSessionFrame->SetLocal();
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
}
// proof session not connected
if ((!fActDesc->fLocal) && (!fActDesc->fAttached) &&
(fActFrame != fServerFrame)) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fServerFrame);
fActFrame = fServerFrame;
}
// proof session connected
if ((!fActDesc->fLocal) && (fActDesc->fConnected) &&
(fActDesc->fAttached)) {
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
}
fSessionFrame->SetLocal(kFALSE);
}
fSessionFrame->SetLogLevel(fActDesc->fLogLevel);
fServerFrame->SetLogLevel(fActDesc->fLogLevel);
if (fActDesc->fAutoEnable)
fSessionFrame->CheckAutoEnPack(kTRUE);
else
fSessionFrame->CheckAutoEnPack(kFALSE);
// update session information frame
fSessionFrame->ProofInfos();
fSessionFrame->UpdatePackages();
fServerFrame->SetAddEnabled(kFALSE);
fServerFrame->SetConnectEnabled();
}
else if (entry->GetParent()->GetParent()->GetParent() == 0) { // query
obj = (TObject *)entry->GetParent()->GetUserData();
if (obj->IsA() == TSessionDescription::Class()) {
fActDesc = (TSessionDescription *)obj;
}
obj = (TObject *)entry->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
fActDesc->fActQuery = (TQueryDescription *)obj;
}
// update query informations and buttons state
fQueryFrame->UpdateInfos();
fQueryFrame->UpdateButtons(fActDesc->fActQuery);
if (fActFrame != fQueryFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fQueryFrame);
fActFrame = fQueryFrame;
}
if ((fActDesc->fConnected) && (fActDesc->fAttached) &&
(fActDesc->fActQuery->fStatus != TQueryDescription::kSessionQueryRunning) &&
(fActDesc->fActQuery->fStatus != TQueryDescription::kSessionQuerySubmitted) )
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonUp);
// trick to update feedback histos
OnCascadeMenu();
}
else { // a list (input, output)
obj = (TObject *)entry->GetParent()->GetParent()->GetUserData();
if (obj->IsA() == TSessionDescription::Class()) {
fActDesc = (TSessionDescription *)obj;
}
obj = (TObject *)entry->GetParent()->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
fActDesc->fActQuery = (TQueryDescription *)obj;
}
if (fActDesc->fActQuery) {
// update input/output list views
fInputFrame->RemoveAll();
fOutputFrame->RemoveAll();
if (fActDesc->fActQuery->fResult) {
objlist = fActDesc->fActQuery->fResult->GetOutputList();
if (objlist) {
TIter nexto(objlist);
while ((obj = (TObject *) nexto())) {
fOutputFrame->AddObject(obj);
}
}
objlist = fActDesc->fActQuery->fResult->GetInputList();
if (objlist) {
TIter nexti(objlist);
while ((obj = (TObject *) nexti())) {
fInputFrame->AddObject(obj);
}
}
}
else {
TChain *chain = (TChain *)fActDesc->fActQuery->fChain;
if (chain) {
objlist = ((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile()->GetOutputList();
if (objlist) {
TIter nexto(objlist);
while ((obj = (TObject *) nexto())) {
fOutputFrame->AddObject(obj);
}
}
}
}
fInputFrame->Resize();
fOutputFrame->Resize();
fClient->NeedRedraw(fOutputFrame->GetLVContainer());
fClient->NeedRedraw(fInputFrame->GetLVContainer());
}
// switch frames
if (strstr(entry->GetText(),"Output")) {
if (fActFrame != fOutputFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fOutputFrame);
fActFrame = fOutputFrame;
}
}
else if (strstr(entry->GetText(),"Input")) {
if (fActFrame != fInputFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fInputFrame);
fActFrame = fInputFrame;
}
}
}
if (btn == 3) { // right button
// place popup menus
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
obj = (TObject *)item->GetUserData();
if (obj && obj->IsA() == TQueryDescription::Class()) {
fPopupQry->PlaceMenu(x, y, 1, 1);
}
else if (obj && obj->IsA() == TSessionDescription::Class()) {
if (!fActDesc->fLocal)
fPopupSrv->PlaceMenu(x, y, 1, 1);
}
}
// enable / disable menu entries
if (fActDesc->fConnected && fActDesc->fAttached) {
fSessionMenu->EnableEntry(kSessionGetQueries);
fSessionMenu->EnableEntry(kSessionShowStatus);
fPopupSrv->EnableEntry(kSessionGetQueries);
fPopupSrv->EnableEntry(kSessionShowStatus);
fPopupSrv->EnableEntry(kSessionDisconnect);
fPopupSrv->EnableEntry(kSessionShutdown);
fPopupSrv->EnableEntry(kSessionCleanup);
fPopupSrv->EnableEntry(kSessionReset);
fSessionMenu->EnableEntry(kSessionDisconnect);
fSessionMenu->EnableEntry(kSessionShutdown);
fSessionMenu->EnableEntry(kSessionCleanup);
fSessionMenu->EnableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonUp);
fQueryMenu->EnableEntry(kQuerySubmit);
fPopupQry->EnableEntry(kQuerySubmit);
}
else {
fSessionMenu->DisableEntry(kSessionGetQueries);
fSessionMenu->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionGetQueries);
fPopupSrv->DisableEntry(kSessionShowStatus);
if (entry->GetParent() != 0)
fSessionMenu->EnableEntry(kSessionDelete);
fPopupSrv->EnableEntry(kSessionDelete);
fPopupSrv->DisableEntry(kSessionDisconnect);
fPopupSrv->DisableEntry(kSessionShutdown);
fPopupSrv->DisableEntry(kSessionCleanup);
fPopupSrv->DisableEntry(kSessionReset);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
fQueryMenu->DisableEntry(kQuerySubmit);
fPopupQry->DisableEntry(kQuerySubmit);
}
if (fActDesc->fLocal) {
fSessionMenu->DisableEntry(kSessionDelete);
fSessionMenu->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
fQueryMenu->EnableEntry(kQuerySubmit);
fPopupQry->EnableEntry(kQuerySubmit);
}
}
//______________________________________________________________________________
void TSessionViewer::OnListTreeDoubleClicked(TGListTreeItem *entry, Int_t /*btn*/)
{
// Handle mouse double clicks in list tree (connect to server).
if (entry == fSessionItem)
return;
if (entry->GetParent()->GetParent() == 0) { // Server
if (entry->GetUserData()) {
TObject *obj = (TObject *)entry->GetUserData();
if (obj->IsA() != TSessionDescription::Class())
return;
fActDesc = (TSessionDescription*)obj;
// if Proof valid, update connection infos
}
if ((!fActDesc->fLocal) && ((!fActDesc->fConnected) ||
(!fActDesc->fAttached))) {
fServerFrame->OnBtnConnectClicked();
}
}
}
//______________________________________________________________________________
void TSessionViewer::Terminate()
{
// Terminate Session : save configuration, clean temporary files and close
// Proof connections.
// clean-up temporary files
TString pathtmp;
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectFile);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectCmd);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
// close opened Proof sessions (if any)
TIter next(fSessions);
TSessionDescription *desc = 0;
while ((desc = (TSessionDescription *)next())) {
if (desc->fAttached && desc->fProof &&
desc->fProof->IsValid())
desc->fProof->Detach();
}
// Save configuration
if (fAutoSave)
WriteConfiguration();
}
//______________________________________________________________________________
void TSessionViewer::CloseWindow()
{
// Close main Session Viewer window.
// clean-up temporary files
TString pathtmp;
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectFile);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectCmd);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
// Save configuration
if (fAutoSave)
WriteConfiguration();
fSessions->Delete();
if (fSessionItem)
fSessionHierarchy->DeleteChildren(fSessionItem);
delete fSessionHierarchy; // this has been put int TGCanvas which isn't a
// TGComposite frame and doesn't do cleanups.
fClient->FreePicture(fLocal);
fClient->FreePicture(fProofCon);
fClient->FreePicture(fProofDiscon);
fClient->FreePicture(fQueryCon);
fClient->FreePicture(fQueryDiscon);
fClient->FreePicture(fBaseIcon);
delete fTimer;
DeleteWindow();
}
//______________________________________________________________________________
void TSessionViewer::ChangeRightLogo(const char *name)
{
// Change the right logo (used for animation).
fClient->FreePicture(fRightIconPicture);
fRightIconPicture = (TGPicture *)fClient->GetPicture(name);
fRightIcon->SetPicture(fRightIconPicture);
}
//______________________________________________________________________________
void TSessionViewer::EnableTimer()
{
// Enable animation timer.
if (!fTimer) fTimer = new TTimer(this, 500);
fTimer->Reset();
fTimer->TurnOn();
time( &fStart );
}
//______________________________________________________________________________
void TSessionViewer::DisableTimer()
{
// Disable animation timer.
if (fTimer)
fTimer->TurnOff();
ChangeRightLogo("proof_disconnected.xpm");
}
//______________________________________________________________________________
Bool_t TSessionViewer::HandleTimer(TTimer *)
{
// Handle animation timer.
char line[120];
struct tm *connected;
Int_t count = gRandom->Integer(4);
if (count > 3) {
count = 0;
}
if (fChangePic)
ChangeRightLogo(xpm_names[count]);
time( &fElapsed );
time_t elapsed_time = (time_t)difftime( fElapsed, fStart );
connected = gmtime( &elapsed_time );
sprintf(line," %02d:%02d:%02d", connected->tm_hour,
connected->tm_min, connected->tm_sec);
fStatusBar->SetText(line, 2);
if (fActDesc->fLocal) {
if ((fActDesc->fActQuery) &&
(fActDesc->fActQuery->fStatus ==
TQueryDescription::kSessionQueryRunning)) {
TChain *chain = (TChain *)fActDesc->fActQuery->fChain;
if (chain)
fQueryFrame->ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
}
}
fTimer->Reset();
return kTRUE;
}
//______________________________________________________________________________
void TSessionViewer::LogMessage(const char *msg, Bool_t all)
{
// Load/append a log msg in the log frame.
if (fLogWindow) {
if (all) {
// load buffer
fLogWindow->LoadBuffer(msg);
} else {
// append
fLogWindow->AddBuffer(msg);
}
}
}
//______________________________________________________________________________
void TSessionViewer::QueryResultReady(char *query)
{
// Handle signal "query result ready" coming from Proof session.
char strtmp[256];
sprintf(strtmp,"Query Result Ready for %s", query);
// show information on status bar
ShowInfo(strtmp);
TGListTreeItem *item=0, *item2=0;
TQueryDescription *lquery = 0;
// loop over actual queries to find which one is ready
TIter nexts(fSessions);
TSessionDescription *desc = 0;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if (desc && !desc->fAttached)
continue;
TIter nextp(desc->fQueries);
while ((lquery = (TQueryDescription *)nextp())) {
if (lquery->fReference.Contains(query)) {
// results are ready for this query
lquery->fResult = desc->fProof->GetQueryResult(query);
lquery->fStatus = TQueryDescription::kSessionQueryFromProof;
if (!lquery->fResult)
break;
// get query status
lquery->fStatus = lquery->fResult->IsFinalized() ?
TQueryDescription::kSessionQueryFinalized :
(TQueryDescription::ESessionQueryStatus)lquery->fResult->GetStatus();
// get data set
TObject *o = lquery->fResult->GetInputObject("TDSet");
if (o)
lquery->fChain = (TDSet *) o;
item = fSessionHierarchy->FindItemByObj(fSessionItem, desc);
if (item) {
item2 = fSessionHierarchy->FindItemByObj(item, lquery);
}
if (item2) {
// add input and output list entries
if (lquery->fResult->GetInputList())
if (!fSessionHierarchy->FindChildByName(item2, "InputList"))
fSessionHierarchy->AddItem(item2, "InputList");
if (lquery->fResult->GetOutputList())
if (!fSessionHierarchy->FindChildByName(item2, "OutputList"))
fSessionHierarchy->AddItem(item2, "OutputList");
}
// update list tree, query frame informations, and buttons state
fClient->NeedRedraw(fSessionHierarchy);
fQueryFrame->UpdateInfos();
fQueryFrame->UpdateButtons(lquery);
break;
}
}
}
}
//______________________________________________________________________________
void TSessionViewer::CleanupSession()
{
// Clean-up Proof session.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TSessionDescription::Class()) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid()) return;
TString m;
m.Form("Are you sure to cleanup the session \"%s::%s\"",
fActDesc->fName.Data(), fActDesc->fTag.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBYes | kMBNo | kMBCancel, &result);
if (result == kMBYes) {
// send cleanup request for the session specified by the tag reference
TString sessiontag;
sessiontag.Form("session-%s",fActDesc->fTag.Data());
fActDesc->fProof->CleanupSession(sessiontag.Data());
// clear the list of queries
fActDesc->fQueries->Clear();
fSessionHierarchy->DeleteChildren(item);
fSessionFrame->OnBtnGetQueriesClicked();
if (fAutoSave)
WriteConfiguration();
}
// update list tree
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::ResetSession()
{
// Reset Proof session.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TSessionDescription::Class()) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid()) return;
TString m;
m.Form("Do you really want to reset the session \"%s::%s\"",
fActDesc->fName.Data(), fActDesc->fAddress.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBYes | kMBNo | kMBCancel, &result);
if (result == kMBYes) {
// reset the session
TProof::Mgr(fActDesc->fAddress)->Reset(fActDesc->fUserName);
// reset connected flag
fActDesc->fAttached = kFALSE;
fActDesc->fProof = 0;
// disable animation timer
DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fSessionHierarchy->FindChildByData(
fSessionItem, fActDesc);
item->SetPictures(fProofDiscon, fProofDiscon);
OnListTreeClicked(fSessionHierarchy->GetSelected(), 1, 0, 0);
fClient->NeedRedraw(fSessionHierarchy);
fStatusBar->SetText("", 1);
}
// update list tree
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::DeleteQuery()
{
// Delete query from list tree and ask user if he wants do delete it also
// from server.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
TString m;
Int_t result = 0;
if (fActDesc->fAttached && fActDesc->fProof && fActDesc->fProof->IsValid()) {
if ((fActDesc->fActQuery->fStatus == TQueryDescription::kSessionQuerySubmitted) ||
(fActDesc->fActQuery->fStatus == TQueryDescription::kSessionQueryRunning) ) {
new TGMsgBox(fClient->GetRoot(), this, "Delete Query",
"Deleting running queries is not allowed", kMBIconExclamation,
kMBOk, &result);
return;
}
m.Form("Do you want to delete query \"%s\" from server too ?",
query->fQueryName.Data());
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), kMBIconQuestion,
kMBYes | kMBNo | kMBCancel, &result);
}
else {
m.Form("Dou you really want to delete query \"%s\" ?",
query->fQueryName.Data());
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), kMBIconQuestion,
kMBOk | kMBCancel, &result);
}
if (result == kMBYes) {
fActDesc->fProof->Remove(query->fReference.Data());
fActDesc->fQueries->Remove((TObject *)query);
fSessionHierarchy->DeleteItem(item);
delete query;
}
else if (result == kMBNo || result == kMBOk) {
fActDesc->fQueries->Remove((TObject *)query);
fSessionHierarchy->DeleteItem(item);
delete query;
}
fClient->NeedRedraw(fSessionHierarchy);
if (fAutoSave)
WriteConfiguration();
}
//______________________________________________________________________________
void TSessionViewer::EditQuery()
{
// Edit currently selected query.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
TNewQueryDlg *dlg = new TNewQueryDlg(this, 350, 310, query, kTRUE);
dlg->Popup();
}
//______________________________________________________________________________
void TSessionViewer::StartViewer()
{
// Start TreeViewer from selected TChain.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
if (!query->fChain && query->fResult &&
(obj = query->fResult->GetInputObject("TDSet"))) {
query->fChain = (TDSet *) obj;
}
if (query->fChain->IsA() == TChain::Class())
((TChain *)query->fChain)->StartViewer();
else if (query->fChain->IsA() == TDSet::Class())
((TDSet *)query->fChain)->StartViewer();
}
//______________________________________________________________________________
void TSessionViewer::ShowPackages()
{
// Query the list of uploaded packages from proof and display it
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fLocal) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->ShowPackages(kTRUE);
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfPackages()
{
// Update the list of packages.
TObjString *packname;
TPackageDescription *package;
if (fActDesc->fConnected && fActDesc->fAttached &&
fActDesc->fProof && fActDesc->fProof->IsValid() &&
fActDesc->fProof->IsParallel()) {
//fActDesc->fPackages->Clear();
TList *packlist = fActDesc->fProof->GetListOfEnabledPackages();
if(packlist) {
TIter nextenabled(packlist);
while ((packname = (TObjString *)nextenabled())) {
package = new TPackageDescription;
package->fName = packname->GetName();
package->fName += ".par";
package->fPathName = package->fName;
package->fId = fActDesc->fPackages->GetEntries();
package->fUploaded = kTRUE;
package->fEnabled = kTRUE;
if (!fActDesc->fPackages->FindObject(package->fName)) {
fActDesc->fPackages->Add((TObject *)package);
}
}
}
packlist = fActDesc->fProof->GetListOfPackages();
if(packlist) {
TIter nextpack(packlist);
while ((packname = (TObjString *)nextpack())) {
package = new TPackageDescription;
package->fName = packname->GetName();
package->fName += ".par";
package->fPathName = package->fName;
package->fId = fActDesc->fPackages->GetEntries();
package->fUploaded = kTRUE;
package->fEnabled = kFALSE;
if (!fActDesc->fPackages->FindObject(package->fName)) {
fActDesc->fPackages->Add((TObject *)package);
}
}
}
}
// fSessionFrame->UpdatePackages();
}
//______________________________________________________________________________
void TSessionViewer::ShowEnabledPackages()
{
// Query list of enabled packages from proof and display it
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fLocal) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->ShowEnabledPackages(kTRUE);
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::ShowLog(const char *queryref)
{
// Display the content of the temporary log file for queryref
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fProof) {
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fActDesc->fProof->Connect("LogMessage(const char*,Bool_t)",
"TSessionViewer", this, "LogMessage(const char*,Bool_t)");
Bool_t logonly = fActDesc->fProof->SendingLogToWindow();
fActDesc->fProof->SendLogToWindow(kTRUE);
if (queryref)
fActDesc->fProof->ShowLog(queryref);
else
fActDesc->fProof->ShowLog(0);
fActDesc->fProof->SendLogToWindow(logonly);
// set log window position at the bottom of Session Viewer
gVirtualX->TranslateCoordinates(GetId(),
fClient->GetDefaultRoot()->GetId(), 0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
gVirtualX->SetCursor(GetId(), 0);
}
}
//______________________________________________________________________________
void TSessionViewer::ShowInfo(const char *txt)
{
// Display text in status bar.
fStatusBar->SetText(txt,0);
fClient->NeedRedraw(fStatusBar);
gSystem->ProcessEvents();
}
//______________________________________________________________________________
void TSessionViewer::ShowStatus()
{
// Retrieve and display Proof status.
Window_t wdummy;
Int_t ax, ay;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->GetStatus();
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::StartupMessage(char *msg, Bool_t, Int_t done, Int_t total)
{
// Handle startup message (connection progress) coming from Proof session.
Float_t pos = Float_t(Double_t(done * 100)/Double_t(total));
fConnectProg->SetPosition(pos);
fStatusBar->SetText(msg, 1);
}
//______________________________________________________________________________
void TSessionViewer::MyHandleMenu(Int_t id)
{
// Handle session viewer custom popup menus.
switch (id) {
case kSessionDelete:
fServerFrame->OnBtnDeleteClicked();
break;
case kSessionConnect:
fServerFrame->OnBtnConnectClicked();
break;
case kSessionDisconnect:
fSessionFrame->OnBtnDisconnectClicked();
break;
case kSessionShutdown:
fSessionFrame->ShutdownSession();
break;
case kSessionCleanup:
CleanupSession();
break;
case kSessionReset:
ResetSession();
break;
case kSessionBrowse:
if (fActDesc->fProof && fActDesc->fProof->IsValid()) {
TBrowser *b = new TBrowser();
fActDesc->fProof->Browse(b);
}
break;
case kSessionShowStatus:
ShowStatus();
break;
case kSessionGetQueries:
fSessionFrame->OnBtnGetQueriesClicked();
break;
case kQueryEdit:
EditQuery();
break;
case kQueryDelete:
DeleteQuery();
break;
case kQueryStartViewer:
StartViewer();
break;
case kQuerySubmit:
fQueryFrame->OnBtnSubmit();
break;
}
}
//______________________________________________________________________________
void TSessionViewer::OnCascadeMenu()
{
// Handle feedback histograms configuration menu.
// divide stats canvas by number of selected feedback histos
fQueryFrame->GetStatsCanvas()->cd();
fQueryFrame->GetStatsCanvas()->Clear();
fQueryFrame->GetStatsCanvas()->Modified();
fQueryFrame->GetStatsCanvas()->Update();
if (!fActDesc || !fActDesc->fActQuery) return;
fActDesc->fNbHistos = 0;
Int_t i = 0;
if (fActDesc->fAttached && fActDesc->fProof &&
fActDesc->fProof->IsValid()) {
if (fOptionsMenu->IsEntryChecked(kOptionsFeedback)) {
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fCascadeMenu->IsEntryChecked(41+i)) {
fActDesc->fProof->AddFeedback(kFeedbackHistos[i]);
}
i++;
}
}
else {
// if feedback option not selected, clear Proof's feedback option
fActDesc->fProof->ClearFeedback();
}
}
i = 0;
// loop over feedback histo list
while (kFeedbackHistos[i]) {
// check if user has selected this histogram in the option menu
if (fCascadeMenu->IsEntryChecked(41+i))
fActDesc->fNbHistos++;
i++;
}
fQueryFrame->GetStatsCanvas()->SetEditable(kTRUE);
fQueryFrame->GetStatsCanvas()->Clear();
if (fActDesc->fNbHistos == 4)
fQueryFrame->GetStatsCanvas()->Divide(2, 2);
else if (fActDesc->fNbHistos > 4)
fQueryFrame->GetStatsCanvas()->Divide(3, 2);
else
fQueryFrame->GetStatsCanvas()->Divide(fActDesc->fNbHistos, 1);
// if actual query has results, update feedback histos
if (fActDesc->fActQuery && fActDesc->fActQuery->fResult &&
fActDesc->fActQuery->fResult->GetOutputList()) {
fQueryFrame->UpdateHistos(fActDesc->fActQuery->fResult->GetOutputList());
fQueryFrame->ResetProgressDialog("", 0, 0, 0);
}
else if (fActDesc->fActQuery) {
fQueryFrame->ResetProgressDialog(fActDesc->fActQuery->fSelectorString,
fActDesc->fActQuery->fNbFiles,
fActDesc->fActQuery->fFirstEntry,
fActDesc->fActQuery->fNoEntries);
}
fQueryFrame->UpdateInfos();
}
//______________________________________________________________________________
Bool_t TSessionViewer::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
// Handle messages send to the TSessionViewer object. E.g. all menu entries
// messages.
TNewQueryDlg *dlg;
switch (GET_MSG(msg)) {
case kC_COMMAND:
switch (GET_SUBMSG(msg)) {
case kCM_BUTTON:
case kCM_MENU:
switch (parm1) {
case kFileCloseViewer:
CloseWindow();
break;
case kFileLoadConfig:
{
TGFileInfo fi;
fi.fFilename = (char *)gSystem->BaseName(fConfigFile);
fi.fIniDir = strdup((char *)gSystem->HomeDirectory());
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), this, kFDOpen, &fi);
if (fi.fFilename) {
fConfigFile = fi.fFilename;
ReadConfiguration(fConfigFile);
OnListTreeClicked(fSessionHierarchy->GetSelected(), 1, 0, 0);
}
}
break;
case kFileSaveConfig:
{
TGFileInfo fi;
fi.fFilename = (char *)gSystem->BaseName(fConfigFile);
fi.fIniDir = strdup((char *)gSystem->HomeDirectory());
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), this, kFDSave, &fi);
if (fi.fFilename) {
fConfigFile = fi.fFilename;
WriteConfiguration(fConfigFile);
}
}
break;
case kFileQuit:
Terminate();
if (!gApplication->ReturnFromRun())
delete this;
gApplication->Terminate(0);
break;
case kSessionNew:
fServerFrame->OnBtnNewServerClicked();
break;
case kSessionAdd:
fServerFrame->OnBtnAddClicked();
break;
case kSessionDelete:
fServerFrame->OnBtnDeleteClicked();
break;
case kSessionCleanup:
CleanupSession();
break;
case kSessionReset:
ResetSession();
break;
case kSessionConnect:
fServerFrame->OnBtnConnectClicked();
break;
case kSessionDisconnect:
fSessionFrame->OnBtnDisconnectClicked();
break;
case kSessionShutdown:
fSessionFrame->ShutdownSession();
break;
case kSessionShowStatus:
ShowStatus();
break;
case kSessionGetQueries:
fSessionFrame->OnBtnGetQueriesClicked();
break;
case kQueryNew:
dlg = new TNewQueryDlg(this, 350, 310);
dlg->Popup();
break;
case kQueryEdit:
EditQuery();
break;
case kQueryDelete:
DeleteQuery();
break;
case kQueryStartViewer:
StartViewer();
break;
case kQuerySubmit:
fQueryFrame->OnBtnSubmit();
break;
case kOptionsAutoSave:
if(fOptionsMenu->IsEntryChecked(kOptionsAutoSave)) {
fOptionsMenu->UnCheckEntry(kOptionsAutoSave);
fAutoSave = kFALSE;
}
else {
fOptionsMenu->CheckEntry(kOptionsAutoSave);
fAutoSave = kTRUE;
}
break;
case kOptionsStatsHist:
if(fOptionsMenu->IsEntryChecked(kOptionsStatsHist)) {
fOptionsMenu->UnCheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 1);
}
break;
case kOptionsStatsTrace:
if(fOptionsMenu->IsEntryChecked(kOptionsStatsTrace)) {
fOptionsMenu->UnCheckEntry(kOptionsStatsTrace);
gEnv->SetValue("Proof.StatsTrace", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsStatsTrace);
gEnv->SetValue("Proof.StatsTrace", 1);
}
break;
case kOptionsSlaveStatsTrace:
if(fOptionsMenu->IsEntryChecked(kOptionsSlaveStatsTrace)) {
fOptionsMenu->UnCheckEntry(kOptionsSlaveStatsTrace);
gEnv->SetValue("Proof.SlaveStatsTrace", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsSlaveStatsTrace);
gEnv->SetValue("Proof.SlaveStatsTrace", 1);
}
break;
case kOptionsFeedback:
if(fOptionsMenu->IsEntryChecked(kOptionsFeedback)) {
fOptionsMenu->UnCheckEntry(kOptionsFeedback);
}
else {
fOptionsMenu->CheckEntry(kOptionsFeedback);
}
break;
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
if (fCascadeMenu->IsEntryChecked(parm1)) {
fCascadeMenu->UnCheckEntry(parm1);
}
else {
fCascadeMenu->CheckEntry(parm1);
}
OnCascadeMenu();
break;
case 50:
if (fCascadeMenu->IsEntryChecked(parm1)) {
fCascadeMenu->UnCheckEntry(parm1);
}
else {
fCascadeMenu->CheckEntry(parm1);
}
OnCascadeMenu();
break;
case kHelpAbout:
{
#ifdef R__UNIX
TString rootx;
# ifdef ROOTBINDIR
rootx = ROOTBINDIR;
# else
rootx = gSystem->Getenv("ROOTSYS");
if (!rootx.IsNull()) rootx += "/bin";
# endif
rootx += "/root -a &";
gSystem->Exec(rootx);
#else
#ifdef WIN32
new TWin32SplashThread(kTRUE);
#else
char str[32];
sprintf(str, "About ROOT %s...", gROOT->GetVersion());
TRootHelpDialog *hd = new TRootHelpDialog(this, str, 600, 400);
hd->SetText(gHelpAbout);
hd->Popup();
#endif
#endif
}
break;
default:
break;
}
default:
break;
}
default:
break;
}
return kTRUE;
}
From Bertrand:
Change default parent parameter in TSessionViewer ctor,
to be able to embed it.
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@19536 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/sessionviewer:$Name: $:$Id: TSessionViewer.cxx,v 1.13 2007/06/21 15:42:50 pcanal Exp $
// Author: Marek Biskup, Jakub Madejczyk, Bertrand Bellenot 10/08/2005
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TSessionViewer //
// //
// Widget used to manage PROOF or local sessions, PROOF connections, //
// queries construction and results handling. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TApplication.h"
#include "TROOT.h"
#include "THashList.h"
#include "TClass.h"
#include "TSystem.h"
#include "TGFileDialog.h"
#include "TBrowser.h"
#include "TGButton.h"
#include "TGLayout.h"
#include "TGListTree.h"
#include "TGCanvas.h"
#include "TGLabel.h"
#include "TGTextEntry.h"
#include "TGNumberEntry.h"
#include "TGTableLayout.h"
#include "TGComboBox.h"
#include "TGSplitter.h"
#include "TGProgressBar.h"
#include "TGListView.h"
#include "TGMsgBox.h"
#include "TGMenu.h"
#include "TGStatusBar.h"
#include "TGIcon.h"
#include "TChain.h"
#include "TDSet.h"
#include "TFileInfo.h"
#include "TProof.h"
#include "TRandom.h"
#include "TSessionViewer.h"
#include "TSessionLogView.h"
#include "TQueryResult.h"
#include "TGTextView.h"
#include "TGMenu.h"
#include "TGToolBar.h"
#include "TGTab.h"
#include "TRootEmbeddedCanvas.h"
#include "TCanvas.h"
#include "TGMimeTypes.h"
#include "TInterpreter.h"
#include "TContextMenu.h"
#include "TG3DLine.h"
#include "TSessionDialogs.h"
#include "TEnv.h"
#include "TH2.h"
#include "TTreePlayer.h"
#ifdef WIN32
#include "TWin32SplashThread.h"
#endif
TSessionViewer *gSessionViewer = 0;
const char *kConfigFile = ".proofgui.conf";
ClassImp(TQueryDescription)
ClassImp(TSessionDescription)
ClassImp(TSessionServerFrame)
ClassImp(TSessionFrame)
ClassImp(TSessionQueryFrame)
ClassImp(TSessionOutputFrame)
ClassImp(TSessionInputFrame)
ClassImp(TSessionViewer)
const char *xpm_names[] = {
"monitor01.xpm",
"monitor02.xpm",
"monitor03.xpm",
"monitor04.xpm",
0
};
const char *conftypes[] = {
"Config files", "*.conf",
"All files", "*.*",
0, 0
};
const char *pkgtypes[] = {
"Package files", "*.par",
"All files", "*.*",
0, 0
};
const char *macrotypes[] = {
"C files", "*.[C|c]*",
"All files", "*",
0, 0
};
const char *kFeedbackHistos[] = {
"PROOF_PacketsHist",
"PROOF_EventsHist",
"PROOF_NodeHist",
"PROOF_LatencyHist",
"PROOF_ProcTimeHist",
"PROOF_CpuTimeHist",
0
};
const char* const kSession_RedirectFile = ".templog";
const char* const kSession_RedirectCmd = ".tempcmd";
// Menu command id's
enum ESessionViewerCommands {
kFileLoadConfig,
kFileSaveConfig,
kFileCloseViewer,
kFileQuit,
kSessionNew,
kSessionAdd,
kSessionDelete,
kSessionGetQueries,
kSessionConnect,
kSessionDisconnect,
kSessionShutdown,
kSessionCleanup,
kSessionBrowse,
kSessionShowStatus,
kSessionReset,
kQueryNew,
kQueryEdit,
kQueryDelete,
kQuerySubmit,
kQueryStartViewer,
kOptionsAutoSave,
kOptionsStatsHist,
kOptionsStatsTrace,
kOptionsSlaveStatsTrace,
kOptionsFeedback,
kHelpAbout
};
const char *xpm_toolbar[] = {
"fileopen.xpm",
"filesaveas.xpm",
"",
"connect.xpm",
"disconnect.xpm",
"",
"query_new.xpm",
"query_submit.xpm",
"",
"about.xpm",
"",
"quit.xpm",
0
};
ToolBarData_t tb_data[] = {
{ "", "Open Config File", kFALSE, kFileLoadConfig, 0 },
{ "", "Save Config File", kFALSE, kFileSaveConfig, 0 },
{ "", 0, 0, -1, 0 },
{ "", "Connect", kFALSE, kSessionConnect, 0 },
{ "", "Disconnect", kFALSE, kSessionDisconnect, 0 },
{ "", 0, 0, -1, 0 },
{ "", "New Query", kFALSE, kQueryNew, 0 },
{ "", "Submit Query", kFALSE, kQuerySubmit, 0 },
{ "", 0, 0, -1, 0 },
{ "", "About Root", kFALSE, kHelpAbout, 0 },
{ "", 0, 0, -1, 0 },
{ "", "Exit Root", kFALSE, kFileQuit, 0 },
{ 0, 0, 0, 0, 0 }
};
////////////////////////////////////////////////////////////////////////////////
// Server Frame
//______________________________________________________________________________
TSessionServerFrame::TSessionServerFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fFrmNewServer(0), fTxtName(0), fTxtAddress(0),
fTxtConfig(0), fTxtUsrName(0), fViewer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionServerFrame::~TSessionServerFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionServerFrame::Build(TSessionViewer *gui)
{
// Build server configuration frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fViewer = gui;
fFrmNewServer = new TGGroupFrame(this, "New Session");
fFrmNewServer->SetCleanup(kDeepCleanup);
AddFrame(fFrmNewServer, new TGLayoutHints(kLHintsExpandX, 2, 2, 2, 2));
fFrmNewServer->SetLayoutManager(new TGMatrixLayout(fFrmNewServer, 0, 2, 8));
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Session Name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtName = new TGTextEntry(fFrmNewServer,
(const char *)0, 1), new TGLayoutHints());
fTxtName->Resize(156, fTxtName->GetDefaultHeight());
fTxtName->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Server name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtAddress = new TGTextEntry(fFrmNewServer,
(const char *)0, 2), new TGLayoutHints());
fTxtAddress->Resize(156, fTxtAddress->GetDefaultHeight());
fTxtAddress->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Port (default: 1093):"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fNumPort = new TGNumberEntry(fFrmNewServer, 1093, 5,
3, TGNumberFormat::kNESInteger,TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0, 65535),new TGLayoutHints());
fNumPort->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Configuration File:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtConfig = new TGTextEntry(fFrmNewServer,
(const char *)0, 4), new TGLayoutHints());
fTxtConfig->Resize(156, fTxtConfig->GetDefaultHeight());
fTxtConfig->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Log Level:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fLogLevel = new TGNumberEntry(fFrmNewServer, 0, 5, 5,
TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax, 0, 5),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fLogLevel->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "User Name:"),
new TGLayoutHints(kLHintsLeft, 3, 3, 3, 3));
fFrmNewServer->AddFrame(fTxtUsrName = new TGTextEntry(fFrmNewServer,
(const char *)0, 6), new TGLayoutHints());
fTxtUsrName->Resize(156, fTxtUsrName->GetDefaultHeight());
fTxtUsrName->Associate(this);
fFrmNewServer->AddFrame(new TGLabel(fFrmNewServer, "Process mode :"),
new TGLayoutHints(kLHintsLeft | kLHintsBottom | kLHintsExpandX,
3, 3, 3, 3));
fFrmNewServer->AddFrame(fSync = new TGCheckButton(fFrmNewServer,
"&Synchronous"), new TGLayoutHints(kLHintsLeft | kLHintsBottom |
kLHintsExpandX, 3, 3, 3, 3));
fSync->SetToolTipText("Default Process Mode");
fSync->SetState(kButtonDown);
AddFrame(fBtnAdd = new TGTextButton(this, " Save "),
new TGLayoutHints(kLHintsTop | kLHintsCenterX, 5, 5, 15, 5));
fBtnAdd->SetToolTipText("Add server to the list");
fBtnAdd->Connect("Clicked()", "TSessionServerFrame", this,
"OnBtnAddClicked()");
AddFrame(fBtnConnect = new TGTextButton(this, " Connect "),
new TGLayoutHints(kLHintsTop | kLHintsCenterX, 5, 5, 15, 5));
fBtnConnect->Connect("Clicked()", "TSessionServerFrame", this,
"OnBtnConnectClicked()");
fBtnConnect->SetToolTipText("Connect to the selected server");
fTxtConfig->Connect("DoubleClicked()", "TSessionServerFrame", this,
"OnConfigFileClicked()");
fTxtName->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtAddress->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtConfig->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fTxtUsrName->Connect("TextChanged(char*)", "TSessionServerFrame", this,
"SettingsChanged()");
fSync->Connect("Clicked()", "TSessionServerFrame", this,
"SettingsChanged()");
fLogLevel->Connect("ValueChanged(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fLogLevel->Connect("ValueSet(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fNumPort->Connect("ValueChanged(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
fNumPort->Connect("ValueSet(Long_t)", "TSessionServerFrame", this,
"SettingsChanged()");
}
//______________________________________________________________________________
void TSessionServerFrame::SettingsChanged()
{
// Settings have changed, update GUI accordingly.
TGTextEntry *sender = dynamic_cast<TGTextEntry*>((TQObject*)gTQSender);
Bool_t issync = (fSync->GetState() == kButtonDown);
if ((fViewer->GetActDesc()->fLocal) ||
(strcmp(fViewer->GetActDesc()->GetName(), fTxtName->GetText())) ||
(strcmp(fViewer->GetActDesc()->fAddress.Data(), fTxtAddress->GetText())) ||
(strcmp(fViewer->GetActDesc()->fConfigFile.Data(), fTxtConfig->GetText())) ||
(strcmp(fViewer->GetActDesc()->fUserName.Data(), fTxtUsrName->GetText())) ||
(fViewer->GetActDesc()->fLogLevel != fLogLevel->GetIntNumber()) ||
(fViewer->GetActDesc()->fPort != fNumPort->GetIntNumber()) ||
(fViewer->GetActDesc()->fSync != issync)) {
ShowFrame(fBtnAdd);
HideFrame(fBtnConnect);
}
else {
HideFrame(fBtnAdd);
ShowFrame(fBtnConnect);
}
if (sender) {
sender->SetFocus();
}
}
//______________________________________________________________________________
Bool_t TSessionServerFrame::HandleExpose(Event_t * /*event*/)
{
// Handle expose event in server frame.
//fTxtName->SelectAll();
//fTxtName->SetFocus();
return kTRUE;
}
//______________________________________________________________________________
void TSessionServerFrame::OnConfigFileClicked()
{
// Browse configuration files.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
TGFileInfo fi;
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), fViewer, kFDOpen, &fi);
if (!fi.fFilename) return;
fTxtConfig->SetText(gSystem->BaseName(fi.fFilename));
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnDeleteClicked()
{
// Delete selected session configuration (remove it from the list).
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
TString name(fTxtName->GetText());
TIter next(fViewer->GetSessions());
TSessionDescription *desc = fViewer->GetActDesc();
if (desc->fLocal) {
Int_t retval;
new TGMsgBox(fClient->GetRoot(), this, "Error Deleting Session",
"Deleting Local Sessions is not allowed !",
kMBIconExclamation,kMBOk,&retval);
return;
}
// ask for confirmation
TString m;
m.Form("Are you sure to delete the server \"%s\"",
desc->fName.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBOk | kMBCancel, &result);
// if confirmed, delete it
if (result == kMBOk) {
// remove the Proof session from gROOT list of Proofs
if (desc->fConnected && desc->fAttached && desc->fProof) {
desc->fProof->Detach("S");
}
// remove it from our sessions list
fViewer->GetSessions()->Remove((TObject *)desc);
// update configuration file
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
fViewer->GetSessionHierarchy()->DeleteItem(item);
TObject *obj = fViewer->GetSessions()->Last();
item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), (void *)obj);
if (item) {
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(item);
fViewer->GetSessionHierarchy()->HighlightItem(item);
fViewer->GetSessionHierarchy()->SetSelected(item);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->OnListTreeClicked(item, 1, 0, 0);
}
}
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnConnectClicked()
{
// Connect to selected server.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if (!fViewer->GetSessions()->FindObject(fTxtName->GetText())) {
OnBtnAddClicked();
}
else {
fViewer->GetActDesc()->fAddress = fTxtAddress->GetText();
fViewer->GetActDesc()->fPort = fNumPort->GetIntNumber();
if (strlen(fTxtConfig->GetText()) > 1)
fViewer->GetActDesc()->fConfigFile = TString(fTxtConfig->GetText());
else
fViewer->GetActDesc()->fConfigFile = "";
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fUserName = fTxtUsrName->GetText();
fViewer->GetActDesc()->fSync = (fSync->GetState() == kButtonDown);
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
// set flag busy
fViewer->SetBusy();
// avoid input events in list tree while connecting
fViewer->GetSessionHierarchy()->RemoveInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone, kFALSE);
// set watch cursor to indicate connection in progress
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(),
gVirtualX->CreateCursor(kWatch));
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
// display connection progress bar in first part of status bar
fViewer->GetStatusBar()->GetBarPart(0)->ShowFrame(fViewer->GetConnectProg());
// connect to proof startup message (to update progress bar)
TQObject::Connect("TProof", "StartupMessage(char *,Bool_t,Int_t,Int_t)",
"TSessionViewer", fViewer, "StartupMessage(char *,Bool_t,Int_t,Int_t)");
// collect and set-up configuration
TString url = fTxtUsrName->GetText();
url += "@"; url += fTxtAddress->GetText();
if (fNumPort->GetIntNumber() > 0) {
url += ":";
url += fNumPort->GetIntNumber();
}
TProofDesc *desc;
fViewer->GetActDesc()->fProofMgr = TProofMgr::Create(url);
if (!fViewer->GetActDesc()->fProofMgr->IsValid()) {
// hide connection progress bar from status bar
fViewer->GetStatusBar()->GetBarPart(0)->HideFrame(fViewer->GetConnectProg());
// release busy flag
fViewer->SetBusy(kFALSE);
// restore cursors and input
gVirtualX->SetCursor(GetId(), 0);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone);
fViewer->GetSessionHierarchy()->AddInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(), 0);
return;
}
fViewer->UpdateListOfSessions();
// check if the session already exist before to recreate it
TList *sessions = fViewer->GetActDesc()->fProofMgr->QuerySessions("");
if (sessions) {
TIter nextp(sessions);
// loop over existing Proof sessions
while ((desc = (TProofDesc *)nextp())) {
if ((desc->GetName() == fViewer->GetActDesc()->fTag) ||
(desc->GetTitle() == fViewer->GetActDesc()->fName)) {
fViewer->GetActDesc()->fProof =
fViewer->GetActDesc()->fProofMgr->AttachSession(desc->GetLocalId(), kTRUE);
fViewer->GetActDesc()->fTag = desc->GetName();
fViewer->GetActDesc()->fProof->SetAlias(fViewer->GetActDesc()->fName);
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fAttached = kTRUE;
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fProof->AddFeedback(kFeedbackHistos[i]);
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
// connect feedback signal
fViewer->GetActDesc()->fProof->Connect("Feedback(TList *objs)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Feedback(TList *objs)");
gROOT->Time();
}
else {
// if feedback option not selected, clear Proof's feedback option
fViewer->GetActDesc()->fProof->ClearFeedback();
}
break;
}
}
}
if (fViewer->GetActDesc()->fProof == 0) {
if (fViewer->GetActDesc()->fProofMgr->IsValid()) {
fViewer->GetActDesc()->fProof = fViewer->GetActDesc()->fProofMgr->CreateSession(
fViewer->GetActDesc()->fConfigFile);
sessions = fViewer->GetActDesc()->fProofMgr->QuerySessions("");
desc = (TProofDesc *)sessions->Last();
if (desc) {
fViewer->GetActDesc()->fProof->SetAlias(fViewer->GetActDesc()->fName);
fViewer->GetActDesc()->fTag = desc->GetName();
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fAttached = kTRUE;
}
}
}
if (fViewer->GetActDesc()->fProof) {
fViewer->GetActDesc()->fConfigFile = fViewer->GetActDesc()->fProof->GetConfFile();
fViewer->GetActDesc()->fUserName = fViewer->GetActDesc()->fProof->GetUser();
fViewer->GetActDesc()->fPort = fViewer->GetActDesc()->fProof->GetPort();
fViewer->GetActDesc()->fLogLevel = fViewer->GetActDesc()->fProof->GetLogLevel();
if (fViewer->GetActDesc()->fLogLevel < 0)
fViewer->GetActDesc()->fLogLevel = 0;
fViewer->GetActDesc()->fAddress = fViewer->GetActDesc()->fProof->GetMaster();
fViewer->GetActDesc()->fConnected = kTRUE;
fViewer->GetActDesc()->fProof->SetBit(TProof::kUsingSessionGui);
}
fViewer->UpdateListOfSessions();
// check if connected and valid
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
// set log level
fViewer->GetActDesc()->fProof->SetLogLevel(fViewer->GetActDesc()->fLogLevel);
// set query type (synch / asynch)
fViewer->GetActDesc()->fProof->SetQueryMode(fViewer->GetActDesc()->fSync ?
TProof::kSync : TProof::kAsync);
// set connected flag
fViewer->GetActDesc()->fConnected = kTRUE;
// change list tree item picture to connected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(),fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofConPict(), fViewer->GetProofConPict());
// update viewer
fViewer->OnListTreeClicked(item, 1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
// connect to progress related signals
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"IndicateStop(Bool_t)");
fViewer->GetActDesc()->fProof->Connect(
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
fViewer->EnableTimer();
// change status bar right icon to connected pixmap
fViewer->ChangeRightLogo("monitor01.xpm");
// do not animate yet
fViewer->SetChangePic(kFALSE);
// connect to signal "query result ready"
fViewer->GetActDesc()->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", fViewer, "QueryResultReady(char *)");
// display connection information on status bar
TString msg;
msg.Form("PROOF Cluster %s ready", fViewer->GetActDesc()->fName.Data());
fViewer->GetStatusBar()->SetText(msg.Data(), 1);
fViewer->GetSessionFrame()->ProofInfos();
fViewer->UpdateListOfPackages();
fViewer->GetSessionFrame()->UpdateListOfDataSets();
// Enable previously uploaded packages if in auto-enable mode
if (fViewer->GetActDesc()->fAutoEnable) {
TPackageDescription *package;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
if (!package->fEnabled) {
if (fViewer->GetActDesc()->fProof->EnablePackage(package->fName) != 0)
Error("Submit", "Enable package failed");
else {
package->fEnabled = kTRUE;
fViewer->GetSessionFrame()->UpdatePackages();
}
}
}
}
}
// hide connection progress bar from status bar
fViewer->GetStatusBar()->GetBarPart(0)->HideFrame(fViewer->GetConnectProg());
// release busy flag
fViewer->SetBusy(kFALSE);
// restore cursors and input
gVirtualX->SetCursor(GetId(), 0);
gVirtualX->GrabButton(fViewer->GetSessionHierarchy()->GetId(), kAnyButton,
kAnyModifier, kButtonPressMask | kButtonReleaseMask, kNone, kNone);
fViewer->GetSessionHierarchy()->AddInput(kPointerMotionMask |
kEnterWindowMask | kLeaveWindowMask | kKeyPressMask);
gVirtualX->SetCursor(fViewer->GetSessionHierarchy()->GetId(), 0);
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnNewServerClicked()
{
// Reset server configuration fields.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->HighlightItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->SetSelected(fViewer->GetSessionItem());
fViewer->OnListTreeClicked(fViewer->GetSessionItem(), 1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fTxtName->SetText("");
fTxtAddress->SetText("");
fTxtConfig->SetText("");
fNumPort->SetIntNumber(1093);
fLogLevel->SetIntNumber(0);
fTxtUsrName->SetText("");
}
//______________________________________________________________________________
void TSessionServerFrame::OnBtnAddClicked()
{
// Add newly created session configuration in the list of sessions.
Int_t retval;
Bool_t newSession = kTRUE;
TSessionDescription* desc = 0;
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if ((!fTxtName->GetBuffer()->GetTextLength()) ||
(!fTxtAddress->GetBuffer()->GetTextLength()) ||
(!fTxtUsrName->GetBuffer()->GetTextLength())) {
new TGMsgBox(fClient->GetRoot(), fViewer, "Error Adding Session",
"At least one required field is empty !",
kMBIconExclamation, kMBOk, &retval);
return;
}
TObject *obj = fViewer->GetSessions()->FindObject(fTxtName->GetText());
if (obj)
desc = dynamic_cast<TSessionDescription*>(obj);
if (desc) {
new TGMsgBox(fClient->GetRoot(), fViewer, "Adding Session",
Form("The session \"%s\" already exists ! Overwrite ?",
fTxtName->GetText()), kMBIconQuestion, kMBYes | kMBNo |
kMBCancel, &retval);
if (retval != kMBYes)
return;
newSession = kFALSE;
}
if (newSession) {
desc = new TSessionDescription();
desc->fName = fTxtName->GetText();
desc->fTag = "";
desc->fQueries = new TList();
desc->fPackages = new TList();
desc->fActQuery = 0;
desc->fProof = 0;
desc->fProofMgr = 0;
desc->fAutoEnable = kFALSE;
desc->fAddress = fTxtAddress->GetText();
desc->fPort = fNumPort->GetIntNumber();
desc->fConnected = kFALSE;
desc->fAttached = kFALSE;
desc->fLocal = kFALSE;
if (strlen(fTxtConfig->GetText()) > 1)
desc->fConfigFile = TString(fTxtConfig->GetText());
else
desc->fConfigFile = "";
desc->fLogLevel = fLogLevel->GetIntNumber();
desc->fUserName = fTxtUsrName->GetText();
desc->fSync = (fSync->GetState() == kButtonDown);
// add newly created session config to our session list
fViewer->GetSessions()->Add((TObject *)desc);
// save into configuration file
TGListTreeItem *item = fViewer->GetSessionHierarchy()->AddItem(
fViewer->GetSessionItem(), desc->fName.Data(),
fViewer->GetProofDisconPict(), fViewer->GetProofDisconPict());
fViewer->GetSessionHierarchy()->SetToolTipItem(item, "Proof Session");
item->SetUserData(desc);
fViewer->GetSessionHierarchy()->ClearHighlighted();
fViewer->GetSessionHierarchy()->OpenItem(fViewer->GetSessionItem());
fViewer->GetSessionHierarchy()->OpenItem(item);
fViewer->GetSessionHierarchy()->HighlightItem(item);
fViewer->GetSessionHierarchy()->SetSelected(item);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->OnListTreeClicked(item, 1, 0, 0);
}
else {
fViewer->GetActDesc()->fName = fTxtName->GetText();
fViewer->GetActDesc()->fAddress = fTxtAddress->GetText();
fViewer->GetActDesc()->fPort = fNumPort->GetIntNumber();
if (strlen(fTxtConfig->GetText()) > 1)
fViewer->GetActDesc()->fConfigFile = TString(fTxtConfig->GetText());
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fUserName = fTxtUsrName->GetText();
fViewer->GetActDesc()->fSync = (fSync->GetState() == kButtonDown);
TGListTreeItem *item2 = fViewer->GetSessionHierarchy()->GetSelected();
item2->SetUserData(fViewer->GetActDesc());
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
}
HideFrame(fBtnAdd);
ShowFrame(fBtnConnect);
if (fViewer->IsAutoSave())
fViewer->WriteConfiguration();
}
//______________________________________________________________________________
void TSessionServerFrame::Update(TSessionDescription* desc)
{
// Update fields with values from session description desc.
if (desc->fLocal) {
fTxtName->SetText("");
fTxtAddress->SetText("");
fNumPort->SetIntNumber(1093);
fTxtConfig->SetText("");
fTxtUsrName->SetText("");
fLogLevel->SetIntNumber(0);
return;
}
fTxtName->SetText(desc->fName);
fTxtAddress->SetText(desc->fAddress);
fNumPort->SetIntNumber(desc->fPort);
fLogLevel->SetIntNumber(desc->fLogLevel);
if (desc->fConfigFile.Length() > 1) {
fTxtConfig->SetText(desc->fConfigFile);
}
else {
fTxtConfig->SetText("");
}
fTxtUsrName->SetText(desc->fUserName);
}
//______________________________________________________________________________
Bool_t TSessionServerFrame::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
// Process messages for session server frame.
// Used to navigate between text entry fields.
switch (GET_MSG(msg)) {
case kC_TEXTENTRY:
switch (GET_SUBMSG(msg)) {
case kTE_ENTER:
case kTE_TAB:
switch (parm1) {
case 1: // session name
fTxtAddress->SelectAll();
fTxtAddress->SetFocus();
break;
case 2: // server address
fNumPort->GetNumberEntry()->SelectAll();
fNumPort->GetNumberEntry()->SetFocus();
break;
case 3: // port number
fTxtConfig->SelectAll();
fTxtConfig->SetFocus();
break;
case 4: // configuration file
fLogLevel->GetNumberEntry()->SelectAll();
fLogLevel->GetNumberEntry()->SetFocus();
break;
case 5: // log level
fTxtUsrName->SelectAll();
fTxtUsrName->SetFocus();
break;
case 6: // user name
fTxtName->SelectAll();
fTxtName->SetFocus();
break;
}
break;
default:
break;
}
break;
default:
break;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
// Session Frame
//______________________________________________________________________________
TSessionFrame::TSessionFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h)
{
// Constructor.
}
//______________________________________________________________________________
TSessionFrame::~TSessionFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionFrame::Build(TSessionViewer *gui)
{
// Build session frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fViewer = gui;
Int_t i,j;
// main session tab
fTab = new TGTab(this, 200, 200);
AddFrame(fTab, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 2, 2, 2));
// add "Status" tab element
TGCompositeFrame *tf = fTab->AddTab("Status");
fFA = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFA, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add first session information line
fInfoLine[0] = new TGLabel(fFA, " ");
fFA->AddFrame(fInfoLine[0], new TGLayoutHints(kLHintsCenterX |
kLHintsExpandX, 5, 5, 15, 5));
TGCompositeFrame* frmInfos = new TGHorizontalFrame(fFA, 350, 100);
frmInfos->SetLayoutManager(new TGTableLayout(frmInfos, 9, 2));
// add session information lines
j = 0;
for (i=0;i<17;i+=2) {
fInfoLine[i+1] = new TGLabel(frmInfos, " ");
frmInfos->AddFrame(fInfoLine[i+1], new TGTableLayoutHints(0, 1, j, j+1,
kLHintsLeft | kLHintsCenterY, 5, 5, 2, 2));
fInfoLine[i+2] = new TGLabel(frmInfos, " ");
frmInfos->AddFrame(fInfoLine[i+2], new TGTableLayoutHints(1, 2, j, j+1,
kLHintsLeft | kLHintsCenterY, 5, 5, 2, 2));
j++;
}
fFA->AddFrame(frmInfos, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY, 5, 5, 5, 5));
// add "new query" and "get queries" buttons
TGCompositeFrame* frmBut1 = new TGHorizontalFrame(fFA, 350, 100);
frmBut1->SetCleanup(kDeepCleanup);
frmBut1->AddFrame(fBtnNewQuery = new TGTextButton(frmBut1, "New Query..."),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5));
fBtnNewQuery->SetToolTipText("Open New Query Dialog");
frmBut1->AddFrame(fBtnGetQueries = new TGTextButton(frmBut1, " Get Queries "),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5));
fBtnGetQueries->SetToolTipText("Get List of Queries from the server");
fBtnShowLog = new TGTextButton(frmBut1, "Show log...");
fBtnShowLog->SetToolTipText("Show Session log (opens log window)");
frmBut1->AddFrame(fBtnShowLog, new TGLayoutHints(kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fFA->AddFrame(frmBut1, new TGLayoutHints(kLHintsLeft | kLHintsBottom |
kLHintsExpandX));
// add "Commands" tab element
tf = fTab->AddTab("Commands");
fFC = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFC, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add comand line label and text entry
TGCompositeFrame* frmCmd = new TGHorizontalFrame(fFC, 350, 100);
frmCmd->SetCleanup(kDeepCleanup);
frmCmd->AddFrame(new TGLabel(frmCmd, "Command Line :"),
new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 5, 5, 15, 5));
fCommandBuf = new TGTextBuffer(120);
frmCmd->AddFrame(fCommandTxt = new TGTextEntry(frmCmd,
fCommandBuf ),new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandX, 5, 5, 15, 5));
fFC->AddFrame(frmCmd, new TGLayoutHints(kLHintsExpandX, 5, 5, 10, 5));
// connect command line text entry to "return pressed" signal
fCommandTxt->Connect("ReturnPressed()", "TSessionFrame", this,
"OnCommandLine()");
// check box for option "clear view"
fClearCheck = new TGCheckButton(fFC, "Clear view after each command");
fFC->AddFrame(fClearCheck,new TGLayoutHints(kLHintsLeft | kLHintsTop,
10, 5, 5, 5));
fClearCheck->SetState(kButtonUp);
// add text view for redirected output
fFC->AddFrame(new TGLabel(fFC, "Output :"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 10, 5, 5, 5));
fInfoTextView = new TGTextView(fFC, 330, 150, "", kSunkenFrame |
kDoubleBorder);
fFC->AddFrame(fInfoTextView, new TGLayoutHints(kLHintsLeft |
kLHintsTop | kLHintsExpandX | kLHintsExpandY, 10, 10, 5, 5));
// add "Packages" tab element
tf = fTab->AddTab("Packages");
fFB = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFB, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing packages listbox and control buttons
TGCompositeFrame* frmcanvas = new TGHorizontalFrame(fFB, 350, 100);
// packages listbox
fLBPackages = new TGListBox(frmcanvas);
fLBPackages->Resize(80,150);
fLBPackages->SetMultipleSelections(kFALSE);
frmcanvas->AddFrame(fLBPackages, new TGLayoutHints(kLHintsExpandX |
kLHintsExpandY, 5, 5, 5, 5));
// control buttons frame
TGCompositeFrame* frmBut2 = new TGVerticalFrame(frmcanvas, 150, 100);
fChkMulti = new TGCheckButton(frmBut2, "Multiple Selection");
fChkMulti->SetToolTipText("Enable multiple selection in the package list");
frmBut2->AddFrame(fChkMulti, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
fBtnAdd = new TGTextButton(frmBut2, " Add... ");
fBtnAdd->SetToolTipText("Add a package to the list");
frmBut2->AddFrame(fBtnAdd,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRemove = new TGTextButton(frmBut2, "Remove");
fBtnRemove->SetToolTipText("Remove package from the list");
frmBut2->AddFrame(fBtnRemove,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnUp = new TGTextButton(frmBut2, "Move Up");
fBtnUp->SetToolTipText("Move package one step upward in the list");
frmBut2->AddFrame(fBtnUp,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnDown = new TGTextButton(frmBut2, "Move Down");
fBtnDown->SetToolTipText("Move package one step downward in the list");
frmBut2->AddFrame(fBtnDown,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
frmcanvas->AddFrame(frmBut2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY));
fFB->AddFrame(frmcanvas, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
TGCompositeFrame* frmLeg = new TGHorizontalFrame(fFB, 300, 100);
frmLeg->SetCleanup(kDeepCleanup);
TGPicture *pic1 = (TGPicture *)fClient->GetPicture("package.xpm");
TGIcon *icn1 = new TGIcon(frmLeg, pic1, pic1->GetWidth(), pic1->GetHeight());
frmLeg->AddFrame(icn1, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Local"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
TGPicture *pic2 = (TGPicture *)fClient->GetPicture("package_delete.xpm");
TGIcon *icn2 = new TGIcon(frmLeg, pic2, pic2->GetWidth(), pic2->GetHeight());
frmLeg->AddFrame(icn2, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Uploaded"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
TGPicture *pic3 = (TGPicture *)fClient->GetPicture("package_add.xpm");
TGIcon *icn3 = new TGIcon(frmLeg, pic3, pic3->GetWidth(), pic3->GetHeight());
frmLeg->AddFrame(icn3, new TGLayoutHints(kLHintsLeft | kLHintsTop,
5, 5, 0, 5));
frmLeg->AddFrame(new TGLabel(frmLeg, ": Enabled"),
new TGLayoutHints(kLHintsLeft | kLHintsTop, 0, 10, 0, 5));
fFB->AddFrame(frmLeg, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX, 0, 0, 0, 0));
TGCompositeFrame* frmBtn = new TGHorizontalFrame(fFB, 300, 100);
frmBtn->SetCleanup(kDeepCleanup);
frmBtn->AddFrame(fBtnUpload = new TGTextButton(frmBtn,
" Upload "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnUpload->SetToolTipText("Upload selected package(s) to the server");
frmBtn->AddFrame(fBtnEnable = new TGTextButton(frmBtn,
" Enable "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnEnable->SetToolTipText("Enable selected package(s) on the server");
frmBtn->AddFrame(fBtnDisable = new TGTextButton(frmBtn,
" Disable "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnDisable->SetToolTipText("Disable selected package(s) on the server");
frmBtn->AddFrame(fBtnClear = new TGTextButton(frmBtn,
" Clear "), new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsCenterY, 5, 5, 5, 5));
fBtnClear->SetToolTipText("Clear all packages on the server");
fFB->AddFrame(frmBtn, new TGLayoutHints(kLHintsExpandX, 0, 0, 0, 0));
fBtnClear->SetEnabled(kFALSE);
TGCompositeFrame* frmBtn3 = new TGHorizontalFrame(fFB, 300, 100);
frmBtn3->SetCleanup(kDeepCleanup);
fBtnShow = new TGTextButton(frmBtn3, "Show packages");
fBtnShow->SetToolTipText("Show (list) available packages on the server");
frmBtn3->AddFrame(fBtnShow,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnShowEnabled = new TGTextButton(frmBtn3, "Show Enabled");
fBtnShowEnabled->SetToolTipText("Show (list) enabled packages on the server");
frmBtn3->AddFrame(fBtnShowEnabled,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fFB->AddFrame(frmBtn3, new TGLayoutHints(kLHintsExpandX, 0, 0, 0, 0));
fChkEnable = new TGCheckButton(fFB, "Enable at session startup");
fChkEnable->SetToolTipText("Enable packages on the server at startup time");
fFB->AddFrame(fChkEnable, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// add "DataSets" tab element
tf = fTab->AddTab("DataSets");
fFE = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFE, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing datasets treeview and control buttons
TGCompositeFrame* frmdataset = new TGHorizontalFrame(fFE, 350, 100);
// datasets list tree
fDSetView = new TGCanvas(frmdataset, 200, 200, kSunkenFrame | kDoubleBorder);
frmdataset->AddFrame(fDSetView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
5, 5, 5, 5));
fDataSetTree = new TGListTree(fDSetView, kHorizontalFrame);
fDataSetTree->AddItem(0, "DataSets");
// control buttons frame
TGCompositeFrame* frmBut3 = new TGVerticalFrame(frmdataset, 150, 100);
fBtnUploadDSet = new TGTextButton(frmBut3, " Upload... ");
fBtnUploadDSet->SetToolTipText("Upload a dataset to the cluster");
frmBut3->AddFrame(fBtnUploadDSet, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRemoveDSet = new TGTextButton(frmBut3, "Remove");
fBtnRemoveDSet->SetToolTipText("Remove dataset from the cluster");
frmBut3->AddFrame(fBtnRemoveDSet,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnVerifyDSet = new TGTextButton(frmBut3, "Verify");
fBtnVerifyDSet->SetToolTipText("Verify dataset on the cluster");
frmBut3->AddFrame(fBtnVerifyDSet,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnRefresh = new TGTextButton(frmBut3, "Refresh List");
fBtnRefresh->SetToolTipText("Refresh List of DataSet/Files present on the cluster");
frmBut3->AddFrame(fBtnRefresh,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 15, 5));
frmdataset->AddFrame(frmBut3, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY, 5, 5, 5, 0));
fFE->AddFrame(frmdataset, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
// add "Options" tab element
tf = fTab->AddTab("Options");
fFD = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFD, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// add Log Level label and text entry
TGCompositeFrame* frmLog = new TGHorizontalFrame(fFD, 310, 100, kFixedWidth);
frmLog->SetCleanup(kDeepCleanup);
frmLog->AddFrame(fApplyLogLevel = new TGTextButton(frmLog,
" Apply "), new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 10, 5, 5, 5));
fApplyLogLevel->SetToolTipText("Apply currently selected log level");
fLogLevel = new TGNumberEntry(frmLog, 0, 5, 5, TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0, 5);
frmLog->AddFrame(fLogLevel, new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 5, 5, 5, 5));
frmLog->AddFrame(new TGLabel(frmLog, "Log Level :"),
new TGLayoutHints(kLHintsRight | kLHintsCenterY, 5, 5, 5, 5));
fFD->AddFrame(frmLog, new TGLayoutHints(kLHintsLeft, 5, 5, 15, 5));
// add Parallel Nodes label and text entry
TGCompositeFrame* frmPar = new TGHorizontalFrame(fFD, 310, 100, kFixedWidth);
frmPar->SetCleanup(kDeepCleanup);
frmPar->AddFrame(fApplyParallel = new TGTextButton(frmPar,
" Apply "), new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 10, 5, 5, 5));
fApplyParallel->SetToolTipText("Apply currently selected parallel nodes");
fTxtParallel = new TGTextEntry(frmPar);
fTxtParallel->SetAlignment(kTextRight);
fTxtParallel->SetText("99999");
fTxtParallel->Resize(fLogLevel->GetDefaultWidth(), fTxtParallel->GetDefaultHeight());
frmPar->AddFrame(fTxtParallel, new TGLayoutHints(kLHintsRight |
kLHintsCenterY, 5, 5, 5, 5));
frmPar->AddFrame(new TGLabel(frmPar, "Set Parallel Nodes :"),
new TGLayoutHints(kLHintsRight | kLHintsCenterY, 5, 5, 5, 5));
fFD->AddFrame(frmPar, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// connect button actions to functions
fBtnShowLog->Connect("Clicked()", "TSessionFrame", this,
"OnBtnShowLogClicked()");
fBtnNewQuery->Connect("Clicked()", "TSessionFrame", this,
"OnBtnNewQueryClicked()");
fBtnGetQueries->Connect("Clicked()", "TSessionFrame", this,
"OnBtnGetQueriesClicked()");
fChkEnable->Connect("Toggled(Bool_t)", "TSessionFrame", this,
"OnStartupEnable(Bool_t)");
fChkMulti->Connect("Toggled(Bool_t)", "TSessionFrame", this,
"OnMultipleSelection(Bool_t)");
fBtnAdd->Connect("Clicked()", "TSessionFrame", this,
"OnBtnAddClicked()");
fBtnRemove->Connect("Clicked()", "TSessionFrame", this,
"OnBtnRemoveClicked()");
fBtnUp->Connect("Clicked()", "TSessionFrame", this,
"OnBtnUpClicked()");
fBtnDown->Connect("Clicked()", "TSessionFrame", this,
"OnBtnDownClicked()");
fApplyLogLevel->Connect("Clicked()", "TSessionFrame", this,
"OnApplyLogLevel()");
fApplyParallel->Connect("Clicked()", "TSessionFrame", this,
"OnApplyParallel()");
fBtnUpload->Connect("Clicked()", "TSessionFrame", this,
"OnUploadPackages()");
fBtnEnable->Connect("Clicked()", "TSessionFrame", this,
"OnEnablePackages()");
fBtnDisable->Connect("Clicked()", "TSessionFrame", this,
"OnDisablePackages()");
fBtnClear->Connect("Clicked()", "TSessionFrame", this,
"OnClearPackages()");
fBtnShowEnabled->Connect("Clicked()", "TSessionViewer", fViewer,
"ShowEnabledPackages()");
fBtnShow->Connect("Clicked()", "TSessionViewer", fViewer,
"ShowPackages()");
fBtnUploadDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnUploadDSet()");
fBtnRemoveDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnRemoveDSet()");
fBtnVerifyDSet->Connect("Clicked()", "TSessionFrame", this,
"OnBtnVerifyDSet()");
fBtnRefresh->Connect("Clicked()", "TSessionFrame", this,
"UpdateListOfDataSets()");
}
//______________________________________________________________________________
void TSessionFrame::ProofInfos()
{
// Display informations on current session.
char buf[256];
// if local session
if (fViewer->GetActDesc()->fLocal) {
sprintf(buf, "*** Local Session on %s ***", gSystem->HostName());
fInfoLine[0]->SetText(buf);
UserGroup_t *userGroup = gSystem->GetUserInfo();
fInfoLine[1]->SetText("User :");
sprintf(buf, "%s", userGroup->fRealName.Data());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("Working directory :");
sprintf(buf, "%s", gSystem->WorkingDirectory());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText(" ");
fInfoLine[6]->SetText(" ");
fInfoLine[7]->SetText(" ");
fInfoLine[8]->SetText(" ");
fInfoLine[9]->SetText(" ");
fInfoLine[10]->SetText(" ");
fInfoLine[11]->SetText(" ");
fInfoLine[12]->SetText(" ");
fInfoLine[13]->SetText(" ");
fInfoLine[14]->SetText(" ");
fInfoLine[15]->SetText(" ");
fInfoLine[16]->SetText(" ");
fInfoLine[17]->SetText(" ");
fInfoLine[18]->SetText(" ");
delete userGroup;
Layout();
Resize(GetDefaultSize());
return;
}
// return if not a valid Proof session
if (!fViewer->GetActDesc()->fConnected ||
!fViewer->GetActDesc()->fAttached ||
!fViewer->GetActDesc()->fProof ||
!fViewer->GetActDesc()->fProof->IsValid())
return;
if (!fViewer->GetActDesc()->fProof->IsMaster()) {
if (fViewer->GetActDesc()->fProof->IsParallel())
sprintf(buf,"*** Connected to %s (parallel mode, %d workers) ***",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
else
sprintf(buf, "*** Connected to %s (sequential mode) ***",
fViewer->GetActDesc()->fProof->GetMaster());
fInfoLine[0]->SetText(buf);
fInfoLine[1]->SetText("Port number : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetPort());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("User : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetUser());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText("Client protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetClientProtocol());
fInfoLine[6]->SetText(buf);
fInfoLine[7]->SetText("Remote protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetRemoteProtocol());
fInfoLine[8]->SetText(buf);
fInfoLine[9]->SetText("Log level : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetLogLevel());
fInfoLine[10]->SetText(buf);
fInfoLine[11]->SetText("Session unique tag : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->IsValid() ?
fViewer->GetActDesc()->fProof->GetSessionTag() : " ");
fInfoLine[12]->SetText(buf);
fInfoLine[13]->SetText("Total MB's processed :");
sprintf(buf, "%.2f", float(fViewer->GetActDesc()->fProof->GetBytesRead())/(1024*1024));
fInfoLine[14]->SetText(buf);
fInfoLine[15]->SetText("Total real time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetRealTime());
fInfoLine[16]->SetText(buf);
fInfoLine[17]->SetText("Total CPU time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetCpuTime());
fInfoLine[18]->SetText(buf);
}
else {
if (fViewer->GetActDesc()->fProof->IsParallel())
sprintf(buf,"*** Master server %s (parallel mode, %d workers) ***",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
else
sprintf(buf, "*** Master server %s (sequential mode) ***",
fViewer->GetActDesc()->fProof->GetMaster());
fInfoLine[0]->SetText(buf);
fInfoLine[1]->SetText("Port number : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetPort());
fInfoLine[2]->SetText(buf);
fInfoLine[3]->SetText("User : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetUser());
fInfoLine[4]->SetText(buf);
fInfoLine[5]->SetText("Protocol version : ");
sprintf(buf, "%d", fViewer->GetActDesc()->fProof->GetClientProtocol());
fInfoLine[6]->SetText(buf);
fInfoLine[7]->SetText("Image name : ");
sprintf(buf, "%s",fViewer->GetActDesc()->fProof->GetImage());
fInfoLine[8]->SetText(buf);
fInfoLine[9]->SetText("Config directory : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetConfDir());
fInfoLine[10]->SetText(buf);
fInfoLine[11]->SetText("Config file : ");
sprintf(buf, "%s", fViewer->GetActDesc()->fProof->GetConfFile());
fInfoLine[12]->SetText(buf);
fInfoLine[13]->SetText("Total MB's processed :");
sprintf(buf, "%.2f", float(fViewer->GetActDesc()->fProof->GetBytesRead())/(1024*1024));
fInfoLine[14]->SetText(buf);
fInfoLine[15]->SetText("Total real time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetRealTime());
fInfoLine[16]->SetText(buf);
fInfoLine[17]->SetText("Total CPU time used (s) :");
sprintf(buf, "%.3f", fViewer->GetActDesc()->fProof->GetCpuTime());
fInfoLine[18]->SetText(buf);
}
Layout();
Resize(GetDefaultSize());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnUploadDSet()
{
// Open Upload Dataset dialog.
if (fViewer->IsBusy())
return;
if (fViewer->GetActDesc()->fLocal) return;
new TUploadDataSetDlg(fViewer, 450, 360);
}
//______________________________________________________________________________
void TSessionFrame::UpdateListOfDataSets()
{
// Update list of dataset present on the cluster.
TObjString *dsetname;
TFileInfo *dsetfilename;
// cleanup the list
fDataSetTree->DeleteChildren(fDataSetTree->GetFirstItem());
if (fViewer->GetActDesc()->fConnected && fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof && fViewer->GetActDesc()->fProof->IsValid() &&
fViewer->GetActDesc()->fProof->IsParallel()) {
const TGPicture *dseticon = fClient->GetPicture("rootdb_t.xpm");
// ask for the list of datasets
TList *dsetlist = fViewer->GetActDesc()->fProof->GetDataSets();
if(dsetlist) {
TGListTreeItem *dsetitem;
fDataSetTree->OpenItem(fDataSetTree->GetFirstItem());
TIter nextdset(dsetlist);
while ((dsetname = (TObjString *)nextdset())) {
if (!fDataSetTree->FindItemByObj(fDataSetTree->GetFirstItem(), dsetname)) {
// add the dataset in the tree
dsetitem = fDataSetTree->AddItem(fDataSetTree->GetFirstItem(),
dsetname->GetName(), dsetname);
// ask for the list of files in the dataset
TList *dsetfilelist = fViewer->GetActDesc()->fProof->GetDataSet(
dsetname->GetName());
if(dsetfilelist) {
TIter nextdsetfile(dsetfilelist);
while ((dsetfilename = (TFileInfo *)nextdsetfile())) {
if (! fDataSetTree->FindItemByObj(dsetitem, dsetfilename)) {
// if not already in, add the file name in the tree
fDataSetTree->AddItem(dsetitem,
dsetfilename->GetFirstUrl()->GetUrl(),
dsetfilename, dseticon, dseticon);
}
}
// open the dataset item in order to show the files
fDataSetTree->OpenItem(dsetitem);
}
}
}
}
}
// refresh list tree
fClient->NeedRedraw(fDataSetTree);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnRemoveDSet()
{
// Remove dataset from the list and from the cluster.
TGListTreeItem *item;
TObjString *obj = 0;
if (fViewer->GetActDesc()->fLocal) return;
item = fDataSetTree->GetSelected();
if (!item) return;
if (item->GetParent() == 0) return;
if (item->GetParent() == fDataSetTree->GetFirstItem()) {
// Dataset itself
obj = (TObjString *)item->GetUserData();
}
else if (item->GetParent()->GetParent() == fDataSetTree->GetFirstItem()) {
// One file of the dataset
obj = (TObjString *)item->GetParent()->GetUserData();
}
// if valid Proof session, set parallel slaves
if (obj && fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->RemoveDataSet(obj->GetName());
UpdateListOfDataSets();
}
}
//______________________________________________________________________________
void TSessionFrame::OnBtnVerifyDSet()
{
// Verify that the files in the selected dataset are present on the cluster.
TGListTreeItem *item;
TObjString *obj = 0;
if (fViewer->GetActDesc()->fLocal) return;
item = fDataSetTree->GetSelected();
if (!item) return;
if (item->GetParent() == 0) return;
if (item->GetParent() == fDataSetTree->GetFirstItem()) {
// Dataset itself
obj = (TObjString *)item->GetUserData();
}
else if (item->GetParent()->GetParent() == fDataSetTree->GetFirstItem()) {
// One file of the dataset
obj = (TObjString *)item->GetParent()->GetUserData();
}
// if valid Proof session, set parallel slaves
if (obj && fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->VerifyDataSet(obj->GetName());
}
}
//______________________________________________________________________________
void TSessionFrame::OnApplyLogLevel()
{
// Apply selected log level on current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, set log level
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fLogLevel = fLogLevel->GetIntNumber();
fViewer->GetActDesc()->fProof->SetLogLevel(fViewer->GetActDesc()->fLogLevel);
}
fViewer->GetSessionFrame()->ProofInfos();
}
//______________________________________________________________________________
void TSessionFrame::OnApplyParallel()
{
// Apply selected number of workers on current Proof session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, set parallel slaves
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
Int_t nodes = atoi(fTxtParallel->GetText());
fViewer->GetActDesc()->fProof->SetParallel(nodes);
}
fViewer->GetSessionFrame()->ProofInfos();
}
//______________________________________________________________________________
void TSessionFrame::OnMultipleSelection(Bool_t on)
{
// Handle multiple selection check button.
fLBPackages->SetMultipleSelections(on);
}
//______________________________________________________________________________
void TSessionFrame::OnStartupEnable(Bool_t on)
{
// Handle multiple selection check button.
if (fViewer->GetActDesc())
fViewer->GetActDesc()->fAutoEnable = on;
}
//______________________________________________________________________________
void TSessionFrame::UpdatePackages()
{
// Update list of packages.
TPackageDescription *package;
const TGPicture *pict;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnUploadPackages()
{
// Upload selected package(s) to the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, upload packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
if (fViewer->GetActDesc()->fProof->UploadPackage(name.Data()) != 0)
Error("Submit", "Upload package failed");
else {
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
package->fUploaded = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(
fClient->GetPicture("package_delete.xpm"));
}
}
}
UpdatePackages();
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnEnablePackages()
{
// Enable selected package(s) in the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, enable packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fBtnEnable->SetState(kButtonDisabled);
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
if (!package->fUploaded) {
if (fViewer->GetActDesc()->fProof->UploadPackage(name.Data()) != 0)
Error("Submit", "Upload package failed");
else {
package->fUploaded = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(
fClient->GetPicture("package_delete.xpm"));
}
}
}
if (fViewer->GetActDesc()->fProof->EnablePackage(name) != 0)
Error("Submit", "Enable package failed");
else {
package->fEnabled = kTRUE;
((TGIconLBEntry *)obj)->SetPicture(fClient->GetPicture("package_add.xpm"));
}
}
UpdatePackages();
fBtnEnable->SetState(kButtonUp);
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnDisablePackages()
{
// Disable selected package(s) in the current session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, disable (clear) packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TObject *obj;
TList selected;
fLBPackages->GetSelectedEntries(&selected);
TIter next(&selected);
while ((obj = next())) {
TString name = obj->GetTitle();
if (fViewer->GetActDesc()->fProof->ClearPackage(name) != 0)
Error("Submit", "Clear package failed");
else {
TObject *o = fViewer->GetActDesc()->fPackages->FindObject(gSystem->BaseName(name));
if (!o) continue;
TPackageDescription *package =
dynamic_cast<TPackageDescription *>(o);
if (package) {
package->fEnabled = kFALSE;
package->fUploaded = kFALSE;
((TGIconLBEntry *)obj)->SetPicture(fClient->GetPicture("package.xpm"));
}
}
}
UpdatePackages();
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnClearPackages()
{
// Clear (disable) all packages in the current session.
TPackageDescription *package;
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, clear packages
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
if (fViewer->GetActDesc()->fProof->ClearPackages() != 0)
Error("Submit", "Clear packages failed");
else {
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fEnabled = kFALSE;
}
}
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnAddClicked()
{
// Open file dialog and add selected package file to the list.
if (fViewer->IsBusy())
return;
TGFileInfo fi;
TPackageDescription *package;
TGIconLBEntry *entry;
fi.fFileTypes = pkgtypes;
new TGFileDialog(fClient->GetRoot(), fViewer, kFDOpen, &fi);
if (fi.fMultipleSelection && fi.fFileNamesList) {
TObjString *el;
TIter next(fi.fFileNamesList);
while ((el = (TObjString *) next())) {
package = new TPackageDescription;
package->fName = gSystem->BaseName(gSystem->UnixPathName(el->GetString()));
package->fPathName = gSystem->UnixPathName(el->GetString());
package->fId = fViewer->GetActDesc()->fPackages->GetEntries();
package->fUploaded = kFALSE;
package->fEnabled = kFALSE;
fViewer->GetActDesc()->fPackages->Add((TObject *)package);
entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName,
fClient->GetPicture("package.xpm"));
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
}
else if (fi.fFilename) {
package = new TPackageDescription;
package->fName = gSystem->BaseName(gSystem->UnixPathName(fi.fFilename));
package->fPathName = gSystem->UnixPathName(fi.fFilename);
package->fId = fViewer->GetActDesc()->fPackages->GetEntries();
package->fUploaded = kFALSE;
package->fEnabled = kFALSE;
fViewer->GetActDesc()->fPackages->Add((TObject *)package);
entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName,
fClient->GetPicture("package.xpm"));
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnRemoveClicked()
{
// Remove selected package from the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnUpClicked()
{
// Move selected package entry one position up in the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
if (pos <= 0) return;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
package = (TPackageDescription *)fViewer->GetActDesc()->fPackages->At(pos);
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
package->fId -= 1;
fViewer->GetActDesc()->fPackages->AddAt(package, package->fId);
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Select(pos-1);
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnDownClicked()
{
// Move selected package entry one position down in the list.
TPackageDescription *package;
const TGPicture *pict;
Int_t pos = fLBPackages->GetSelected();
if (pos == -1 || pos == fViewer->GetActDesc()->fPackages->GetEntries()-1)
return;
fLBPackages->RemoveEntries(0, fLBPackages->GetNumberOfEntries());
package = (TPackageDescription *)fViewer->GetActDesc()->fPackages->At(pos);
fViewer->GetActDesc()->fPackages->Remove(
fViewer->GetActDesc()->fPackages->At(pos));
package->fId += 1;
fViewer->GetActDesc()->fPackages->AddAt(package, package->fId);
Int_t id = 0;
TIter next(fViewer->GetActDesc()->fPackages);
while ((package = (TPackageDescription *)next())) {
package->fId = id;
id++;
if (package->fEnabled)
pict = fClient->GetPicture("package_add.xpm");
else if (package->fUploaded)
pict = fClient->GetPicture("package_delete.xpm");
else
pict = fClient->GetPicture("package.xpm");
TGIconLBEntry *entry = new TGIconLBEntry(fLBPackages->GetContainer(),
package->fId, package->fPathName, pict);
fLBPackages->AddEntry(entry, new TGLayoutHints(kLHintsExpandX | kLHintsTop));
}
fLBPackages->Select(pos+1);
fLBPackages->Layout();
fClient->NeedRedraw(fLBPackages->GetContainer());
}
//______________________________________________________________________________
void TSessionFrame::OnBtnDisconnectClicked()
{
// Disconnect from current Proof session.
// if local session, do nothing
if (fViewer->GetActDesc()->fLocal) return;
// if valid Proof session, disconnect (close)
if (fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Detach();
}
// reset connected flag
fViewer->GetActDesc()->fAttached = kFALSE;
fViewer->GetActDesc()->fProof = 0;
// disable animation timer
fViewer->DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofDisconPict(),
fViewer->GetProofDisconPict());
// update viewer
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->GetStatusBar()->SetText("", 1);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnShowLogClicked()
{
// Show session log.
fViewer->ShowLog(0);
}
//______________________________________________________________________________
void TSessionFrame::OnBtnNewQueryClicked()
{
// Call "New Query" Dialog.
TNewQueryDlg *dlg = new TNewQueryDlg(fViewer, 350, 310);
dlg->Popup();
}
//______________________________________________________________________________
void TSessionFrame::OnBtnGetQueriesClicked()
{
// Get list of queries from current Proof server and populate the list tree.
TList *lqueries = 0;
TQueryResult *query = 0;
TQueryDescription *newquery = 0, *lquery = 0;
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
lqueries = fViewer->GetActDesc()->fProof->GetListOfQueries();
}
if (lqueries) {
TIter nextp(lqueries);
// loop over list of queries received from Proof server
while ((query = (TQueryResult *)nextp())) {
// create new query description
newquery = new TQueryDescription();
newquery->fReference = Form("%s:%s", query->GetTitle(),
query->GetName());
// check in our tree if it is already there
TGListTreeItem *item =
fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
// if already there, skip
if (fViewer->GetSessionHierarchy()->FindChildByName(item,
newquery->fReference.Data()))
continue;
// check also in our query description list
Bool_t found = kFALSE;
TIter nextp(fViewer->GetActDesc()->fQueries);
while ((lquery = (TQueryDescription *)nextp())) {
if (lquery->fReference.CompareTo(newquery->fReference) == 0) {
found = kTRUE;
break;
}
}
if (found) continue;
// build new query description with infos from Proof
newquery->fStatus = query->IsFinalized() ?
TQueryDescription::kSessionQueryFinalized :
(TQueryDescription::ESessionQueryStatus)query->GetStatus();
newquery->fSelectorString = query->GetSelecImp()->GetName();
newquery->fQueryName = Form("%s:%s", query->GetTitle(),
query->GetName());
newquery->fOptions = query->GetOptions();
newquery->fEventList = "";
newquery->fNbFiles = 0;
newquery->fNoEntries = query->GetEntries();
newquery->fFirstEntry = query->GetFirst();
newquery->fResult = query;
newquery->fChain = 0;
fViewer->GetActDesc()->fQueries->Add((TObject *)newquery);
TGListTreeItem *item2 = fViewer->GetSessionHierarchy()->AddItem(item,
newquery->fQueryName, fViewer->GetQueryConPict(),
fViewer->GetQueryConPict());
item2->SetUserData(newquery);
if (query->GetInputList())
fViewer->GetSessionHierarchy()->AddItem(item2, "InputList");
if (query->GetOutputList())
fViewer->GetSessionHierarchy()->AddItem(item2, "OutputList");
}
}
// at the end, update list tree
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
}
//______________________________________________________________________________
void TSessionFrame::OnCommandLine()
{
// Command line handling.
// get command string
const char *cmd = fCommandTxt->GetText();
char opt[2];
// form temporary file path
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectCmd);
// if check box "clear view" is checked, open temp file in write mode
// (overwrite), in append mode otherwise.
if (fClearCheck->IsOn())
sprintf(opt, "w");
else
sprintf(opt, "a");
// if valid Proof session, pass the command to Proof
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), opt) != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
// execute command line
fViewer->GetActDesc()->fProof->Exec(cmd);
// restore back stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
// if check box "clear view" is checked, clear text view
if (fClearCheck->IsOn())
fInfoTextView->Clear();
// load (display) temp file in text view
fInfoTextView->LoadFile(pathtmp.Data());
// set focus to "command line" text entry
fCommandTxt->SetFocus();
}
else {
// if no Proof session, or Proof session not valid,
// lets execute command line by TApplication
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), opt) != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
}
// execute command line
gApplication->ProcessLine(cmd);
// restore back stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
}
// if check box "clear view" is checked, clear text view
if (fClearCheck->IsOn())
fInfoTextView->Clear();
// load (display) temp file in text view
fInfoTextView->LoadFile(pathtmp.Data());
// set focus to "command line" text entry
fCommandTxt->SetFocus();
}
// display bottom of text view
fInfoTextView->ShowBottom();
}
//______________________________________________________________________________
void TSessionFrame::SetLocal(Bool_t local)
{
// Switch widgets status/visibility for local/remote sessions.
if (local) {
fBtnGetQueries->SetState(kButtonDisabled);
fBtnShowLog->SetState(kButtonDisabled);
fTab->HideFrame(fTab->GetTabTab("Options"));
fTab->HideFrame(fTab->GetTabTab("Packages"));
fTab->HideFrame(fTab->GetTabTab("DataSets"));
}
else {
fBtnGetQueries->SetState(kButtonUp);
fBtnShowLog->SetState(kButtonUp);
fTab->ShowFrame(fTab->GetTabTab("Options"));
fTab->ShowFrame(fTab->GetTabTab("Packages"));
fTab->ShowFrame(fTab->GetTabTab("DataSets"));
}
}
//______________________________________________________________________________
void TSessionFrame::ShutdownSession()
{
// Shutdown current session.
// do nothing if connection in progress
if (fViewer->IsBusy())
return;
if (fViewer->GetActDesc()->fLocal) {
Int_t retval;
new TGMsgBox(fClient->GetRoot(), this, "Error Shutting down Session",
"Shutting down Local Sessions is not allowed !",
kMBIconExclamation,kMBOk,&retval);
return;
}
if (!fViewer->GetActDesc()->fAttached ||
!fViewer->GetActDesc()->fProof ||
!fViewer->GetActDesc()->fProof->IsValid())
return;
// ask for confirmation
TString m;
m.Form("Are you sure to shutdown the session \"%s\"",
fViewer->GetActDesc()->fName.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBOk | kMBCancel, &result);
// if confirmed, delete it
if (result != kMBOk)
return;
// remove the Proof session from gROOT list of Proofs
fViewer->GetActDesc()->fProof->Detach("S");
// reset connected flag
fViewer->GetActDesc()->fAttached = kFALSE;
fViewer->GetActDesc()->fProof = 0;
// disable animation timer
fViewer->DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fViewer->GetSessionHierarchy()->FindChildByData(
fViewer->GetSessionItem(), fViewer->GetActDesc());
item->SetPictures(fViewer->GetProofDisconPict(),
fViewer->GetProofDisconPict());
// update viewer
fViewer->OnListTreeClicked(fViewer->GetSessionHierarchy()->GetSelected(),
1, 0, 0);
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fViewer->GetStatusBar()->SetText("", 1);
}
//////////////////////////////////////////////////////////////////////////
// Edit Query Frame
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TEditQueryFrame::TEditQueryFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h, kVerticalFrame)
{
// Create a new Query dialog, used by the Session Viewer, to Edit a Query if
// the editmode flag is set, or to create a new one if not set.
}
//______________________________________________________________________________
TEditQueryFrame::~TEditQueryFrame()
{
// Delete query dialog.
Cleanup();
}
//______________________________________________________________________________
void TEditQueryFrame::Build(TSessionViewer *gui)
{
// Build the "new query" dialog.
TGButton *btnTmp;
fViewer = gui;
SetCleanup(kDeepCleanup);
SetLayoutManager(new TGTableLayout(this, 6, 5));
// add "Query Name" label and text entry
AddFrame(new TGLabel(this, "Query Name :"),
new TGTableLayoutHints(0, 1, 0, 1, kLHintsCenterY, 5, 5, 4, 0));
AddFrame(fTxtQueryName = new TGTextEntry(this,
(const char *)0, 1), new TGTableLayoutHints(1, 2, 0, 1,
kLHintsCenterY, 5, 5, 4, 0));
// add "TChain" label and text entry
AddFrame(new TGLabel(this, "TChain :"),
new TGTableLayoutHints(0, 1, 1, 2, kLHintsCenterY, 5, 5, 4, 0));
AddFrame(fTxtChain = new TGTextEntry(this,
(const char *)0, 2), new TGTableLayoutHints(1, 2, 1, 2,
kLHintsCenterY, 5, 5, 4, 0));
fTxtChain->SetToolTipText("Specify TChain or TDSet from memory or file");
fTxtChain->SetEnabled(kFALSE);
// add "Browse" button
AddFrame(btnTmp = new TGTextButton(this, "Browse..."),
new TGTableLayoutHints(2, 3, 1, 2, kLHintsCenterY, 5, 0, 4, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseChain()");
// add "Selector" label and text entry
AddFrame(new TGLabel(this, "Selector :"),
new TGTableLayoutHints(0, 1, 2, 3, kLHintsCenterY, 5, 5, 0, 0));
AddFrame(fTxtSelector = new TGTextEntry(this,
(const char *)0, 3), new TGTableLayoutHints(1, 2, 2, 3,
kLHintsCenterY, 5, 5, 0, 0));
// add "Browse" button
AddFrame(btnTmp = new TGTextButton(this, "Browse..."),
new TGTableLayoutHints(2, 3, 2, 3, kLHintsCenterY, 5, 0, 0, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseSelector()");
// add "Less <<" ("More >>") button
AddFrame(fBtnMore = new TGTextButton(this, " Less << "),
new TGTableLayoutHints(2, 3, 4, 5, kLHintsCenterY, 5, 5, 4, 0));
fBtnMore->Connect("Clicked()", "TEditQueryFrame", this, "OnNewQueryMore()");
// add (initially hidden) options frame
fFrmMore = new TGCompositeFrame(this, 200, 200);
fFrmMore->SetCleanup(kDeepCleanup);
AddFrame(fFrmMore, new TGTableLayoutHints(0, 3, 5, 6,
kLHintsExpandX | kLHintsExpandY));
fFrmMore->SetLayoutManager(new TGTableLayout(fFrmMore, 4, 3));
// add "Options" label and text entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Options :"),
new TGTableLayoutHints(0, 1, 0, 1, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fTxtOptions = new TGTextEntry(fFrmMore,
(const char *)0, 4), new TGTableLayoutHints(1, 2, 0, 1, 0, 17,
0, 0, 8));
fTxtOptions->SetText("ASYN");
// add "Nb Entries" label and number entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Nb Entries :"),
new TGTableLayoutHints(0, 1, 1, 2, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fNumEntries = new TGNumberEntry(fFrmMore, 0, 5, -1,
TGNumberFormat::kNESInteger, TGNumberFormat::kNEAAnyNumber,
TGNumberFormat::kNELNoLimits), new TGTableLayoutHints(1, 2, 1, 2,
0, 17, 0, 0, 8));
fNumEntries->SetIntNumber(-1);
// add "First Entry" label and number entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "First entry :"),
new TGTableLayoutHints(0, 1, 2, 3, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fNumFirstEntry = new TGNumberEntry(fFrmMore, 0, 5, -1,
TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits), new TGTableLayoutHints(1, 2, 2, 3, 0,
17, 0, 0, 8));
// add "Event list" label and text entry
fFrmMore->AddFrame(new TGLabel(fFrmMore, "Event list :"),
new TGTableLayoutHints(0, 1, 3, 4, kLHintsCenterY, 5, 5, 0, 0));
fFrmMore->AddFrame(fTxtEventList = new TGTextEntry(fFrmMore,
(const char *)0, 6), new TGTableLayoutHints(1, 2, 3, 4, 0, 17,
5, 0, 0));
// add "Browse" button
fFrmMore->AddFrame(btnTmp = new TGTextButton(fFrmMore, "Browse..."),
new TGTableLayoutHints(2, 3, 3, 4, 0, 6, 0, 0, 8));
btnTmp->Connect("Clicked()", "TEditQueryFrame", this, "OnBrowseEventList()");
fTxtQueryName->Associate(this);
fTxtChain->Associate(this);
fTxtSelector->Associate(this);
fTxtOptions->Associate(this);
fNumEntries->Associate(this);
fNumFirstEntry->Associate(this);
fTxtEventList->Associate(this);
fTxtQueryName->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtChain->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtSelector->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtOptions->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
fNumEntries->Connect("ValueChanged(Long_t)", "TEditQueryFrame", this,
"SettingsChanged()");
fNumFirstEntry->Connect("ValueChanged(Long_t)", "TEditQueryFrame", this,
"SettingsChanged()");
fTxtEventList->Connect("TextChanged(char*)", "TEditQueryFrame", this,
"SettingsChanged()");
}
//______________________________________________________________________________
void TEditQueryFrame::OnNewQueryMore()
{
// Show/hide options frame and update button text accordingly.
if (IsVisible(fFrmMore)) {
HideFrame(fFrmMore);
fBtnMore->SetText(" More >> ");
}
else {
ShowFrame(fFrmMore);
fBtnMore->SetText(" Less << ");
}
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseChain()
{
// Call new chain dialog.
TNewChainDlg *dlg = new TNewChainDlg(fClient->GetRoot(), this);
dlg->Connect("OnElementSelected(TObject *)", "TEditQueryFrame",
this, "OnElementSelected(TObject *)");
}
//____________________________________________________________________________
void TEditQueryFrame::OnElementSelected(TObject *obj)
{
// Handle OnElementSelected signal coming from new chain dialog.
if (obj) {
fChain = obj;
if (obj->IsA() == TChain::Class())
fTxtChain->SetText(((TChain *)fChain)->GetName());
else if (obj->IsA() == TDSet::Class())
fTxtChain->SetText(((TDSet *)fChain)->GetObjName());
}
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseSelector()
{
// Open file browser to choose selector macro.
TGFileInfo fi;
fi.fFileTypes = macrotypes;
new TGFileDialog(fClient->GetRoot(), this, kFDOpen, &fi);
if (!fi.fFilename) return;
fTxtSelector->SetText(gSystem->UnixPathName(fi.fFilename));
}
//______________________________________________________________________________
void TEditQueryFrame::OnBrowseEventList()
{
//Browse event list
}
//______________________________________________________________________________
void TEditQueryFrame::OnBtnSave()
{
// Save current settings in main session viewer.
// if we are in edition mode and query description is valid,
// use it, otherwise create a new one
TQueryDescription *newquery;
if (fQuery)
newquery = fQuery;
else
newquery = new TQueryDescription();
// update query description fields
newquery->fSelectorString = fTxtSelector->GetText();
if (fChain) {
newquery->fTDSetString = fChain->GetName();
newquery->fChain = fChain;
}
else {
newquery->fTDSetString = "";
newquery->fChain = 0;
}
newquery->fQueryName = fTxtQueryName->GetText();
newquery->fOptions = fTxtOptions->GetText();
newquery->fNoEntries = fNumEntries->GetIntNumber();
newquery->fFirstEntry = fNumFirstEntry->GetIntNumber();
newquery->fNbFiles = 0;
newquery->fResult = 0;
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class())
newquery->fNbFiles = ((TChain *)newquery->fChain)->GetListOfFiles()->GetEntriesFast();
else if (newquery->fChain->IsA() == TDSet::Class())
newquery->fNbFiles = ((TDSet *)newquery->fChain)->GetListOfElements()->GetSize();
}
// update user data with modified query description
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
fViewer->GetSessionHierarchy()->RenameItem(item, newquery->fQueryName);
item->SetUserData(newquery);
// update list tree
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
fTxtQueryName->SelectAll();
fTxtQueryName->SetFocus();
fViewer->WriteConfiguration();
fViewer->GetQueryFrame()->Modified(kFALSE);
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fConnected &&
fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
fViewer->GetQueryFrame()->GetTab()->SetTab("Status");
fViewer->GetQueryFrame()->OnBtnSubmit();
}
}
//______________________________________________________________________________
void TEditQueryFrame::SettingsChanged()
{
// Settings have changed, update GUI accordingly.
if (fQuery) {
if ((strcmp(fQuery->fSelectorString.Data(), fTxtSelector->GetText())) ||
(strcmp(fQuery->fQueryName.Data(), fTxtQueryName->GetText())) ||
(strcmp(fQuery->fOptions.Data(), fTxtOptions->GetText())) ||
(fQuery->fNoEntries != fNumEntries->GetIntNumber()) ||
(fQuery->fFirstEntry != fNumFirstEntry->GetIntNumber()) ||
(fQuery->fChain != fChain)) {
fViewer->GetQueryFrame()->Modified(kTRUE);
}
else {
fViewer->GetQueryFrame()->Modified(kFALSE);
}
}
else {
if ((fTxtQueryName->GetText()) &&
((fTxtQueryName->GetText()) ||
(fTxtChain->GetText())))
fViewer->GetQueryFrame()->Modified(kTRUE);
else
fViewer->GetQueryFrame()->Modified(kFALSE);
}
}
//______________________________________________________________________________
void TEditQueryFrame::UpdateFields(TQueryDescription *desc)
{
// Update entry fields with query description values.
fChain = 0;
fQuery = desc;
fTxtChain->SetText("");
if (desc->fChain) {
fChain = desc->fChain;
fTxtChain->SetText(desc->fTDSetString);
}
fTxtQueryName->SetText(desc->fQueryName);
fTxtSelector->SetText(desc->fSelectorString);
fTxtOptions->SetText(desc->fOptions);
fNumEntries->SetIntNumber(desc->fNoEntries);
fNumFirstEntry->SetIntNumber(desc->fFirstEntry);
fTxtEventList->SetText(desc->fEventList);
}
////////////////////////////////////////////////////////////////////////////////
// Query Frame
//______________________________________________________________________________
TSessionQueryFrame::TSessionQueryFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h)
{
// Constructor
}
//______________________________________________________________________________
TSessionQueryFrame::~TSessionQueryFrame()
{
// Destructor.
Cleanup();
}
//______________________________________________________________________________
void TSessionQueryFrame::Build(TSessionViewer *gui)
{
// Build query informations frame.
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
fFirst = fEntries = fPrevTotal = 0;
fPrevProcessed = 0;
fViewer = gui;
fModified = kFALSE;
// main query tab
fTab = new TGTab(this, 200, 200);
AddFrame(fTab, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 2, 2, 2));
// add "Status" tab element
TGCompositeFrame *tf = fTab->AddTab("Status");
fFB = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFB, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// new frame containing control buttons and feedback histos canvas
TGCompositeFrame* frmcanvas = new TGHorizontalFrame(fFB, 350, 100);
// control buttons frame
TGCompositeFrame* frmBut2 = new TGVerticalFrame(frmcanvas, 150, 100);
fBtnSubmit = new TGTextButton(frmBut2, " Submit ");
fBtnSubmit->SetToolTipText("Submit (process) selected query");
frmBut2->AddFrame(fBtnSubmit,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnStop = new TGTextButton(frmBut2, "Stop");
fBtnStop->SetToolTipText("Stop processing query");
frmBut2->AddFrame(fBtnStop,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
fBtnAbort = new TGTextButton(frmBut2, "Abort");
fBtnAbort->SetToolTipText("Abort processing query");
frmBut2->AddFrame(fBtnAbort,new TGLayoutHints(kLHintsCenterY | kLHintsLeft |
kLHintsExpandX, 5, 5, 5, 5));
frmcanvas->AddFrame(frmBut2, new TGLayoutHints(kLHintsLeft | kLHintsCenterY |
kLHintsExpandY));
// feedback histos embedded canvas
fECanvas = new TRootEmbeddedCanvas("fECanvas", frmcanvas, 400, 150);
fStatsCanvas = fECanvas->GetCanvas();
fStatsCanvas->SetFillColor(10);
fStatsCanvas->SetBorderMode(0);
frmcanvas->AddFrame(fECanvas, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
fFB->AddFrame(frmcanvas, new TGLayoutHints(kLHintsLeft | kLHintsTop |
kLHintsExpandX | kLHintsExpandY));
// progress infos label
fLabInfos = new TGLabel(fFB, " ");
fFB->AddFrame(fLabInfos, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// progress status label
fLabStatus = new TGLabel(fFB, " ");
fFB->AddFrame(fLabStatus, new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
//progress bar
frmProg = new TGHProgressBar(fFB, TGProgressBar::kFancy, 350 - 20);
frmProg->ShowPosition();
frmProg->SetBarColor("green");
fFB->AddFrame(frmProg, new TGLayoutHints(kLHintsExpandX, 5, 5, 5, 5));
// total progress infos
fFB->AddFrame(fTotal = new TGLabel(fFB,
" Estimated time left : 00:00:00 (--- events of --- processed) "),
new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// progress rate infos
fFB->AddFrame(fRate = new TGLabel(fFB,
" Processing Rate : -- events/sec "),
new TGLayoutHints(kLHintsLeft, 5, 5, 5, 5));
// add "Results" tab element
tf = fTab->AddTab("Results");
fFC = new TGCompositeFrame(tf, 100, 100, kVerticalFrame);
tf->AddFrame(fFC, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX | kLHintsExpandY));
// query result (header) information text view
fInfoTextView = new TGTextView(fFC, 330, 185, "", kSunkenFrame |
kDoubleBorder);
fFC->AddFrame(fInfoTextView, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandY | kLHintsExpandX, 5, 5, 10, 10));
// add "Retrieve", "Finalize" and "Show Log" buttons
TGCompositeFrame* frmBut3 = new TGHorizontalFrame(fFC, 350, 100);
fBtnRetrieve = new TGTextButton(frmBut3, "Retrieve");
fBtnRetrieve->SetToolTipText("Retrieve query results");
frmBut3->AddFrame(fBtnRetrieve,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fBtnFinalize = new TGTextButton(frmBut3, "Finalize");
fBtnFinalize->SetToolTipText("Finalize query");
frmBut3->AddFrame(fBtnFinalize,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fBtnShowLog = new TGTextButton(frmBut3, "Show Log");
fBtnShowLog->SetToolTipText("Show query log (open log window)");
frmBut3->AddFrame(fBtnShowLog,new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 5, 5, 10, 10));
fFC->AddFrame(frmBut3, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandX));
// add "Results" tab element
tf = fTab->AddTab("Edit Query");
fFD = new TEditQueryFrame(tf, 100, 100);
fFD->Build(fViewer);
tf->AddFrame(fFD, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 10, 0));
TString btntxt;
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
btntxt = " Submit ";
}
else {
btntxt = " Apply changes ";
}
tf->AddFrame(fBtnSave = new TGTextButton(tf, btntxt),
new TGLayoutHints(kLHintsTop | kLHintsLeft, 10, 5, 25, 5));
// connect button actions to functions
fBtnSave->Connect("Clicked()", "TEditQueryFrame", fFD,
"OnBtnSave()");
fBtnSubmit->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnSubmit()");
fBtnFinalize->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnFinalize()");
fBtnStop->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnStop()");
fBtnAbort->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnAbort()");
fBtnShowLog->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnShowLog()");
fBtnRetrieve->Connect("Clicked()", "TSessionQueryFrame", this,
"OnBtnRetrieve()");
// fBtnSave->SetState(kButtonDisabled);
Resize(350, 310);
}
//______________________________________________________________________________
void TSessionQueryFrame::Modified(Bool_t mod)
{
// Notify changes in query editor settings.
fModified = mod;
if (fModified) {
fBtnSave->SetState(kButtonUp);
}
else {
fBtnSave->SetState(kButtonDisabled);
}
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()))
fBtnSave->SetState(kButtonUp);
}
//______________________________________________________________________________
void TSessionQueryFrame::Feedback(TList *objs)
{
// Feedback function connected to Feedback signal.
// Used to update feedback histograms.
// if no actual session, just return
if (!fViewer->GetActDesc()->fAttached)
return;
if (!fViewer->GetActDesc()->fProof)
return;
if ((fViewer->GetActDesc()->fActQuery) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQuerySubmitted) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQueryRunning) )
return;
TProof *sender = dynamic_cast<TProof*>((TQObject*)gTQSender);
// if Proof sender match actual session one, update feedback histos
if (sender && (sender == fViewer->GetActDesc()->fProof))
UpdateHistos(objs);
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateHistos(TList *objs)
{
// Update feedback histograms.
TVirtualPad *save = gPad;
TObject *o;
Int_t pos = 1;
Int_t i = 0;
while (kFeedbackHistos[i]) {
// check if user has selected this histogram in the option menu
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
if ( (o = objs->FindObject(kFeedbackHistos[i]))) {
fStatsCanvas->cd(pos);
gPad->SetEditable(kTRUE);
if (TH1 *h = dynamic_cast<TH1*>(o)) {
h->SetStats(0);
h->SetBarWidth(0.75);
h->SetBarOffset(0.125);
h->SetFillColor(9);
h->Draw("bar");
pos++;
}
else if (TH2 *h2 = dynamic_cast<TH2*>(o)) {
h2->Draw();
pos++;
}
gPad->Modified();
}
}
i++;
}
// update canvas
fStatsCanvas->cd();
fStatsCanvas->Modified();
fStatsCanvas->Update();
if (save != 0) {
save->cd();
} else {
gPad = 0;
}
}
//______________________________________________________________________________
void TSessionQueryFrame::Progress(Long64_t total, Long64_t processed)
{
// Update progress bar and status labels.
// if no actual session, just return
if (!fViewer->GetActDesc()->fProof)
return;
// if Proof sender does't match actual session one, return
TProof *sender = dynamic_cast<TProof*>((TQObject*)gTQSender);
if (!sender || (sender != fViewer->GetActDesc()->fProof))
return;
if ((fViewer->GetActDesc()->fActQuery) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQuerySubmitted) &&
(fViewer->GetActDesc()->fActQuery->fStatus !=
TQueryDescription::kSessionQueryRunning) ) {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
return;
}
if (total < 0)
total = fPrevTotal;
else
fPrevTotal = total;
// if no change since last call, just return
if (fPrevProcessed == processed)
return;
char *buf;
// Update informations at first call
if (fEntries != total) {
buf = Form("PROOF cluster : \"%s\" - %d worker nodes",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
fLabInfos->SetText(buf);
fEntries = total;
buf = Form(" %d files, %lld events, starting event %lld",
fFiles, fEntries, fFirst);
fLabStatus->SetText(buf);
}
// compute progress bar position and update
Float_t pos = (Float_t)((Double_t)(processed * 100)/(Double_t)total);
frmProg->SetPosition(pos);
// if 100%, stop animation and set icon to "connected"
if (pos >= 100.0) {
fViewer->SetChangePic(kFALSE);
fViewer->ChangeRightLogo("monitor01.xpm");
}
// get current time
if ((fViewer->GetActDesc()->fActQuery->fStatus ==
TQueryDescription::kSessionQueryRunning) ||
(fViewer->GetActDesc()->fActQuery->fStatus ==
TQueryDescription::kSessionQuerySubmitted))
fViewer->GetActDesc()->fActQuery->fEndTime = gSystem->Now();
TTime tdiff = fViewer->GetActDesc()->fActQuery->fEndTime -
fViewer->GetActDesc()->fActQuery->fStartTime;
Float_t eta = 0;
if (processed)
eta = ((Float_t)((Long_t)tdiff)*total/Float_t(processed) -
Long_t(tdiff))/1000.;
if (processed == total) {
// finished
buf = Form(" Processed : %lld events in %.1f sec", total, Long_t(tdiff)/1000.);
fTotal->SetText(buf);
} else {
// update status infos
buf = Form(" Estimated time left : %.1f sec (%lld events of %lld processed) ",
eta, processed, total);
fTotal->SetText(buf);
}
if (processed > 0 && (Long_t)tdiff > 0) {
buf = Form(" Processing Rate : %.1f events/sec ",
(Float_t)processed/(Long_t)tdiff*1000.);
fRate->SetText(buf);
}
fPrevProcessed = processed;
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::Progress(Long64_t total, Long64_t processed,
Long64_t /*bytesread*/ , Float_t /*initTime*/,
Float_t /*procTime*/, Float_t /*evtrti*/,
Float_t /*mbrti*/)
{
// New version of Progress (just forward to the old version
// for the time being).
Progress(total, processed);
}
//______________________________________________________________________________
void TSessionQueryFrame::ProgressLocal(Long64_t total, Long64_t processed)
{
// Update progress bar and status labels.
char cproc[80];
Int_t status;
switch (fViewer->GetActDesc()->fActQuery->fStatus) {
case TQueryDescription::kSessionQueryAborted:
strcpy(cproc, " - ABORTED");
status = kAborted;
break;
case TQueryDescription::kSessionQueryStopped:
strcpy(cproc, " - STOPPED");
status = kStopped;
break;
case TQueryDescription::kSessionQueryRunning:
strcpy(cproc, " ");
status = kRunning;
break;
case TQueryDescription::kSessionQueryCompleted:
case TQueryDescription::kSessionQueryFinalized:
strcpy(cproc, " ");
status = kDone;
break;
default:
status = -1;
break;
}
if (processed < 0) processed = 0;
frmProg->SetBarColor("green");
if (status == kAborted)
frmProg->SetBarColor("red");
else if (status == kStopped)
frmProg->SetBarColor("yellow");
else if (status == -1 ) {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
return;
}
if (total < 0)
total = fPrevTotal;
else
fPrevTotal = total;
// if no change since last call, just return
char *buf;
// Update informations at first call
if (fEntries != total) {
fLabInfos->SetText("Local Session");
fEntries = total;
buf = Form(" %d files, %lld events, starting event %lld",
fFiles, fEntries, fFirst);
fLabStatus->SetText(buf);
}
// compute progress bar position and update
Float_t pos = 0.0;
if (processed > 0 && total > 0)
pos = (Float_t)((Double_t)(processed * 100)/(Double_t)total);
frmProg->SetPosition(pos);
// if 100%, stop animation and set icon to "connected"
if (pos >= 100.0) {
fViewer->SetChangePic(kFALSE);
fViewer->ChangeRightLogo("monitor01.xpm");
}
// get current time
if (status == kRunning)
fViewer->GetActDesc()->fActQuery->fEndTime = gSystem->Now();
TTime tdiff = fViewer->GetActDesc()->fActQuery->fEndTime -
fViewer->GetActDesc()->fActQuery->fStartTime;
Float_t eta = 0;
if (processed)
eta = ((Float_t)((Long_t)tdiff)*total/(Float_t)(processed) -
(Long_t)(tdiff))/1000.;
if ((processed != total) && (status == kRunning)) {
// update status infos
buf = Form(" Estimated time left : %.1f sec (%lld events of %lld processed) ",
eta, processed, total);
fTotal->SetText(buf);
} else {
buf = Form(" Processed : %ld events in %.1f sec", (Long_t)processed,
(Long_t)tdiff/1000.0);
strcat(buf, cproc);
fTotal->SetText(buf);
}
if (processed > 0 && (Long_t)tdiff > 0) {
buf = Form(" Processing Rate : %.1f events/sec ",
(Float_t)processed/(Long_t)tdiff*1000.);
fRate->SetText(buf);
}
fPrevProcessed = processed;
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::IndicateStop(Bool_t aborted)
{
// Indicate that Cancel or Stop was clicked.
if (aborted == kTRUE) {
// Aborted
frmProg->SetBarColor("red");
}
else {
// Stopped
frmProg->SetBarColor("yellow");
}
// disconnect progress related signals
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Disconnect("Progress(Long64_t,Long64_t)",
this, "Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Disconnect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
this, "Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Disconnect("StopProcess(Bool_t)", this,
"IndicateStop(Bool_t)");
}
}
//______________________________________________________________________________
void TSessionQueryFrame::ResetProgressDialog(const char * /*selector*/, Int_t files,
Long64_t first, Long64_t entries)
{
// Reset progress frame information fields.
char *buf;
fFiles = files > 0 ? files : 0;
fFirst = first;
fEntries = entries;
fPrevProcessed = 0;
fPrevTotal = 0;
if (!fViewer->GetActDesc()->fLocal) {
frmProg->SetBarColor("green");
frmProg->Reset();
}
buf = Form("%0d files, %0lld events, starting event %0lld",
fFiles > 0 ? fFiles : 0, fEntries > 0 ? fEntries : 0,
fFirst >= 0 ? fFirst : 0);
fLabStatus->SetText(buf);
// Reconnect the slots
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", this, "Progress(Long64_t,Long64_t)");
fViewer->GetActDesc()->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", this,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fViewer->GetActDesc()->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", this, "IndicateStop(Bool_t)");
sprintf(buf, "PROOF cluster : \"%s\" - %d worker nodes",
fViewer->GetActDesc()->fProof->GetMaster(),
fViewer->GetActDesc()->fProof->GetParallel());
fLabInfos->SetText(buf);
}
else if (fViewer->GetActDesc()->fLocal) {
fStatsCanvas->Clear();
fLabInfos->SetText("Local Session");
fLabStatus->SetText(" ");
}
else {
fLabInfos->SetText(" ");
fLabStatus->SetText(" ");
}
fFB->Layout();
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnFinalize()
{
// Finalize query.
// check if Proof is valid
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
gPad->SetEditable(kFALSE);
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
// as it can take time, set watch cursor
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
TQueryDescription *query = (TQueryDescription *)obj;
fViewer->GetActDesc()->fProof->Finalize(query->fReference);
UpdateButtons(query);
// restore cursor
gVirtualX->SetCursor(GetId(), 0);
}
}
if (fViewer->GetActDesc()->fLocal) {
gPad->SetEditable(kFALSE);
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain)
((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile()->Terminate();
}
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnStop()
{
// Stop processing query.
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->StopProcess(kFALSE);
}
if (fViewer->GetActDesc()->fLocal) {
gROOT->SetInterrupt();
fViewer->GetActDesc()->fActQuery->fStatus =
TQueryDescription::kSessionQueryStopped;
}
// stop icon animation and set connected icon
fViewer->ChangeRightLogo("monitor01.xpm");
fViewer->SetChangePic(kFALSE);
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnShowLog()
{
// Show query log.
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *query = (TQueryDescription *)obj;
fViewer->ShowLog(query->fReference.Data());
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnRetrieve()
{
// Retrieve query.
// check for proof validity
if (fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
// as it can take time, set watch cursor
gVirtualX->SetCursor(GetId(), gVirtualX->CreateCursor(kWatch));
TQueryDescription *query = (TQueryDescription *)obj;
Int_t rc = fViewer->GetActDesc()->fProof->Retrieve(query->fReference);
if (rc == 0)
fViewer->OnCascadeMenu();
// restore cursor
gVirtualX->SetCursor(GetId(), 0);
}
}
if (fViewer->GetActDesc()->fLocal) {
TGListTreeItem *item=0, *item2=0;
item = fViewer->GetSessionHierarchy()->FindItemByObj(fViewer->GetSessionItem(),
fViewer->GetActDesc());
if (item) {
item2 = fViewer->GetSessionHierarchy()->FindItemByObj(item,
fViewer->GetActDesc()->fActQuery);
}
if (item2) {
// add input and output list entries
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain) {
TSelector *selector = ((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile();
if (selector) {
TList *objlist = selector->GetOutputList();
if (objlist)
if (!fViewer->GetSessionHierarchy()->FindChildByName(item2, "OutputList"))
fViewer->GetSessionHierarchy()->AddItem(item2, "OutputList");
}
}
}
// update list tree, query frame informations, and buttons state
fClient->NeedRedraw(fViewer->GetSessionHierarchy());
UpdateInfos();
UpdateButtons(fViewer->GetActDesc()->fActQuery);
}
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnAbort()
{
// Abort processing query.
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->StopProcess(kTRUE);
}
if (fViewer->GetActDesc()->fLocal) {
gROOT->SetInterrupt();
fViewer->GetActDesc()->fActQuery->fStatus =
TQueryDescription::kSessionQueryAborted;
}
// stop icon animation and set connected icon
fViewer->ChangeRightLogo("monitor01.xpm");
fViewer->SetChangePic(kFALSE);
}
//______________________________________________________________________________
void TSessionQueryFrame::OnBtnSubmit()
{
// Submit query.
Int_t retval;
Long64_t id = 0;
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
// retrieve query description attached to list tree item
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *newquery = (TQueryDescription *)obj;
// reset progress informations
ResetProgressDialog(newquery->fSelectorString,
newquery->fNbFiles, newquery->fFirstEntry, newquery->fNoEntries);
// set query start time
newquery->fStartTime = gSystem->Now();
fViewer->GetActDesc()->fNbHistos = 0;
// check for proof validity
if (fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) {
fViewer->GetActDesc()->fProof->SetBit(TProof::kUsingSessionGui);
// set query description status to submitted
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
// if feedback option selected
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fProof->AddFeedback(kFeedbackHistos[i]);
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
// connect feedback signal
fViewer->GetActDesc()->fProof->Connect("Feedback(TList *objs)",
"TSessionQueryFrame", fViewer->GetQueryFrame(),
"Feedback(TList *objs)");
gROOT->Time();
}
else {
// if feedback option not selected, clear Proof's feedback option
fViewer->GetActDesc()->fProof->ClearFeedback();
}
// set current proof session
fViewer->GetActDesc()->fProof->cd();
// check if parameter file has been specified
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class()) {
// TChain case
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
((TChain *)newquery->fChain)->SetProof(fViewer->GetActDesc()->fProof);
id = ((TChain *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries > 0 ? newquery->fNoEntries : 1234567890,
newquery->fFirstEntry);
}
else if (newquery->fChain->IsA() == TDSet::Class()) {
// TDSet case
newquery->fStatus = TQueryDescription::kSessionQuerySubmitted;
id = ((TDSet *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries,
newquery->fFirstEntry);
}
}
else {
Error("Submit", "No TChain defined; skipping");
newquery->fStatus = TQueryDescription::kSessionQueryCreated;
return;
}
// set query reference id to unique identifier
newquery->fReference= Form("session-%s:q%lld",
fViewer->GetActDesc()->fProof->GetSessionTag(), id);
// start icon animation
fViewer->SetChangePic(kTRUE);
}
else if (fViewer->GetActDesc()->fLocal) { // local session case
// if feedback option selected
if (fViewer->GetOptionsMenu()->IsEntryChecked(kOptionsFeedback)) {
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fViewer->GetCascadeMenu()->IsEntryChecked(41+i)) {
fViewer->GetActDesc()->fNbHistos++;
}
i++;
}
}
if (newquery->fChain) {
if (newquery->fChain->IsA() == TChain::Class()) {
// TChain case
newquery->fStatus = TQueryDescription::kSessionQueryRunning;
fViewer->EnableTimer();
UpdateButtons(newquery);
gPad->SetEditable(kFALSE);
((TChain *)newquery->fChain)->SetTimerInterval(100);
id = ((TChain *)newquery->fChain)->Process(newquery->fSelectorString,
newquery->fOptions,
newquery->fNoEntries > 0 ? newquery->fNoEntries : 1234567890,
newquery->fFirstEntry);
((TChain *)newquery->fChain)->SetTimerInterval(0);
OnBtnRetrieve();
TChain *chain = (TChain *)newquery->fChain;
ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
if ((newquery->fStatus != TQueryDescription::kSessionQueryAborted) &&
(newquery->fStatus != TQueryDescription::kSessionQueryStopped))
newquery->fStatus = TQueryDescription::kSessionQueryCompleted;
UpdateButtons(newquery);
}
else {
new TGMsgBox(fClient->GetRoot(), this, "Error Submitting Query",
"Only TChains are allowed in Local Session (no TDSet) !",
kMBIconExclamation,kMBOk,&retval);
}
}
else {
Error("Submit", "No TChain defined; skipping");
newquery->fStatus = TQueryDescription::kSessionQueryCreated;
return;
}
// set query reference id to unique identifier
newquery->fReference = Form("local-session-%s:q%lld", newquery->fQueryName.Data(), id);
}
// update buttons state
UpdateButtons(newquery);
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateButtons(TQueryDescription *desc)
{
// Update buttons state for the current query status.
TGListTreeItem *item = fViewer->GetSessionHierarchy()->GetSelected();
if (!item) return;
// retrieve query description attached to list tree item
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class())
return;
TQueryDescription *query = (TQueryDescription *)obj;
if (desc != query) return;
Bool_t submit_en = kFALSE;
if ((fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid()) ||
fViewer->GetActDesc()->fLocal)
submit_en = kTRUE;
switch (desc->fStatus) {
case TQueryDescription::kSessionQueryFromProof:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryCompleted:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
if (((desc->fResult == 0) || (desc->fResult &&
(desc->fResult->IsFinalized() ||
(desc->fResult->GetInputObject("TDSet") == 0)))) &&
!(fViewer->GetActDesc()->fLocal))
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryCreated:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQuerySubmitted:
fBtnSubmit->SetEnabled(kFALSE);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kTRUE);
fBtnAbort->SetEnabled(kTRUE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryRunning:
fBtnSubmit->SetEnabled(kFALSE);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kTRUE);
fBtnAbort->SetEnabled(kTRUE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryStopped:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kTRUE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kTRUE);
break;
case TQueryDescription::kSessionQueryAborted:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
case TQueryDescription::kSessionQueryFinalized:
fBtnSubmit->SetEnabled(submit_en);
fBtnFinalize->SetEnabled(kFALSE);
fBtnStop->SetEnabled(kFALSE);
fBtnAbort->SetEnabled(kFALSE);
fBtnShowLog->SetEnabled(kTRUE);
fBtnRetrieve->SetEnabled(kFALSE);
break;
default:
break;
}
if (fViewer->GetActDesc()->fLocal &&
!(fViewer->GetActDesc()->fActQuery->fChain)) {
fBtnFinalize->SetEnabled(kFALSE);
fBtnRetrieve->SetEnabled(kFALSE);
}
}
//______________________________________________________________________________
void TSessionQueryFrame::UpdateInfos()
{
// Update query information (header) text view.
char *buffer;
const char *qst[] = {"aborted ", "submitted", "running ",
"stopped ", "completed"};
if (fViewer->GetActDesc()->fActQuery)
fFD->UpdateFields(fViewer->GetActDesc()->fActQuery);
if (fViewer->GetActDesc()->fLocal ||
(fViewer->GetActDesc()->fConnected &&
fViewer->GetActDesc()->fAttached &&
fViewer->GetActDesc()->fProof &&
fViewer->GetActDesc()->fProof->IsValid())) {
fBtnSave->SetText(" Submit ");
}
else {
fBtnSave->SetText(" Apply changes ");
}
fClient->NeedRedraw(fBtnSave);
fInfoTextView->Clear();
if (!fViewer->GetActDesc()->fActQuery ||
!fViewer->GetActDesc()->fActQuery->fResult) {
ResetProgressDialog("", 0, 0, 0);
if (fViewer->GetActDesc()->fLocal) {
if (fViewer->GetActDesc()->fActQuery) {
TChain *chain = (TChain *)fViewer->GetActDesc()->fActQuery->fChain;
if (chain) {
ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
}
else {
ProgressLocal(0, 0);
}
UpdateButtons(fViewer->GetActDesc()->fActQuery);
}
}
else {
fTotal->SetText(" Estimated time left : 0.0 sec (0 events of 0 processed) ");
fRate->SetText(" Processing Rate : 0.0f events/sec ");
frmProg->Reset();
fFB->Layout();
}
return;
}
TQueryResult *result = fViewer->GetActDesc()->fActQuery->fResult;
// Status label
Int_t st = (result->GetStatus() > 0 && result->GetStatus() <=
TQueryResult::kCompleted) ? result->GetStatus() : 0;
Int_t qry = result->GetSeqNum();
buffer = Form("------------------------------------------------------\n");
// Print header
if (!result->IsDraw()) {
const char *fin = result->IsFinalized() ? "finalized" : qst[st];
const char *arc = result->IsArchived() ? "(A)" : "";
buffer = Form("%s Query No : %d\n", buffer, qry);
buffer = Form("%s Ref : \"%s:%s\"\n", buffer, result->GetTitle(),
result->GetName());
buffer = Form("%s Selector : %s\n", buffer,
result->GetSelecImp()->GetTitle());
buffer = Form("%s Status : %9s%s\n", buffer, fin, arc);
buffer = Form("%s------------------------------------------------------\n",
buffer);
} else {
buffer = Form("%s Query No : %d\n", buffer, qry);
buffer = Form("%s Ref : \"%s:%s\"\n", buffer, result->GetTitle(),
result->GetName());
buffer = Form("%s Selector : %s\n", buffer,
result->GetSelecImp()->GetTitle());
buffer = Form("%s------------------------------------------------------\n",
buffer);
}
// Time information
Int_t elapsed = (Int_t)(result->GetEndTime().Convert() -
result->GetStartTime().Convert());
buffer = Form("%s Started : %s\n",buffer,
result->GetStartTime().AsString());
buffer = Form("%s Real time : %d sec (CPU time: %.1f sec)\n", buffer, elapsed,
result->GetUsedCPU());
// Number of events processed, rate, size
Double_t rate = 0.0;
if (result->GetEntries() > -1 && elapsed > 0)
rate = result->GetEntries() / (Double_t)elapsed ;
Float_t size = ((Float_t)result->GetBytes())/(1024*1024);
buffer = Form("%s Processed : %lld events (size: %.3f MBs)\n",buffer,
result->GetEntries(), size);
buffer = Form("%s Rate : %.1f evts/sec\n",buffer, rate);
// Package information
if (strlen(result->GetParList()) > 1) {
buffer = Form("%s Packages : %s\n",buffer, result->GetParList());
}
// Result information
TString res = result->GetResultFile();
if (!result->IsArchived()) {
Int_t dq = res.Index("queries");
if (dq > -1) {
res.Remove(0,res.Index("queries"));
res.Insert(0,"<PROOF_SandBox>/");
}
if (res.BeginsWith("-")) {
res = (result->GetStatus() == TQueryResult::kAborted) ?
"not available" : "sent to client";
}
}
if (res.Length() > 1) {
buffer = Form("%s------------------------------------------------------\n",
buffer);
buffer = Form("%s Results : %s\n",buffer, res.Data());
}
if (result->GetOutputList() && result->GetOutputList()->GetSize() > 0) {
buffer = Form("%s Outlist : %d objects\n",buffer,
result->GetOutputList()->GetSize());
buffer = Form("%s------------------------------------------------------\n",
buffer);
}
fInfoTextView->LoadBuffer(buffer);
//Float_t pos = Float_t((Double_t)(result->GetEntries() * 100)/(Double_t)total);
if (result->GetStatus() == TQueryResult::kAborted)
frmProg->SetBarColor("red");
else if (result->GetStatus() == TQueryResult::kStopped)
frmProg->SetBarColor("yellow");
else
frmProg->SetBarColor("green");
frmProg->SetPosition(100.0);
buffer = Form(" Processed : %lld events in %.1f sec", result->GetEntries(),
(Float_t)elapsed);
fTotal->SetText(buffer);
buffer = Form(" Processing Rate : %.1f events/sec ", rate);
fRate->SetText(buffer);
fFB->Layout();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Output frame
//______________________________________________________________________________
TSessionOutputFrame::TSessionOutputFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fLVContainer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionOutputFrame::~TSessionOutputFrame()
{
// Destructor.
delete fLVContainer; // this container is inside the TGListView and is not
// deleted automatically
Cleanup();
}
//______________________________________________________________________________
void TSessionOutputFrame::Build(TSessionViewer *gui)
{
// Build query output information frame.
fViewer = gui;
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
// Container of object TGListView
TGListView *frmListView = new TGListView(this, 340, 190);
fLVContainer = new TGLVContainer(frmListView, kSunkenFrame, GetWhitePixel());
fLVContainer->Associate(frmListView);
fLVContainer->SetCleanup(kDeepCleanup);
AddFrame(frmListView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
frmListView->Connect("Clicked(TGLVEntry*, Int_t, Int_t, Int_t)",
"TSessionOutputFrame", this,
"OnElementClicked(TGLVEntry* ,Int_t, Int_t, Int_t)");
frmListView->Connect("DoubleClicked(TGLVEntry*, Int_t, Int_t, Int_t)",
"TSessionOutputFrame", this,
"OnElementDblClicked(TGLVEntry* ,Int_t, Int_t, Int_t)");
}
//______________________________________________________________________________
void TSessionOutputFrame::OnElementClicked(TGLVEntry* entry, Int_t btn, Int_t x,
Int_t y)
{
// Handle mouse clicks on list view items.
TObject *obj = (TObject *)entry->GetUserData();
if ((obj) && (btn ==3)) {
// if right button, popup context menu
fViewer->GetContextMenu()->Popup(x, y, obj, (TBrowser *)0);
}
}
//______________________________________________________________________________
void TSessionOutputFrame::OnElementDblClicked(TGLVEntry* entry, Int_t , Int_t, Int_t)
{
// Handle double-clicks on list view items.
char action[512];
TString act;
TObject *obj = (TObject *)entry->GetUserData();
TString ext = obj->GetName();
gPad->SetEditable(kFALSE);
// check default action from root.mimes
if (fClient->GetMimeTypeList()->GetAction(obj->IsA()->GetName(), action)) {
act = Form("((%s*)0x%lx)%s", obj->IsA()->GetName(), (Long_t)obj, action);
if (act[0] == '!') {
act.Remove(0, 1);
gSystem->Exec(act.Data());
} else {
// do not allow browse
if (!act.Contains("Browse"))
gROOT->ProcessLine(act.Data());
}
}
}
//______________________________________________________________________________
void TSessionOutputFrame::AddObject(TObject *obj)
{
// Add object to output list view.
TGLVEntry *item;
if (obj) {
item = new TGLVEntry(fLVContainer, obj->GetName(), obj->IsA()->GetName());
item->SetUserData(obj);
fLVContainer->AddItem(item);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Input Frame
//______________________________________________________________________________
TSessionInputFrame::TSessionInputFrame(TGWindow* p, Int_t w, Int_t h) :
TGCompositeFrame(p, w, h), fLVContainer(0)
{
// Constructor.
}
//______________________________________________________________________________
TSessionInputFrame::~TSessionInputFrame()
{
// Destructor.
delete fLVContainer; // this container is inside the TGListView and is not
// deleted automatically
Cleanup();
}
//______________________________________________________________________________
void TSessionInputFrame::Build(TSessionViewer *gui)
{
// Build query input informations frame.
fViewer = gui;
SetLayoutManager(new TGVerticalLayout(this));
SetCleanup(kDeepCleanup);
// Container of object TGListView
TGListView *frmListView = new TGListView(this, 340, 190);
fLVContainer = new TGLVContainer(frmListView, kSunkenFrame, GetWhitePixel());
fLVContainer->Associate(frmListView);
fLVContainer->SetCleanup(kDeepCleanup);
AddFrame(frmListView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
4, 4, 4, 4));
}
//______________________________________________________________________________
void TSessionInputFrame::AddObject(TObject *obj)
{
// Add object to input list view.
TGLVEntry *item;
if (obj) {
item = new TGLVEntry(fLVContainer, obj->GetName(), obj->IsA()->GetName());
item->SetUserData(obj);
fLVContainer->AddItem(item);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Session Viewer Main Frame
//______________________________________________________________________________
TSessionViewer::TSessionViewer(const char *name, UInt_t w, UInt_t h) :
TGMainFrame(gClient->GetRoot(), w, h), fSessionHierarchy(0), fSessionItem(0)
{
// Main Session viewer constructor.
// only one session viewer allowed
if (gSessionViewer)
return;
Build();
SetWindowName(name);
Resize(w, h);
gSessionViewer = this;
}
//______________________________________________________________________________
TSessionViewer::TSessionViewer(const char *name, Int_t x, Int_t y, UInt_t w,
UInt_t h) : TGMainFrame(gClient->GetRoot(), w, h),
fSessionHierarchy(0), fSessionItem(0)
{
// Main Session viewer constructor.
// only one session viewer allowed
if (gSessionViewer)
return;
Build();
SetWindowName(name);
Move(x, y);
Resize(w, h);
gSessionViewer = this;
}
//______________________________________________________________________________
void TSessionViewer::ReadConfiguration(const char *filename)
{
// Read configuration file and populate list of sessions
// list of queries and list of packages.
// Read and set also global options as feedback histos.
if (fViewerEnv)
delete fViewerEnv;
fViewerEnv = new TEnv();
const char *fn = (filename && strlen(filename)) ? filename : fConfigFile.Data();
fViewerEnv->ReadFile(fn, kEnvUser);
Bool_t bval = (Bool_t)fViewerEnv->GetValue("Option.Feedback", 1);
if (bval)
fOptionsMenu->CheckEntry(kOptionsFeedback);
else
fOptionsMenu->UnCheckEntry(kOptionsFeedback);
bval = (Bool_t)fViewerEnv->GetValue("Option.MasterHistos", 1);
if (bval) {
fOptionsMenu->CheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 1);
}
else {
fOptionsMenu->UnCheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 0);
}
bval = (Bool_t)fViewerEnv->GetValue("Option.MasterEvents", 0);
if (bval)
fOptionsMenu->CheckEntry(kOptionsStatsTrace);
else
fOptionsMenu->UnCheckEntry(kOptionsStatsTrace);
bval = (Bool_t)fViewerEnv->GetValue("Option.WorkerEvents", 0);
if (bval)
fOptionsMenu->CheckEntry(kOptionsSlaveStatsTrace);
else
fOptionsMenu->UnCheckEntry(kOptionsSlaveStatsTrace);
Int_t i = 0;
while (kFeedbackHistos[i]) {
bval = (Bool_t)fViewerEnv->GetValue(Form("Option.%s",kFeedbackHistos[i]),
i == 1 ? 1 : 0);
if (bval)
fCascadeMenu->CheckEntry(41+i);
else
fCascadeMenu->UnCheckEntry(41+i);
i++;
}
TSessionDescription *proofDesc;
fSessions->Delete();
if (fSessionItem)
fSessionHierarchy->DeleteChildren(fSessionItem);
else
fSessionItem = fSessionHierarchy->AddItem(0, "Sessions", fBaseIcon,
fBaseIcon);
// add local session description
TGListTreeItem *item = fSessionHierarchy->AddItem(fSessionItem, "Local",
fLocal, fLocal);
fSessionHierarchy->SetToolTipItem(item, "Local Session");
TSessionDescription *localdesc = new TSessionDescription();
localdesc->fTag = "";
localdesc->fName = "Local";
localdesc->fAddress = "Local";
localdesc->fPort = 0;
localdesc->fConfigFile = "";
localdesc->fLogLevel = 0;
localdesc->fUserName = "";
localdesc->fQueries = new TList();
localdesc->fPackages = new TList();
localdesc->fActQuery = 0;
localdesc->fProof = 0;
localdesc->fProofMgr = 0;
localdesc->fLocal = kTRUE;
localdesc->fSync = kTRUE;
localdesc->fAutoEnable = kFALSE;
localdesc->fNbHistos = 0;
item->SetUserData(localdesc);
fSessions->Add((TObject *)localdesc);
fActDesc = localdesc;
TIter next(fViewerEnv->GetTable());
TEnvRec *er;
while ((er = (TEnvRec*) next())) {
const char *s;
if ((s = strstr(er->GetName(), "SessionDescription."))) {
const char *val = fViewerEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
char *v = StrDup(val);
s += 7;
while (1) {
TString name = strtok(!cnt ? v : 0, ";");
if (name.IsNull()) break;
TString sessiontag = strtok(0, ";");
TString address = strtok(0, ";");
if (address.IsNull()) break;
TString port = strtok(0, ";");
if (port.IsNull()) break;
TString loglevel = strtok(0, ";");
if (loglevel.IsNull()) break;
TString configfile = strtok(0, ";");
TString user = strtok(0, ";");
if (user.IsNull()) break;
TString sync = strtok(0, ";");
TString autoen = strtok(0, ";");
// build session description
proofDesc = new TSessionDescription();
proofDesc->fTag = sessiontag.Length() > 2 ? sessiontag.Data() : "";
proofDesc->fName = name;
proofDesc->fAddress = address;
proofDesc->fPort = atoi(port);
proofDesc->fConfigFile = configfile.Length() > 2 ? configfile.Data() : "";
proofDesc->fLogLevel = atoi(loglevel);
proofDesc->fConnected = kFALSE;
proofDesc->fAttached = kFALSE;
proofDesc->fLocal = kFALSE;
proofDesc->fQueries = new TList();
proofDesc->fPackages = new TList();
proofDesc->fActQuery = 0;
proofDesc->fProof = 0;
proofDesc->fProofMgr = 0;
proofDesc->fSync = (Bool_t)(atoi(sync));
proofDesc->fAutoEnable = (Bool_t)(atoi(autoen));
proofDesc->fUserName = user;
fSessions->Add((TObject *)proofDesc);
item = fSessionHierarchy->AddItem(
fSessionItem, proofDesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item->SetUserData(proofDesc);
fActDesc = proofDesc;
cnt++;
}
delete [] v;
}
}
if ((s = strstr(er->GetName(), "QueryDescription."))) {
const char *val = fViewerEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
char *v = StrDup(val);
s += 7;
while (1) {
TString status = strtok(!cnt ? v : 0, ";");
if (status.IsNull()) break;
TString reference = strtok(0, ";");
if (reference.IsNull()) break;
TString queryname = strtok(0, ";");
if (queryname.IsNull()) break;
TString selector = strtok(0, ";");
if (selector.IsNull()) break;
TString dset = strtok(0, ";");
TString options = strtok(0, ";");
TString eventlist = strtok(0, ";");
TString nbfiles = strtok(0, ";");
TString nbentries = strtok(0, ";");
TString firstentry = strtok(0, ";");
TQueryDescription *newquery = new TQueryDescription();
newquery->fStatus =
(TQueryDescription::ESessionQueryStatus)(atoi(status));
newquery->fSelectorString = selector.Length() > 2 ? selector.Data() : "";
newquery->fReference = reference.Length() > 2 ? reference.Data() : "";
newquery->fTDSetString = dset.Length() > 2 ? dset.Data() : "";
newquery->fQueryName = queryname.Length() > 2 ? queryname.Data() : "";
newquery->fOptions = options.Length() > 2 ? options.Data() : "";
newquery->fEventList = eventlist.Length() > 2 ? eventlist.Data() : "";
newquery->fNbFiles = atoi(nbfiles);
newquery->fNoEntries = atoi(nbentries);
newquery->fFirstEntry = atoi(firstentry);
newquery->fResult = 0;
newquery->fChain = 0;
fActDesc->fQueries->Add((TObject *)newquery);
cnt++;
TGListTreeItem *item1 = fSessionHierarchy->FindChildByData(
fSessionItem, fActDesc);
TGListTreeItem *item2 = fSessionHierarchy->AddItem(
item1, newquery->fQueryName, fQueryCon, fQueryCon);
item2->SetUserData(newquery);
}
delete [] v;
}
}
}
fSessionHierarchy->ClearHighlighted();
fSessionHierarchy->OpenItem(fSessionItem);
if (fActDesc == localdesc) {
fSessionHierarchy->HighlightItem(fSessionItem);
fSessionHierarchy->SetSelected(fSessionItem);
}
else {
fSessionHierarchy->OpenItem(item);
fSessionHierarchy->HighlightItem(item);
fSessionHierarchy->SetSelected(item);
}
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfProofs()
{
// Update list of existing Proof sessions.
// get list of proof sessions
Bool_t found = kFALSE;
Bool_t exists = kFALSE;
TGListTreeItem *item = 0;
TSeqCollection *proofs = gROOT->GetListOfProofs();
TSessionDescription *desc = 0;
TSessionDescription *newdesc;
if (proofs) {
TObject *o = proofs->First();
if (o && dynamic_cast<TProofMgr *>(o)) {
TProofMgr *mgr = dynamic_cast<TProofMgr *>(o);
if (mgr->QuerySessions("L")) {
TIter nxd(mgr->QuerySessions("L"));
TProofDesc *d = 0;
TProof *p = 0;
while ((d = (TProofDesc *)nxd())) {
TIter nextfs(fSessions);
// check if session exists in the list
while ((desc = (TSessionDescription *)nextfs())) {
if ((desc->fTag == d->GetName()) ||
(desc->fName == d->GetTitle())) {
exists = kTRUE;
break;
}
}
TIter nexts(fSessions);
found = kFALSE;
p = d->GetProof();
while ((desc = (TSessionDescription *)nexts())) {
if (desc->fConnected && desc->fAttached)
continue;
if (p && (exists && ((desc->fTag == d->GetName()) ||
(desc->fName == d->GetTitle())) ||
(!exists && (desc->fAddress == p->GetMaster())))) {
desc->fConnected = kTRUE;
desc->fAttached = kTRUE;
desc->fProof = p;
desc->fProofMgr = mgr;
desc->fTag = d->GetName();
item = fSessionHierarchy->FindChildByData(fSessionItem,
desc);
if (item) {
item->SetPictures(fProofCon, fProofCon);
if (item == fSessionHierarchy->GetSelected()) {
fActDesc->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t)");
fActDesc->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
fActDesc->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fQueryFrame,
"IndicateStop(Bool_t)");
fActDesc->fProof->Connect(
"ResetProgressDialog(const char*, Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
EnableTimer();
// change status bar right icon to connected pixmap
ChangeRightLogo("monitor01.xpm");
// do not animate yet
SetChangePic(kFALSE);
// connect to signal "query result ready"
fActDesc->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", this, "QueryResultReady(char *)");
// display connection information on status bar
TString msg;
msg.Form("PROOF Cluster %s ready", fActDesc->fName.Data());
fStatusBar->SetText(msg.Data(), 1);
UpdateListOfPackages();
fSessionFrame->UpdatePackages();
fSessionFrame->UpdateListOfDataSets();
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fPopupSrv->EnableEntry(kSessionDisconnect);
fSessionMenu->EnableEntry(kSessionDisconnect);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonUp);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
fSessionFrame->SetLogLevel(fActDesc->fLogLevel);
// update session information frame
fSessionFrame->ProofInfos();
fSessionFrame->SetLocal(kFALSE);
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
}
}
}
if (desc->fLogLevel < 0)
desc->fLogLevel = 0;
found = kTRUE;
break;
}
}
if (found) continue;
p = d->GetProof();
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fTag = d->GetName();
newdesc->fName = d->GetTitle();
newdesc->fAddress = d->GetTitle();
newdesc->fConnected = kFALSE;
newdesc->fAttached = kFALSE;
newdesc->fProofMgr = mgr;
p = d->GetProof();
if (p) {
newdesc->fConnected = kTRUE;
newdesc->fAttached = kTRUE;
newdesc->fAddress = p->GetMaster();
newdesc->fConfigFile = p->GetConfFile();
newdesc->fUserName = p->GetUser();
newdesc->fPort = p->GetPort();
newdesc->fLogLevel = p->GetLogLevel();
newdesc->fProof = p;
newdesc->fProof->Connect("Progress(Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t)");
newdesc->fProof->Connect("Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)",
"TSessionQueryFrame", fQueryFrame,
"Progress(Long64_t,Long64_t,Long64_t,Float_t,Float_t,Float_t,Float_t)");
newdesc->fProof->Connect("StopProcess(Bool_t)",
"TSessionQueryFrame", fQueryFrame,
"IndicateStop(Bool_t)");
newdesc->fProof->Connect(
"ResetProgressDialog(const char*, Int_t,Long64_t,Long64_t)",
"TSessionQueryFrame", fQueryFrame,
"ResetProgressDialog(const char*,Int_t,Long64_t,Long64_t)");
// enable timer used for status bar icon's animation
EnableTimer();
// change status bar right icon to connected pixmap
ChangeRightLogo("monitor01.xpm");
// do not animate yet
SetChangePic(kFALSE);
// connect to signal "query result ready"
newdesc->fProof->Connect("QueryResultReady(char *)",
"TSessionViewer", this, "QueryResultReady(char *)");
}
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fActQuery = 0;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
if (p)
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofCon, fProofCon);
else
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
}
}
return;
}
TIter nextp(proofs);
TProof *proof;
// loop over existing Proof sessions
while ((proof = (TProof *)nextp())) {
TIter nexts(fSessions);
found = kFALSE;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if (desc->fProof == proof) {
desc->fConnected = kTRUE;
desc->fAttached = kTRUE;
found = kTRUE;
break;
}
}
if (found) continue;
// create new session description
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fName = proof->GetMaster();
newdesc->fConfigFile = proof->GetConfFile();
newdesc->fUserName = proof->GetUser();
newdesc->fPort = proof->GetPort();
newdesc->fLogLevel = proof->GetLogLevel();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fAddress = proof->GetMaster();
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
newdesc->fProof = proof;
newdesc->fActQuery = 0;
newdesc->fConnected = kTRUE;
newdesc->fAttached = kTRUE;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofCon, fProofCon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
}
}
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfSessions()
{
// Update list of existing Proof sessions.
// get list of proof sessions
TGListTreeItem *item;
TList *sessions = fActDesc->fProofMgr->QuerySessions("");
if (sessions) {
TIter nextp(sessions);
TProofDesc *pdesc;
TProof *proof;
TSessionDescription *newdesc;
// loop over existing Proof sessions
while ((pdesc = (TProofDesc *)nextp())) {
TIter nexts(fSessions);
TSessionDescription *desc = 0;
Bool_t found = kFALSE;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if ((desc->fTag == pdesc->GetName()) ||
(desc->fName == pdesc->GetTitle())) {
desc->fConnected = kTRUE;
found = kTRUE;
break;
}
}
if (found) continue;
// create new session description
newdesc = new TSessionDescription();
// and fill informations from Proof session
newdesc->fTag = pdesc->GetName();
newdesc->fName = pdesc->GetTitle();
proof = pdesc->GetProof();
if (proof) {
newdesc->fConfigFile = proof->GetConfFile();
newdesc->fUserName = proof->GetUser();
newdesc->fPort = proof->GetPort();
newdesc->fLogLevel = proof->GetLogLevel();
if (newdesc->fLogLevel < 0)
newdesc->fLogLevel = 0;
newdesc->fAddress = proof->GetMaster();
newdesc->fProof = proof;
}
else {
newdesc->fProof = 0;
newdesc->fConfigFile = "";
newdesc->fUserName = fActDesc->fUserName;
newdesc->fPort = fActDesc->fPort;
newdesc->fLogLevel = 0;
newdesc->fAddress = fActDesc->fAddress;
}
newdesc->fQueries = new TList();
newdesc->fPackages = new TList();
newdesc->fProofMgr = fActDesc->fProofMgr;
newdesc->fActQuery = 0;
newdesc->fConnected = kTRUE;
newdesc->fAttached = kFALSE;
newdesc->fLocal = kFALSE;
newdesc->fSync = kFALSE;
newdesc->fAutoEnable = kFALSE;
newdesc->fNbHistos = 0;
// add new session description in list tree
item = fSessionHierarchy->AddItem(fSessionItem, newdesc->fName.Data(),
fProofDiscon, fProofDiscon);
fSessionHierarchy->SetToolTipItem(item, "Proof Session");
item ->SetUserData(newdesc);
// and in our session description list
fSessions->Add(newdesc);
// set actual description to the last one
}
}
}
//______________________________________________________________________________
void TSessionViewer::WriteConfiguration(const char *filename)
{
// Save actual configuration in config file "filename".
TSessionDescription *session;
TQueryDescription *query;
Int_t scnt = 0, qcnt = 1;
const char *fname = filename ? filename : fConfigFile.Data();
delete fViewerEnv;
gSystem->Unlink(fname);
fViewerEnv = new TEnv();
fViewerEnv->SetValue("Option.Feedback",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsFeedback));
fViewerEnv->SetValue("Option.MasterHistos",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsStatsHist));
fViewerEnv->SetValue("Option.MasterEvents",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsStatsTrace));
fViewerEnv->SetValue("Option.WorkerEvents",
(Int_t)fOptionsMenu->IsEntryChecked(kOptionsSlaveStatsTrace));
Int_t i = 0;
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
fViewerEnv->SetValue(Form("Option.%s",kFeedbackHistos[i]),
(Int_t)fCascadeMenu->IsEntryChecked(41+i));
i++;
}
TIter snext(fSessions);
while ((session = (TSessionDescription *) snext())) {
if ((scnt > 0) && ((session->fAddress.Length() < 3) ||
session->fUserName.Length() < 2)) {
// skip gROOT's list of sessions
continue;
}
if ((scnt > 0) && (session->fName == session->fAddress)) {
// skip gROOT's list of proofs
continue;
}
TString sessionstring;
sessionstring += session->fName;
sessionstring += ";";
sessionstring += session->fTag.Length() > 1 ? session->fTag.Data() : " ";
sessionstring += ";";
sessionstring += session->fAddress;
sessionstring += ";";
sessionstring += Form("%d", session->fPort);
sessionstring += ";";
sessionstring += Form("%d", session->fLogLevel);
sessionstring += ";";
sessionstring += session->fConfigFile.Length() > 1 ? session->fConfigFile.Data() : " ";
sessionstring += ";";
sessionstring += session->fUserName;
sessionstring += ";";
sessionstring += Form("%d", session->fSync);
sessionstring += ";";
sessionstring += Form("%d", session->fAutoEnable);
if (scnt > 0) // skip local session
fViewerEnv->SetValue(Form("SessionDescription.%d",scnt), sessionstring);
scnt++;
TIter qnext(session->fQueries);
while ((query = (TQueryDescription *) qnext())) {
TString querystring;
querystring += Form("%d", query->fStatus);
querystring += ";";
querystring += query->fReference.Length() > 1 ? query->fReference.Data() : " ";
querystring += ";";
querystring += query->fQueryName;
querystring += ";";
querystring += query->fSelectorString.Length() > 1 ? query->fSelectorString.Data() : " ";
querystring += ";";
querystring += query->fTDSetString.Length() > 1 ? query->fTDSetString.Data() : " ";
querystring += ";";
querystring += query->fOptions.Length() > 1 ? query->fOptions.Data() : " ";
querystring += ";";
querystring += query->fEventList.Length() > 1 ? query->fEventList.Data() : " ";
querystring += ";";
querystring += Form("%d",query->fNbFiles);
querystring += ";";
querystring += Form("%d",query->fNoEntries);
querystring += ";";
querystring += Form("%d",query->fFirstEntry);
fViewerEnv->SetValue(Form("QueryDescription.%d",qcnt), querystring);
qcnt++;
}
}
fViewerEnv->WriteFile(fname);
}
//______________________________________________________________________________
void TSessionViewer::Build()
{
// Build main session viewer frame and subframes.
char line[120];
fActDesc = 0;
fActFrame = 0;
fLogWindow = 0;
fBusy = kFALSE;
fAutoSave = kTRUE;
SetCleanup(kDeepCleanup);
// set minimun size
SetWMSizeHints(400 + 200, 370+50, 2000, 1000, 1, 1);
// collect icons
fLocal = fClient->GetPicture("local_session.xpm");
fProofCon = fClient->GetPicture("proof_connected.xpm");
fProofDiscon = fClient->GetPicture("proof_disconnected.xpm");
fQueryCon = fClient->GetPicture("query_connected.xpm");
fQueryDiscon = fClient->GetPicture("query_disconnected.xpm");
fBaseIcon = fClient->GetPicture("proof_base.xpm");
//--- File menu
fFileMenu = new TGPopupMenu(fClient->GetRoot());
fFileMenu->AddEntry("&Load Config...", kFileLoadConfig);
fFileMenu->AddEntry("&Save Config...", kFileSaveConfig);
fFileMenu->AddSeparator();
fFileMenu->AddEntry("&Close Viewer", kFileCloseViewer);
fFileMenu->AddSeparator();
fFileMenu->AddEntry("&Quit ROOT", kFileQuit);
//--- Session menu
fSessionMenu = new TGPopupMenu(gClient->GetRoot());
fSessionMenu->AddLabel("Session Management");
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&New Session", kSessionNew);
fSessionMenu->AddEntry("&Add to the list", kSessionAdd);
fSessionMenu->AddEntry("De&lete", kSessionDelete);
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&Connect...", kSessionConnect);
fSessionMenu->AddEntry("&Disconnect", kSessionDisconnect);
fSessionMenu->AddEntry("Shutdo&wn", kSessionShutdown);
fSessionMenu->AddEntry("&Show status",kSessionShowStatus);
fSessionMenu->AddEntry("&Get Queries",kSessionGetQueries);
fSessionMenu->AddSeparator();
fSessionMenu->AddEntry("&Cleanup", kSessionCleanup);
fSessionMenu->AddEntry("&Reset",kSessionReset);
fSessionMenu->DisableEntry(kSessionAdd);
//--- Query menu
fQueryMenu = new TGPopupMenu(gClient->GetRoot());
fQueryMenu->AddLabel("Query Management");
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("&New...", kQueryNew);
fQueryMenu->AddEntry("&Edit", kQueryEdit);
fQueryMenu->AddEntry("&Submit", kQuerySubmit);
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("Start &Viewer", kQueryStartViewer);
fQueryMenu->AddSeparator();
fQueryMenu->AddEntry("&Delete", kQueryDelete);
fViewerEnv = 0;
#ifdef WIN32
fConfigFile = Form("%s\\%s", gSystem->HomeDirectory(), kConfigFile);
#else
fConfigFile = Form("%s/%s", gSystem->HomeDirectory(), kConfigFile);
#endif
fCascadeMenu = new TGPopupMenu(fClient->GetRoot());
Int_t i = 0;
while (kFeedbackHistos[i]) {
fCascadeMenu->AddEntry(kFeedbackHistos[i], 41+i);
i++;
}
fCascadeMenu->AddEntry("User defined...", 50);
// disable it for now (until implemented)
fCascadeMenu->DisableEntry(50);
//--- Options menu
fOptionsMenu = new TGPopupMenu(fClient->GetRoot());
fOptionsMenu->AddLabel("Global Options");
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("&Autosave Config", kOptionsAutoSave);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("Master &Histos", kOptionsStatsHist);
fOptionsMenu->AddEntry("&Master Events", kOptionsStatsTrace);
fOptionsMenu->AddEntry("&Worker Events", kOptionsSlaveStatsTrace);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddEntry("Feedback &Active", kOptionsFeedback);
fOptionsMenu->AddSeparator();
fOptionsMenu->AddPopup("&Feedback Histos", fCascadeMenu);
fOptionsMenu->CheckEntry(kOptionsAutoSave);
//--- Help menu
fHelpMenu = new TGPopupMenu(gClient->GetRoot());
fHelpMenu->AddEntry("&About ROOT...", kHelpAbout);
fFileMenu->Associate(this);
fSessionMenu->Associate(this);
fQueryMenu->Associate(this);
fOptionsMenu->Associate(this);
fCascadeMenu->Associate(this);
fHelpMenu->Associate(this);
//--- create menubar and add popup menus
fMenuBar = new TGMenuBar(this, 1, 1, kHorizontalFrame);
fMenuBar->AddPopup("&File", fFileMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Session", fSessionMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Query", fQueryMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Options", fOptionsMenu, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 0, 4, 0, 0));
fMenuBar->AddPopup("&Help", fHelpMenu, new TGLayoutHints(kLHintsTop |
kLHintsRight));
TGHorizontal3DLine *toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
AddFrame(fMenuBar, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 0, 0, 1, 1));
toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
//---- toolbar
int spacing = 8;
fToolBar = new TGToolBar(this, 60, 20, kHorizontalFrame);
for (int i = 0; xpm_toolbar[i]; i++) {
tb_data[i].fPixmap = xpm_toolbar[i];
if (strlen(xpm_toolbar[i]) == 0) {
spacing = 8;
continue;
}
fToolBar->AddButton(this, &tb_data[i], spacing);
spacing = 0;
}
AddFrame(fToolBar, new TGLayoutHints(kLHintsTop | kLHintsExpandX, 0, 0, 0, 0));
toolBarSep = new TGHorizontal3DLine(this);
AddFrame(toolBarSep, new TGLayoutHints(kLHintsTop | kLHintsExpandX));
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonDisabled);
fPopupSrv = new TGPopupMenu(fClient->GetRoot());
fPopupSrv->AddEntry("Connect",kSessionConnect);
fPopupSrv->AddEntry("Disconnect",kSessionDisconnect);
fPopupSrv->AddEntry("Shutdown",kSessionShutdown);
fPopupSrv->AddEntry("Browse",kSessionBrowse);
fPopupSrv->AddEntry("Show status",kSessionShowStatus);
fPopupSrv->AddEntry("Delete", kSessionDelete);
fPopupSrv->AddEntry("Get Queries",kSessionGetQueries);
fPopupSrv->AddSeparator();
fPopupSrv->AddEntry("Cleanup", kSessionCleanup);
fPopupSrv->AddEntry("Reset",kSessionReset);
fPopupSrv->Connect("Activated(Int_t)","TSessionViewer", this,
"MyHandleMenu(Int_t)");
fPopupQry = new TGPopupMenu(fClient->GetRoot());
fPopupQry->AddEntry("Edit",kQueryEdit);
fPopupQry->AddEntry("Submit",kQuerySubmit);
fPopupQry->AddSeparator();
fPopupQry->AddEntry("Start &Viewer", kQueryStartViewer);
fPopupQry->AddSeparator();
fPopupQry->AddEntry("Delete",kQueryDelete);
fPopupQry->Connect("Activated(Int_t)","TSessionViewer", this,
"MyHandleMenu(Int_t)");
fSessionMenu->DisableEntry(kSessionGetQueries);
fSessionMenu->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionGetQueries);
fPopupSrv->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionDisconnect);
fPopupSrv->DisableEntry(kSessionShutdown);
fPopupSrv->DisableEntry(kSessionCleanup);
fPopupSrv->DisableEntry(kSessionReset);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
//--- Horizontal mother frame -----------------------------------------------
fHf = new TGHorizontalFrame(this, 10, 10);
fHf->SetCleanup(kDeepCleanup);
//--- fV1 -------------------------------------------------------------------
fV1 = new TGVerticalFrame(fHf, 100, 100, kFixedWidth);
fV1->SetCleanup(kDeepCleanup);
fTreeView = new TGCanvas(fV1, 100, 200, kSunkenFrame | kDoubleBorder);
fV1->AddFrame(fTreeView, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY,
2, 0, 0, 0));
fSessionHierarchy = new TGListTree(fTreeView, kHorizontalFrame);
fSessionHierarchy->DisableOpen();
fSessionHierarchy->Connect("Clicked(TGListTreeItem*,Int_t,Int_t,Int_t)",
"TSessionViewer", this,
"OnListTreeClicked(TGListTreeItem*, Int_t, Int_t, Int_t)");
fSessionHierarchy->Connect("DoubleClicked(TGListTreeItem*,Int_t)",
"TSessionViewer", this,
"OnListTreeDoubleClicked(TGListTreeItem*, Int_t)");
fV1->Resize(fTreeView->GetDefaultWidth()+100, fV1->GetDefaultHeight());
//--- fV2 -------------------------------------------------------------------
fV2 = new TGVerticalFrame(fHf, 350, 310);
fV2->SetCleanup(kDeepCleanup);
//--- Server Frame ----------------------------------------------------------
fServerFrame = new TSessionServerFrame(fV2, 350, 310);
fSessions = new TList;
ReadConfiguration();
fServerFrame->Build(this);
fV2->AddFrame(fServerFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Session Frame ---------------------------------------------------------
fSessionFrame = new TSessionFrame(fV2, 350, 310);
fSessionFrame->Build(this);
fV2->AddFrame(fSessionFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Query Frame -----------------------------------------------------------
fQueryFrame = new TSessionQueryFrame(fV2, 350, 310);
fQueryFrame->Build(this);
fV2->AddFrame(fQueryFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Output Frame ----------------------------------------------------------
fOutputFrame = new TSessionOutputFrame(fV2, 350, 310);
fOutputFrame->Build(this);
fV2->AddFrame(fOutputFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
//--- Input Frame -----------------------------------------------------------
fInputFrame = new TSessionInputFrame(fV2, 350, 310);
fInputFrame->Build(this);
fV2->AddFrame(fInputFrame, new TGLayoutHints(kLHintsTop | kLHintsExpandX |
kLHintsExpandY, 2, 0, 1, 2));
fHf->AddFrame(fV1, new TGLayoutHints(kLHintsLeft | kLHintsExpandY));
// add vertical splitter between list tree and frames
TGVSplitter *splitter = new TGVSplitter(fHf, 4);
splitter->SetFrame(fV1, kTRUE);
fHf->AddFrame(splitter,new TGLayoutHints(kLHintsLeft | kLHintsExpandY));
fHf->AddFrame(new TGVertical3DLine(fHf), new TGLayoutHints(kLHintsLeft |
kLHintsExpandY));
fHf->AddFrame(fV2, new TGLayoutHints(kLHintsRight | kLHintsExpandX |
kLHintsExpandY));
AddFrame(fHf, new TGLayoutHints(kLHintsRight | kLHintsExpandX |
kLHintsExpandY));
// if description available, update server infos frame
if (fActDesc) {
if (!fActDesc->fLocal) {
fServerFrame->Update(fActDesc);
}
else {
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
}
}
//--- Status Bar ------------------------------------------------------------
int parts[] = { 36, 49, 15 };
fStatusBar = new TGStatusBar(this, 10, 10);
fStatusBar->SetCleanup(kDeepCleanup);
fStatusBar->SetParts(parts, 3);
for (int p = 0; p < 3; ++p)
fStatusBar->GetBarPart(p)->SetCleanup(kDeepCleanup);
AddFrame(fStatusBar, new TGLayoutHints(kLHintsTop | kLHintsLeft |
kLHintsExpandX, 0, 0, 1, 1));
// connection icon (animation) and time info
fStatusBar->SetText(" 00:00:00", 2);
TGCompositeFrame *leftpart = fStatusBar->GetBarPart(2);
fRightIconPicture = (TGPicture *)fClient->GetPicture("proof_disconnected.xpm");
fRightIcon = new TGIcon(leftpart, fRightIconPicture,
fRightIconPicture->GetWidth(),fRightIconPicture->GetHeight());
leftpart->AddFrame(fRightIcon, new TGLayoutHints(kLHintsLeft, 2, 0, 0, 0));
// connection progress bar
TGCompositeFrame *rightpart = fStatusBar->GetBarPart(0);
fConnectProg = new TGHProgressBar(rightpart, TGProgressBar::kStandard, 100);
fConnectProg->ShowPosition();
fConnectProg->SetBarColor("green");
rightpart->AddFrame(fConnectProg, new TGLayoutHints(kLHintsExpandX, 1, 1, 1, 1));
// add user info
fUserGroup = gSystem->GetUserInfo();
sprintf(line,"User : %s - %s", fUserGroup->fRealName.Data(),
fUserGroup->fGroup.Data());
fStatusBar->SetText(line, 1);
fTimer = 0;
// create context menu
fContextMenu = new TContextMenu("SessionViewerContextMenu") ;
SetWindowName("ROOT Session Viewer");
MapSubwindows();
MapWindow();
// hide frames
fServerFrame->SetAddEnabled(kFALSE);
fStatusBar->GetBarPart(0)->HideFrame(fConnectProg);
fV2->HideFrame(fSessionFrame);
fV2->HideFrame(fQueryFrame);
fV2->HideFrame(fOutputFrame);
fV2->HideFrame(fInputFrame);
fQueryFrame->GetQueryEditFrame()->OnNewQueryMore();
fActFrame = fServerFrame;
UpdateListOfProofs();
Resize(610, 420);
}
//______________________________________________________________________________
TSessionViewer::~TSessionViewer()
{
// Destructor.
Cleanup();
delete fUserGroup;
if (gSessionViewer == this)
gSessionViewer = 0;
}
//______________________________________________________________________________
void TSessionViewer::OnListTreeClicked(TGListTreeItem *entry, Int_t btn,
Int_t x, Int_t y)
{
// Handle mouse clicks in list tree.
TList *objlist;
TObject *obj;
TString msg;
fSessionMenu->DisableEntry(kSessionAdd);
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonDisabled);
if (entry->GetParent() == 0) { // PROOF
// switch frames only if actual one doesn't match
if (fActFrame != fServerFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fServerFrame);
fActFrame = fServerFrame;
}
fSessionMenu->DisableEntry(kSessionDelete);
fSessionMenu->EnableEntry(kSessionAdd);
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
}
else if (entry->GetParent()->GetParent() == 0) { // Server
if (entry->GetUserData()) {
obj = (TObject *)entry->GetUserData();
if (obj->IsA() != TSessionDescription::Class())
return;
// update server frame informations
fServerFrame->Update((TSessionDescription *)obj);
fActDesc = (TSessionDescription*)obj;
// if Proof valid, update connection infos
if (fActDesc->fConnected && fActDesc->fAttached &&
fActDesc->fProof && fActDesc->fProof->IsValid()) {
fActDesc->fProof->cd();
msg.Form("PROOF Cluster %s ready", fActDesc->fName.Data());
}
else {
msg.Form("PROOF Cluster %s not connected", fActDesc->fName.Data());
}
fStatusBar->SetText(msg.Data(), 1);
}
if ((fActDesc->fConnected) && (fActDesc->fAttached)) {
fPopupSrv->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
UpdateListOfPackages();
fSessionFrame->UpdateListOfDataSets();
}
else {
fPopupSrv->EnableEntry(kSessionConnect);
fSessionMenu->EnableEntry(kSessionConnect);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonUp);
}
// local session
if (fActDesc->fLocal) {
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
UpdateListOfPackages();
fSessionFrame->UpdateListOfDataSets();
}
fSessionFrame->SetLocal();
fServerFrame->SetAddEnabled();
fServerFrame->SetConnectEnabled(kFALSE);
}
// proof session not connected
if ((!fActDesc->fLocal) && (!fActDesc->fAttached) &&
(fActFrame != fServerFrame)) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fServerFrame);
fActFrame = fServerFrame;
}
// proof session connected
if ((!fActDesc->fLocal) && (fActDesc->fConnected) &&
(fActDesc->fAttached)) {
if (fActFrame != fSessionFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fSessionFrame);
fActFrame = fSessionFrame;
}
fSessionFrame->SetLocal(kFALSE);
}
fSessionFrame->SetLogLevel(fActDesc->fLogLevel);
fServerFrame->SetLogLevel(fActDesc->fLogLevel);
if (fActDesc->fAutoEnable)
fSessionFrame->CheckAutoEnPack(kTRUE);
else
fSessionFrame->CheckAutoEnPack(kFALSE);
// update session information frame
fSessionFrame->ProofInfos();
fSessionFrame->UpdatePackages();
fServerFrame->SetAddEnabled(kFALSE);
fServerFrame->SetConnectEnabled();
}
else if (entry->GetParent()->GetParent()->GetParent() == 0) { // query
obj = (TObject *)entry->GetParent()->GetUserData();
if (obj->IsA() == TSessionDescription::Class()) {
fActDesc = (TSessionDescription *)obj;
}
obj = (TObject *)entry->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
fActDesc->fActQuery = (TQueryDescription *)obj;
}
// update query informations and buttons state
fQueryFrame->UpdateInfos();
fQueryFrame->UpdateButtons(fActDesc->fActQuery);
if (fActFrame != fQueryFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fQueryFrame);
fActFrame = fQueryFrame;
}
if ((fActDesc->fConnected) && (fActDesc->fAttached) &&
(fActDesc->fActQuery->fStatus != TQueryDescription::kSessionQueryRunning) &&
(fActDesc->fActQuery->fStatus != TQueryDescription::kSessionQuerySubmitted) )
fToolBar->GetButton(kQuerySubmit)->SetState(kButtonUp);
// trick to update feedback histos
OnCascadeMenu();
}
else { // a list (input, output)
obj = (TObject *)entry->GetParent()->GetParent()->GetUserData();
if (obj->IsA() == TSessionDescription::Class()) {
fActDesc = (TSessionDescription *)obj;
}
obj = (TObject *)entry->GetParent()->GetUserData();
if (obj->IsA() == TQueryDescription::Class()) {
fActDesc->fActQuery = (TQueryDescription *)obj;
}
if (fActDesc->fActQuery) {
// update input/output list views
fInputFrame->RemoveAll();
fOutputFrame->RemoveAll();
if (fActDesc->fActQuery->fResult) {
objlist = fActDesc->fActQuery->fResult->GetOutputList();
if (objlist) {
TIter nexto(objlist);
while ((obj = (TObject *) nexto())) {
fOutputFrame->AddObject(obj);
}
}
objlist = fActDesc->fActQuery->fResult->GetInputList();
if (objlist) {
TIter nexti(objlist);
while ((obj = (TObject *) nexti())) {
fInputFrame->AddObject(obj);
}
}
}
else {
TChain *chain = (TChain *)fActDesc->fActQuery->fChain;
if (chain) {
objlist = ((TTreePlayer *)(chain->GetPlayer()))->GetSelectorFromFile()->GetOutputList();
if (objlist) {
TIter nexto(objlist);
while ((obj = (TObject *) nexto())) {
fOutputFrame->AddObject(obj);
}
}
}
}
fInputFrame->Resize();
fOutputFrame->Resize();
fClient->NeedRedraw(fOutputFrame->GetLVContainer());
fClient->NeedRedraw(fInputFrame->GetLVContainer());
}
// switch frames
if (strstr(entry->GetText(),"Output")) {
if (fActFrame != fOutputFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fOutputFrame);
fActFrame = fOutputFrame;
}
}
else if (strstr(entry->GetText(),"Input")) {
if (fActFrame != fInputFrame) {
fV2->HideFrame(fActFrame);
fV2->ShowFrame(fInputFrame);
fActFrame = fInputFrame;
}
}
}
if (btn == 3) { // right button
// place popup menus
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
obj = (TObject *)item->GetUserData();
if (obj && obj->IsA() == TQueryDescription::Class()) {
fPopupQry->PlaceMenu(x, y, 1, 1);
}
else if (obj && obj->IsA() == TSessionDescription::Class()) {
if (!fActDesc->fLocal)
fPopupSrv->PlaceMenu(x, y, 1, 1);
}
}
// enable / disable menu entries
if (fActDesc->fConnected && fActDesc->fAttached) {
fSessionMenu->EnableEntry(kSessionGetQueries);
fSessionMenu->EnableEntry(kSessionShowStatus);
fPopupSrv->EnableEntry(kSessionGetQueries);
fPopupSrv->EnableEntry(kSessionShowStatus);
fPopupSrv->EnableEntry(kSessionDisconnect);
fPopupSrv->EnableEntry(kSessionShutdown);
fPopupSrv->EnableEntry(kSessionCleanup);
fPopupSrv->EnableEntry(kSessionReset);
fSessionMenu->EnableEntry(kSessionDisconnect);
fSessionMenu->EnableEntry(kSessionShutdown);
fSessionMenu->EnableEntry(kSessionCleanup);
fSessionMenu->EnableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonUp);
fQueryMenu->EnableEntry(kQuerySubmit);
fPopupQry->EnableEntry(kQuerySubmit);
}
else {
fSessionMenu->DisableEntry(kSessionGetQueries);
fSessionMenu->DisableEntry(kSessionShowStatus);
fPopupSrv->DisableEntry(kSessionGetQueries);
fPopupSrv->DisableEntry(kSessionShowStatus);
if (entry->GetParent() != 0)
fSessionMenu->EnableEntry(kSessionDelete);
fPopupSrv->EnableEntry(kSessionDelete);
fPopupSrv->DisableEntry(kSessionDisconnect);
fPopupSrv->DisableEntry(kSessionShutdown);
fPopupSrv->DisableEntry(kSessionCleanup);
fPopupSrv->DisableEntry(kSessionReset);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
fQueryMenu->DisableEntry(kQuerySubmit);
fPopupQry->DisableEntry(kQuerySubmit);
}
if (fActDesc->fLocal) {
fSessionMenu->DisableEntry(kSessionDelete);
fSessionMenu->DisableEntry(kSessionConnect);
fSessionMenu->DisableEntry(kSessionDisconnect);
fSessionMenu->DisableEntry(kSessionShutdown);
fSessionMenu->DisableEntry(kSessionCleanup);
fSessionMenu->DisableEntry(kSessionReset);
fToolBar->GetButton(kSessionDisconnect)->SetState(kButtonDisabled);
fToolBar->GetButton(kSessionConnect)->SetState(kButtonDisabled);
fQueryMenu->EnableEntry(kQuerySubmit);
fPopupQry->EnableEntry(kQuerySubmit);
}
}
//______________________________________________________________________________
void TSessionViewer::OnListTreeDoubleClicked(TGListTreeItem *entry, Int_t /*btn*/)
{
// Handle mouse double clicks in list tree (connect to server).
if (entry == fSessionItem)
return;
if (entry->GetParent()->GetParent() == 0) { // Server
if (entry->GetUserData()) {
TObject *obj = (TObject *)entry->GetUserData();
if (obj->IsA() != TSessionDescription::Class())
return;
fActDesc = (TSessionDescription*)obj;
// if Proof valid, update connection infos
}
if ((!fActDesc->fLocal) && ((!fActDesc->fConnected) ||
(!fActDesc->fAttached))) {
fServerFrame->OnBtnConnectClicked();
}
}
}
//______________________________________________________________________________
void TSessionViewer::Terminate()
{
// Terminate Session : save configuration, clean temporary files and close
// Proof connections.
// clean-up temporary files
TString pathtmp;
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectFile);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectCmd);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
// close opened Proof sessions (if any)
TIter next(fSessions);
TSessionDescription *desc = 0;
while ((desc = (TSessionDescription *)next())) {
if (desc->fAttached && desc->fProof &&
desc->fProof->IsValid())
desc->fProof->Detach();
}
// Save configuration
if (fAutoSave)
WriteConfiguration();
}
//______________________________________________________________________________
void TSessionViewer::CloseWindow()
{
// Close main Session Viewer window.
// clean-up temporary files
TString pathtmp;
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectFile);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
pathtmp = Form("%s/%s", gSystem->TempDirectory(), kSession_RedirectCmd);
if (!gSystem->AccessPathName(pathtmp)) {
gSystem->Unlink(pathtmp);
}
// Save configuration
if (fAutoSave)
WriteConfiguration();
fSessions->Delete();
if (fSessionItem)
fSessionHierarchy->DeleteChildren(fSessionItem);
delete fSessionHierarchy; // this has been put int TGCanvas which isn't a
// TGComposite frame and doesn't do cleanups.
fClient->FreePicture(fLocal);
fClient->FreePicture(fProofCon);
fClient->FreePicture(fProofDiscon);
fClient->FreePicture(fQueryCon);
fClient->FreePicture(fQueryDiscon);
fClient->FreePicture(fBaseIcon);
delete fTimer;
DeleteWindow();
}
//______________________________________________________________________________
void TSessionViewer::ChangeRightLogo(const char *name)
{
// Change the right logo (used for animation).
fClient->FreePicture(fRightIconPicture);
fRightIconPicture = (TGPicture *)fClient->GetPicture(name);
fRightIcon->SetPicture(fRightIconPicture);
}
//______________________________________________________________________________
void TSessionViewer::EnableTimer()
{
// Enable animation timer.
if (!fTimer) fTimer = new TTimer(this, 500);
fTimer->Reset();
fTimer->TurnOn();
time( &fStart );
}
//______________________________________________________________________________
void TSessionViewer::DisableTimer()
{
// Disable animation timer.
if (fTimer)
fTimer->TurnOff();
ChangeRightLogo("proof_disconnected.xpm");
}
//______________________________________________________________________________
Bool_t TSessionViewer::HandleTimer(TTimer *)
{
// Handle animation timer.
char line[120];
struct tm *connected;
Int_t count = gRandom->Integer(4);
if (count > 3) {
count = 0;
}
if (fChangePic)
ChangeRightLogo(xpm_names[count]);
time( &fElapsed );
time_t elapsed_time = (time_t)difftime( fElapsed, fStart );
connected = gmtime( &elapsed_time );
sprintf(line," %02d:%02d:%02d", connected->tm_hour,
connected->tm_min, connected->tm_sec);
fStatusBar->SetText(line, 2);
if (fActDesc->fLocal) {
if ((fActDesc->fActQuery) &&
(fActDesc->fActQuery->fStatus ==
TQueryDescription::kSessionQueryRunning)) {
TChain *chain = (TChain *)fActDesc->fActQuery->fChain;
if (chain)
fQueryFrame->ProgressLocal(chain->GetEntries(),
chain->GetReadEntry()+1);
}
}
fTimer->Reset();
return kTRUE;
}
//______________________________________________________________________________
void TSessionViewer::LogMessage(const char *msg, Bool_t all)
{
// Load/append a log msg in the log frame.
if (fLogWindow) {
if (all) {
// load buffer
fLogWindow->LoadBuffer(msg);
} else {
// append
fLogWindow->AddBuffer(msg);
}
}
}
//______________________________________________________________________________
void TSessionViewer::QueryResultReady(char *query)
{
// Handle signal "query result ready" coming from Proof session.
char strtmp[256];
sprintf(strtmp,"Query Result Ready for %s", query);
// show information on status bar
ShowInfo(strtmp);
TGListTreeItem *item=0, *item2=0;
TQueryDescription *lquery = 0;
// loop over actual queries to find which one is ready
TIter nexts(fSessions);
TSessionDescription *desc = 0;
// check if session is already in the list
while ((desc = (TSessionDescription *)nexts())) {
if (desc && !desc->fAttached)
continue;
TIter nextp(desc->fQueries);
while ((lquery = (TQueryDescription *)nextp())) {
if (lquery->fReference.Contains(query)) {
// results are ready for this query
lquery->fResult = desc->fProof->GetQueryResult(query);
lquery->fStatus = TQueryDescription::kSessionQueryFromProof;
if (!lquery->fResult)
break;
// get query status
lquery->fStatus = lquery->fResult->IsFinalized() ?
TQueryDescription::kSessionQueryFinalized :
(TQueryDescription::ESessionQueryStatus)lquery->fResult->GetStatus();
// get data set
TObject *o = lquery->fResult->GetInputObject("TDSet");
if (o)
lquery->fChain = (TDSet *) o;
item = fSessionHierarchy->FindItemByObj(fSessionItem, desc);
if (item) {
item2 = fSessionHierarchy->FindItemByObj(item, lquery);
}
if (item2) {
// add input and output list entries
if (lquery->fResult->GetInputList())
if (!fSessionHierarchy->FindChildByName(item2, "InputList"))
fSessionHierarchy->AddItem(item2, "InputList");
if (lquery->fResult->GetOutputList())
if (!fSessionHierarchy->FindChildByName(item2, "OutputList"))
fSessionHierarchy->AddItem(item2, "OutputList");
}
// update list tree, query frame informations, and buttons state
fClient->NeedRedraw(fSessionHierarchy);
fQueryFrame->UpdateInfos();
fQueryFrame->UpdateButtons(lquery);
break;
}
}
}
}
//______________________________________________________________________________
void TSessionViewer::CleanupSession()
{
// Clean-up Proof session.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TSessionDescription::Class()) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid()) return;
TString m;
m.Form("Are you sure to cleanup the session \"%s::%s\"",
fActDesc->fName.Data(), fActDesc->fTag.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBYes | kMBNo | kMBCancel, &result);
if (result == kMBYes) {
// send cleanup request for the session specified by the tag reference
TString sessiontag;
sessiontag.Form("session-%s",fActDesc->fTag.Data());
fActDesc->fProof->CleanupSession(sessiontag.Data());
// clear the list of queries
fActDesc->fQueries->Clear();
fSessionHierarchy->DeleteChildren(item);
fSessionFrame->OnBtnGetQueriesClicked();
if (fAutoSave)
WriteConfiguration();
}
// update list tree
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::ResetSession()
{
// Reset Proof session.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TSessionDescription::Class()) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid()) return;
TString m;
m.Form("Do you really want to reset the session \"%s::%s\"",
fActDesc->fName.Data(), fActDesc->fAddress.Data());
Int_t result;
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), 0,
kMBYes | kMBNo | kMBCancel, &result);
if (result == kMBYes) {
// reset the session
TProof::Mgr(fActDesc->fAddress)->Reset(fActDesc->fUserName);
// reset connected flag
fActDesc->fAttached = kFALSE;
fActDesc->fProof = 0;
// disable animation timer
DisableTimer();
// change list tree item picture to disconnected pixmap
TGListTreeItem *item = fSessionHierarchy->FindChildByData(
fSessionItem, fActDesc);
item->SetPictures(fProofDiscon, fProofDiscon);
OnListTreeClicked(fSessionHierarchy->GetSelected(), 1, 0, 0);
fClient->NeedRedraw(fSessionHierarchy);
fStatusBar->SetText("", 1);
}
// update list tree
fClient->NeedRedraw(fSessionHierarchy);
}
//______________________________________________________________________________
void TSessionViewer::DeleteQuery()
{
// Delete query from list tree and ask user if he wants do delete it also
// from server.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
TString m;
Int_t result = 0;
if (fActDesc->fAttached && fActDesc->fProof && fActDesc->fProof->IsValid()) {
if ((fActDesc->fActQuery->fStatus == TQueryDescription::kSessionQuerySubmitted) ||
(fActDesc->fActQuery->fStatus == TQueryDescription::kSessionQueryRunning) ) {
new TGMsgBox(fClient->GetRoot(), this, "Delete Query",
"Deleting running queries is not allowed", kMBIconExclamation,
kMBOk, &result);
return;
}
m.Form("Do you want to delete query \"%s\" from server too ?",
query->fQueryName.Data());
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), kMBIconQuestion,
kMBYes | kMBNo | kMBCancel, &result);
}
else {
m.Form("Dou you really want to delete query \"%s\" ?",
query->fQueryName.Data());
new TGMsgBox(fClient->GetRoot(), this, "", m.Data(), kMBIconQuestion,
kMBOk | kMBCancel, &result);
}
if (result == kMBYes) {
fActDesc->fProof->Remove(query->fReference.Data());
fActDesc->fQueries->Remove((TObject *)query);
fSessionHierarchy->DeleteItem(item);
delete query;
}
else if (result == kMBNo || result == kMBOk) {
fActDesc->fQueries->Remove((TObject *)query);
fSessionHierarchy->DeleteItem(item);
delete query;
}
fClient->NeedRedraw(fSessionHierarchy);
if (fAutoSave)
WriteConfiguration();
}
//______________________________________________________________________________
void TSessionViewer::EditQuery()
{
// Edit currently selected query.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
TNewQueryDlg *dlg = new TNewQueryDlg(this, 350, 310, query, kTRUE);
dlg->Popup();
}
//______________________________________________________________________________
void TSessionViewer::StartViewer()
{
// Start TreeViewer from selected TChain.
TGListTreeItem *item = fSessionHierarchy->GetSelected();
if (!item) return;
TObject *obj = (TObject *)item->GetUserData();
if (obj->IsA() != TQueryDescription::Class()) return;
TQueryDescription *query = (TQueryDescription *)obj;
if (!query->fChain && query->fResult &&
(obj = query->fResult->GetInputObject("TDSet"))) {
query->fChain = (TDSet *) obj;
}
if (query->fChain->IsA() == TChain::Class())
((TChain *)query->fChain)->StartViewer();
else if (query->fChain->IsA() == TDSet::Class())
((TDSet *)query->fChain)->StartViewer();
}
//______________________________________________________________________________
void TSessionViewer::ShowPackages()
{
// Query the list of uploaded packages from proof and display it
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fLocal) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->ShowPackages(kTRUE);
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::UpdateListOfPackages()
{
// Update the list of packages.
TObjString *packname;
TPackageDescription *package;
if (fActDesc->fConnected && fActDesc->fAttached &&
fActDesc->fProof && fActDesc->fProof->IsValid() &&
fActDesc->fProof->IsParallel()) {
//fActDesc->fPackages->Clear();
TList *packlist = fActDesc->fProof->GetListOfEnabledPackages();
if(packlist) {
TIter nextenabled(packlist);
while ((packname = (TObjString *)nextenabled())) {
package = new TPackageDescription;
package->fName = packname->GetName();
package->fName += ".par";
package->fPathName = package->fName;
package->fId = fActDesc->fPackages->GetEntries();
package->fUploaded = kTRUE;
package->fEnabled = kTRUE;
if (!fActDesc->fPackages->FindObject(package->fName)) {
fActDesc->fPackages->Add((TObject *)package);
}
}
}
packlist = fActDesc->fProof->GetListOfPackages();
if(packlist) {
TIter nextpack(packlist);
while ((packname = (TObjString *)nextpack())) {
package = new TPackageDescription;
package->fName = packname->GetName();
package->fName += ".par";
package->fPathName = package->fName;
package->fId = fActDesc->fPackages->GetEntries();
package->fUploaded = kTRUE;
package->fEnabled = kFALSE;
if (!fActDesc->fPackages->FindObject(package->fName)) {
fActDesc->fPackages->Add((TObject *)package);
}
}
}
}
// fSessionFrame->UpdatePackages();
}
//______________________________________________________________________________
void TSessionViewer::ShowEnabledPackages()
{
// Query list of enabled packages from proof and display it
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fLocal) return;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->ShowEnabledPackages(kTRUE);
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::ShowLog(const char *queryref)
{
// Display the content of the temporary log file for queryref
// into a new text window.
Window_t wdummy;
Int_t ax, ay;
if (fActDesc->fProof) {
gVirtualX->SetCursor(GetId(),gVirtualX->CreateCursor(kWatch));
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fActDesc->fProof->Connect("LogMessage(const char*,Bool_t)",
"TSessionViewer", this, "LogMessage(const char*,Bool_t)");
Bool_t logonly = fActDesc->fProof->SendingLogToWindow();
fActDesc->fProof->SendLogToWindow(kTRUE);
if (queryref)
fActDesc->fProof->ShowLog(queryref);
else
fActDesc->fProof->ShowLog(0);
fActDesc->fProof->SendLogToWindow(logonly);
// set log window position at the bottom of Session Viewer
gVirtualX->TranslateCoordinates(GetId(),
fClient->GetDefaultRoot()->GetId(), 0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
gVirtualX->SetCursor(GetId(), 0);
}
}
//______________________________________________________________________________
void TSessionViewer::ShowInfo(const char *txt)
{
// Display text in status bar.
fStatusBar->SetText(txt,0);
fClient->NeedRedraw(fStatusBar);
gSystem->ProcessEvents();
}
//______________________________________________________________________________
void TSessionViewer::ShowStatus()
{
// Retrieve and display Proof status.
Window_t wdummy;
Int_t ax, ay;
if (!fActDesc->fProof || !fActDesc->fProof->IsValid())
return;
TString pathtmp = Form("%s/%s", gSystem->TempDirectory(),
kSession_RedirectFile);
// redirect stdout/stderr to temp file
if (gSystem->RedirectOutput(pathtmp.Data(), "w") != 0) {
Error("ShowStatus", "stdout/stderr redirection failed; skipping");
return;
}
fActDesc->fProof->GetStatus();
// restore stdout/stderr
if (gSystem->RedirectOutput(0) != 0) {
Error("ShowStatus", "stdout/stderr retore failed; skipping");
return;
}
if (!fLogWindow) {
fLogWindow = new TSessionLogView(this, 700, 100);
} else {
// Clear window
fLogWindow->Clear();
}
fLogWindow->LoadFile(pathtmp.Data());
gVirtualX->TranslateCoordinates(GetId(), fClient->GetDefaultRoot()->GetId(),
0, 0, ax, ay, wdummy);
fLogWindow->Move(ax, ay + GetHeight() + 35);
fLogWindow->Popup();
}
//______________________________________________________________________________
void TSessionViewer::StartupMessage(char *msg, Bool_t, Int_t done, Int_t total)
{
// Handle startup message (connection progress) coming from Proof session.
Float_t pos = Float_t(Double_t(done * 100)/Double_t(total));
fConnectProg->SetPosition(pos);
fStatusBar->SetText(msg, 1);
}
//______________________________________________________________________________
void TSessionViewer::MyHandleMenu(Int_t id)
{
// Handle session viewer custom popup menus.
switch (id) {
case kSessionDelete:
fServerFrame->OnBtnDeleteClicked();
break;
case kSessionConnect:
fServerFrame->OnBtnConnectClicked();
break;
case kSessionDisconnect:
fSessionFrame->OnBtnDisconnectClicked();
break;
case kSessionShutdown:
fSessionFrame->ShutdownSession();
break;
case kSessionCleanup:
CleanupSession();
break;
case kSessionReset:
ResetSession();
break;
case kSessionBrowse:
if (fActDesc->fProof && fActDesc->fProof->IsValid()) {
TBrowser *b = new TBrowser();
fActDesc->fProof->Browse(b);
}
break;
case kSessionShowStatus:
ShowStatus();
break;
case kSessionGetQueries:
fSessionFrame->OnBtnGetQueriesClicked();
break;
case kQueryEdit:
EditQuery();
break;
case kQueryDelete:
DeleteQuery();
break;
case kQueryStartViewer:
StartViewer();
break;
case kQuerySubmit:
fQueryFrame->OnBtnSubmit();
break;
}
}
//______________________________________________________________________________
void TSessionViewer::OnCascadeMenu()
{
// Handle feedback histograms configuration menu.
// divide stats canvas by number of selected feedback histos
fQueryFrame->GetStatsCanvas()->cd();
fQueryFrame->GetStatsCanvas()->Clear();
fQueryFrame->GetStatsCanvas()->Modified();
fQueryFrame->GetStatsCanvas()->Update();
if (!fActDesc || !fActDesc->fActQuery) return;
fActDesc->fNbHistos = 0;
Int_t i = 0;
if (fActDesc->fAttached && fActDesc->fProof &&
fActDesc->fProof->IsValid()) {
if (fOptionsMenu->IsEntryChecked(kOptionsFeedback)) {
// browse list of feedback histos and check user's selected ones
while (kFeedbackHistos[i]) {
if (fCascadeMenu->IsEntryChecked(41+i)) {
fActDesc->fProof->AddFeedback(kFeedbackHistos[i]);
}
i++;
}
}
else {
// if feedback option not selected, clear Proof's feedback option
fActDesc->fProof->ClearFeedback();
}
}
i = 0;
// loop over feedback histo list
while (kFeedbackHistos[i]) {
// check if user has selected this histogram in the option menu
if (fCascadeMenu->IsEntryChecked(41+i))
fActDesc->fNbHistos++;
i++;
}
fQueryFrame->GetStatsCanvas()->SetEditable(kTRUE);
fQueryFrame->GetStatsCanvas()->Clear();
if (fActDesc->fNbHistos == 4)
fQueryFrame->GetStatsCanvas()->Divide(2, 2);
else if (fActDesc->fNbHistos > 4)
fQueryFrame->GetStatsCanvas()->Divide(3, 2);
else
fQueryFrame->GetStatsCanvas()->Divide(fActDesc->fNbHistos, 1);
// if actual query has results, update feedback histos
if (fActDesc->fActQuery && fActDesc->fActQuery->fResult &&
fActDesc->fActQuery->fResult->GetOutputList()) {
fQueryFrame->UpdateHistos(fActDesc->fActQuery->fResult->GetOutputList());
fQueryFrame->ResetProgressDialog("", 0, 0, 0);
}
else if (fActDesc->fActQuery) {
fQueryFrame->ResetProgressDialog(fActDesc->fActQuery->fSelectorString,
fActDesc->fActQuery->fNbFiles,
fActDesc->fActQuery->fFirstEntry,
fActDesc->fActQuery->fNoEntries);
}
fQueryFrame->UpdateInfos();
}
//______________________________________________________________________________
Bool_t TSessionViewer::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
// Handle messages send to the TSessionViewer object. E.g. all menu entries
// messages.
TNewQueryDlg *dlg;
switch (GET_MSG(msg)) {
case kC_COMMAND:
switch (GET_SUBMSG(msg)) {
case kCM_BUTTON:
case kCM_MENU:
switch (parm1) {
case kFileCloseViewer:
CloseWindow();
break;
case kFileLoadConfig:
{
TGFileInfo fi;
fi.fFilename = (char *)gSystem->BaseName(fConfigFile);
fi.fIniDir = strdup((char *)gSystem->HomeDirectory());
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), this, kFDOpen, &fi);
if (fi.fFilename) {
fConfigFile = fi.fFilename;
ReadConfiguration(fConfigFile);
OnListTreeClicked(fSessionHierarchy->GetSelected(), 1, 0, 0);
}
}
break;
case kFileSaveConfig:
{
TGFileInfo fi;
fi.fFilename = (char *)gSystem->BaseName(fConfigFile);
fi.fIniDir = strdup((char *)gSystem->HomeDirectory());
fi.fFileTypes = conftypes;
new TGFileDialog(fClient->GetRoot(), this, kFDSave, &fi);
if (fi.fFilename) {
fConfigFile = fi.fFilename;
WriteConfiguration(fConfigFile);
}
}
break;
case kFileQuit:
Terminate();
if (!gApplication->ReturnFromRun())
delete this;
gApplication->Terminate(0);
break;
case kSessionNew:
fServerFrame->OnBtnNewServerClicked();
break;
case kSessionAdd:
fServerFrame->OnBtnAddClicked();
break;
case kSessionDelete:
fServerFrame->OnBtnDeleteClicked();
break;
case kSessionCleanup:
CleanupSession();
break;
case kSessionReset:
ResetSession();
break;
case kSessionConnect:
fServerFrame->OnBtnConnectClicked();
break;
case kSessionDisconnect:
fSessionFrame->OnBtnDisconnectClicked();
break;
case kSessionShutdown:
fSessionFrame->ShutdownSession();
break;
case kSessionShowStatus:
ShowStatus();
break;
case kSessionGetQueries:
fSessionFrame->OnBtnGetQueriesClicked();
break;
case kQueryNew:
dlg = new TNewQueryDlg(this, 350, 310);
dlg->Popup();
break;
case kQueryEdit:
EditQuery();
break;
case kQueryDelete:
DeleteQuery();
break;
case kQueryStartViewer:
StartViewer();
break;
case kQuerySubmit:
fQueryFrame->OnBtnSubmit();
break;
case kOptionsAutoSave:
if(fOptionsMenu->IsEntryChecked(kOptionsAutoSave)) {
fOptionsMenu->UnCheckEntry(kOptionsAutoSave);
fAutoSave = kFALSE;
}
else {
fOptionsMenu->CheckEntry(kOptionsAutoSave);
fAutoSave = kTRUE;
}
break;
case kOptionsStatsHist:
if(fOptionsMenu->IsEntryChecked(kOptionsStatsHist)) {
fOptionsMenu->UnCheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsStatsHist);
gEnv->SetValue("Proof.StatsHist", 1);
}
break;
case kOptionsStatsTrace:
if(fOptionsMenu->IsEntryChecked(kOptionsStatsTrace)) {
fOptionsMenu->UnCheckEntry(kOptionsStatsTrace);
gEnv->SetValue("Proof.StatsTrace", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsStatsTrace);
gEnv->SetValue("Proof.StatsTrace", 1);
}
break;
case kOptionsSlaveStatsTrace:
if(fOptionsMenu->IsEntryChecked(kOptionsSlaveStatsTrace)) {
fOptionsMenu->UnCheckEntry(kOptionsSlaveStatsTrace);
gEnv->SetValue("Proof.SlaveStatsTrace", 0);
}
else {
fOptionsMenu->CheckEntry(kOptionsSlaveStatsTrace);
gEnv->SetValue("Proof.SlaveStatsTrace", 1);
}
break;
case kOptionsFeedback:
if(fOptionsMenu->IsEntryChecked(kOptionsFeedback)) {
fOptionsMenu->UnCheckEntry(kOptionsFeedback);
}
else {
fOptionsMenu->CheckEntry(kOptionsFeedback);
}
break;
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
if (fCascadeMenu->IsEntryChecked(parm1)) {
fCascadeMenu->UnCheckEntry(parm1);
}
else {
fCascadeMenu->CheckEntry(parm1);
}
OnCascadeMenu();
break;
case 50:
if (fCascadeMenu->IsEntryChecked(parm1)) {
fCascadeMenu->UnCheckEntry(parm1);
}
else {
fCascadeMenu->CheckEntry(parm1);
}
OnCascadeMenu();
break;
case kHelpAbout:
{
#ifdef R__UNIX
TString rootx;
# ifdef ROOTBINDIR
rootx = ROOTBINDIR;
# else
rootx = gSystem->Getenv("ROOTSYS");
if (!rootx.IsNull()) rootx += "/bin";
# endif
rootx += "/root -a &";
gSystem->Exec(rootx);
#else
#ifdef WIN32
new TWin32SplashThread(kTRUE);
#else
char str[32];
sprintf(str, "About ROOT %s...", gROOT->GetVersion());
TRootHelpDialog *hd = new TRootHelpDialog(this, str, 600, 400);
hd->SetText(gHelpAbout);
hd->Popup();
#endif
#endif
}
break;
default:
break;
}
default:
break;
}
default:
break;
}
return kTRUE;
}
|
//
// pipeline-control-state-machine.cpp
//
// Created by Peter Gusev on 10 June 2016.
// Copyright 2013-2016 Regents of the University of California
//
#include "pipeline-control-state-machine.hpp"
#include <boost/make_shared.hpp>
#include <boost/assign.hpp>
#include "clock.hpp"
#include "latency-control.hpp"
#include "interest-control.hpp"
#include "pipeliner.hpp"
#include "frame-data.hpp"
#include "playout-control.hpp"
#include "statistics.hpp"
#include "sample-estimator.hpp"
using namespace ndnrtc;
using namespace ndnrtc::statistics;
namespace ndnrtc
{
const std::string kStateIdle = "Idle";
const std::string kStateBootstrapping = "Bootstrapping";
const std::string kStateAdjusting = "Adjusting";
const std::string kStateFetching = "Fetching";
}
#define STATE_TRANSITION(s, t) (StateEventPair(s, PipelineControlEvent::Type::t))
#define MAKE_TRANSITION(s, t) (StateEventPair(s, t))
#define ENABLE_IF(T, M) template <typename U = T, typename boost::enable_if<typename boost::is_same<M, U>>::type... X>
#define LOG_USING(ptr, lvl) boost::dynamic_pointer_cast<ndnlog::new_api::ILoggingObject>(ptr)->getLogger()->log((ndnlog::NdnLogType)lvl, boost::dynamic_pointer_cast<ndnlog::new_api::ILoggingObject>(ptr).get())
template <typename MetadataClass>
class ReceivedMetadataProcessing
{
public:
ReceivedMetadataProcessing() : metadataRequestedMs_(0), metadataReceivedMs_(0) {}
protected:
ENABLE_IF(MetadataClass, VideoThreadMeta)
bool processMetadata(boost::shared_ptr<VideoThreadMeta> metadata,
boost::shared_ptr<PipelineControlStateMachine::Struct> ctrl)
{
if (metadata)
{
unsigned char gopPos = metadata->getGopPos();
unsigned int gopSize = metadata->getCoderParams().gop_;
PacketNumber deltaToFetch, keyToFetch;
double metadataDrd = (double)getMetadataDrd();
unsigned int pipelineInitial =
ctrl->interestControl_->getCurrentStrategy()->calculateDemand(metadata->getRate(),
metadataDrd, metadataDrd * 0.05);
LOG_USING(ctrl->pipeliner_, ndnlog::NdnLoggerLevelDebug)
<< "received metadata. delta seq " << metadata->getSeqNo().first
<< " key seq " << metadata->getSeqNo().second
<< " gop pos " << (int)gopPos
<< " gop size " << gopSize
<< " rate " << metadata->getRate()
<< " drd " << metadataDrd
<< std::endl;
// add some smart logic about what to fetch next...
if (gopPos < ((float)gopSize / 2.))
{
// initial pipeline size helps us determine from which delta frame we need to start playback
startOffSeqNums_.first = metadata->getSeqNo().first + pipelineInitial;
startOffSeqNums_.second = metadata->getSeqNo().second;
// now we need to determine sequence number of delta from which we need to start fetching
// for this case, it will be the beginning of the GOP
PacketNumber firstDeltaInGop = (gopPos ? metadata->getSeqNo().first - (gopPos - 1) : metadata->getSeqNo().first);
deltaToFetch = firstDeltaInGop;
keyToFetch = metadata->getSeqNo().second;
pipelineInitial += gopPos;
}
else
{
startOffSeqNums_.first = (pipelineInitial < (gopSize-gopPos) ? -1 : metadata->getSeqNo().first + pipelineInitial;
startOffSeqNums_.second = metadata->getSeqNo().second + 1;
// should fetch next key
deltaToFetch = metadata->getSeqNo().first;
keyToFetch = metadata->getSeqNo().second + 1;
pipelineInitial += (gopSize - gopPos);
}
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().deltaAvgSegNum_,
SampleClass::Delta, SegmentClass::Data);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().deltaAvgParitySegNum_,
SampleClass::Delta, SegmentClass::Parity);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().keyAvgSegNum_,
SampleClass::Key, SegmentClass::Data);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().keyAvgParitySegNum_,
SampleClass::Key, SegmentClass::Parity);
ctrl->interestControl_->initialize(metadata->getRate(), pipelineInitial);
ctrl->pipeliner_->setSequenceNumber(deltaToFetch, SampleClass::Delta);
ctrl->pipeliner_->setSequenceNumber(keyToFetch, SampleClass::Key);
ctrl->pipeliner_->setNeedSample(SampleClass::Key);
ctrl->pipeliner_->segmentArrived(ctrl->threadPrefix_);
bootstrapSeqNums_.first = deltaToFetch;
bootstrapSeqNums_.second = keyToFetch;
LOG_USING(ctrl->playoutControl_, ndnlog::NdnLoggerLevelInfo)
<< "playback start off sequence numbers: "
<< startOffSeqNums_.first << " (delta) "
<< startOffSeqNums_.second << " (key)"
<< std::endl;
return true;
}
return false;
}
// TODO: update code for audio too
ENABLE_IF(MetadataClass, AudioThreadMeta)
bool processMetadata(boost::shared_ptr<AudioThreadMeta> metadata,
boost::shared_ptr<PipelineControlStateMachine::Struct> ctrl)
{
if (metadata)
{
PacketNumber bundleNo = metadata->getBundleNo();
// TODO: this needs to be calculated based on current sample rate and DRD
unsigned int pipelineInitial = 2 * InterestControl::MinPipelineSize;
ctrl->interestControl_->initialize(metadata->getRate(), pipelineInitial);
ctrl->pipeliner_->setSequenceNumber(bundleNo, SampleClass::Delta);
ctrl->pipeliner_->setNeedSample(SampleClass::Delta);
ctrl->pipeliner_->segmentArrived(ctrl->threadPrefix_);
bootstrapSeqNums_.first = bundleNo;
bootstrapSeqNums_.second = -1;
return true;
}
return false;
}
boost::shared_ptr<MetadataClass> extractMetadata(boost::shared_ptr<const WireSegment> segment)
{
ImmutableHeaderPacket<DataSegmentHeader> packet(segment->getData()->getContent());
NetworkData nd(packet.getPayload().size(), packet.getPayload().data());
return boost::make_shared<MetadataClass>(boost::move(nd));
}
protected:
void markMetadataRequested() { metadataRequestedMs_ = clock::millisecondTimestamp(); }
void markMetadataReceived() { metadataReceivedMs_ = clock::millisecondTimestamp(); }
int64_t getMetadataDrd() { return (metadataReceivedMs_ - metadataRequestedMs_); }
ENABLE_IF(MetadataClass, AudioThreadMeta)
PacketNumber getStartOffSequenceNumber() { return startOffSeqNums_.first; }
ENABLE_IF(MetadataClass, AudioThreadMeta)
PacketNumber getBootstrapSequenceNumber() { return bootstrapSeqNums_.first; }
ENABLE_IF(MetadataClass, VideoThreadMeta)
std::pair<PacketNumber, PacketNumber> getStartOffSequenceNumber() { return startOffSeqNums_; }
ENABLE_IF(MetadataClass, VideoThreadMeta)
std::pair<PacketNumber, PacketNumber> getBootstrapSequenceNumber() { return bootstrapSeqNums_; }
private:
int64_t metadataRequestedMs_, metadataReceivedMs_;
std::pair<PacketNumber, PacketNumber> bootstrapSeqNums_;
std::pair<PacketNumber, PacketNumber> startOffSeqNums_;
};
/**
* Idle state. System is in idle state when it first created.
* On entry:
* - resets control structures (pipeliner, interest control, latency control, etc.)
* On exit:
* - nothing
* Processed events:
* - Start: switches to Bootstrapping
* - Init: switches to Adjusting
* - Reset: resets control structures
*/
class Idle : public PipelineControlState
{
public:
Idle(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateIdle; }
void enter() override
{
ctrl_->buffer_->reset();
ctrl_->pipeliner_->reset();
ctrl_->latencyControl_->reset();
ctrl_->interestControl_->reset();
ctrl_->playoutControl_->allowPlayout(false);
}
int toInt() override { return (int)StateId::Idle; }
};
/**
* Bootstrapping state. Sytem is in this state while waiting for the answer of
* the thread metadata Interest.
* On entry:
* - sends out metadata Interest (accesses pipeliner)
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: ignored
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: transition to Adjusting state
*/
template <typename MetadataClass>
class BootstrappingT : public PipelineControlState,
public ReceivedMetadataProcessing<MetadataClass>
{
public:
BootstrappingT(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateBootstrapping; }
void enter() override { askMetadata(); }
int toInt() override { return (int)StateId::Bootstrapping; }
protected:
std::string onTimeout(const boost::shared_ptr<const EventTimeout> &ev) override
{
askMetadata();
return str();
}
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override
{
if (ev->getSegment()->isMeta())
return receivedMetadata(boost::dynamic_pointer_cast<const EventSegment>(ev));
else
{ // process frame segments
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
// check whether it's time to switch
if (receivedStartOffSegment(ev->getSegment()))
{
// since we are fetching older frames, we'll need to fast forward playback
// to minimize playback latency
int playbackFastForwardMs = calculatePlaybackFfwdInterval(ev->getSegment());
ctrl_->playoutControl_->allowPlayout(true, playbackFastForwardMs);
return kStateAdjusting;
}
return str();
}
}
void askMetadata()
{
ReceivedMetadataProcessing<MetadataClass>::markMetadataRequested();
ctrl_->pipeliner_->setNeedMetadata();
ctrl_->pipeliner_->express(ctrl_->threadPrefix_);
}
std::string receivedMetadata(const boost::shared_ptr<const EventSegment> &ev)
{
ReceivedMetadataProcessing<MetadataClass>::markMetadataReceived();
metadata_ = ReceivedMetadataProcessing<MetadataClass>::extractMetadata(ev->getSegment());
ReceivedMetadataProcessing<MetadataClass>::processMetadata(metadata_, ctrl_);
// if (metadata && ReceivedMetadataProcessing<MetadataClass>::processMetadata(metadata, ctrl_))
// return kStateAdjusting;
return kStateBootstrapping;
}
private:
boost::shared_ptr<MetadataClass> metadata_;
ENABLE_IF(MetadataClass, AudioThreadMeta)
bool receivedStartOffSegment(const boost::shared_ptr<const WireSegment> &seg)
{
// TODO: finish it for audio
return true;
}
ENABLE_IF(MetadataClass, AudioThreadMeta)
int calculatePlaybackFfwdInterval(const boost::shared_ptr<const WireSegment> &seg)
{
return 0;
}
ENABLE_IF(MetadataClass, VideoThreadMeta)
bool receivedStartOffSegment(const boost::shared_ptr<const WireSegment> &seg)
{
// compare sequence number of received sample with saved start off sequence numbers
PacketNumber startOffDeltaSeqNo = ReceivedMetadataProcessing<MetadataClass>::getStartOffSequenceNumber().first;
PacketNumber startOffKeySeqNo = ReceivedMetadataProcessing<MetadataClass>::getStartOffSequenceNumber().second;
boost::shared_ptr<const WireData<VideoFrameSegmentHeader>> videoFrameSegment =
boost::dynamic_pointer_cast<const WireData<VideoFrameSegmentHeader>>(seg);
ImmutableHeaderPacket<VideoFrameSegmentHeader> segmentPacket = videoFrameSegment->segment();
PacketNumber currentDeltaSeqNo = seg->isDelta() ? seg->getSampleNo() : segmentPacket.getHeader().pairedSequenceNo_ ;
PacketNumber currentKeySeqNo = seg->isDelta() ? segmentPacket.getHeader().pairedSequenceNo_ : seg->getSampleNo() ;
return (currentDeltaSeqNo >= startOffDeltaSeqNo) && (currentKeySeqNo >= startOffKeySeqNo);
}
ENABLE_IF(MetadataClass, VideoThreadMeta)
int calculatePlaybackFfwdInterval(const boost::shared_ptr<const WireSegment> &seg)
{
boost::shared_ptr<const WireData<VideoFrameSegmentHeader>> videoFrameSegment =
boost::dynamic_pointer_cast<const WireData<VideoFrameSegmentHeader>>(seg);
ImmutableHeaderPacket<VideoFrameSegmentHeader> segmentPacket = videoFrameSegment->segment();
PacketNumber currentDeltaSeqNo = seg->isDelta() ? seg->getSampleNo() : segmentPacket.getHeader().pairedSequenceNo_;
return (int)((double)(currentDeltaSeqNo - ReceivedMetadataProcessing<MetadataClass>::getBootstrapSequenceNumber().first) * metadata_->getRate());
}
};
typedef BootstrappingT<AudioThreadMeta> BootstrappingAudio;
typedef BootstrappingT<VideoThreadMeta> BootstrappingVideo;
/**
* Adjusting state. System is in this state while it tries to minimize the size
* of the pipeline.
* On entry:
* - does nothing
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: resets to idle
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: checks interest control (for pipeline decreases), checks latency
* control whether latest data arrival stopped, if so, restores previous
* pipeline size and transitions to Fetching state
*/
class Adjusting : public PipelineControlState
{
public:
Adjusting(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateAdjusting; }
void enter() override;
int toInt() override { return (int)StateId::Adjusting; }
private:
unsigned int pipelineLowerLimit_;
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override;
};
/**
* Fetching state. System is in this state when it receives latest data and
* the pipeline size is minimized.
* On entry:
* - does nothing
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: resets to idle
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: checks interest control, checks latency control, transitions to
* Adjust state if latest data arrival stops
*/
class Fetching : public PipelineControlState
{
public:
Fetching(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateFetching; }
int toInt() override { return (int)StateId::Fetching; }
private:
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override;
};
//******************************************************************************
std::string
PipelineControlEvent::toString() const
{
switch (e_)
{
case PipelineControlEvent::Start:
return "Start";
case PipelineControlEvent::Reset:
return "Reset";
case PipelineControlEvent::Starvation:
return "Starvation";
case PipelineControlEvent::Segment:
return "Segment";
case PipelineControlEvent::Timeout:
return "Timeout";
default:
return "Unknown";
}
}
//******************************************************************************
PipelineControlStateMachine
PipelineControlStateMachine::defaultStateMachine(PipelineControlStateMachine::Struct ctrl)
{
boost::shared_ptr<PipelineControlStateMachine::Struct>
pctrl(boost::make_shared<PipelineControlStateMachine::Struct>(ctrl));
return PipelineControlStateMachine(pctrl, defaultConsumerStatesMap(pctrl));
}
PipelineControlStateMachine
PipelineControlStateMachine::videoStateMachine(Struct ctrl)
{
boost::shared_ptr<PipelineControlStateMachine::Struct>
pctrl(boost::make_shared<PipelineControlStateMachine::Struct>(ctrl));
return PipelineControlStateMachine(pctrl, videoConsumerStatesMap(pctrl));
}
PipelineControlStateMachine::StatesMap
PipelineControlStateMachine::defaultConsumerStatesMap(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl)
{
return {
{kStateIdle, boost::make_shared<Idle>(ctrl)},
{kStateBootstrapping, boost::make_shared<BootstrappingAudio>(ctrl)},
{kStateAdjusting, boost::make_shared<Adjusting>(ctrl)},
{kStateFetching, boost::make_shared<Fetching>(ctrl)}};
}
PipelineControlStateMachine::StatesMap
PipelineControlStateMachine::videoConsumerStatesMap(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl)
{
return {
{kStateIdle, boost::make_shared<Idle>(ctrl)},
{kStateBootstrapping, boost::make_shared<BootstrappingVideo>(ctrl)},
{kStateAdjusting, boost::make_shared<Adjusting>(ctrl)},
{kStateFetching, boost::make_shared<Fetching>(ctrl)}};
}
//******************************************************************************
PipelineControlStateMachine::PipelineControlStateMachine(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl,
PipelineControlStateMachine::StatesMap statesMap)
: ppCtrl_(ctrl),
states_(statesMap),
currentState_(states_[kStateIdle]),
lastEventTimestamp_(clock::millisecondTimestamp())
{
assert(ppCtrl_->buffer_.get());
assert(ppCtrl_->pipeliner_.get());
assert(ppCtrl_->interestControl_.get());
assert(ppCtrl_->latencyControl_.get());
assert(ppCtrl_->playoutControl_.get());
currentState_->enter();
description_ = "state-machine";
// add indirection to avoid confusion in C++11 (Ubuntu)
const TransitionMap m = boost::assign::map_list_of
(STATE_TRANSITION(kStateIdle, Start), kStateBootstrapping)
(STATE_TRANSITION(kStateBootstrapping, Reset), kStateIdle)
(STATE_TRANSITION(kStateAdjusting, Reset), kStateIdle)
(STATE_TRANSITION(kStateAdjusting, Starvation), kStateIdle)
(STATE_TRANSITION(kStateFetching, Reset), kStateIdle)
(STATE_TRANSITION(kStateFetching, Starvation), kStateIdle);
stateMachineTable_ = m;
}
PipelineControlStateMachine::~PipelineControlStateMachine()
{
currentState_->exit();
}
std::string
PipelineControlStateMachine::getState() const
{
return currentState_->str();
}
void PipelineControlStateMachine::dispatch(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
// dispatchEvent allows current state to react to the event.
// if state need to be switched, then next state name is returned.
// every state knows its own behavior to the event.
// state might also ignore the event. in this case, it returns
// its own name.
std::string nextState = currentState_->dispatchEvent(ev);
// if we got new state - transition to it
if (nextState != currentState_->str())
{
if (states_.find(nextState) == states_.end())
throw std::runtime_error(std::string("Unsupported state: " + nextState).c_str());
switchToState(states_[nextState], ev);
}
else
// otherwise - check whether state machine table defines transition
// for this event
if (!transition(ev))
{
for (auto o : observers_)
o->onStateMachineReceivedEvent(ev, currentState_->str());
}
}
void PipelineControlStateMachine::attach(IPipelineControlStateMachineObserver *observer)
{
if (observer)
observers_.push_back(observer);
}
void PipelineControlStateMachine::detach(IPipelineControlStateMachineObserver *observer)
{
std::vector<IPipelineControlStateMachineObserver *>::iterator it = std::find(observers_.begin(), observers_.end(), observer);
if (it != observers_.end())
observers_.erase(it);
}
#pragma mark - private
bool PipelineControlStateMachine::transition(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
if (stateMachineTable_.find(MAKE_TRANSITION(currentState_->str(), ev->getType())) ==
stateMachineTable_.end())
return false;
std::string stateStr = stateMachineTable_[MAKE_TRANSITION(currentState_->str(), ev->getType())];
switchToState(states_[stateStr], ev);
return true;
}
void PipelineControlStateMachine::switchToState(const boost::shared_ptr<PipelineControlState> &state,
const boost::shared_ptr<const PipelineControlEvent> &event)
{
int64_t now = clock::millisecondTimestamp();
int64_t stateDuration = (lastEventTimestamp_ ? now - lastEventTimestamp_ : 0);
lastEventTimestamp_ = now;
LogInfoC << "[" << currentState_->str() << "]-("
<< event->toString() << ")->[" << state->str() << "] "
<< stateDuration << "ms" << std::endl;
currentState_->exit();
currentState_ = state;
currentState_->enter();
for (auto o : observers_)
o->onStateMachineChangedState(event, currentState_->str());
if (event->toString() == boost::make_shared<EventStarvation>(0)->toString())
(*ppCtrl_->sstorage_)[Indicator::RebufferingsNum]++;
(*ppCtrl_->sstorage_)[Indicator::State] = (double)state->toInt();
}
//******************************************************************************
std::string
PipelineControlState::dispatchEvent(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
switch (ev->getType())
{
case PipelineControlEvent::Start:
return onStart(ev);
case PipelineControlEvent::Reset:
return onReset(ev);
case PipelineControlEvent::Starvation:
return onStarvation(boost::dynamic_pointer_cast<const EventStarvation>(ev));
case PipelineControlEvent::Timeout:
return onTimeout(boost::dynamic_pointer_cast<const EventTimeout>(ev));
case PipelineControlEvent::Segment:
return onSegment(boost::dynamic_pointer_cast<const EventSegment>(ev));
default:
return str();
}
}
//******************************************************************************
void Adjusting::enter()
{
pipelineLowerLimit_ = ctrl_->interestControl_->pipelineLimit();
}
std::string
Adjusting::onSegment(const boost::shared_ptr<const EventSegment> &ev)
{
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
PipelineAdjust cmd = ctrl_->latencyControl_->getCurrentCommand();
if (cmd == PipelineAdjust::IncreasePipeline)
{
ctrl_->interestControl_->markLowerLimit(pipelineLowerLimit_);
return kStateFetching;
}
if (cmd == PipelineAdjust::DecreasePipeline)
pipelineLowerLimit_ = ctrl_->interestControl_->pipelineLimit();
return str();
}
//******************************************************************************
std::string
Fetching::onSegment(const boost::shared_ptr<const EventSegment> &ev)
{
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
if (ctrl_->latencyControl_->getCurrentCommand() == PipelineAdjust::IncreasePipeline)
{
// ctrl_->interestControl_->markLowerLimit(interestControl::MinPipelineSize);
return kStateAdjusting;
}
return str();
}
•`_´•
//
// pipeline-control-state-machine.cpp
//
// Created by Peter Gusev on 10 June 2016.
// Copyright 2013-2016 Regents of the University of California
//
#include "pipeline-control-state-machine.hpp"
#include <boost/make_shared.hpp>
#include <boost/assign.hpp>
#include "clock.hpp"
#include "latency-control.hpp"
#include "interest-control.hpp"
#include "pipeliner.hpp"
#include "frame-data.hpp"
#include "playout-control.hpp"
#include "statistics.hpp"
#include "sample-estimator.hpp"
using namespace ndnrtc;
using namespace ndnrtc::statistics;
namespace ndnrtc
{
const std::string kStateIdle = "Idle";
const std::string kStateBootstrapping = "Bootstrapping";
const std::string kStateAdjusting = "Adjusting";
const std::string kStateFetching = "Fetching";
}
#define STATE_TRANSITION(s, t) (StateEventPair(s, PipelineControlEvent::Type::t))
#define MAKE_TRANSITION(s, t) (StateEventPair(s, t))
#define ENABLE_IF(T, M) template <typename U = T, typename boost::enable_if<typename boost::is_same<M, U>>::type... X>
#define LOG_USING(ptr, lvl) boost::dynamic_pointer_cast<ndnlog::new_api::ILoggingObject>(ptr)->getLogger()->log((ndnlog::NdnLogType)lvl, boost::dynamic_pointer_cast<ndnlog::new_api::ILoggingObject>(ptr).get())
template <typename MetadataClass>
class ReceivedMetadataProcessing
{
public:
ReceivedMetadataProcessing() : metadataRequestedMs_(0), metadataReceivedMs_(0) {}
protected:
ENABLE_IF(MetadataClass, VideoThreadMeta)
bool processMetadata(boost::shared_ptr<VideoThreadMeta> metadata,
boost::shared_ptr<PipelineControlStateMachine::Struct> ctrl)
{
if (metadata)
{
unsigned char gopPos = metadata->getGopPos();
unsigned int gopSize = metadata->getCoderParams().gop_;
PacketNumber deltaToFetch, keyToFetch;
double metadataDrd = (double)getMetadataDrd();
unsigned int pipelineInitial =
ctrl->interestControl_->getCurrentStrategy()->calculateDemand(metadata->getRate(),
metadataDrd, metadataDrd * 0.05);
LOG_USING(ctrl->pipeliner_, ndnlog::NdnLoggerLevelDebug)
<< "received metadata. delta seq " << metadata->getSeqNo().first
<< " key seq " << metadata->getSeqNo().second
<< " gop pos " << (int)gopPos
<< " gop size " << gopSize
<< " rate " << metadata->getRate()
<< " drd " << metadataDrd
<< std::endl;
// add some smart logic about what to fetch next...
if (gopPos < ((float)gopSize / 2.))
{
// initial pipeline size helps us determine from which delta frame we need to start playback
startOffSeqNums_.first = metadata->getSeqNo().first + pipelineInitial;
startOffSeqNums_.second = metadata->getSeqNo().second;
// now we need to determine sequence number of delta from which we need to start fetching
// for this case, it will be the beginning of the GOP
PacketNumber firstDeltaInGop = (gopPos ? metadata->getSeqNo().first - (gopPos - 1) : metadata->getSeqNo().first);
deltaToFetch = firstDeltaInGop;
keyToFetch = metadata->getSeqNo().second;
pipelineInitial += gopPos;
}
else
{
startOffSeqNums_.first = pipelineInitial < (gopSize-gopPos) ? -1 : metadata->getSeqNo().first + pipelineInitial;
startOffSeqNums_.second = metadata->getSeqNo().second + 1;
// should fetch next key
deltaToFetch = metadata->getSeqNo().first;
keyToFetch = metadata->getSeqNo().second + 1;
pipelineInitial += (gopSize - gopPos);
}
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().deltaAvgSegNum_,
SampleClass::Delta, SegmentClass::Data);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().deltaAvgParitySegNum_,
SampleClass::Delta, SegmentClass::Parity);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().keyAvgSegNum_,
SampleClass::Key, SegmentClass::Data);
ctrl->sampleEstimator_->bootstrapSegmentNumber(metadata->getSegInfo().keyAvgParitySegNum_,
SampleClass::Key, SegmentClass::Parity);
ctrl->interestControl_->initialize(metadata->getRate(), pipelineInitial);
ctrl->pipeliner_->setSequenceNumber(deltaToFetch, SampleClass::Delta);
ctrl->pipeliner_->setSequenceNumber(keyToFetch, SampleClass::Key);
ctrl->pipeliner_->setNeedSample(SampleClass::Key);
ctrl->pipeliner_->segmentArrived(ctrl->threadPrefix_);
bootstrapSeqNums_.first = deltaToFetch;
bootstrapSeqNums_.second = keyToFetch;
LOG_USING(ctrl->playoutControl_, ndnlog::NdnLoggerLevelInfo)
<< "playback start off sequence numbers: "
<< startOffSeqNums_.first << " (delta) "
<< startOffSeqNums_.second << " (key)"
<< std::endl;
return true;
}
return false;
}
// TODO: update code for audio too
ENABLE_IF(MetadataClass, AudioThreadMeta)
bool processMetadata(boost::shared_ptr<AudioThreadMeta> metadata,
boost::shared_ptr<PipelineControlStateMachine::Struct> ctrl)
{
if (metadata)
{
PacketNumber bundleNo = metadata->getBundleNo();
// TODO: this needs to be calculated based on current sample rate and DRD
unsigned int pipelineInitial = 2 * InterestControl::MinPipelineSize;
ctrl->interestControl_->initialize(metadata->getRate(), pipelineInitial);
ctrl->pipeliner_->setSequenceNumber(bundleNo, SampleClass::Delta);
ctrl->pipeliner_->setNeedSample(SampleClass::Delta);
ctrl->pipeliner_->segmentArrived(ctrl->threadPrefix_);
bootstrapSeqNums_.first = bundleNo;
bootstrapSeqNums_.second = -1;
return true;
}
return false;
}
boost::shared_ptr<MetadataClass> extractMetadata(boost::shared_ptr<const WireSegment> segment)
{
ImmutableHeaderPacket<DataSegmentHeader> packet(segment->getData()->getContent());
NetworkData nd(packet.getPayload().size(), packet.getPayload().data());
return boost::make_shared<MetadataClass>(boost::move(nd));
}
protected:
void markMetadataRequested() { metadataRequestedMs_ = clock::millisecondTimestamp(); }
void markMetadataReceived() { metadataReceivedMs_ = clock::millisecondTimestamp(); }
int64_t getMetadataDrd() { return (metadataReceivedMs_ - metadataRequestedMs_); }
ENABLE_IF(MetadataClass, AudioThreadMeta)
PacketNumber getStartOffSequenceNumber() { return startOffSeqNums_.first; }
ENABLE_IF(MetadataClass, AudioThreadMeta)
PacketNumber getBootstrapSequenceNumber() { return bootstrapSeqNums_.first; }
ENABLE_IF(MetadataClass, VideoThreadMeta)
std::pair<PacketNumber, PacketNumber> getStartOffSequenceNumber() { return startOffSeqNums_; }
ENABLE_IF(MetadataClass, VideoThreadMeta)
std::pair<PacketNumber, PacketNumber> getBootstrapSequenceNumber() { return bootstrapSeqNums_; }
private:
int64_t metadataRequestedMs_, metadataReceivedMs_;
std::pair<PacketNumber, PacketNumber> bootstrapSeqNums_;
std::pair<PacketNumber, PacketNumber> startOffSeqNums_;
};
/**
* Idle state. System is in idle state when it first created.
* On entry:
* - resets control structures (pipeliner, interest control, latency control, etc.)
* On exit:
* - nothing
* Processed events:
* - Start: switches to Bootstrapping
* - Init: switches to Adjusting
* - Reset: resets control structures
*/
class Idle : public PipelineControlState
{
public:
Idle(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateIdle; }
void enter() override
{
ctrl_->buffer_->reset();
ctrl_->pipeliner_->reset();
ctrl_->latencyControl_->reset();
ctrl_->interestControl_->reset();
ctrl_->playoutControl_->allowPlayout(false);
}
int toInt() override { return (int)StateId::Idle; }
};
/**
* Bootstrapping state. Sytem is in this state while waiting for the answer of
* the thread metadata Interest.
* On entry:
* - sends out metadata Interest (accesses pipeliner)
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: ignored
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: transition to Adjusting state
*/
template <typename MetadataClass>
class BootstrappingT : public PipelineControlState,
public ReceivedMetadataProcessing<MetadataClass>
{
public:
BootstrappingT(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateBootstrapping; }
void enter() override { askMetadata(); }
int toInt() override { return (int)StateId::Bootstrapping; }
protected:
std::string onTimeout(const boost::shared_ptr<const EventTimeout> &ev) override
{
askMetadata();
return str();
}
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override
{
if (ev->getSegment()->isMeta())
return receivedMetadata(boost::dynamic_pointer_cast<const EventSegment>(ev));
else
{ // process frame segments
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
// check whether it's time to switch
if (receivedStartOffSegment(ev->getSegment()))
{
// since we are fetching older frames, we'll need to fast forward playback
// to minimize playback latency
int playbackFastForwardMs = calculatePlaybackFfwdInterval(ev->getSegment());
ctrl_->playoutControl_->allowPlayout(true, playbackFastForwardMs);
return kStateAdjusting;
}
return str();
}
}
void askMetadata()
{
ReceivedMetadataProcessing<MetadataClass>::markMetadataRequested();
ctrl_->pipeliner_->setNeedMetadata();
ctrl_->pipeliner_->express(ctrl_->threadPrefix_);
}
std::string receivedMetadata(const boost::shared_ptr<const EventSegment> &ev)
{
ReceivedMetadataProcessing<MetadataClass>::markMetadataReceived();
metadata_ = ReceivedMetadataProcessing<MetadataClass>::extractMetadata(ev->getSegment());
ReceivedMetadataProcessing<MetadataClass>::processMetadata(metadata_, ctrl_);
// if (metadata && ReceivedMetadataProcessing<MetadataClass>::processMetadata(metadata, ctrl_))
// return kStateAdjusting;
return kStateBootstrapping;
}
private:
boost::shared_ptr<MetadataClass> metadata_;
ENABLE_IF(MetadataClass, AudioThreadMeta)
bool receivedStartOffSegment(const boost::shared_ptr<const WireSegment> &seg)
{
// TODO: finish it for audio
return true;
}
ENABLE_IF(MetadataClass, AudioThreadMeta)
int calculatePlaybackFfwdInterval(const boost::shared_ptr<const WireSegment> &seg)
{
return 0;
}
ENABLE_IF(MetadataClass, VideoThreadMeta)
bool receivedStartOffSegment(const boost::shared_ptr<const WireSegment> &seg)
{
// compare sequence number of received sample with saved start off sequence numbers
PacketNumber startOffDeltaSeqNo = ReceivedMetadataProcessing<MetadataClass>::getStartOffSequenceNumber().first;
PacketNumber startOffKeySeqNo = ReceivedMetadataProcessing<MetadataClass>::getStartOffSequenceNumber().second;
boost::shared_ptr<const WireData<VideoFrameSegmentHeader>> videoFrameSegment =
boost::dynamic_pointer_cast<const WireData<VideoFrameSegmentHeader>>(seg);
ImmutableHeaderPacket<VideoFrameSegmentHeader> segmentPacket = videoFrameSegment->segment();
PacketNumber currentDeltaSeqNo = seg->isDelta() ? seg->getSampleNo() : segmentPacket.getHeader().pairedSequenceNo_ ;
PacketNumber currentKeySeqNo = seg->isDelta() ? segmentPacket.getHeader().pairedSequenceNo_ : seg->getSampleNo() ;
return (currentDeltaSeqNo >= startOffDeltaSeqNo) && (currentKeySeqNo >= startOffKeySeqNo);
}
ENABLE_IF(MetadataClass, VideoThreadMeta)
int calculatePlaybackFfwdInterval(const boost::shared_ptr<const WireSegment> &seg)
{
boost::shared_ptr<const WireData<VideoFrameSegmentHeader>> videoFrameSegment =
boost::dynamic_pointer_cast<const WireData<VideoFrameSegmentHeader>>(seg);
ImmutableHeaderPacket<VideoFrameSegmentHeader> segmentPacket = videoFrameSegment->segment();
PacketNumber currentDeltaSeqNo = seg->isDelta() ? seg->getSampleNo() : segmentPacket.getHeader().pairedSequenceNo_;
return (int)((double)(currentDeltaSeqNo - ReceivedMetadataProcessing<MetadataClass>::getBootstrapSequenceNumber().first) * metadata_->getRate());
}
};
typedef BootstrappingT<AudioThreadMeta> BootstrappingAudio;
typedef BootstrappingT<VideoThreadMeta> BootstrappingVideo;
/**
* Adjusting state. System is in this state while it tries to minimize the size
* of the pipeline.
* On entry:
* - does nothing
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: resets to idle
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: checks interest control (for pipeline decreases), checks latency
* control whether latest data arrival stopped, if so, restores previous
* pipeline size and transitions to Fetching state
*/
class Adjusting : public PipelineControlState
{
public:
Adjusting(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateAdjusting; }
void enter() override;
int toInt() override { return (int)StateId::Adjusting; }
private:
unsigned int pipelineLowerLimit_;
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override;
};
/**
* Fetching state. System is in this state when it receives latest data and
* the pipeline size is minimized.
* On entry:
* - does nothing
* On exit:
* - nothing
* Processed events:
* - Start: ignored
* - Reset: resets to idle
* - Starvation: resets to idle
* - Timeout: re-issue Interest (accesses pipeliner)
* - Segment: checks interest control, checks latency control, transitions to
* Adjust state if latest data arrival stops
*/
class Fetching : public PipelineControlState
{
public:
Fetching(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl) : PipelineControlState(ctrl) {}
std::string str() const override { return kStateFetching; }
int toInt() override { return (int)StateId::Fetching; }
private:
std::string onSegment(const boost::shared_ptr<const EventSegment> &ev) override;
};
//******************************************************************************
std::string
PipelineControlEvent::toString() const
{
switch (e_)
{
case PipelineControlEvent::Start:
return "Start";
case PipelineControlEvent::Reset:
return "Reset";
case PipelineControlEvent::Starvation:
return "Starvation";
case PipelineControlEvent::Segment:
return "Segment";
case PipelineControlEvent::Timeout:
return "Timeout";
default:
return "Unknown";
}
}
//******************************************************************************
PipelineControlStateMachine
PipelineControlStateMachine::defaultStateMachine(PipelineControlStateMachine::Struct ctrl)
{
boost::shared_ptr<PipelineControlStateMachine::Struct>
pctrl(boost::make_shared<PipelineControlStateMachine::Struct>(ctrl));
return PipelineControlStateMachine(pctrl, defaultConsumerStatesMap(pctrl));
}
PipelineControlStateMachine
PipelineControlStateMachine::videoStateMachine(Struct ctrl)
{
boost::shared_ptr<PipelineControlStateMachine::Struct>
pctrl(boost::make_shared<PipelineControlStateMachine::Struct>(ctrl));
return PipelineControlStateMachine(pctrl, videoConsumerStatesMap(pctrl));
}
PipelineControlStateMachine::StatesMap
PipelineControlStateMachine::defaultConsumerStatesMap(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl)
{
return {
{kStateIdle, boost::make_shared<Idle>(ctrl)},
{kStateBootstrapping, boost::make_shared<BootstrappingAudio>(ctrl)},
{kStateAdjusting, boost::make_shared<Adjusting>(ctrl)},
{kStateFetching, boost::make_shared<Fetching>(ctrl)}};
}
PipelineControlStateMachine::StatesMap
PipelineControlStateMachine::videoConsumerStatesMap(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl)
{
return {
{kStateIdle, boost::make_shared<Idle>(ctrl)},
{kStateBootstrapping, boost::make_shared<BootstrappingVideo>(ctrl)},
{kStateAdjusting, boost::make_shared<Adjusting>(ctrl)},
{kStateFetching, boost::make_shared<Fetching>(ctrl)}};
}
//******************************************************************************
PipelineControlStateMachine::PipelineControlStateMachine(const boost::shared_ptr<PipelineControlStateMachine::Struct> &ctrl,
PipelineControlStateMachine::StatesMap statesMap)
: ppCtrl_(ctrl),
states_(statesMap),
currentState_(states_[kStateIdle]),
lastEventTimestamp_(clock::millisecondTimestamp())
{
assert(ppCtrl_->buffer_.get());
assert(ppCtrl_->pipeliner_.get());
assert(ppCtrl_->interestControl_.get());
assert(ppCtrl_->latencyControl_.get());
assert(ppCtrl_->playoutControl_.get());
currentState_->enter();
description_ = "state-machine";
// add indirection to avoid confusion in C++11 (Ubuntu)
const TransitionMap m = boost::assign::map_list_of
(STATE_TRANSITION(kStateIdle, Start), kStateBootstrapping)
(STATE_TRANSITION(kStateBootstrapping, Reset), kStateIdle)
(STATE_TRANSITION(kStateAdjusting, Reset), kStateIdle)
(STATE_TRANSITION(kStateAdjusting, Starvation), kStateIdle)
(STATE_TRANSITION(kStateFetching, Reset), kStateIdle)
(STATE_TRANSITION(kStateFetching, Starvation), kStateIdle);
stateMachineTable_ = m;
}
PipelineControlStateMachine::~PipelineControlStateMachine()
{
currentState_->exit();
}
std::string
PipelineControlStateMachine::getState() const
{
return currentState_->str();
}
void PipelineControlStateMachine::dispatch(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
// dispatchEvent allows current state to react to the event.
// if state need to be switched, then next state name is returned.
// every state knows its own behavior to the event.
// state might also ignore the event. in this case, it returns
// its own name.
std::string nextState = currentState_->dispatchEvent(ev);
// if we got new state - transition to it
if (nextState != currentState_->str())
{
if (states_.find(nextState) == states_.end())
throw std::runtime_error(std::string("Unsupported state: " + nextState).c_str());
switchToState(states_[nextState], ev);
}
else
// otherwise - check whether state machine table defines transition
// for this event
if (!transition(ev))
{
for (auto o : observers_)
o->onStateMachineReceivedEvent(ev, currentState_->str());
}
}
void PipelineControlStateMachine::attach(IPipelineControlStateMachineObserver *observer)
{
if (observer)
observers_.push_back(observer);
}
void PipelineControlStateMachine::detach(IPipelineControlStateMachineObserver *observer)
{
std::vector<IPipelineControlStateMachineObserver *>::iterator it = std::find(observers_.begin(), observers_.end(), observer);
if (it != observers_.end())
observers_.erase(it);
}
#pragma mark - private
bool PipelineControlStateMachine::transition(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
if (stateMachineTable_.find(MAKE_TRANSITION(currentState_->str(), ev->getType())) ==
stateMachineTable_.end())
return false;
std::string stateStr = stateMachineTable_[MAKE_TRANSITION(currentState_->str(), ev->getType())];
switchToState(states_[stateStr], ev);
return true;
}
void PipelineControlStateMachine::switchToState(const boost::shared_ptr<PipelineControlState> &state,
const boost::shared_ptr<const PipelineControlEvent> &event)
{
int64_t now = clock::millisecondTimestamp();
int64_t stateDuration = (lastEventTimestamp_ ? now - lastEventTimestamp_ : 0);
lastEventTimestamp_ = now;
LogInfoC << "[" << currentState_->str() << "]-("
<< event->toString() << ")->[" << state->str() << "] "
<< stateDuration << "ms" << std::endl;
currentState_->exit();
currentState_ = state;
currentState_->enter();
for (auto o : observers_)
o->onStateMachineChangedState(event, currentState_->str());
if (event->toString() == boost::make_shared<EventStarvation>(0)->toString())
(*ppCtrl_->sstorage_)[Indicator::RebufferingsNum]++;
(*ppCtrl_->sstorage_)[Indicator::State] = (double)state->toInt();
}
//******************************************************************************
std::string
PipelineControlState::dispatchEvent(const boost::shared_ptr<const PipelineControlEvent> &ev)
{
switch (ev->getType())
{
case PipelineControlEvent::Start:
return onStart(ev);
case PipelineControlEvent::Reset:
return onReset(ev);
case PipelineControlEvent::Starvation:
return onStarvation(boost::dynamic_pointer_cast<const EventStarvation>(ev));
case PipelineControlEvent::Timeout:
return onTimeout(boost::dynamic_pointer_cast<const EventTimeout>(ev));
case PipelineControlEvent::Segment:
return onSegment(boost::dynamic_pointer_cast<const EventSegment>(ev));
default:
return str();
}
}
//******************************************************************************
void Adjusting::enter()
{
pipelineLowerLimit_ = ctrl_->interestControl_->pipelineLimit();
}
std::string
Adjusting::onSegment(const boost::shared_ptr<const EventSegment> &ev)
{
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
PipelineAdjust cmd = ctrl_->latencyControl_->getCurrentCommand();
if (cmd == PipelineAdjust::IncreasePipeline)
{
ctrl_->interestControl_->markLowerLimit(pipelineLowerLimit_);
return kStateFetching;
}
if (cmd == PipelineAdjust::DecreasePipeline)
pipelineLowerLimit_ = ctrl_->interestControl_->pipelineLimit();
return str();
}
//******************************************************************************
std::string
Fetching::onSegment(const boost::shared_ptr<const EventSegment> &ev)
{
ctrl_->pipeliner_->segmentArrived(ctrl_->threadPrefix_);
if (ctrl_->latencyControl_->getCurrentCommand() == PipelineAdjust::IncreasePipeline)
{
// ctrl_->interestControl_->markLowerLimit(interestControl::MinPipelineSize);
return kStateAdjusting;
}
return str();
}
|
#include "gmock/gmock.h"
#include "tcframe/experimental/runner.hpp"
using ::testing::A;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Property;
using ::testing::SizeIs;
using ::testing::Test;
namespace tcframe {
class BaseTestSpecTests : public Test {
protected:
class ProblemSpec : public BaseProblemSpec {
public: // intentionaly public so that input values can be inspected
int A, B;
void InputFormat() {}
};
class TestSpec : public BaseTestSpec<ProblemSpec> {
protected:
void Config() {
setSolutionCommand("python Sol.py");
setTestCasesDir("dir");
}
void InputFinalizer() {
A *= 2;
}
};
class TestSpecWithTestCases : public TestSpec {
protected:
void SampleTestCases() {
addSampleTestCase({"10", "20"});
addSampleTestCase({"30", "40"});
}
void TestCases() {
addOfficialTestCase(OfficialTestCase([=] {A = 1, B = 2;}, "A = 1, B = 2"));
addOfficialTestCase(OfficialTestCase([=] {A = 3, B = 4;}, "A = 3, B = 4"));
}
};
class TestSpecWithTestGroups : public TestSpec {
protected:
void SampleTestCases() {
addSampleTestCase({"10", "20"}, {1, 2});
addSampleTestCase({"30", "40"}, {2});
}
void TestGroup1() {
assignToSubtasks({1, 2});
addOfficialTestCase(OfficialTestCase([=] {A = 1, B = 2;}, "A = 1, B = 2"));
addOfficialTestCase(OfficialTestCase([=] {A = 3, B = 4;}, "A = 3, B = 4"));
addOfficialTestCase(OfficialTestCase([=] {A = 5, B = 6;}, "A = 5, B = 6"));
}
void TestGroup2() {
assignToSubtasks({2});
addOfficialTestCase(OfficialTestCase([=] {A = 101, B = 201;}, "A = 101, B = 201"));
addOfficialTestCase(OfficialTestCase([=] {A = 301, B = 401;}, "A = 301, B = 401"));
}
};
class TestSpecWithRandom : public TestSpec {
protected:
void TestCases() {
addOfficialTestCase(OfficialTestCase([=] {A = rnd.nextInt(1, 100);}, "A = rnd.nextInt(1, 100)"));
}
};
TestSpec spec;
TestSpecWithTestCases specWithTestCases;
TestSpecWithTestGroups specWithTestGroups;
};
TEST_F(BaseTestSpecTests, Config) {
TestConfig config = spec.buildTestConfig();
EXPECT_THAT(config.solutionCommand(), Eq("python Sol.py"));
EXPECT_THAT(config.testCasesDir(), Eq("dir"));
}
TEST_F(BaseTestSpecTests, InputFinalizer) {
TestSuite testSuite = spec.buildTestSuite();
function<void()> inputFinalizer = testSuite.inputFinalizer();
spec.A = 3;
inputFinalizer();
EXPECT_THAT(spec.A, Eq(3 * 2));
}
TEST_F(BaseTestSpecTests, TestSuite) {
TestSuite testSuite = specWithTestCases.buildTestSuite();
EXPECT_THAT(testSuite.sampleTests(), SizeIs(2));
EXPECT_THAT(testSuite.officialTests(), ElementsAre(
AllOf(Property(&TestGroup::id, -1), Property(&TestGroup::officialTestCases, SizeIs(2)))));
}
TEST_F(BaseTestSpecTests, TestSuite_WithGroups) {
TestSuite testSuite = specWithTestGroups.buildTestSuite();
EXPECT_THAT(testSuite.sampleTests(), SizeIs(2));
EXPECT_THAT(testSuite.officialTests(), ElementsAre(
AllOf(Property(&TestGroup::id, 1), Property(&TestGroup::officialTestCases, SizeIs(3))),
AllOf(Property(&TestGroup::id, 2), Property(&TestGroup::officialTestCases, SizeIs(2)))));
}
TEST_F(BaseTestSpecTests, Random_Compiles) {
SUCCEED();
}
}
Remove silly test
#include "gmock/gmock.h"
#include "tcframe/experimental/runner.hpp"
using ::testing::A;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Property;
using ::testing::SizeIs;
using ::testing::Test;
namespace tcframe {
class BaseTestSpecTests : public Test {
protected:
class ProblemSpec : public BaseProblemSpec {
public: // intentionaly public so that input values can be inspected
int A, B;
void InputFormat() {}
};
class TestSpec : public BaseTestSpec<ProblemSpec> {
protected:
void Config() {
setSolutionCommand("python Sol.py");
setTestCasesDir("dir");
}
void InputFinalizer() {
A *= 2;
}
};
class TestSpecWithTestCases : public TestSpec {
protected:
void SampleTestCases() {
addSampleTestCase({"10", "20"});
addSampleTestCase({"30", "40"});
}
void TestCases() {
addOfficialTestCase(OfficialTestCase([=] {A = 1, B = 2;}, "A = 1, B = 2"));
addOfficialTestCase(OfficialTestCase([=] {A = 3, B = 4;}, "A = 3, B = 4"));
}
};
class TestSpecWithTestGroups : public TestSpec {
protected:
void SampleTestCases() {
addSampleTestCase({"10", "20"}, {1, 2});
addSampleTestCase({"30", "40"}, {2});
}
void TestGroup1() {
assignToSubtasks({1, 2});
addOfficialTestCase(OfficialTestCase([=] {A = 1, B = 2;}, "A = 1, B = 2"));
addOfficialTestCase(OfficialTestCase([=] {A = 3, B = 4;}, "A = 3, B = 4"));
addOfficialTestCase(OfficialTestCase([=] {A = 5, B = 6;}, "A = 5, B = 6"));
}
void TestGroup2() {
assignToSubtasks({2});
addOfficialTestCase(OfficialTestCase([=] {A = 101, B = 201;}, "A = 101, B = 201"));
addOfficialTestCase(OfficialTestCase([=] {A = 301, B = 401;}, "A = 301, B = 401"));
}
};
// Testing that rnd is available in TestSpec
class TestSpecWithRandom : public TestSpec {
protected:
void TestCases() {
addOfficialTestCase(OfficialTestCase([=] {A = rnd.nextInt(1, 100);}, "A = rnd.nextInt(1, 100)"));
}
};
TestSpec spec;
TestSpecWithTestCases specWithTestCases;
TestSpecWithTestGroups specWithTestGroups;
};
TEST_F(BaseTestSpecTests, Config) {
TestConfig config = spec.buildTestConfig();
EXPECT_THAT(config.solutionCommand(), Eq("python Sol.py"));
EXPECT_THAT(config.testCasesDir(), Eq("dir"));
}
TEST_F(BaseTestSpecTests, InputFinalizer) {
TestSuite testSuite = spec.buildTestSuite();
function<void()> inputFinalizer = testSuite.inputFinalizer();
spec.A = 3;
inputFinalizer();
EXPECT_THAT(spec.A, Eq(3 * 2));
}
TEST_F(BaseTestSpecTests, TestSuite) {
TestSuite testSuite = specWithTestCases.buildTestSuite();
EXPECT_THAT(testSuite.sampleTests(), SizeIs(2));
EXPECT_THAT(testSuite.officialTests(), ElementsAre(
AllOf(Property(&TestGroup::id, -1), Property(&TestGroup::officialTestCases, SizeIs(2)))));
}
TEST_F(BaseTestSpecTests, TestSuite_WithGroups) {
TestSuite testSuite = specWithTestGroups.buildTestSuite();
EXPECT_THAT(testSuite.sampleTests(), SizeIs(2));
EXPECT_THAT(testSuite.officialTests(), ElementsAre(
AllOf(Property(&TestGroup::id, 1), Property(&TestGroup::officialTestCases, SizeIs(3))),
AllOf(Property(&TestGroup::id, 2), Property(&TestGroup::officialTestCases, SizeIs(2)))));
}
}
|
#include "utest_helper.hpp"
static void compiler_movforphi_undef(void)
{
const size_t w = 16;
const size_t h = 16;
cl_sampler sampler;
cl_image_format format;
cl_image_desc desc;
// Setup kernel and images
OCL_CREATE_KERNEL("test_movforphi_undef");
buf_data[0] = (uint32_t*) malloc(sizeof(uint32_t) * w * h);
for (uint32_t j = 0; j < h; ++j)
for (uint32_t i = 0; i < w; i++)
((uint32_t*)buf_data[0])[j * w + i] = j * w + i;
format.image_channel_order = CL_RGBA;
format.image_channel_data_type = CL_UNSIGNED_INT8;
desc.image_type = CL_MEM_OBJECT_IMAGE2D;
desc.image_width = w;
desc.image_height = h;
desc.image_row_pitch = w * sizeof(uint32_t);
OCL_CREATE_IMAGE(buf[0], CL_MEM_COPY_HOST_PTR, &format, &desc, buf_data[0]);
desc.image_row_pitch = 0;
OCL_CREATE_IMAGE(buf[1], 0, &format, &desc, NULL);
OCL_CREATE_SAMPLER(sampler, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST);
free(buf_data[0]);
buf_data[0] = NULL;
// Run the kernel
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
OCL_SET_ARG(2, sizeof(sampler), &sampler);
globals[0] = w;
globals[1] = h;
locals[0] = 16;
locals[1] = 16;
OCL_NDRANGE(2);
// Check result
OCL_MAP_BUFFER(0);
OCL_MAP_BUFFER(1);
// Just compare the initial 2 data is enough for this case, as the initial 2 data must in the first
// tile box and we can just get the correct coords.
for (uint32_t j = 0; j < 1; ++j)
for (uint32_t i = 0; i < 3; i++)
{
if (i < w - 1)
OCL_ASSERT(((uint32_t*)buf_data[0])[j * w + i + 1] == ((uint32_t*)buf_data[1])[j * w + i]);
}
OCL_UNMAP_BUFFER(0);
OCL_UNMAP_BUFFER(1);
}
MAKE_UTEST_FROM_FUNCTION(compiler_movforphi_undef);
utests: Fix a bug in movforphi test case.
This test case is to trigger a old MovForPHI bug, and it
just use read/write_image. But it has a bug in itself.
As in the kernel, the write image will only write the
first lane data not all the 16 lanes. As the previous
patch fix the write_image bug, thus now the write_image
work correctly and thus it only touch the first data element
thus it trigger the bug in this test case. Now fix it.
Signed-off-by: Zhigang Gong <e04a7b9b70b1e4c6318cf117dcd1a9056e14b97a@linux.intel.com>
#include "utest_helper.hpp"
static void compiler_movforphi_undef(void)
{
const size_t w = 16;
const size_t h = 16;
cl_sampler sampler;
cl_image_format format;
cl_image_desc desc;
// Setup kernel and images
OCL_CREATE_KERNEL("test_movforphi_undef");
buf_data[0] = (uint32_t*) malloc(sizeof(uint32_t) * w * h);
for (uint32_t j = 0; j < h; ++j)
for (uint32_t i = 0; i < w; i++)
((uint32_t*)buf_data[0])[j * w + i] = j * w + i;
format.image_channel_order = CL_RGBA;
format.image_channel_data_type = CL_UNSIGNED_INT8;
desc.image_type = CL_MEM_OBJECT_IMAGE2D;
desc.image_width = w;
desc.image_height = h;
desc.image_row_pitch = w * sizeof(uint32_t);
OCL_CREATE_IMAGE(buf[0], CL_MEM_COPY_HOST_PTR, &format, &desc, buf_data[0]);
desc.image_row_pitch = 0;
OCL_CREATE_IMAGE(buf[1], 0, &format, &desc, NULL);
OCL_CREATE_SAMPLER(sampler, CL_ADDRESS_REPEAT, CL_FILTER_NEAREST);
free(buf_data[0]);
buf_data[0] = NULL;
// Run the kernel
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
OCL_SET_ARG(2, sizeof(sampler), &sampler);
globals[0] = w;
globals[1] = h;
locals[0] = 16;
locals[1] = 16;
OCL_NDRANGE(2);
// Check result
OCL_MAP_BUFFER(0);
OCL_MAP_BUFFER(1);
// Just compare the initial 2 data is enough for this case, as the initial 2 data must in the first
// tile box and we can just get the correct coords.
for (uint32_t j = 0; j < 1; ++j)
for (uint32_t i = 0; i < 3; i++)
{
if (i == 0)
OCL_ASSERT(((uint32_t*)buf_data[0])[j * w + i + 1] == ((uint32_t*)buf_data[1])[j * w + i]);
}
OCL_UNMAP_BUFFER(0);
OCL_UNMAP_BUFFER(1);
}
MAKE_UTEST_FROM_FUNCTION(compiler_movforphi_undef);
|
#include <cassert>
#include "Preset.hpp"
#include "AppConfig.hpp"
#include "BitmapCache.hpp"
#include "I18N.hpp"
#include "wxExtensions.hpp"
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#endif /* _MSC_VER */
#include <algorithm>
#include <fstream>
#include <stdexcept>
#include <unordered_map>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/nowide/cenv.hpp>
#include <boost/nowide/convert.hpp>
#include <boost/nowide/cstdio.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/locale.hpp>
#include <boost/log/trivial.hpp>
#include <wx/image.h>
#include <wx/choice.h>
#include <wx/bmpcbox.h>
#include <wx/wupdlock.h>
#include "libslic3r/libslic3r.h"
#include "libslic3r/Utils.hpp"
#include "libslic3r/PlaceholderParser.hpp"
#include "Plater.hpp"
using boost::property_tree::ptree;
namespace Slic3r {
ConfigFileType guess_config_file_type(const ptree &tree)
{
size_t app_config = 0;
size_t bundle = 0;
size_t config = 0;
for (const ptree::value_type &v : tree) {
if (v.second.empty()) {
if (v.first == "background_processing" ||
v.first == "last_output_path" ||
v.first == "no_controller" ||
v.first == "no_defaults")
++ app_config;
else if (v.first == "nozzle_diameter" ||
v.first == "filament_diameter")
++ config;
} else if (boost::algorithm::starts_with(v.first, "print:") ||
boost::algorithm::starts_with(v.first, "filament:") ||
boost::algorithm::starts_with(v.first, "printer:") ||
v.first == "settings")
++ bundle;
else if (v.first == "presets") {
++ app_config;
++ bundle;
} else if (v.first == "recent") {
for (auto &kvp : v.second)
if (kvp.first == "config_directory" || kvp.first == "skein_directory")
++ app_config;
}
}
return (app_config > bundle && app_config > config) ? CONFIG_FILE_TYPE_APP_CONFIG :
(bundle > config) ? CONFIG_FILE_TYPE_CONFIG_BUNDLE : CONFIG_FILE_TYPE_CONFIG;
}
VendorProfile VendorProfile::from_ini(const boost::filesystem::path &path, bool load_all)
{
ptree tree;
boost::filesystem::ifstream ifs(path);
boost::property_tree::read_ini(ifs, tree);
return VendorProfile::from_ini(tree, path, load_all);
}
static const std::unordered_map<std::string, std::string> pre_family_model_map {{
{ "MK3", "MK3" },
{ "MK3MMU2", "MK3" },
{ "MK2.5", "MK2.5" },
{ "MK2.5MMU2", "MK2.5" },
{ "MK2S", "MK2" },
{ "MK2SMM", "MK2" },
{ "SL1", "SL1" },
}};
VendorProfile VendorProfile::from_ini(const ptree &tree, const boost::filesystem::path &path, bool load_all)
{
static const std::string printer_model_key = "printer_model:";
static const std::string filaments_section = "default_filaments";
static const std::string materials_section = "default_sla_materials";
const std::string id = path.stem().string();
if (! boost::filesystem::exists(path)) {
throw std::runtime_error((boost::format("Cannot load Vendor Config Bundle `%1%`: File not found: `%2%`.") % id % path).str());
}
VendorProfile res(id);
// Helper to get compulsory fields
auto get_or_throw = [&](const ptree &tree, const std::string &key) -> ptree::const_assoc_iterator
{
auto res = tree.find(key);
if (res == tree.not_found()) {
throw std::runtime_error((boost::format("Vendor Config Bundle `%1%` is not valid: Missing secion or key: `%2%`.") % id % key).str());
}
return res;
};
// Load the header
const auto &vendor_section = get_or_throw(tree, "vendor")->second;
res.name = get_or_throw(vendor_section, "name")->second.data();
auto config_version_str = get_or_throw(vendor_section, "config_version")->second.data();
auto config_version = Semver::parse(config_version_str);
if (! config_version) {
throw std::runtime_error((boost::format("Vendor Config Bundle `%1%` is not valid: Cannot parse config_version: `%2%`.") % id % config_version_str).str());
} else {
res.config_version = std::move(*config_version);
}
// Load URLs
const auto config_update_url = vendor_section.find("config_update_url");
if (config_update_url != vendor_section.not_found()) {
res.config_update_url = config_update_url->second.data();
}
const auto changelog_url = vendor_section.find("changelog_url");
if (changelog_url != vendor_section.not_found()) {
res.changelog_url = changelog_url->second.data();
}
if (! load_all) {
return res;
}
// Load printer models
for (auto §ion : tree) {
if (boost::starts_with(section.first, printer_model_key)) {
VendorProfile::PrinterModel model;
model.id = section.first.substr(printer_model_key.size());
model.name = section.second.get<std::string>("name", model.id);
const char *technology_fallback = boost::algorithm::starts_with(model.id, "SL") ? "SLA" : "FFF";
auto technology_field = section.second.get<std::string>("technology", technology_fallback);
if (! ConfigOptionEnum<PrinterTechnology>::from_string(technology_field, model.technology)) {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Invalid printer technology field: `%2%`") % id % technology_field;
model.technology = ptFFF;
}
model.family = section.second.get<std::string>("family", std::string());
if (model.family.empty() && res.name == "Prusa Research") {
// If no family is specified, it can be inferred for known printers
const auto from_pre_map = pre_family_model_map.find(model.id);
if (from_pre_map != pre_family_model_map.end()) { model.family = from_pre_map->second; }
}
#if 0
// Remove SLA printers from the initial alpha.
if (model.technology == ptSLA)
continue;
#endif
section.second.get<std::string>("variants", "");
const auto variants_field = section.second.get<std::string>("variants", "");
std::vector<std::string> variants;
if (Slic3r::unescape_strings_cstyle(variants_field, variants)) {
for (const std::string &variant_name : variants) {
if (model.variant(variant_name) == nullptr)
model.variants.emplace_back(VendorProfile::PrinterVariant(variant_name));
}
} else {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Malformed variants field: `%2%`") % id % variants_field;
}
auto default_materials_field = section.second.get<std::string>("default_materials", "");
if (default_materials_field.empty())
default_materials_field = section.second.get<std::string>("default_filaments", "");
if (Slic3r::unescape_strings_cstyle(default_materials_field, model.default_materials)) {
Slic3r::sort_remove_duplicates(model.default_materials);
} else {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Malformed default_materials field: `%2%`") % id % default_materials_field;
}
model.bed_model = section.second.get<std::string>("bed_model", "");
model.bed_texture = section.second.get<std::string>("bed_texture", "");
if (! model.id.empty() && ! model.variants.empty())
res.models.push_back(std::move(model));
}
}
// Load filaments and sla materials to be installed by default
const auto filaments = tree.find(filaments_section);
if (filaments != tree.not_found()) {
for (auto &pair : filaments->second) {
if (pair.second.data() == "1") {
res.default_filaments.insert(pair.first);
}
}
}
const auto materials = tree.find(materials_section);
if (materials != tree.not_found()) {
for (auto &pair : materials->second) {
if (pair.second.data() == "1") {
res.default_sla_materials.insert(pair.first);
}
}
}
return res;
}
std::vector<std::string> VendorProfile::families() const
{
std::vector<std::string> res;
unsigned num_familiies = 0;
for (auto &model : models) {
if (std::find(res.begin(), res.end(), model.family) == res.end()) {
res.push_back(model.family);
num_familiies++;
}
}
return res;
}
// Suffix to be added to a modified preset name in the combo box.
static std::string g_suffix_modified = " (modified)";
const std::string& Preset::suffix_modified()
{
return g_suffix_modified;
}
void Preset::update_suffix_modified()
{
g_suffix_modified = (" (" + _(L("modified")) + ")").ToUTF8().data();
}
// Remove an optional "(modified)" suffix from a name.
// This converts a UI name to a unique preset identifier.
std::string Preset::remove_suffix_modified(const std::string &name)
{
return boost::algorithm::ends_with(name, g_suffix_modified) ?
name.substr(0, name.size() - g_suffix_modified.size()) :
name;
}
// Update new extruder fields at the printer profile.
void Preset::normalize(DynamicPrintConfig &config)
{
auto *nozzle_diameter = dynamic_cast<const ConfigOptionFloats*>(config.option("nozzle_diameter"));
if (nozzle_diameter != nullptr)
// Loaded the FFF Printer settings. Verify, that all extruder dependent values have enough values.
config.set_num_extruders((unsigned int)nozzle_diameter->values.size());
if (config.option("filament_diameter") != nullptr) {
// This config contains single or multiple filament presets.
// Ensure that the filament preset vector options contain the correct number of values.
size_t n = (nozzle_diameter == nullptr) ? 1 : nozzle_diameter->values.size();
const auto &defaults = FullPrintConfig::defaults();
for (const std::string &key : Preset::filament_options()) {
if (key == "compatible_prints" || key == "compatible_printers")
continue;
auto *opt = config.option(key, false);
/*assert(opt != nullptr);
assert(opt->is_vector());*/
if (opt != nullptr && opt->is_vector())
static_cast<ConfigOptionVectorBase*>(opt)->resize(n, defaults.option(key));
}
// The following keys are mandatory for the UI, but they are not part of FullPrintConfig, therefore they are handled separately.
for (const std::string &key : { "filament_settings_id" }) {
auto *opt = config.option(key, false);
assert(opt == nullptr || opt->type() == coStrings);
if (opt != nullptr && opt->type() == coStrings)
static_cast<ConfigOptionStrings*>(opt)->values.resize(n, std::string());
}
}
}
std::string Preset::remove_invalid_keys(DynamicPrintConfig &config, const DynamicPrintConfig &default_config)
{
std::string incorrect_keys;
for (const std::string &key : config.keys())
if (! default_config.has(key)) {
if (incorrect_keys.empty())
incorrect_keys = key;
else {
incorrect_keys += ", ";
incorrect_keys += key;
}
config.erase(key);
}
return incorrect_keys;
}
void Preset::save()
{
this->config.save(this->file);
}
// Return a label of this preset, consisting of a name and a "(modified)" suffix, if this preset is dirty.
std::string Preset::label() const
{
return this->name + (this->is_dirty ? g_suffix_modified : "");
}
bool is_compatible_with_print(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_print, const PresetWithVendorProfile &active_printer)
{
if (preset.vendor != nullptr && preset.vendor != active_printer.vendor)
// The current profile has a vendor assigned and it is different from the active print's vendor.
return false;
auto &condition = preset.preset.compatible_prints_condition();
auto *compatible_prints = dynamic_cast<const ConfigOptionStrings*>(preset.preset.config.option("compatible_prints"));
bool has_compatible_prints = compatible_prints != nullptr && ! compatible_prints->values.empty();
if (! has_compatible_prints && ! condition.empty()) {
try {
return PlaceholderParser::evaluate_boolean_expression(condition, active_print.preset.config);
} catch (const std::runtime_error &err) {
//FIXME in case of an error, return "compatible with everything".
printf("Preset::is_compatible_with_print - parsing error of compatible_prints_condition %s:\n%s\n", active_print.preset.name.c_str(), err.what());
return true;
}
}
return preset.preset.is_default || active_print.preset.name.empty() || ! has_compatible_prints ||
std::find(compatible_prints->values.begin(), compatible_prints->values.end(), active_print.preset.name) !=
compatible_prints->values.end();
}
bool is_compatible_with_printer(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_printer, const DynamicPrintConfig *extra_config)
{
if (preset.vendor != nullptr && preset.vendor != active_printer.vendor)
// The current profile has a vendor assigned and it is different from the active print's vendor.
return false;
auto &condition = preset.preset.compatible_printers_condition();
auto *compatible_printers = dynamic_cast<const ConfigOptionStrings*>(preset.preset.config.option("compatible_printers"));
bool has_compatible_printers = compatible_printers != nullptr && ! compatible_printers->values.empty();
if (! has_compatible_printers && ! condition.empty()) {
try {
return PlaceholderParser::evaluate_boolean_expression(condition, active_printer.preset.config, extra_config);
} catch (const std::runtime_error &err) {
//FIXME in case of an error, return "compatible with everything".
printf("Preset::is_compatible_with_printer - parsing error of compatible_printers_condition %s:\n%s\n", active_printer.preset.name.c_str(), err.what());
return true;
}
}
return preset.preset.is_default || active_printer.preset.name.empty() || ! has_compatible_printers ||
std::find(compatible_printers->values.begin(), compatible_printers->values.end(), active_printer.preset.name) !=
compatible_printers->values.end();
}
bool is_compatible_with_printer(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_printer)
{
DynamicPrintConfig config;
config.set_key_value("printer_preset", new ConfigOptionString(active_printer.preset.name));
const ConfigOption *opt = active_printer.preset.config.option("nozzle_diameter");
if (opt)
config.set_key_value("num_extruders", new ConfigOptionInt((int)static_cast<const ConfigOptionFloats*>(opt)->values.size()));
return is_compatible_with_printer(preset, active_printer, &config);
}
void Preset::set_visible_from_appconfig(const AppConfig &app_config)
{
if (vendor == nullptr) { return; }
if (type == TYPE_PRINTER) {
const std::string &model = config.opt_string("printer_model");
const std::string &variant = config.opt_string("printer_variant");
if (model.empty() || variant.empty()) { return; }
is_visible = app_config.get_variant(vendor->id, model, variant);
} else if (type == TYPE_FILAMENT) {
is_visible = app_config.has("filaments", name);
} else if (type == TYPE_SLA_MATERIAL) {
is_visible = app_config.has("sla_materials", name);
}
}
const std::vector<std::string>& Preset::print_options()
{
static std::vector<std::string> s_opts {
"layer_height", "first_layer_height", "perimeters", "spiral_vase", "slice_closing_radius",
"top_solid_layers", "top_solid_min_thickness", "bottom_solid_layers", "bottom_solid_min_thickness",
"extra_perimeters", "ensure_vertical_shell_thickness", "avoid_crossing_perimeters", "thin_walls", "overhangs",
"seam_position", "external_perimeters_first", "fill_density", "fill_pattern", "top_fill_pattern", "bottom_fill_pattern",
"infill_every_layers", "infill_only_where_needed", "solid_infill_every_layers", "fill_angle", "bridge_angle",
"solid_infill_below_area", "only_retract_when_crossing_perimeters", "infill_first", "max_print_speed",
"max_volumetric_speed",
#ifdef HAS_PRESSURE_EQUALIZER
"max_volumetric_extrusion_rate_slope_positive", "max_volumetric_extrusion_rate_slope_negative",
#endif /* HAS_PRESSURE_EQUALIZER */
"perimeter_speed", "small_perimeter_speed", "external_perimeter_speed", "infill_speed", "solid_infill_speed",
"top_solid_infill_speed", "support_material_speed", "support_material_xy_spacing", "support_material_interface_speed",
"bridge_speed", "gap_fill_speed", "travel_speed", "first_layer_speed", "perimeter_acceleration", "infill_acceleration",
"bridge_acceleration", "first_layer_acceleration", "default_acceleration", "skirts", "skirt_distance", "skirt_height",
"min_skirt_length", "brim_width", "support_material", "support_material_auto", "support_material_threshold", "support_material_enforce_layers",
"raft_layers", "support_material_pattern", "support_material_with_sheath", "support_material_spacing",
"support_material_synchronize_layers", "support_material_angle", "support_material_interface_layers",
"support_material_interface_spacing", "support_material_interface_contact_loops", "support_material_contact_distance",
"support_material_buildplate_only", "dont_support_bridges", "notes", "complete_objects", "extruder_clearance_radius",
"extruder_clearance_height", "gcode_comments", "gcode_label_objects", "output_filename_format", "post_process", "perimeter_extruder",
"infill_extruder", "solid_infill_extruder", "support_material_extruder", "support_material_interface_extruder",
"ooze_prevention", "standby_temperature_delta", "interface_shells", "extrusion_width", "first_layer_extrusion_width",
"perimeter_extrusion_width", "external_perimeter_extrusion_width", "infill_extrusion_width", "solid_infill_extrusion_width",
"top_infill_extrusion_width", "support_material_extrusion_width", "infill_overlap", "bridge_flow_ratio", "clip_multipart_objects",
"elefant_foot_compensation", "xy_size_compensation", "threads", "resolution", "wipe_tower", "wipe_tower_x", "wipe_tower_y",
"wipe_tower_width", "wipe_tower_rotation_angle", "wipe_tower_bridging", "single_extruder_multi_material_priming",
"wipe_tower_no_sparse_layers", "compatible_printers", "compatible_printers_condition", "inherits"
};
return s_opts;
}
const std::vector<std::string>& Preset::filament_options()
{
static std::vector<std::string> s_opts {
"filament_colour", "filament_diameter", "filament_type", "filament_soluble", "filament_notes", "filament_max_volumetric_speed",
"extrusion_multiplier", "filament_density", "filament_cost", "filament_loading_speed", "filament_loading_speed_start", "filament_load_time",
"filament_unloading_speed", "filament_unloading_speed_start", "filament_unload_time", "filament_toolchange_delay", "filament_cooling_moves",
"filament_cooling_initial_speed", "filament_cooling_final_speed", "filament_ramming_parameters", "filament_minimal_purge_on_wipe_tower",
"temperature", "first_layer_temperature", "bed_temperature", "first_layer_bed_temperature", "fan_always_on", "cooling", "min_fan_speed",
"max_fan_speed", "bridge_fan_speed", "disable_fan_first_layers", "fan_below_layer_time", "slowdown_below_layer_time", "min_print_speed",
"start_filament_gcode", "end_filament_gcode",
// Retract overrides
"filament_retract_length", "filament_retract_lift", "filament_retract_lift_above", "filament_retract_lift_below", "filament_retract_speed", "filament_deretract_speed", "filament_retract_restart_extra", "filament_retract_before_travel",
"filament_retract_layer_change", "filament_wipe", "filament_retract_before_wipe",
// Profile compatibility
"filament_vendor", "compatible_prints", "compatible_prints_condition", "compatible_printers", "compatible_printers_condition", "inherits"
};
return s_opts;
}
const std::vector<std::string>& Preset::printer_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"printer_technology",
"bed_shape", "bed_custom_texture", "bed_custom_model", "z_offset", "gcode_flavor", "use_relative_e_distances", "serial_port", "serial_speed",
"use_firmware_retraction", "use_volumetric_e", "variable_layer_height",
"host_type", "print_host", "printhost_apikey", "printhost_cafile",
"single_extruder_multi_material", "start_gcode", "end_gcode", "before_layer_gcode", "layer_gcode", "toolchange_gcode",
"between_objects_gcode", "printer_vendor", "printer_model", "printer_variant", "printer_notes", "cooling_tube_retraction",
"cooling_tube_length", "high_current_on_filament_swap", "parking_pos_retraction", "extra_loading_move", "max_print_height",
"default_print_profile", "inherits",
"remaining_times", "silent_mode", "machine_max_acceleration_extruding", "machine_max_acceleration_retracting",
"machine_max_acceleration_x", "machine_max_acceleration_y", "machine_max_acceleration_z", "machine_max_acceleration_e",
"machine_max_feedrate_x", "machine_max_feedrate_y", "machine_max_feedrate_z", "machine_max_feedrate_e",
"machine_min_extruding_rate", "machine_min_travel_rate",
"machine_max_jerk_x", "machine_max_jerk_y", "machine_max_jerk_z", "machine_max_jerk_e",
"thumbnails"
};
s_opts.insert(s_opts.end(), Preset::nozzle_options().begin(), Preset::nozzle_options().end());
}
return s_opts;
}
// The following nozzle options of a printer profile will be adjusted to match the size
// of the nozzle_diameter vector.
const std::vector<std::string>& Preset::nozzle_options()
{
return print_config_def.extruder_option_keys();
}
const std::vector<std::string>& Preset::sla_print_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"layer_height",
"faded_layers",
"supports_enable",
"support_head_front_diameter",
"support_head_penetration",
"support_head_width",
"support_pillar_diameter",
"support_max_bridges_on_pillar",
"support_pillar_connection_mode",
"support_buildplate_only",
"support_pillar_widening_factor",
"support_base_diameter",
"support_base_height",
"support_base_safety_distance",
"support_critical_angle",
"support_max_bridge_length",
"support_max_pillar_link_distance",
"support_object_elevation",
"support_points_density_relative",
"support_points_minimal_distance",
"slice_closing_radius",
"pad_enable",
"pad_wall_thickness",
"pad_wall_height",
"pad_brim_size",
"pad_max_merge_distance",
// "pad_edge_radius",
"pad_wall_slope",
"pad_object_gap",
"pad_around_object",
"pad_around_object_everywhere",
"pad_object_connector_stride",
"pad_object_connector_width",
"pad_object_connector_penetration",
"hollowing_enable",
"hollowing_min_thickness",
"hollowing_quality",
"hollowing_closing_distance",
"output_filename_format",
"default_sla_print_profile",
"compatible_printers",
"compatible_printers_condition",
"inherits"
};
}
return s_opts;
}
const std::vector<std::string>& Preset::sla_material_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"material_type",
"initial_layer_height",
"bottle_cost",
"bottle_volume",
"bottle_weight",
"material_density",
"exposure_time",
"initial_exposure_time",
"material_correction",
"material_notes",
"material_vendor",
"default_sla_material_profile",
"compatible_prints", "compatible_prints_condition",
"compatible_printers", "compatible_printers_condition", "inherits"
};
}
return s_opts;
}
const std::vector<std::string>& Preset::sla_printer_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"printer_technology",
"bed_shape", "bed_custom_texture", "bed_custom_model", "max_print_height",
"display_width", "display_height", "display_pixels_x", "display_pixels_y",
"display_mirror_x", "display_mirror_y",
"display_orientation",
"fast_tilt_time", "slow_tilt_time", "area_fill",
"relative_correction",
"absolute_correction",
"elefant_foot_compensation",
"elefant_foot_min_width",
"gamma_correction",
"min_exposure_time", "max_exposure_time",
"min_initial_exposure_time", "max_initial_exposure_time",
"print_host", "printhost_apikey", "printhost_cafile",
"printer_notes",
"inherits"
};
}
return s_opts;
}
PresetCollection::PresetCollection(Preset::Type type, const std::vector<std::string> &keys, const Slic3r::StaticPrintConfig &defaults, const std::string &default_name) :
m_type(type),
m_edited_preset(type, "", false),
m_idx_selected(0),
m_bitmap_main_frame(new wxBitmap),
m_bitmap_add(new wxBitmap),
m_bitmap_cache(new GUI::BitmapCache)
{
// Insert just the default preset.
this->add_default_preset(keys, defaults, default_name);
m_edited_preset.config.apply(m_presets.front().config);
}
PresetCollection::~PresetCollection()
{
delete m_bitmap_main_frame;
m_bitmap_main_frame = nullptr;
delete m_bitmap_add;
m_bitmap_add = nullptr;
delete m_bitmap_cache;
m_bitmap_cache = nullptr;
}
void PresetCollection::reset(bool delete_files)
{
if (m_presets.size() > m_num_default_presets) {
if (delete_files) {
// Erase the preset files.
for (Preset &preset : m_presets)
if (! preset.is_default && ! preset.is_external && ! preset.is_system)
boost::nowide::remove(preset.file.c_str());
}
// Don't use m_presets.resize() here as it requires a default constructor for Preset.
m_presets.erase(m_presets.begin() + m_num_default_presets, m_presets.end());
this->select_preset(0);
}
m_map_alias_to_profile_name.clear();
m_map_system_profile_renamed.clear();
}
void PresetCollection::add_default_preset(const std::vector<std::string> &keys, const Slic3r::StaticPrintConfig &defaults, const std::string &preset_name)
{
// Insert just the default preset.
m_presets.emplace_back(Preset(this->type(), preset_name, true));
m_presets.back().config.apply_only(defaults, keys.empty() ? defaults.keys() : keys);
m_presets.back().loaded = true;
++ m_num_default_presets;
}
// Load all presets found in dir_path.
// Throws an exception on error.
void PresetCollection::load_presets(const std::string &dir_path, const std::string &subdir)
{
boost::filesystem::path dir = boost::filesystem::canonical(boost::filesystem::path(dir_path) / subdir).make_preferred();
m_dir_path = dir.string();
std::string errors_cummulative;
// Store the loaded presets into a new vector, otherwise the binary search for already existing presets would be broken.
// (see the "Preset already present, not loading" message).
std::deque<Preset> presets_loaded;
for (auto &dir_entry : boost::filesystem::directory_iterator(dir))
if (Slic3r::is_ini_file(dir_entry)) {
std::string name = dir_entry.path().filename().string();
// Remove the .ini suffix.
name.erase(name.size() - 4);
if (this->find_preset(name, false)) {
// This happens when there's is a preset (most likely legacy one) with the same name as a system preset
// that's already been loaded from a bundle.
BOOST_LOG_TRIVIAL(warning) << "Preset already present, not loading: " << name;
continue;
}
try {
Preset preset(m_type, name, false);
preset.file = dir_entry.path().string();
// Load the preset file, apply preset values on top of defaults.
try {
DynamicPrintConfig config;
config.load_from_ini(preset.file);
// Find a default preset for the config. The PrintPresetCollection provides different default preset based on the "printer_technology" field.
const Preset &default_preset = this->default_preset_for(config);
preset.config = default_preset.config;
preset.config.apply(std::move(config));
Preset::normalize(preset.config);
// Report configuration fields, which are misplaced into a wrong group.
std::string incorrect_keys = Preset::remove_invalid_keys(config, default_preset.config);
if (! incorrect_keys.empty())
BOOST_LOG_TRIVIAL(error) << "Error in a preset file: The preset \"" <<
preset.file << "\" contains the following incorrect keys: " << incorrect_keys << ", which were removed";
preset.loaded = true;
} catch (const std::ifstream::failure &err) {
throw std::runtime_error(std::string("The selected preset cannot be loaded: ") + preset.file + "\n\tReason: " + err.what());
} catch (const std::runtime_error &err) {
throw std::runtime_error(std::string("Failed loading the preset file: ") + preset.file + "\n\tReason: " + err.what());
}
presets_loaded.emplace_back(preset);
} catch (const std::runtime_error &err) {
errors_cummulative += err.what();
errors_cummulative += "\n";
}
}
m_presets.insert(m_presets.end(), std::make_move_iterator(presets_loaded.begin()), std::make_move_iterator(presets_loaded.end()));
std::sort(m_presets.begin() + m_num_default_presets, m_presets.end());
this->select_preset(first_visible_idx());
if (! errors_cummulative.empty())
throw std::runtime_error(errors_cummulative);
}
// Load a preset from an already parsed config file, insert it into the sorted sequence of presets
// and select it, losing previous modifications.
Preset& PresetCollection::load_preset(const std::string &path, const std::string &name, const DynamicPrintConfig &config, bool select)
{
DynamicPrintConfig cfg(this->default_preset().config);
cfg.apply_only(config, cfg.keys(), true);
return this->load_preset(path, name, std::move(cfg), select);
}
enum class ProfileHostParams
{
Same,
Different,
Anonymized,
};
static ProfileHostParams profile_host_params_same_or_anonymized(const DynamicPrintConfig &cfg_old, const DynamicPrintConfig &cfg_new)
{
auto opt_print_host_old = cfg_old.option<ConfigOptionString>("print_host");
auto opt_printhost_apikey_old = cfg_old.option<ConfigOptionString>("printhost_apikey");
auto opt_printhost_cafile_old = cfg_old.option<ConfigOptionString>("printhost_cafile");
auto opt_print_host_new = cfg_new.option<ConfigOptionString>("print_host");
auto opt_printhost_apikey_new = cfg_new.option<ConfigOptionString>("printhost_apikey");
auto opt_printhost_cafile_new = cfg_new.option<ConfigOptionString>("printhost_cafile");
// If the new print host data is undefined, use the old data.
bool new_print_host_undefined = (opt_print_host_new == nullptr || opt_print_host_new ->empty()) &&
(opt_printhost_apikey_new == nullptr || opt_printhost_apikey_new ->empty()) &&
(opt_printhost_cafile_new == nullptr || opt_printhost_cafile_new ->empty());
if (new_print_host_undefined)
return ProfileHostParams::Anonymized;
auto opt_same = [](const ConfigOptionString *l, const ConfigOptionString *r) {
return ((l == nullptr || l->empty()) && (r == nullptr || r->empty())) ||
(l != nullptr && r != nullptr && l->value == r->value);
};
return (opt_same(opt_print_host_old, opt_print_host_new) && opt_same(opt_printhost_apikey_old, opt_printhost_apikey_new) &&
opt_same(opt_printhost_cafile_old, opt_printhost_cafile_new)) ? ProfileHostParams::Same : ProfileHostParams::Different;
}
static bool profile_print_params_same(const DynamicPrintConfig &cfg_old, const DynamicPrintConfig &cfg_new)
{
t_config_option_keys diff = cfg_old.diff(cfg_new);
// Following keys are used by the UI, not by the slicing core, therefore they are not important
// when comparing profiles for equality. Ignore them.
for (const char *key : { "compatible_prints", "compatible_prints_condition",
"compatible_printers", "compatible_printers_condition", "inherits",
"print_settings_id", "filament_settings_id", "sla_print_settings_id", "sla_material_settings_id", "printer_settings_id",
"printer_model", "printer_variant", "default_print_profile", "default_filament_profile", "default_sla_print_profile", "default_sla_material_profile",
"print_host", "printhost_apikey", "printhost_cafile" })
diff.erase(std::remove(diff.begin(), diff.end(), key), diff.end());
// Preset with the same name as stored inside the config exists.
return diff.empty() && profile_host_params_same_or_anonymized(cfg_old, cfg_new) != ProfileHostParams::Different;
}
// Load a preset from an already parsed config file, insert it into the sorted sequence of presets
// and select it, losing previous modifications.
// In case
Preset& PresetCollection::load_external_preset(
// Path to the profile source file (a G-code, an AMF or 3MF file, a config file)
const std::string &path,
// Name of the profile, derived from the source file name.
const std::string &name,
// Original name of the profile, extracted from the loaded config. Empty, if the name has not been stored.
const std::string &original_name,
// Config to initialize the preset from.
const DynamicPrintConfig &config,
// Select the preset after loading?
bool select)
{
// Load the preset over a default preset, so that the missing fields are filled in from the default preset.
DynamicPrintConfig cfg(this->default_preset_for(config).config);
cfg.apply_only(config, cfg.keys(), true);
// Is there a preset already loaded with the name stored inside the config?
std::deque<Preset>::iterator it = this->find_preset_internal(original_name);
bool found = it != m_presets.end() && it->name == original_name;
if (! found) {
// Try to match the original_name against the "renamed_from" profile names of loaded system profiles.
it = this->find_preset_renamed(original_name);
found = it != m_presets.end();
}
if (found) {
if (profile_print_params_same(it->config, cfg)) {
// The preset exists and it matches the values stored inside config.
if (select)
this->select_preset(it - m_presets.begin());
return *it;
}
if (profile_host_params_same_or_anonymized(it->config, cfg) == ProfileHostParams::Anonymized) {
// The project being loaded is anonymized. Replace the empty host keys of the loaded profile with the data from the original profile.
// See "Octoprint Settings when Opening a .3MF file" GH issue #3244
auto opt_update = [it, &cfg](const std::string &opt_key) {
auto opt = it->config.option<ConfigOptionString>(opt_key);
if (opt != nullptr)
cfg.set_key_value(opt_key, opt->clone());
};
opt_update("print_host");
opt_update("printhost_apikey");
opt_update("printhost_cafile");
}
}
// Update the "inherits" field.
std::string &inherits = Preset::inherits(cfg);
if (found && inherits.empty()) {
// There is a profile with the same name already loaded. Should we update the "inherits" field?
if (it->vendor == nullptr)
inherits = it->inherits();
else
inherits = it->name;
}
// The external preset does not match an internal preset, load the external preset.
std::string new_name;
for (size_t idx = 0;; ++ idx) {
std::string suffix;
if (original_name.empty()) {
if (idx > 0)
suffix = " (" + std::to_string(idx) + ")";
} else {
if (idx == 0)
suffix = " (" + original_name + ")";
else
suffix = " (" + original_name + "-" + std::to_string(idx) + ")";
}
new_name = name + suffix;
it = this->find_preset_internal(new_name);
if (it == m_presets.end() || it->name != new_name)
// Unique profile name. Insert a new profile.
break;
if (profile_print_params_same(it->config, cfg)) {
// The preset exists and it matches the values stored inside config.
if (select)
this->select_preset(it - m_presets.begin());
return *it;
}
// Form another profile name.
}
// Insert a new profile.
Preset &preset = this->load_preset(path, new_name, std::move(cfg), select);
preset.is_external = true;
if (&this->get_selected_preset() == &preset)
this->get_edited_preset().is_external = true;
return preset;
}
Preset& PresetCollection::load_preset(const std::string &path, const std::string &name, DynamicPrintConfig &&config, bool select)
{
auto it = this->find_preset_internal(name);
if (it == m_presets.end() || it->name != name) {
// The preset was not found. Create a new preset.
it = m_presets.emplace(it, Preset(m_type, name, false));
}
Preset &preset = *it;
preset.file = path;
preset.config = std::move(config);
preset.loaded = true;
preset.is_dirty = false;
if (select)
this->select_preset_by_name(name, true);
return preset;
}
void PresetCollection::save_current_preset(const std::string &new_name)
{
// 1) Find the preset with a new_name or create a new one,
// initialize it with the edited config.
auto it = this->find_preset_internal(new_name);
if (it != m_presets.end() && it->name == new_name) {
// Preset with the same name found.
Preset &preset = *it;
if (preset.is_default || preset.is_external || preset.is_system)
// Cannot overwrite the default preset.
return;
// Overwriting an existing preset.
preset.config = std::move(m_edited_preset.config);
// The newly saved preset will be activated -> make it visible.
preset.is_visible = true;
} else {
// Creating a new preset.
Preset &preset = *m_presets.insert(it, m_edited_preset);
std::string &inherits = preset.inherits();
std::string old_name = preset.name;
preset.name = new_name;
preset.file = this->path_from_name(new_name);
preset.vendor = nullptr;
if (preset.is_system) {
// Inheriting from a system preset.
inherits = /* preset.vendor->name + "/" + */ old_name;
} else if (inherits.empty()) {
// Inheriting from a user preset. Link the new preset to the old preset.
// inherits = old_name;
} else {
// Inherited from a user preset. Just maintain the "inherited" flag,
// meaning it will inherit from either the system preset, or the inherited user preset.
}
preset.is_default = false;
preset.is_system = false;
preset.is_external = false;
// The newly saved preset will be activated -> make it visible.
preset.is_visible = true;
// Just system presets have aliases
preset.alias.clear();
}
// 2) Activate the saved preset.
this->select_preset_by_name(new_name, true);
// 2) Store the active preset to disk.
this->get_selected_preset().save();
}
bool PresetCollection::delete_current_preset()
{
const Preset &selected = this->get_selected_preset();
if (selected.is_default)
return false;
if (! selected.is_external && ! selected.is_system) {
// Erase the preset file.
boost::nowide::remove(selected.file.c_str());
}
// Remove the preset from the list.
m_presets.erase(m_presets.begin() + m_idx_selected);
// Find the next visible preset.
size_t new_selected_idx = m_idx_selected;
if (new_selected_idx < m_presets.size())
for (; new_selected_idx < m_presets.size() && ! m_presets[new_selected_idx].is_visible; ++ new_selected_idx) ;
if (new_selected_idx == m_presets.size())
for (--new_selected_idx; new_selected_idx > 0 && !m_presets[new_selected_idx].is_visible; --new_selected_idx);
this->select_preset(new_selected_idx);
return true;
}
bool PresetCollection::delete_preset(const std::string& name)
{
auto it = this->find_preset_internal(name);
const Preset& preset = *it;
if (preset.is_default)
return false;
if (!preset.is_external && !preset.is_system) {
// Erase the preset file.
boost::nowide::remove(preset.file.c_str());
}
m_presets.erase(it);
return true;
}
void PresetCollection::load_bitmap_default(const std::string &file_name)
{
*m_bitmap_main_frame = create_scaled_bitmap(file_name);
}
void PresetCollection::load_bitmap_add(const std::string &file_name)
{
*m_bitmap_add = create_scaled_bitmap(file_name);
}
const Preset* PresetCollection::get_selected_preset_parent() const
{
if (this->get_selected_idx() == -1)
// This preset collection has no preset activated yet. Only the get_edited_preset() is valid.
return nullptr;
const Preset &selected_preset = this->get_selected_preset();
if (selected_preset.is_system || selected_preset.is_default)
return &selected_preset;
const Preset &edited_preset = this->get_edited_preset();
const std::string &inherits = edited_preset.inherits();
const Preset *preset = nullptr;
if (inherits.empty()) {
if (selected_preset.is_external)
return nullptr;
preset = &this->default_preset(m_type == Preset::Type::TYPE_PRINTER && edited_preset.printer_technology() == ptSLA ? 1 : 0);
} else
preset = this->find_preset(inherits, false);
if (preset == nullptr) {
// Resolve the "renamed_from" field.
assert(! inherits.empty());
auto it = this->find_preset_renamed(inherits);
if (it != m_presets.end())
preset = &(*it);
}
return (preset == nullptr/* || preset->is_default*/ || preset->is_external) ? nullptr : preset;
}
const Preset* PresetCollection::get_preset_parent(const Preset& child) const
{
const std::string &inherits = child.inherits();
if (inherits.empty())
// return this->get_selected_preset().is_system ? &this->get_selected_preset() : nullptr;
return nullptr;
const Preset* preset = this->find_preset(inherits, false);
if (preset == nullptr) {
auto it = this->find_preset_renamed(inherits);
if (it != m_presets.end())
preset = &(*it);
}
return (preset == nullptr/* || preset->is_default */|| preset->is_external) ? nullptr : preset;
}
// Return vendor of the first parent profile, for which the vendor is defined, or null if such profile does not exist.
PresetWithVendorProfile PresetCollection::get_preset_with_vendor_profile(const Preset &preset) const
{
const Preset *p = &preset;
const VendorProfile *v = nullptr;
do {
if (p->vendor != nullptr) {
v = p->vendor;
break;
}
p = this->get_preset_parent(*p);
} while (p != nullptr);
return PresetWithVendorProfile(preset, v);
}
const std::string& PresetCollection::get_preset_name_by_alias(const std::string& alias) const
{
for (
// Find the 1st profile name with the alias.
auto it = Slic3r::lower_bound_by_predicate(m_map_alias_to_profile_name.begin(), m_map_alias_to_profile_name.end(), [&alias](auto &l){ return l.first < alias; });
// Continue over all profile names with the same alias.
it != m_map_alias_to_profile_name.end() && it->first == alias; ++ it)
if (auto it_preset = this->find_preset_internal(it->second);
it_preset != m_presets.end() && it_preset->name == it->second &&
it_preset->is_visible && (it_preset->is_compatible || (it_preset - m_presets.begin()) == m_idx_selected))
return it_preset->name;
return alias;
}
const std::string& PresetCollection::get_suffix_modified() {
return g_suffix_modified;
}
// Return a preset by its name. If the preset is active, a temporary copy is returned.
// If a preset is not found by its name, null is returned.
Preset* PresetCollection::find_preset(const std::string &name, bool first_visible_if_not_found)
{
Preset key(m_type, name, false);
auto it = this->find_preset_internal(name);
// Ensure that a temporary copy is returned if the preset found is currently selected.
return (it != m_presets.end() && it->name == key.name) ? &this->preset(it - m_presets.begin()) :
first_visible_if_not_found ? &this->first_visible() : nullptr;
}
// Return index of the first visible preset. Certainly at least the '- default -' preset shall be visible.
size_t PresetCollection::first_visible_idx() const
{
size_t idx = m_default_suppressed ? m_num_default_presets : 0;
for (; idx < this->m_presets.size(); ++ idx)
if (m_presets[idx].is_visible)
break;
if (idx == m_presets.size())
idx = 0;
return idx;
}
void PresetCollection::set_default_suppressed(bool default_suppressed)
{
if (m_default_suppressed != default_suppressed) {
m_default_suppressed = default_suppressed;
bool default_visible = ! default_suppressed || m_idx_selected < m_num_default_presets;
for (size_t i = 0; i < m_num_default_presets; ++ i)
m_presets[i].is_visible = default_visible;
}
}
size_t PresetCollection::update_compatible_internal(const PresetWithVendorProfile &active_printer, const PresetWithVendorProfile *active_print, PresetSelectCompatibleType unselect_if_incompatible)
{
DynamicPrintConfig config;
config.set_key_value("printer_preset", new ConfigOptionString(active_printer.preset.name));
const ConfigOption *opt = active_printer.preset.config.option("nozzle_diameter");
if (opt)
config.set_key_value("num_extruders", new ConfigOptionInt((int)static_cast<const ConfigOptionFloats*>(opt)->values.size()));
for (size_t idx_preset = m_num_default_presets; idx_preset < m_presets.size(); ++ idx_preset) {
bool selected = idx_preset == m_idx_selected;
Preset &preset_selected = m_presets[idx_preset];
Preset &preset_edited = selected ? m_edited_preset : preset_selected;
const PresetWithVendorProfile this_preset_with_vendor_profile = this->get_preset_with_vendor_profile(preset_edited);
bool was_compatible = preset_edited.is_compatible;
preset_edited.is_compatible = is_compatible_with_printer(this_preset_with_vendor_profile, active_printer, &config);
if (active_print != nullptr)
preset_edited.is_compatible &= is_compatible_with_print(this_preset_with_vendor_profile, *active_print, active_printer);
if (! preset_edited.is_compatible && selected &&
(unselect_if_incompatible == PresetSelectCompatibleType::Always || (unselect_if_incompatible == PresetSelectCompatibleType::OnlyIfWasCompatible && was_compatible)))
m_idx_selected = -1;
if (selected)
preset_selected.is_compatible = preset_edited.is_compatible;
}
return m_idx_selected;
}
// Save the preset under a new name. If the name is different from the old one,
// a new preset is stored into the list of presets.
// All presets are marked as not modified and the new preset is activated.
//void PresetCollection::save_current_preset(const std::string &new_name);
// Delete the current preset, activate the first visible preset.
//void PresetCollection::delete_current_preset();
// Update the wxChoice UI component from this list of presets.
// Hide the
void PresetCollection::update_plater_ui(GUI::PresetComboBox *ui)
{
if (ui == nullptr)
return;
// Otherwise fill in the list from scratch.
ui->Freeze();
ui->Clear();
size_t selected_preset_item = INT_MAX; // some value meaning that no one item is selected
const Preset &selected_preset = this->get_selected_preset();
// Show wide icons if the currently selected preset is not compatible with the current printer,
// and draw a red flag in front of the selected preset.
bool wide_icons = ! selected_preset.is_compatible && m_bitmap_incompatible != nullptr;
/* It's supposed that standard size of an icon is 16px*16px for 100% scaled display.
* So set sizes for solid_colored icons used for filament preset
* and scale them in respect to em_unit value
*/
const float scale_f = ui->em_unit() * 0.1f;
const int icon_height = 16 * scale_f + 0.5f;
const int icon_width = 16 * scale_f + 0.5f;
const int thin_space_icon_width = 4 * scale_f + 0.5f;
const int wide_space_icon_width = 6 * scale_f + 0.5f;
std::map<wxString, wxBitmap*> nonsys_presets;
wxString selected = "";
wxString tooltip = "";
if (!this->m_presets.front().is_visible)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap));
for (size_t i = this->m_presets.front().is_visible ? 0 : m_num_default_presets; i < this->m_presets.size(); ++ i) {
const Preset &preset = this->m_presets[i];
if (! preset.is_visible || (! preset.is_compatible && i != m_idx_selected))
continue;
std::string bitmap_key = "";
// !!! Temporary solution, till refactoring: create and use "sla_printer" icon instead of m_bitmap_main_frame
wxBitmap main_bmp = m_bitmap_main_frame ? *m_bitmap_main_frame : wxNullBitmap;
if (m_type == Preset::TYPE_PRINTER && preset.printer_technology()==ptSLA ) {
bitmap_key = "sla_printer";
main_bmp = create_scaled_bitmap("sla_printer");
}
// If the filament preset is not compatible and there is a "red flag" icon loaded, show it left
// to the filament color image.
if (wide_icons)
bitmap_key += preset.is_compatible ? ",cmpt" : ",ncmpt";
bitmap_key += (preset.is_system || preset.is_default) ? ",syst" : ",nsyst";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
if (wide_icons)
// Paint a red flag for incompatible presets.
bmps.emplace_back(preset.is_compatible ? m_bitmap_cache->mkclear(icon_width, icon_height) : *m_bitmap_incompatible);
// Paint the color bars.
bmps.emplace_back(m_bitmap_cache->mkclear(thin_space_icon_width, icon_height));
bmps.emplace_back(main_bmp);
// Paint a lock at the system presets.
bmps.emplace_back(m_bitmap_cache->mkclear(wide_space_icon_width, icon_height));
bmps.emplace_back((preset.is_system || preset.is_default) ? *m_bitmap_lock : m_bitmap_cache->mkclear(icon_width, icon_height));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
const std::string name = preset.alias.empty() ? preset.name : preset.alias;
if (preset.is_default || preset.is_system) {
ui->Append(wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str()),
(bmp == 0) ? main_bmp : *bmp);
if (i == m_idx_selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX) {
selected_preset_item = ui->GetCount() - 1;
tooltip = wxString::FromUTF8(preset.name.c_str());
}
}
else
{
nonsys_presets.emplace(wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str()), bmp/*preset.is_compatible*/);
if (i == m_idx_selected) {
selected = wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str());
tooltip = wxString::FromUTF8(preset.name.c_str());
}
}
if (i + 1 == m_num_default_presets)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap));
}
if (!nonsys_presets.empty())
{
ui->set_label_marker(ui->Append(PresetCollection::separator(L("User presets")), wxNullBitmap));
for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) {
ui->Append(it->first, *it->second);
if (it->first == selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
}
if (m_type == Preset::TYPE_PRINTER || m_type == Preset::TYPE_SLA_MATERIAL) {
std::string bitmap_key = "";
// If the filament preset is not compatible and there is a "red flag" icon loaded, show it left
// to the filament color image.
if (wide_icons)
bitmap_key += "wide,";
bitmap_key += "edit_preset_list";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
if (wide_icons)
// Paint a red flag for incompatible presets.
bmps.emplace_back(m_bitmap_cache->mkclear(icon_width, icon_height));
// Paint the color bars.
bmps.emplace_back(m_bitmap_cache->mkclear(thin_space_icon_width, icon_height));
bmps.emplace_back(*m_bitmap_main_frame);
// Paint a lock at the system presets.
bmps.emplace_back(m_bitmap_cache->mkclear(wide_space_icon_width, icon_height));
// bmps.emplace_back(m_bitmap_add ? *m_bitmap_add : wxNullBitmap);
bmps.emplace_back(create_scaled_bitmap("edit_uni"));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
if (m_type == Preset::TYPE_SLA_MATERIAL)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("Add/Remove materials")), *bmp), GUI::PresetComboBox::LABEL_ITEM_WIZARD_MATERIALS);
else
ui->set_label_marker(ui->Append(PresetCollection::separator(L("Add/Remove printers")), *bmp), GUI::PresetComboBox::LABEL_ITEM_WIZARD_PRINTERS);
}
/* But, if selected_preset_item is still equal to INT_MAX, it means that
* there is no presets added to the list.
* So, select last combobox item ("Add/Remove preset")
*/
if (selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
ui->SetSelection(selected_preset_item);
ui->SetToolTip(tooltip.IsEmpty() ? ui->GetString(selected_preset_item) : tooltip);
ui->check_selection();
ui->Thaw();
// Update control min size after rescale (changed Display DPI under MSW)
if (ui->GetMinWidth() != 20 * ui->em_unit())
ui->SetMinSize(wxSize(20 * ui->em_unit(), ui->GetSize().GetHeight()));
}
size_t PresetCollection::update_tab_ui(wxBitmapComboBox *ui, bool show_incompatible, const int em/* = 10*/)
{
if (ui == nullptr)
return 0;
ui->Freeze();
ui->Clear();
size_t selected_preset_item = INT_MAX; // some value meaning that no one item is selected
/* It's supposed that standard size of an icon is 16px*16px for 100% scaled display.
* So set sizes for solid_colored(empty) icons used for preset
* and scale them in respect to em_unit value
*/
const float scale_f = em * 0.1f;
const int icon_height = 16 * scale_f + 0.5f;
const int icon_width = 16 * scale_f + 0.5f;
std::map<wxString, wxBitmap*> nonsys_presets;
wxString selected = "";
if (!this->m_presets.front().is_visible)
ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap);
for (size_t i = this->m_presets.front().is_visible ? 0 : m_num_default_presets; i < this->m_presets.size(); ++i) {
const Preset &preset = this->m_presets[i];
if (! preset.is_visible || (! show_incompatible && ! preset.is_compatible && i != m_idx_selected))
continue;
std::string bitmap_key = "tab";
// !!! Temporary solution, till refactoring: create and use "sla_printer" icon instead of m_bitmap_main_frame
wxBitmap main_bmp = m_bitmap_main_frame ? *m_bitmap_main_frame : wxNullBitmap;
if (m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA) {
bitmap_key = "sla_printer";
main_bmp = create_scaled_bitmap("sla_printer");
}
bitmap_key += preset.is_compatible ? ",cmpt" : ",ncmpt";
bitmap_key += (preset.is_system || preset.is_default) ? ",syst" : ",nsyst";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
const wxBitmap* tmp_bmp = preset.is_compatible ? m_bitmap_compatible : m_bitmap_incompatible;
bmps.emplace_back((tmp_bmp == 0) ? main_bmp : *tmp_bmp);
// Paint a lock at the system presets.
bmps.emplace_back((preset.is_system || preset.is_default) ? *m_bitmap_lock : m_bitmap_cache->mkclear(icon_width, icon_height));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
if (preset.is_default || preset.is_system) {
ui->Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str()),
(bmp == 0) ? main_bmp : *bmp);
if (i == m_idx_selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
else
{
nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str()), bmp/*preset.is_compatible*/);
if (i == m_idx_selected)
selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str());
}
if (i + 1 == m_num_default_presets)
ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap);
}
if (!nonsys_presets.empty())
{
ui->Append(PresetCollection::separator(L("User presets")), wxNullBitmap);
for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) {
ui->Append(it->first, *it->second);
if (it->first == selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
}
if (m_type == Preset::TYPE_PRINTER) {
wxBitmap *bmp = m_bitmap_cache->find("edit_printer_list");
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
bmps.emplace_back(*m_bitmap_main_frame);
// bmps.emplace_back(m_bitmap_add ? *m_bitmap_add : wxNullBitmap);
bmps.emplace_back(create_scaled_bitmap("edit_uni"));
bmp = m_bitmap_cache->insert("add_printer_tab", bmps);
}
ui->Append(PresetCollection::separator("Add a new printer"), *bmp);
}
/* But, if selected_preset_item is still equal to INT_MAX, it means that
* there is no presets added to the list.
* So, select last combobox item ("Add/Remove preset")
*/
if (selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
ui->SetSelection(selected_preset_item);
ui->SetToolTip(ui->GetString(selected_preset_item));
ui->Thaw();
return selected_preset_item;
}
// Update a dirty floag of the current preset, update the labels of the UI component accordingly.
// Return true if the dirty flag changed.
bool PresetCollection::update_dirty_ui(wxBitmapComboBox *ui)
{
wxWindowUpdateLocker noUpdates(ui);
// 1) Update the dirty flag of the current preset.
bool was_dirty = this->get_selected_preset().is_dirty;
bool is_dirty = current_is_dirty();
this->get_selected_preset().is_dirty = is_dirty;
this->get_edited_preset().is_dirty = is_dirty;
// 2) Update the labels.
for (unsigned int ui_id = 0; ui_id < ui->GetCount(); ++ ui_id) {
std::string old_label = ui->GetString(ui_id).utf8_str().data();
std::string preset_name = Preset::remove_suffix_modified(old_label);
const Preset *preset = this->find_preset(preset_name, false);
// The old_label could be the "----- system presets ------" or the "------- user presets --------" separator.
// assert(preset != nullptr);
if (preset != nullptr) {
std::string new_label = preset->is_dirty ? preset->name + g_suffix_modified : preset->name;
if (old_label != new_label)
ui->SetString(ui_id, wxString::FromUTF8(new_label.c_str()));
}
}
#ifdef __APPLE__
// wxWidgets on OSX do not upload the text of the combo box line automatically.
// Force it to update by re-selecting.
ui->SetSelection(ui->GetSelection());
#endif /* __APPLE __ */
return was_dirty != is_dirty;
}
template<class T>
void add_correct_opts_to_diff(const std::string &opt_key, t_config_option_keys& vec, const ConfigBase &other, const ConfigBase &this_c)
{
const T* opt_init = static_cast<const T*>(other.option(opt_key));
const T* opt_cur = static_cast<const T*>(this_c.option(opt_key));
int opt_init_max_id = opt_init->values.size() - 1;
for (int i = 0; i < opt_cur->values.size(); i++)
{
int init_id = i <= opt_init_max_id ? i : 0;
if (opt_cur->values[i] != opt_init->values[init_id])
vec.emplace_back(opt_key + "#" + std::to_string(i));
}
}
// Use deep_diff to correct return of changed options, considering individual options for each extruder.
inline t_config_option_keys deep_diff(const ConfigBase &config_this, const ConfigBase &config_other)
{
t_config_option_keys diff;
for (const t_config_option_key &opt_key : config_this.keys()) {
const ConfigOption *this_opt = config_this.option(opt_key);
const ConfigOption *other_opt = config_other.option(opt_key);
if (this_opt != nullptr && other_opt != nullptr && *this_opt != *other_opt)
{
if (opt_key == "bed_shape" || opt_key == "thumbnails" || opt_key == "compatible_prints" || opt_key == "compatible_printers") {
diff.emplace_back(opt_key);
continue;
}
switch (other_opt->type())
{
case coInts: add_correct_opts_to_diff<ConfigOptionInts >(opt_key, diff, config_other, config_this); break;
case coBools: add_correct_opts_to_diff<ConfigOptionBools >(opt_key, diff, config_other, config_this); break;
case coFloats: add_correct_opts_to_diff<ConfigOptionFloats >(opt_key, diff, config_other, config_this); break;
case coStrings: add_correct_opts_to_diff<ConfigOptionStrings >(opt_key, diff, config_other, config_this); break;
case coPercents:add_correct_opts_to_diff<ConfigOptionPercents >(opt_key, diff, config_other, config_this); break;
case coPoints: add_correct_opts_to_diff<ConfigOptionPoints >(opt_key, diff, config_other, config_this); break;
default: diff.emplace_back(opt_key); break;
}
}
}
return diff;
}
std::vector<std::string> PresetCollection::dirty_options(const Preset *edited, const Preset *reference, const bool deep_compare /*= false*/)
{
std::vector<std::string> changed;
if (edited != nullptr && reference != nullptr) {
changed = deep_compare ?
deep_diff(edited->config, reference->config) :
reference->config.diff(edited->config);
// The "compatible_printers" option key is handled differently from the others:
// It is not mandatory. If the key is missing, it means it is compatible with any printer.
// If the key exists and it is empty, it means it is compatible with no printer.
std::initializer_list<const char*> optional_keys { "compatible_prints", "compatible_printers" };
for (auto &opt_key : optional_keys) {
if (reference->config.has(opt_key) != edited->config.has(opt_key))
changed.emplace_back(opt_key);
}
}
return changed;
}
// Select a new preset. This resets all the edits done to the currently selected preset.
// If the preset with index idx does not exist, a first visible preset is selected.
Preset& PresetCollection::select_preset(size_t idx)
{
for (Preset &preset : m_presets)
preset.is_dirty = false;
if (idx >= m_presets.size())
idx = first_visible_idx();
m_idx_selected = idx;
m_edited_preset = m_presets[idx];
bool default_visible = ! m_default_suppressed || m_idx_selected < m_num_default_presets;
for (size_t i = 0; i < m_num_default_presets; ++i)
m_presets[i].is_visible = default_visible;
return m_presets[idx];
}
bool PresetCollection::select_preset_by_name(const std::string &name_w_suffix, bool force)
{
std::string name = Preset::remove_suffix_modified(name_w_suffix);
// 1) Try to find the preset by its name.
auto it = this->find_preset_internal(name);
size_t idx = 0;
if (it != m_presets.end() && it->name == name && it->is_visible)
// Preset found by its name and it is visible.
idx = it - m_presets.begin();
else {
// Find the first visible preset.
for (size_t i = m_default_suppressed ? m_num_default_presets : 0; i < m_presets.size(); ++ i)
if (m_presets[i].is_visible) {
idx = i;
break;
}
// If the first visible preset was not found, return the 0th element, which is the default preset.
}
// 2) Select the new preset.
if (m_idx_selected != idx || force) {
this->select_preset(idx);
return true;
}
return false;
}
bool PresetCollection::select_preset_by_name_strict(const std::string &name)
{
// 1) Try to find the preset by its name.
auto it = this->find_preset_internal(name);
size_t idx = (size_t)-1;
if (it != m_presets.end() && it->name == name && it->is_visible)
// Preset found by its name.
idx = it - m_presets.begin();
// 2) Select the new preset.
if (idx != (size_t)-1) {
this->select_preset(idx);
return true;
}
m_idx_selected = idx;
return false;
}
// Merge one vendor's presets with the other vendor's presets, report duplicates.
std::vector<std::string> PresetCollection::merge_presets(PresetCollection &&other, const VendorMap &new_vendors)
{
std::vector<std::string> duplicates;
for (Preset &preset : other.m_presets) {
if (preset.is_default || preset.is_external)
continue;
Preset key(m_type, preset.name);
auto it = std::lower_bound(m_presets.begin() + m_num_default_presets, m_presets.end(), key);
if (it == m_presets.end() || it->name != preset.name) {
if (preset.vendor != nullptr) {
// Re-assign a pointer to the vendor structure in the new PresetBundle.
auto it = new_vendors.find(preset.vendor->id);
assert(it != new_vendors.end());
preset.vendor = &it->second;
}
this->m_presets.emplace(it, std::move(preset));
} else
duplicates.emplace_back(std::move(preset.name));
}
return duplicates;
}
void PresetCollection::update_map_alias_to_profile_name()
{
m_map_alias_to_profile_name.clear();
for (const Preset &preset : m_presets)
m_map_alias_to_profile_name.emplace_back(preset.alias, preset.name);
std::sort(m_map_alias_to_profile_name.begin(), m_map_alias_to_profile_name.end(), [](auto &l, auto &r) { return l.first < r.first; });
}
void PresetCollection::update_map_system_profile_renamed()
{
m_map_system_profile_renamed.clear();
for (Preset &preset : m_presets)
for (const std::string &renamed_from : preset.renamed_from) {
const auto [it, success] = m_map_system_profile_renamed.insert(std::pair<std::string, std::string>(renamed_from, preset.name));
if (! success)
BOOST_LOG_TRIVIAL(error) << boost::format("Preset name \"%1%\" was marked as renamed from \"%2%\", though preset name \"%3%\" was marked as renamed from \"%2%\" as well.") % preset.name % renamed_from % it->second;
}
}
std::string PresetCollection::name() const
{
switch (this->type()) {
case Preset::TYPE_PRINT: return L("print");
case Preset::TYPE_FILAMENT: return L("filament");
case Preset::TYPE_SLA_PRINT: return L("SLA print");
case Preset::TYPE_SLA_MATERIAL: return L("SLA material");
case Preset::TYPE_PRINTER: return L("printer");
default: return "invalid";
}
}
std::string PresetCollection::section_name() const
{
switch (this->type()) {
case Preset::TYPE_PRINT: return "print";
case Preset::TYPE_FILAMENT: return "filament";
case Preset::TYPE_SLA_PRINT: return "sla_print";
case Preset::TYPE_SLA_MATERIAL: return "sla_material";
case Preset::TYPE_PRINTER: return "printer";
default: return "invalid";
}
}
std::vector<std::string> PresetCollection::system_preset_names() const
{
size_t num = 0;
for (const Preset &preset : m_presets)
if (preset.is_system)
++ num;
std::vector<std::string> out;
out.reserve(num);
for (const Preset &preset : m_presets)
if (preset.is_system)
out.emplace_back(preset.name);
std::sort(out.begin(), out.end());
return out;
}
// Generate a file path from a profile name. Add the ".ini" suffix if it is missing.
std::string PresetCollection::path_from_name(const std::string &new_name) const
{
std::string file_name = boost::iends_with(new_name, ".ini") ? new_name : (new_name + ".ini");
return (boost::filesystem::path(m_dir_path) / file_name).make_preferred().string();
}
void PresetCollection::clear_bitmap_cache()
{
m_bitmap_cache->clear();
}
wxString PresetCollection::separator(const std::string &label)
{
return wxString::FromUTF8(PresetCollection::separator_head()) + _(label) + wxString::FromUTF8(PresetCollection::separator_tail());
}
const Preset& PrinterPresetCollection::default_preset_for(const DynamicPrintConfig &config) const
{
const ConfigOptionEnumGeneric *opt_printer_technology = config.opt<ConfigOptionEnumGeneric>("printer_technology");
return this->default_preset((opt_printer_technology == nullptr || opt_printer_technology->value == ptFFF) ? 0 : 1);
}
const Preset* PrinterPresetCollection::find_by_model_id(const std::string &model_id) const
{
if (model_id.empty()) { return nullptr; }
const auto it = std::find_if(cbegin(), cend(), [&](const Preset &preset) {
return preset.config.opt_string("printer_model") == model_id;
});
return it != cend() ? &*it : nullptr;
}
namespace PresetUtils {
const VendorProfile::PrinterModel* system_printer_model(const Preset &preset)
{
const VendorProfile::PrinterModel *out = nullptr;
if (preset.vendor != nullptr) {
auto *printer_model = preset.config.opt<ConfigOptionString>("printer_model");
if (printer_model != nullptr && ! printer_model->value.empty()) {
auto it = std::find_if(preset.vendor->models.begin(), preset.vendor->models.end(), [printer_model](const VendorProfile::PrinterModel &pm) { return pm.id == printer_model->value; });
if (it != preset.vendor->models.end())
out = &(*it);
}
}
return out;
}
} // namespace PresetUtils
} // namespace Slic3r
When loading installed filaments and SLA materials from PrusaSlicer.ini,
the "renamed_from" property of current profiles was not taken into account.
This lead to a situation where there were no MMU or SLA materials installed
after upgrade from PrusaSlicer 2.2.1 to 2.2. This should work now.
#include <cassert>
#include "Preset.hpp"
#include "AppConfig.hpp"
#include "BitmapCache.hpp"
#include "I18N.hpp"
#include "wxExtensions.hpp"
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#endif /* _MSC_VER */
#include <algorithm>
#include <fstream>
#include <stdexcept>
#include <unordered_map>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/nowide/cenv.hpp>
#include <boost/nowide/convert.hpp>
#include <boost/nowide/cstdio.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/locale.hpp>
#include <boost/log/trivial.hpp>
#include <wx/image.h>
#include <wx/choice.h>
#include <wx/bmpcbox.h>
#include <wx/wupdlock.h>
#include "libslic3r/libslic3r.h"
#include "libslic3r/Utils.hpp"
#include "libslic3r/PlaceholderParser.hpp"
#include "Plater.hpp"
using boost::property_tree::ptree;
namespace Slic3r {
ConfigFileType guess_config_file_type(const ptree &tree)
{
size_t app_config = 0;
size_t bundle = 0;
size_t config = 0;
for (const ptree::value_type &v : tree) {
if (v.second.empty()) {
if (v.first == "background_processing" ||
v.first == "last_output_path" ||
v.first == "no_controller" ||
v.first == "no_defaults")
++ app_config;
else if (v.first == "nozzle_diameter" ||
v.first == "filament_diameter")
++ config;
} else if (boost::algorithm::starts_with(v.first, "print:") ||
boost::algorithm::starts_with(v.first, "filament:") ||
boost::algorithm::starts_with(v.first, "printer:") ||
v.first == "settings")
++ bundle;
else if (v.first == "presets") {
++ app_config;
++ bundle;
} else if (v.first == "recent") {
for (auto &kvp : v.second)
if (kvp.first == "config_directory" || kvp.first == "skein_directory")
++ app_config;
}
}
return (app_config > bundle && app_config > config) ? CONFIG_FILE_TYPE_APP_CONFIG :
(bundle > config) ? CONFIG_FILE_TYPE_CONFIG_BUNDLE : CONFIG_FILE_TYPE_CONFIG;
}
VendorProfile VendorProfile::from_ini(const boost::filesystem::path &path, bool load_all)
{
ptree tree;
boost::filesystem::ifstream ifs(path);
boost::property_tree::read_ini(ifs, tree);
return VendorProfile::from_ini(tree, path, load_all);
}
static const std::unordered_map<std::string, std::string> pre_family_model_map {{
{ "MK3", "MK3" },
{ "MK3MMU2", "MK3" },
{ "MK2.5", "MK2.5" },
{ "MK2.5MMU2", "MK2.5" },
{ "MK2S", "MK2" },
{ "MK2SMM", "MK2" },
{ "SL1", "SL1" },
}};
VendorProfile VendorProfile::from_ini(const ptree &tree, const boost::filesystem::path &path, bool load_all)
{
static const std::string printer_model_key = "printer_model:";
static const std::string filaments_section = "default_filaments";
static const std::string materials_section = "default_sla_materials";
const std::string id = path.stem().string();
if (! boost::filesystem::exists(path)) {
throw std::runtime_error((boost::format("Cannot load Vendor Config Bundle `%1%`: File not found: `%2%`.") % id % path).str());
}
VendorProfile res(id);
// Helper to get compulsory fields
auto get_or_throw = [&](const ptree &tree, const std::string &key) -> ptree::const_assoc_iterator
{
auto res = tree.find(key);
if (res == tree.not_found()) {
throw std::runtime_error((boost::format("Vendor Config Bundle `%1%` is not valid: Missing secion or key: `%2%`.") % id % key).str());
}
return res;
};
// Load the header
const auto &vendor_section = get_or_throw(tree, "vendor")->second;
res.name = get_or_throw(vendor_section, "name")->second.data();
auto config_version_str = get_or_throw(vendor_section, "config_version")->second.data();
auto config_version = Semver::parse(config_version_str);
if (! config_version) {
throw std::runtime_error((boost::format("Vendor Config Bundle `%1%` is not valid: Cannot parse config_version: `%2%`.") % id % config_version_str).str());
} else {
res.config_version = std::move(*config_version);
}
// Load URLs
const auto config_update_url = vendor_section.find("config_update_url");
if (config_update_url != vendor_section.not_found()) {
res.config_update_url = config_update_url->second.data();
}
const auto changelog_url = vendor_section.find("changelog_url");
if (changelog_url != vendor_section.not_found()) {
res.changelog_url = changelog_url->second.data();
}
if (! load_all) {
return res;
}
// Load printer models
for (auto §ion : tree) {
if (boost::starts_with(section.first, printer_model_key)) {
VendorProfile::PrinterModel model;
model.id = section.first.substr(printer_model_key.size());
model.name = section.second.get<std::string>("name", model.id);
const char *technology_fallback = boost::algorithm::starts_with(model.id, "SL") ? "SLA" : "FFF";
auto technology_field = section.second.get<std::string>("technology", technology_fallback);
if (! ConfigOptionEnum<PrinterTechnology>::from_string(technology_field, model.technology)) {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Invalid printer technology field: `%2%`") % id % technology_field;
model.technology = ptFFF;
}
model.family = section.second.get<std::string>("family", std::string());
if (model.family.empty() && res.name == "Prusa Research") {
// If no family is specified, it can be inferred for known printers
const auto from_pre_map = pre_family_model_map.find(model.id);
if (from_pre_map != pre_family_model_map.end()) { model.family = from_pre_map->second; }
}
#if 0
// Remove SLA printers from the initial alpha.
if (model.technology == ptSLA)
continue;
#endif
section.second.get<std::string>("variants", "");
const auto variants_field = section.second.get<std::string>("variants", "");
std::vector<std::string> variants;
if (Slic3r::unescape_strings_cstyle(variants_field, variants)) {
for (const std::string &variant_name : variants) {
if (model.variant(variant_name) == nullptr)
model.variants.emplace_back(VendorProfile::PrinterVariant(variant_name));
}
} else {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Malformed variants field: `%2%`") % id % variants_field;
}
auto default_materials_field = section.second.get<std::string>("default_materials", "");
if (default_materials_field.empty())
default_materials_field = section.second.get<std::string>("default_filaments", "");
if (Slic3r::unescape_strings_cstyle(default_materials_field, model.default_materials)) {
Slic3r::sort_remove_duplicates(model.default_materials);
} else {
BOOST_LOG_TRIVIAL(error) << boost::format("Vendor bundle: `%1%`: Malformed default_materials field: `%2%`") % id % default_materials_field;
}
model.bed_model = section.second.get<std::string>("bed_model", "");
model.bed_texture = section.second.get<std::string>("bed_texture", "");
if (! model.id.empty() && ! model.variants.empty())
res.models.push_back(std::move(model));
}
}
// Load filaments and sla materials to be installed by default
const auto filaments = tree.find(filaments_section);
if (filaments != tree.not_found()) {
for (auto &pair : filaments->second) {
if (pair.second.data() == "1") {
res.default_filaments.insert(pair.first);
}
}
}
const auto materials = tree.find(materials_section);
if (materials != tree.not_found()) {
for (auto &pair : materials->second) {
if (pair.second.data() == "1") {
res.default_sla_materials.insert(pair.first);
}
}
}
return res;
}
std::vector<std::string> VendorProfile::families() const
{
std::vector<std::string> res;
unsigned num_familiies = 0;
for (auto &model : models) {
if (std::find(res.begin(), res.end(), model.family) == res.end()) {
res.push_back(model.family);
num_familiies++;
}
}
return res;
}
// Suffix to be added to a modified preset name in the combo box.
static std::string g_suffix_modified = " (modified)";
const std::string& Preset::suffix_modified()
{
return g_suffix_modified;
}
void Preset::update_suffix_modified()
{
g_suffix_modified = (" (" + _(L("modified")) + ")").ToUTF8().data();
}
// Remove an optional "(modified)" suffix from a name.
// This converts a UI name to a unique preset identifier.
std::string Preset::remove_suffix_modified(const std::string &name)
{
return boost::algorithm::ends_with(name, g_suffix_modified) ?
name.substr(0, name.size() - g_suffix_modified.size()) :
name;
}
// Update new extruder fields at the printer profile.
void Preset::normalize(DynamicPrintConfig &config)
{
auto *nozzle_diameter = dynamic_cast<const ConfigOptionFloats*>(config.option("nozzle_diameter"));
if (nozzle_diameter != nullptr)
// Loaded the FFF Printer settings. Verify, that all extruder dependent values have enough values.
config.set_num_extruders((unsigned int)nozzle_diameter->values.size());
if (config.option("filament_diameter") != nullptr) {
// This config contains single or multiple filament presets.
// Ensure that the filament preset vector options contain the correct number of values.
size_t n = (nozzle_diameter == nullptr) ? 1 : nozzle_diameter->values.size();
const auto &defaults = FullPrintConfig::defaults();
for (const std::string &key : Preset::filament_options()) {
if (key == "compatible_prints" || key == "compatible_printers")
continue;
auto *opt = config.option(key, false);
/*assert(opt != nullptr);
assert(opt->is_vector());*/
if (opt != nullptr && opt->is_vector())
static_cast<ConfigOptionVectorBase*>(opt)->resize(n, defaults.option(key));
}
// The following keys are mandatory for the UI, but they are not part of FullPrintConfig, therefore they are handled separately.
for (const std::string &key : { "filament_settings_id" }) {
auto *opt = config.option(key, false);
assert(opt == nullptr || opt->type() == coStrings);
if (opt != nullptr && opt->type() == coStrings)
static_cast<ConfigOptionStrings*>(opt)->values.resize(n, std::string());
}
}
}
std::string Preset::remove_invalid_keys(DynamicPrintConfig &config, const DynamicPrintConfig &default_config)
{
std::string incorrect_keys;
for (const std::string &key : config.keys())
if (! default_config.has(key)) {
if (incorrect_keys.empty())
incorrect_keys = key;
else {
incorrect_keys += ", ";
incorrect_keys += key;
}
config.erase(key);
}
return incorrect_keys;
}
void Preset::save()
{
this->config.save(this->file);
}
// Return a label of this preset, consisting of a name and a "(modified)" suffix, if this preset is dirty.
std::string Preset::label() const
{
return this->name + (this->is_dirty ? g_suffix_modified : "");
}
bool is_compatible_with_print(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_print, const PresetWithVendorProfile &active_printer)
{
if (preset.vendor != nullptr && preset.vendor != active_printer.vendor)
// The current profile has a vendor assigned and it is different from the active print's vendor.
return false;
auto &condition = preset.preset.compatible_prints_condition();
auto *compatible_prints = dynamic_cast<const ConfigOptionStrings*>(preset.preset.config.option("compatible_prints"));
bool has_compatible_prints = compatible_prints != nullptr && ! compatible_prints->values.empty();
if (! has_compatible_prints && ! condition.empty()) {
try {
return PlaceholderParser::evaluate_boolean_expression(condition, active_print.preset.config);
} catch (const std::runtime_error &err) {
//FIXME in case of an error, return "compatible with everything".
printf("Preset::is_compatible_with_print - parsing error of compatible_prints_condition %s:\n%s\n", active_print.preset.name.c_str(), err.what());
return true;
}
}
return preset.preset.is_default || active_print.preset.name.empty() || ! has_compatible_prints ||
std::find(compatible_prints->values.begin(), compatible_prints->values.end(), active_print.preset.name) !=
compatible_prints->values.end();
}
bool is_compatible_with_printer(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_printer, const DynamicPrintConfig *extra_config)
{
if (preset.vendor != nullptr && preset.vendor != active_printer.vendor)
// The current profile has a vendor assigned and it is different from the active print's vendor.
return false;
auto &condition = preset.preset.compatible_printers_condition();
auto *compatible_printers = dynamic_cast<const ConfigOptionStrings*>(preset.preset.config.option("compatible_printers"));
bool has_compatible_printers = compatible_printers != nullptr && ! compatible_printers->values.empty();
if (! has_compatible_printers && ! condition.empty()) {
try {
return PlaceholderParser::evaluate_boolean_expression(condition, active_printer.preset.config, extra_config);
} catch (const std::runtime_error &err) {
//FIXME in case of an error, return "compatible with everything".
printf("Preset::is_compatible_with_printer - parsing error of compatible_printers_condition %s:\n%s\n", active_printer.preset.name.c_str(), err.what());
return true;
}
}
return preset.preset.is_default || active_printer.preset.name.empty() || ! has_compatible_printers ||
std::find(compatible_printers->values.begin(), compatible_printers->values.end(), active_printer.preset.name) !=
compatible_printers->values.end();
}
bool is_compatible_with_printer(const PresetWithVendorProfile &preset, const PresetWithVendorProfile &active_printer)
{
DynamicPrintConfig config;
config.set_key_value("printer_preset", new ConfigOptionString(active_printer.preset.name));
const ConfigOption *opt = active_printer.preset.config.option("nozzle_diameter");
if (opt)
config.set_key_value("num_extruders", new ConfigOptionInt((int)static_cast<const ConfigOptionFloats*>(opt)->values.size()));
return is_compatible_with_printer(preset, active_printer, &config);
}
void Preset::set_visible_from_appconfig(const AppConfig &app_config)
{
if (vendor == nullptr) { return; }
if (type == TYPE_PRINTER) {
const std::string &model = config.opt_string("printer_model");
const std::string &variant = config.opt_string("printer_variant");
if (model.empty() || variant.empty())
return;
is_visible = app_config.get_variant(vendor->id, model, variant);
} else if (type == TYPE_FILAMENT || type == TYPE_SLA_MATERIAL) {
const char *section_name = (type == TYPE_FILAMENT) ? "filaments" : "sla_materials";
if (app_config.has_section(section_name)) {
// Check whether this profile is marked as "installed" in PrusaSlicer.ini,
// or whether a profile is marked as "installed", which this profile may have been renamed from.
const std::map<std::string, std::string> &installed = app_config.get_section(section_name);
auto has = [&installed](const std::string &name) {
auto it = installed.find(name);
return it != installed.end() && ! it->second.empty();
};
is_visible = has(this->name);
for (auto it = this->renamed_from.begin(); ! is_visible && it != this->renamed_from.end(); ++ it)
is_visible = has(*it);
}
}
}
const std::vector<std::string>& Preset::print_options()
{
static std::vector<std::string> s_opts {
"layer_height", "first_layer_height", "perimeters", "spiral_vase", "slice_closing_radius",
"top_solid_layers", "top_solid_min_thickness", "bottom_solid_layers", "bottom_solid_min_thickness",
"extra_perimeters", "ensure_vertical_shell_thickness", "avoid_crossing_perimeters", "thin_walls", "overhangs",
"seam_position", "external_perimeters_first", "fill_density", "fill_pattern", "top_fill_pattern", "bottom_fill_pattern",
"infill_every_layers", "infill_only_where_needed", "solid_infill_every_layers", "fill_angle", "bridge_angle",
"solid_infill_below_area", "only_retract_when_crossing_perimeters", "infill_first", "max_print_speed",
"max_volumetric_speed",
#ifdef HAS_PRESSURE_EQUALIZER
"max_volumetric_extrusion_rate_slope_positive", "max_volumetric_extrusion_rate_slope_negative",
#endif /* HAS_PRESSURE_EQUALIZER */
"perimeter_speed", "small_perimeter_speed", "external_perimeter_speed", "infill_speed", "solid_infill_speed",
"top_solid_infill_speed", "support_material_speed", "support_material_xy_spacing", "support_material_interface_speed",
"bridge_speed", "gap_fill_speed", "travel_speed", "first_layer_speed", "perimeter_acceleration", "infill_acceleration",
"bridge_acceleration", "first_layer_acceleration", "default_acceleration", "skirts", "skirt_distance", "skirt_height",
"min_skirt_length", "brim_width", "support_material", "support_material_auto", "support_material_threshold", "support_material_enforce_layers",
"raft_layers", "support_material_pattern", "support_material_with_sheath", "support_material_spacing",
"support_material_synchronize_layers", "support_material_angle", "support_material_interface_layers",
"support_material_interface_spacing", "support_material_interface_contact_loops", "support_material_contact_distance",
"support_material_buildplate_only", "dont_support_bridges", "notes", "complete_objects", "extruder_clearance_radius",
"extruder_clearance_height", "gcode_comments", "gcode_label_objects", "output_filename_format", "post_process", "perimeter_extruder",
"infill_extruder", "solid_infill_extruder", "support_material_extruder", "support_material_interface_extruder",
"ooze_prevention", "standby_temperature_delta", "interface_shells", "extrusion_width", "first_layer_extrusion_width",
"perimeter_extrusion_width", "external_perimeter_extrusion_width", "infill_extrusion_width", "solid_infill_extrusion_width",
"top_infill_extrusion_width", "support_material_extrusion_width", "infill_overlap", "bridge_flow_ratio", "clip_multipart_objects",
"elefant_foot_compensation", "xy_size_compensation", "threads", "resolution", "wipe_tower", "wipe_tower_x", "wipe_tower_y",
"wipe_tower_width", "wipe_tower_rotation_angle", "wipe_tower_bridging", "single_extruder_multi_material_priming",
"wipe_tower_no_sparse_layers", "compatible_printers", "compatible_printers_condition", "inherits"
};
return s_opts;
}
const std::vector<std::string>& Preset::filament_options()
{
static std::vector<std::string> s_opts {
"filament_colour", "filament_diameter", "filament_type", "filament_soluble", "filament_notes", "filament_max_volumetric_speed",
"extrusion_multiplier", "filament_density", "filament_cost", "filament_loading_speed", "filament_loading_speed_start", "filament_load_time",
"filament_unloading_speed", "filament_unloading_speed_start", "filament_unload_time", "filament_toolchange_delay", "filament_cooling_moves",
"filament_cooling_initial_speed", "filament_cooling_final_speed", "filament_ramming_parameters", "filament_minimal_purge_on_wipe_tower",
"temperature", "first_layer_temperature", "bed_temperature", "first_layer_bed_temperature", "fan_always_on", "cooling", "min_fan_speed",
"max_fan_speed", "bridge_fan_speed", "disable_fan_first_layers", "fan_below_layer_time", "slowdown_below_layer_time", "min_print_speed",
"start_filament_gcode", "end_filament_gcode",
// Retract overrides
"filament_retract_length", "filament_retract_lift", "filament_retract_lift_above", "filament_retract_lift_below", "filament_retract_speed", "filament_deretract_speed", "filament_retract_restart_extra", "filament_retract_before_travel",
"filament_retract_layer_change", "filament_wipe", "filament_retract_before_wipe",
// Profile compatibility
"filament_vendor", "compatible_prints", "compatible_prints_condition", "compatible_printers", "compatible_printers_condition", "inherits"
};
return s_opts;
}
const std::vector<std::string>& Preset::printer_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"printer_technology",
"bed_shape", "bed_custom_texture", "bed_custom_model", "z_offset", "gcode_flavor", "use_relative_e_distances", "serial_port", "serial_speed",
"use_firmware_retraction", "use_volumetric_e", "variable_layer_height",
"host_type", "print_host", "printhost_apikey", "printhost_cafile",
"single_extruder_multi_material", "start_gcode", "end_gcode", "before_layer_gcode", "layer_gcode", "toolchange_gcode",
"between_objects_gcode", "printer_vendor", "printer_model", "printer_variant", "printer_notes", "cooling_tube_retraction",
"cooling_tube_length", "high_current_on_filament_swap", "parking_pos_retraction", "extra_loading_move", "max_print_height",
"default_print_profile", "inherits",
"remaining_times", "silent_mode", "machine_max_acceleration_extruding", "machine_max_acceleration_retracting",
"machine_max_acceleration_x", "machine_max_acceleration_y", "machine_max_acceleration_z", "machine_max_acceleration_e",
"machine_max_feedrate_x", "machine_max_feedrate_y", "machine_max_feedrate_z", "machine_max_feedrate_e",
"machine_min_extruding_rate", "machine_min_travel_rate",
"machine_max_jerk_x", "machine_max_jerk_y", "machine_max_jerk_z", "machine_max_jerk_e",
"thumbnails"
};
s_opts.insert(s_opts.end(), Preset::nozzle_options().begin(), Preset::nozzle_options().end());
}
return s_opts;
}
// The following nozzle options of a printer profile will be adjusted to match the size
// of the nozzle_diameter vector.
const std::vector<std::string>& Preset::nozzle_options()
{
return print_config_def.extruder_option_keys();
}
const std::vector<std::string>& Preset::sla_print_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"layer_height",
"faded_layers",
"supports_enable",
"support_head_front_diameter",
"support_head_penetration",
"support_head_width",
"support_pillar_diameter",
"support_max_bridges_on_pillar",
"support_pillar_connection_mode",
"support_buildplate_only",
"support_pillar_widening_factor",
"support_base_diameter",
"support_base_height",
"support_base_safety_distance",
"support_critical_angle",
"support_max_bridge_length",
"support_max_pillar_link_distance",
"support_object_elevation",
"support_points_density_relative",
"support_points_minimal_distance",
"slice_closing_radius",
"pad_enable",
"pad_wall_thickness",
"pad_wall_height",
"pad_brim_size",
"pad_max_merge_distance",
// "pad_edge_radius",
"pad_wall_slope",
"pad_object_gap",
"pad_around_object",
"pad_around_object_everywhere",
"pad_object_connector_stride",
"pad_object_connector_width",
"pad_object_connector_penetration",
"hollowing_enable",
"hollowing_min_thickness",
"hollowing_quality",
"hollowing_closing_distance",
"output_filename_format",
"default_sla_print_profile",
"compatible_printers",
"compatible_printers_condition",
"inherits"
};
}
return s_opts;
}
const std::vector<std::string>& Preset::sla_material_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"material_type",
"initial_layer_height",
"bottle_cost",
"bottle_volume",
"bottle_weight",
"material_density",
"exposure_time",
"initial_exposure_time",
"material_correction",
"material_notes",
"material_vendor",
"default_sla_material_profile",
"compatible_prints", "compatible_prints_condition",
"compatible_printers", "compatible_printers_condition", "inherits"
};
}
return s_opts;
}
const std::vector<std::string>& Preset::sla_printer_options()
{
static std::vector<std::string> s_opts;
if (s_opts.empty()) {
s_opts = {
"printer_technology",
"bed_shape", "bed_custom_texture", "bed_custom_model", "max_print_height",
"display_width", "display_height", "display_pixels_x", "display_pixels_y",
"display_mirror_x", "display_mirror_y",
"display_orientation",
"fast_tilt_time", "slow_tilt_time", "area_fill",
"relative_correction",
"absolute_correction",
"elefant_foot_compensation",
"elefant_foot_min_width",
"gamma_correction",
"min_exposure_time", "max_exposure_time",
"min_initial_exposure_time", "max_initial_exposure_time",
"print_host", "printhost_apikey", "printhost_cafile",
"printer_notes",
"inherits"
};
}
return s_opts;
}
PresetCollection::PresetCollection(Preset::Type type, const std::vector<std::string> &keys, const Slic3r::StaticPrintConfig &defaults, const std::string &default_name) :
m_type(type),
m_edited_preset(type, "", false),
m_idx_selected(0),
m_bitmap_main_frame(new wxBitmap),
m_bitmap_add(new wxBitmap),
m_bitmap_cache(new GUI::BitmapCache)
{
// Insert just the default preset.
this->add_default_preset(keys, defaults, default_name);
m_edited_preset.config.apply(m_presets.front().config);
}
PresetCollection::~PresetCollection()
{
delete m_bitmap_main_frame;
m_bitmap_main_frame = nullptr;
delete m_bitmap_add;
m_bitmap_add = nullptr;
delete m_bitmap_cache;
m_bitmap_cache = nullptr;
}
void PresetCollection::reset(bool delete_files)
{
if (m_presets.size() > m_num_default_presets) {
if (delete_files) {
// Erase the preset files.
for (Preset &preset : m_presets)
if (! preset.is_default && ! preset.is_external && ! preset.is_system)
boost::nowide::remove(preset.file.c_str());
}
// Don't use m_presets.resize() here as it requires a default constructor for Preset.
m_presets.erase(m_presets.begin() + m_num_default_presets, m_presets.end());
this->select_preset(0);
}
m_map_alias_to_profile_name.clear();
m_map_system_profile_renamed.clear();
}
void PresetCollection::add_default_preset(const std::vector<std::string> &keys, const Slic3r::StaticPrintConfig &defaults, const std::string &preset_name)
{
// Insert just the default preset.
m_presets.emplace_back(Preset(this->type(), preset_name, true));
m_presets.back().config.apply_only(defaults, keys.empty() ? defaults.keys() : keys);
m_presets.back().loaded = true;
++ m_num_default_presets;
}
// Load all presets found in dir_path.
// Throws an exception on error.
void PresetCollection::load_presets(const std::string &dir_path, const std::string &subdir)
{
boost::filesystem::path dir = boost::filesystem::canonical(boost::filesystem::path(dir_path) / subdir).make_preferred();
m_dir_path = dir.string();
std::string errors_cummulative;
// Store the loaded presets into a new vector, otherwise the binary search for already existing presets would be broken.
// (see the "Preset already present, not loading" message).
std::deque<Preset> presets_loaded;
for (auto &dir_entry : boost::filesystem::directory_iterator(dir))
if (Slic3r::is_ini_file(dir_entry)) {
std::string name = dir_entry.path().filename().string();
// Remove the .ini suffix.
name.erase(name.size() - 4);
if (this->find_preset(name, false)) {
// This happens when there's is a preset (most likely legacy one) with the same name as a system preset
// that's already been loaded from a bundle.
BOOST_LOG_TRIVIAL(warning) << "Preset already present, not loading: " << name;
continue;
}
try {
Preset preset(m_type, name, false);
preset.file = dir_entry.path().string();
// Load the preset file, apply preset values on top of defaults.
try {
DynamicPrintConfig config;
config.load_from_ini(preset.file);
// Find a default preset for the config. The PrintPresetCollection provides different default preset based on the "printer_technology" field.
const Preset &default_preset = this->default_preset_for(config);
preset.config = default_preset.config;
preset.config.apply(std::move(config));
Preset::normalize(preset.config);
// Report configuration fields, which are misplaced into a wrong group.
std::string incorrect_keys = Preset::remove_invalid_keys(config, default_preset.config);
if (! incorrect_keys.empty())
BOOST_LOG_TRIVIAL(error) << "Error in a preset file: The preset \"" <<
preset.file << "\" contains the following incorrect keys: " << incorrect_keys << ", which were removed";
preset.loaded = true;
} catch (const std::ifstream::failure &err) {
throw std::runtime_error(std::string("The selected preset cannot be loaded: ") + preset.file + "\n\tReason: " + err.what());
} catch (const std::runtime_error &err) {
throw std::runtime_error(std::string("Failed loading the preset file: ") + preset.file + "\n\tReason: " + err.what());
}
presets_loaded.emplace_back(preset);
} catch (const std::runtime_error &err) {
errors_cummulative += err.what();
errors_cummulative += "\n";
}
}
m_presets.insert(m_presets.end(), std::make_move_iterator(presets_loaded.begin()), std::make_move_iterator(presets_loaded.end()));
std::sort(m_presets.begin() + m_num_default_presets, m_presets.end());
this->select_preset(first_visible_idx());
if (! errors_cummulative.empty())
throw std::runtime_error(errors_cummulative);
}
// Load a preset from an already parsed config file, insert it into the sorted sequence of presets
// and select it, losing previous modifications.
Preset& PresetCollection::load_preset(const std::string &path, const std::string &name, const DynamicPrintConfig &config, bool select)
{
DynamicPrintConfig cfg(this->default_preset().config);
cfg.apply_only(config, cfg.keys(), true);
return this->load_preset(path, name, std::move(cfg), select);
}
enum class ProfileHostParams
{
Same,
Different,
Anonymized,
};
static ProfileHostParams profile_host_params_same_or_anonymized(const DynamicPrintConfig &cfg_old, const DynamicPrintConfig &cfg_new)
{
auto opt_print_host_old = cfg_old.option<ConfigOptionString>("print_host");
auto opt_printhost_apikey_old = cfg_old.option<ConfigOptionString>("printhost_apikey");
auto opt_printhost_cafile_old = cfg_old.option<ConfigOptionString>("printhost_cafile");
auto opt_print_host_new = cfg_new.option<ConfigOptionString>("print_host");
auto opt_printhost_apikey_new = cfg_new.option<ConfigOptionString>("printhost_apikey");
auto opt_printhost_cafile_new = cfg_new.option<ConfigOptionString>("printhost_cafile");
// If the new print host data is undefined, use the old data.
bool new_print_host_undefined = (opt_print_host_new == nullptr || opt_print_host_new ->empty()) &&
(opt_printhost_apikey_new == nullptr || opt_printhost_apikey_new ->empty()) &&
(opt_printhost_cafile_new == nullptr || opt_printhost_cafile_new ->empty());
if (new_print_host_undefined)
return ProfileHostParams::Anonymized;
auto opt_same = [](const ConfigOptionString *l, const ConfigOptionString *r) {
return ((l == nullptr || l->empty()) && (r == nullptr || r->empty())) ||
(l != nullptr && r != nullptr && l->value == r->value);
};
return (opt_same(opt_print_host_old, opt_print_host_new) && opt_same(opt_printhost_apikey_old, opt_printhost_apikey_new) &&
opt_same(opt_printhost_cafile_old, opt_printhost_cafile_new)) ? ProfileHostParams::Same : ProfileHostParams::Different;
}
static bool profile_print_params_same(const DynamicPrintConfig &cfg_old, const DynamicPrintConfig &cfg_new)
{
t_config_option_keys diff = cfg_old.diff(cfg_new);
// Following keys are used by the UI, not by the slicing core, therefore they are not important
// when comparing profiles for equality. Ignore them.
for (const char *key : { "compatible_prints", "compatible_prints_condition",
"compatible_printers", "compatible_printers_condition", "inherits",
"print_settings_id", "filament_settings_id", "sla_print_settings_id", "sla_material_settings_id", "printer_settings_id",
"printer_model", "printer_variant", "default_print_profile", "default_filament_profile", "default_sla_print_profile", "default_sla_material_profile",
"print_host", "printhost_apikey", "printhost_cafile" })
diff.erase(std::remove(diff.begin(), diff.end(), key), diff.end());
// Preset with the same name as stored inside the config exists.
return diff.empty() && profile_host_params_same_or_anonymized(cfg_old, cfg_new) != ProfileHostParams::Different;
}
// Load a preset from an already parsed config file, insert it into the sorted sequence of presets
// and select it, losing previous modifications.
// In case
Preset& PresetCollection::load_external_preset(
// Path to the profile source file (a G-code, an AMF or 3MF file, a config file)
const std::string &path,
// Name of the profile, derived from the source file name.
const std::string &name,
// Original name of the profile, extracted from the loaded config. Empty, if the name has not been stored.
const std::string &original_name,
// Config to initialize the preset from.
const DynamicPrintConfig &config,
// Select the preset after loading?
bool select)
{
// Load the preset over a default preset, so that the missing fields are filled in from the default preset.
DynamicPrintConfig cfg(this->default_preset_for(config).config);
cfg.apply_only(config, cfg.keys(), true);
// Is there a preset already loaded with the name stored inside the config?
std::deque<Preset>::iterator it = this->find_preset_internal(original_name);
bool found = it != m_presets.end() && it->name == original_name;
if (! found) {
// Try to match the original_name against the "renamed_from" profile names of loaded system profiles.
it = this->find_preset_renamed(original_name);
found = it != m_presets.end();
}
if (found) {
if (profile_print_params_same(it->config, cfg)) {
// The preset exists and it matches the values stored inside config.
if (select)
this->select_preset(it - m_presets.begin());
return *it;
}
if (profile_host_params_same_or_anonymized(it->config, cfg) == ProfileHostParams::Anonymized) {
// The project being loaded is anonymized. Replace the empty host keys of the loaded profile with the data from the original profile.
// See "Octoprint Settings when Opening a .3MF file" GH issue #3244
auto opt_update = [it, &cfg](const std::string &opt_key) {
auto opt = it->config.option<ConfigOptionString>(opt_key);
if (opt != nullptr)
cfg.set_key_value(opt_key, opt->clone());
};
opt_update("print_host");
opt_update("printhost_apikey");
opt_update("printhost_cafile");
}
}
// Update the "inherits" field.
std::string &inherits = Preset::inherits(cfg);
if (found && inherits.empty()) {
// There is a profile with the same name already loaded. Should we update the "inherits" field?
if (it->vendor == nullptr)
inherits = it->inherits();
else
inherits = it->name;
}
// The external preset does not match an internal preset, load the external preset.
std::string new_name;
for (size_t idx = 0;; ++ idx) {
std::string suffix;
if (original_name.empty()) {
if (idx > 0)
suffix = " (" + std::to_string(idx) + ")";
} else {
if (idx == 0)
suffix = " (" + original_name + ")";
else
suffix = " (" + original_name + "-" + std::to_string(idx) + ")";
}
new_name = name + suffix;
it = this->find_preset_internal(new_name);
if (it == m_presets.end() || it->name != new_name)
// Unique profile name. Insert a new profile.
break;
if (profile_print_params_same(it->config, cfg)) {
// The preset exists and it matches the values stored inside config.
if (select)
this->select_preset(it - m_presets.begin());
return *it;
}
// Form another profile name.
}
// Insert a new profile.
Preset &preset = this->load_preset(path, new_name, std::move(cfg), select);
preset.is_external = true;
if (&this->get_selected_preset() == &preset)
this->get_edited_preset().is_external = true;
return preset;
}
Preset& PresetCollection::load_preset(const std::string &path, const std::string &name, DynamicPrintConfig &&config, bool select)
{
auto it = this->find_preset_internal(name);
if (it == m_presets.end() || it->name != name) {
// The preset was not found. Create a new preset.
it = m_presets.emplace(it, Preset(m_type, name, false));
}
Preset &preset = *it;
preset.file = path;
preset.config = std::move(config);
preset.loaded = true;
preset.is_dirty = false;
if (select)
this->select_preset_by_name(name, true);
return preset;
}
void PresetCollection::save_current_preset(const std::string &new_name)
{
// 1) Find the preset with a new_name or create a new one,
// initialize it with the edited config.
auto it = this->find_preset_internal(new_name);
if (it != m_presets.end() && it->name == new_name) {
// Preset with the same name found.
Preset &preset = *it;
if (preset.is_default || preset.is_external || preset.is_system)
// Cannot overwrite the default preset.
return;
// Overwriting an existing preset.
preset.config = std::move(m_edited_preset.config);
// The newly saved preset will be activated -> make it visible.
preset.is_visible = true;
} else {
// Creating a new preset.
Preset &preset = *m_presets.insert(it, m_edited_preset);
std::string &inherits = preset.inherits();
std::string old_name = preset.name;
preset.name = new_name;
preset.file = this->path_from_name(new_name);
preset.vendor = nullptr;
if (preset.is_system) {
// Inheriting from a system preset.
inherits = /* preset.vendor->name + "/" + */ old_name;
} else if (inherits.empty()) {
// Inheriting from a user preset. Link the new preset to the old preset.
// inherits = old_name;
} else {
// Inherited from a user preset. Just maintain the "inherited" flag,
// meaning it will inherit from either the system preset, or the inherited user preset.
}
preset.is_default = false;
preset.is_system = false;
preset.is_external = false;
// The newly saved preset will be activated -> make it visible.
preset.is_visible = true;
// Just system presets have aliases
preset.alias.clear();
}
// 2) Activate the saved preset.
this->select_preset_by_name(new_name, true);
// 2) Store the active preset to disk.
this->get_selected_preset().save();
}
bool PresetCollection::delete_current_preset()
{
const Preset &selected = this->get_selected_preset();
if (selected.is_default)
return false;
if (! selected.is_external && ! selected.is_system) {
// Erase the preset file.
boost::nowide::remove(selected.file.c_str());
}
// Remove the preset from the list.
m_presets.erase(m_presets.begin() + m_idx_selected);
// Find the next visible preset.
size_t new_selected_idx = m_idx_selected;
if (new_selected_idx < m_presets.size())
for (; new_selected_idx < m_presets.size() && ! m_presets[new_selected_idx].is_visible; ++ new_selected_idx) ;
if (new_selected_idx == m_presets.size())
for (--new_selected_idx; new_selected_idx > 0 && !m_presets[new_selected_idx].is_visible; --new_selected_idx);
this->select_preset(new_selected_idx);
return true;
}
bool PresetCollection::delete_preset(const std::string& name)
{
auto it = this->find_preset_internal(name);
const Preset& preset = *it;
if (preset.is_default)
return false;
if (!preset.is_external && !preset.is_system) {
// Erase the preset file.
boost::nowide::remove(preset.file.c_str());
}
m_presets.erase(it);
return true;
}
void PresetCollection::load_bitmap_default(const std::string &file_name)
{
*m_bitmap_main_frame = create_scaled_bitmap(file_name);
}
void PresetCollection::load_bitmap_add(const std::string &file_name)
{
*m_bitmap_add = create_scaled_bitmap(file_name);
}
const Preset* PresetCollection::get_selected_preset_parent() const
{
if (this->get_selected_idx() == -1)
// This preset collection has no preset activated yet. Only the get_edited_preset() is valid.
return nullptr;
const Preset &selected_preset = this->get_selected_preset();
if (selected_preset.is_system || selected_preset.is_default)
return &selected_preset;
const Preset &edited_preset = this->get_edited_preset();
const std::string &inherits = edited_preset.inherits();
const Preset *preset = nullptr;
if (inherits.empty()) {
if (selected_preset.is_external)
return nullptr;
preset = &this->default_preset(m_type == Preset::Type::TYPE_PRINTER && edited_preset.printer_technology() == ptSLA ? 1 : 0);
} else
preset = this->find_preset(inherits, false);
if (preset == nullptr) {
// Resolve the "renamed_from" field.
assert(! inherits.empty());
auto it = this->find_preset_renamed(inherits);
if (it != m_presets.end())
preset = &(*it);
}
return (preset == nullptr/* || preset->is_default*/ || preset->is_external) ? nullptr : preset;
}
const Preset* PresetCollection::get_preset_parent(const Preset& child) const
{
const std::string &inherits = child.inherits();
if (inherits.empty())
// return this->get_selected_preset().is_system ? &this->get_selected_preset() : nullptr;
return nullptr;
const Preset* preset = this->find_preset(inherits, false);
if (preset == nullptr) {
auto it = this->find_preset_renamed(inherits);
if (it != m_presets.end())
preset = &(*it);
}
return (preset == nullptr/* || preset->is_default */|| preset->is_external) ? nullptr : preset;
}
// Return vendor of the first parent profile, for which the vendor is defined, or null if such profile does not exist.
PresetWithVendorProfile PresetCollection::get_preset_with_vendor_profile(const Preset &preset) const
{
const Preset *p = &preset;
const VendorProfile *v = nullptr;
do {
if (p->vendor != nullptr) {
v = p->vendor;
break;
}
p = this->get_preset_parent(*p);
} while (p != nullptr);
return PresetWithVendorProfile(preset, v);
}
const std::string& PresetCollection::get_preset_name_by_alias(const std::string& alias) const
{
for (
// Find the 1st profile name with the alias.
auto it = Slic3r::lower_bound_by_predicate(m_map_alias_to_profile_name.begin(), m_map_alias_to_profile_name.end(), [&alias](auto &l){ return l.first < alias; });
// Continue over all profile names with the same alias.
it != m_map_alias_to_profile_name.end() && it->first == alias; ++ it)
if (auto it_preset = this->find_preset_internal(it->second);
it_preset != m_presets.end() && it_preset->name == it->second &&
it_preset->is_visible && (it_preset->is_compatible || (it_preset - m_presets.begin()) == m_idx_selected))
return it_preset->name;
return alias;
}
const std::string& PresetCollection::get_suffix_modified() {
return g_suffix_modified;
}
// Return a preset by its name. If the preset is active, a temporary copy is returned.
// If a preset is not found by its name, null is returned.
Preset* PresetCollection::find_preset(const std::string &name, bool first_visible_if_not_found)
{
Preset key(m_type, name, false);
auto it = this->find_preset_internal(name);
// Ensure that a temporary copy is returned if the preset found is currently selected.
return (it != m_presets.end() && it->name == key.name) ? &this->preset(it - m_presets.begin()) :
first_visible_if_not_found ? &this->first_visible() : nullptr;
}
// Return index of the first visible preset. Certainly at least the '- default -' preset shall be visible.
size_t PresetCollection::first_visible_idx() const
{
size_t idx = m_default_suppressed ? m_num_default_presets : 0;
for (; idx < this->m_presets.size(); ++ idx)
if (m_presets[idx].is_visible)
break;
if (idx == m_presets.size())
idx = 0;
return idx;
}
void PresetCollection::set_default_suppressed(bool default_suppressed)
{
if (m_default_suppressed != default_suppressed) {
m_default_suppressed = default_suppressed;
bool default_visible = ! default_suppressed || m_idx_selected < m_num_default_presets;
for (size_t i = 0; i < m_num_default_presets; ++ i)
m_presets[i].is_visible = default_visible;
}
}
size_t PresetCollection::update_compatible_internal(const PresetWithVendorProfile &active_printer, const PresetWithVendorProfile *active_print, PresetSelectCompatibleType unselect_if_incompatible)
{
DynamicPrintConfig config;
config.set_key_value("printer_preset", new ConfigOptionString(active_printer.preset.name));
const ConfigOption *opt = active_printer.preset.config.option("nozzle_diameter");
if (opt)
config.set_key_value("num_extruders", new ConfigOptionInt((int)static_cast<const ConfigOptionFloats*>(opt)->values.size()));
for (size_t idx_preset = m_num_default_presets; idx_preset < m_presets.size(); ++ idx_preset) {
bool selected = idx_preset == m_idx_selected;
Preset &preset_selected = m_presets[idx_preset];
Preset &preset_edited = selected ? m_edited_preset : preset_selected;
const PresetWithVendorProfile this_preset_with_vendor_profile = this->get_preset_with_vendor_profile(preset_edited);
bool was_compatible = preset_edited.is_compatible;
preset_edited.is_compatible = is_compatible_with_printer(this_preset_with_vendor_profile, active_printer, &config);
if (active_print != nullptr)
preset_edited.is_compatible &= is_compatible_with_print(this_preset_with_vendor_profile, *active_print, active_printer);
if (! preset_edited.is_compatible && selected &&
(unselect_if_incompatible == PresetSelectCompatibleType::Always || (unselect_if_incompatible == PresetSelectCompatibleType::OnlyIfWasCompatible && was_compatible)))
m_idx_selected = -1;
if (selected)
preset_selected.is_compatible = preset_edited.is_compatible;
}
return m_idx_selected;
}
// Save the preset under a new name. If the name is different from the old one,
// a new preset is stored into the list of presets.
// All presets are marked as not modified and the new preset is activated.
//void PresetCollection::save_current_preset(const std::string &new_name);
// Delete the current preset, activate the first visible preset.
//void PresetCollection::delete_current_preset();
// Update the wxChoice UI component from this list of presets.
// Hide the
void PresetCollection::update_plater_ui(GUI::PresetComboBox *ui)
{
if (ui == nullptr)
return;
// Otherwise fill in the list from scratch.
ui->Freeze();
ui->Clear();
size_t selected_preset_item = INT_MAX; // some value meaning that no one item is selected
const Preset &selected_preset = this->get_selected_preset();
// Show wide icons if the currently selected preset is not compatible with the current printer,
// and draw a red flag in front of the selected preset.
bool wide_icons = ! selected_preset.is_compatible && m_bitmap_incompatible != nullptr;
/* It's supposed that standard size of an icon is 16px*16px for 100% scaled display.
* So set sizes for solid_colored icons used for filament preset
* and scale them in respect to em_unit value
*/
const float scale_f = ui->em_unit() * 0.1f;
const int icon_height = 16 * scale_f + 0.5f;
const int icon_width = 16 * scale_f + 0.5f;
const int thin_space_icon_width = 4 * scale_f + 0.5f;
const int wide_space_icon_width = 6 * scale_f + 0.5f;
std::map<wxString, wxBitmap*> nonsys_presets;
wxString selected = "";
wxString tooltip = "";
if (!this->m_presets.front().is_visible)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap));
for (size_t i = this->m_presets.front().is_visible ? 0 : m_num_default_presets; i < this->m_presets.size(); ++ i) {
const Preset &preset = this->m_presets[i];
if (! preset.is_visible || (! preset.is_compatible && i != m_idx_selected))
continue;
std::string bitmap_key = "";
// !!! Temporary solution, till refactoring: create and use "sla_printer" icon instead of m_bitmap_main_frame
wxBitmap main_bmp = m_bitmap_main_frame ? *m_bitmap_main_frame : wxNullBitmap;
if (m_type == Preset::TYPE_PRINTER && preset.printer_technology()==ptSLA ) {
bitmap_key = "sla_printer";
main_bmp = create_scaled_bitmap("sla_printer");
}
// If the filament preset is not compatible and there is a "red flag" icon loaded, show it left
// to the filament color image.
if (wide_icons)
bitmap_key += preset.is_compatible ? ",cmpt" : ",ncmpt";
bitmap_key += (preset.is_system || preset.is_default) ? ",syst" : ",nsyst";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
if (wide_icons)
// Paint a red flag for incompatible presets.
bmps.emplace_back(preset.is_compatible ? m_bitmap_cache->mkclear(icon_width, icon_height) : *m_bitmap_incompatible);
// Paint the color bars.
bmps.emplace_back(m_bitmap_cache->mkclear(thin_space_icon_width, icon_height));
bmps.emplace_back(main_bmp);
// Paint a lock at the system presets.
bmps.emplace_back(m_bitmap_cache->mkclear(wide_space_icon_width, icon_height));
bmps.emplace_back((preset.is_system || preset.is_default) ? *m_bitmap_lock : m_bitmap_cache->mkclear(icon_width, icon_height));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
const std::string name = preset.alias.empty() ? preset.name : preset.alias;
if (preset.is_default || preset.is_system) {
ui->Append(wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str()),
(bmp == 0) ? main_bmp : *bmp);
if (i == m_idx_selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX) {
selected_preset_item = ui->GetCount() - 1;
tooltip = wxString::FromUTF8(preset.name.c_str());
}
}
else
{
nonsys_presets.emplace(wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str()), bmp/*preset.is_compatible*/);
if (i == m_idx_selected) {
selected = wxString::FromUTF8((/*preset.*/name + (preset.is_dirty ? g_suffix_modified : "")).c_str());
tooltip = wxString::FromUTF8(preset.name.c_str());
}
}
if (i + 1 == m_num_default_presets)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap));
}
if (!nonsys_presets.empty())
{
ui->set_label_marker(ui->Append(PresetCollection::separator(L("User presets")), wxNullBitmap));
for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) {
ui->Append(it->first, *it->second);
if (it->first == selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
}
if (m_type == Preset::TYPE_PRINTER || m_type == Preset::TYPE_SLA_MATERIAL) {
std::string bitmap_key = "";
// If the filament preset is not compatible and there is a "red flag" icon loaded, show it left
// to the filament color image.
if (wide_icons)
bitmap_key += "wide,";
bitmap_key += "edit_preset_list";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
if (wide_icons)
// Paint a red flag for incompatible presets.
bmps.emplace_back(m_bitmap_cache->mkclear(icon_width, icon_height));
// Paint the color bars.
bmps.emplace_back(m_bitmap_cache->mkclear(thin_space_icon_width, icon_height));
bmps.emplace_back(*m_bitmap_main_frame);
// Paint a lock at the system presets.
bmps.emplace_back(m_bitmap_cache->mkclear(wide_space_icon_width, icon_height));
// bmps.emplace_back(m_bitmap_add ? *m_bitmap_add : wxNullBitmap);
bmps.emplace_back(create_scaled_bitmap("edit_uni"));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
if (m_type == Preset::TYPE_SLA_MATERIAL)
ui->set_label_marker(ui->Append(PresetCollection::separator(L("Add/Remove materials")), *bmp), GUI::PresetComboBox::LABEL_ITEM_WIZARD_MATERIALS);
else
ui->set_label_marker(ui->Append(PresetCollection::separator(L("Add/Remove printers")), *bmp), GUI::PresetComboBox::LABEL_ITEM_WIZARD_PRINTERS);
}
/* But, if selected_preset_item is still equal to INT_MAX, it means that
* there is no presets added to the list.
* So, select last combobox item ("Add/Remove preset")
*/
if (selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
ui->SetSelection(selected_preset_item);
ui->SetToolTip(tooltip.IsEmpty() ? ui->GetString(selected_preset_item) : tooltip);
ui->check_selection();
ui->Thaw();
// Update control min size after rescale (changed Display DPI under MSW)
if (ui->GetMinWidth() != 20 * ui->em_unit())
ui->SetMinSize(wxSize(20 * ui->em_unit(), ui->GetSize().GetHeight()));
}
size_t PresetCollection::update_tab_ui(wxBitmapComboBox *ui, bool show_incompatible, const int em/* = 10*/)
{
if (ui == nullptr)
return 0;
ui->Freeze();
ui->Clear();
size_t selected_preset_item = INT_MAX; // some value meaning that no one item is selected
/* It's supposed that standard size of an icon is 16px*16px for 100% scaled display.
* So set sizes for solid_colored(empty) icons used for preset
* and scale them in respect to em_unit value
*/
const float scale_f = em * 0.1f;
const int icon_height = 16 * scale_f + 0.5f;
const int icon_width = 16 * scale_f + 0.5f;
std::map<wxString, wxBitmap*> nonsys_presets;
wxString selected = "";
if (!this->m_presets.front().is_visible)
ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap);
for (size_t i = this->m_presets.front().is_visible ? 0 : m_num_default_presets; i < this->m_presets.size(); ++i) {
const Preset &preset = this->m_presets[i];
if (! preset.is_visible || (! show_incompatible && ! preset.is_compatible && i != m_idx_selected))
continue;
std::string bitmap_key = "tab";
// !!! Temporary solution, till refactoring: create and use "sla_printer" icon instead of m_bitmap_main_frame
wxBitmap main_bmp = m_bitmap_main_frame ? *m_bitmap_main_frame : wxNullBitmap;
if (m_type == Preset::TYPE_PRINTER && preset.printer_technology() == ptSLA) {
bitmap_key = "sla_printer";
main_bmp = create_scaled_bitmap("sla_printer");
}
bitmap_key += preset.is_compatible ? ",cmpt" : ",ncmpt";
bitmap_key += (preset.is_system || preset.is_default) ? ",syst" : ",nsyst";
wxBitmap *bmp = m_bitmap_cache->find(bitmap_key);
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
const wxBitmap* tmp_bmp = preset.is_compatible ? m_bitmap_compatible : m_bitmap_incompatible;
bmps.emplace_back((tmp_bmp == 0) ? main_bmp : *tmp_bmp);
// Paint a lock at the system presets.
bmps.emplace_back((preset.is_system || preset.is_default) ? *m_bitmap_lock : m_bitmap_cache->mkclear(icon_width, icon_height));
bmp = m_bitmap_cache->insert(bitmap_key, bmps);
}
if (preset.is_default || preset.is_system) {
ui->Append(wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str()),
(bmp == 0) ? main_bmp : *bmp);
if (i == m_idx_selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
else
{
nonsys_presets.emplace(wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str()), bmp/*preset.is_compatible*/);
if (i == m_idx_selected)
selected = wxString::FromUTF8((preset.name + (preset.is_dirty ? g_suffix_modified : "")).c_str());
}
if (i + 1 == m_num_default_presets)
ui->Append(PresetCollection::separator(L("System presets")), wxNullBitmap);
}
if (!nonsys_presets.empty())
{
ui->Append(PresetCollection::separator(L("User presets")), wxNullBitmap);
for (std::map<wxString, wxBitmap*>::iterator it = nonsys_presets.begin(); it != nonsys_presets.end(); ++it) {
ui->Append(it->first, *it->second);
if (it->first == selected ||
// just in case: mark selected_preset_item as a first added element
selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
}
}
if (m_type == Preset::TYPE_PRINTER) {
wxBitmap *bmp = m_bitmap_cache->find("edit_printer_list");
if (bmp == nullptr) {
// Create the bitmap with color bars.
std::vector<wxBitmap> bmps;
bmps.emplace_back(*m_bitmap_main_frame);
// bmps.emplace_back(m_bitmap_add ? *m_bitmap_add : wxNullBitmap);
bmps.emplace_back(create_scaled_bitmap("edit_uni"));
bmp = m_bitmap_cache->insert("add_printer_tab", bmps);
}
ui->Append(PresetCollection::separator("Add a new printer"), *bmp);
}
/* But, if selected_preset_item is still equal to INT_MAX, it means that
* there is no presets added to the list.
* So, select last combobox item ("Add/Remove preset")
*/
if (selected_preset_item == INT_MAX)
selected_preset_item = ui->GetCount() - 1;
ui->SetSelection(selected_preset_item);
ui->SetToolTip(ui->GetString(selected_preset_item));
ui->Thaw();
return selected_preset_item;
}
// Update a dirty floag of the current preset, update the labels of the UI component accordingly.
// Return true if the dirty flag changed.
bool PresetCollection::update_dirty_ui(wxBitmapComboBox *ui)
{
wxWindowUpdateLocker noUpdates(ui);
// 1) Update the dirty flag of the current preset.
bool was_dirty = this->get_selected_preset().is_dirty;
bool is_dirty = current_is_dirty();
this->get_selected_preset().is_dirty = is_dirty;
this->get_edited_preset().is_dirty = is_dirty;
// 2) Update the labels.
for (unsigned int ui_id = 0; ui_id < ui->GetCount(); ++ ui_id) {
std::string old_label = ui->GetString(ui_id).utf8_str().data();
std::string preset_name = Preset::remove_suffix_modified(old_label);
const Preset *preset = this->find_preset(preset_name, false);
// The old_label could be the "----- system presets ------" or the "------- user presets --------" separator.
// assert(preset != nullptr);
if (preset != nullptr) {
std::string new_label = preset->is_dirty ? preset->name + g_suffix_modified : preset->name;
if (old_label != new_label)
ui->SetString(ui_id, wxString::FromUTF8(new_label.c_str()));
}
}
#ifdef __APPLE__
// wxWidgets on OSX do not upload the text of the combo box line automatically.
// Force it to update by re-selecting.
ui->SetSelection(ui->GetSelection());
#endif /* __APPLE __ */
return was_dirty != is_dirty;
}
template<class T>
void add_correct_opts_to_diff(const std::string &opt_key, t_config_option_keys& vec, const ConfigBase &other, const ConfigBase &this_c)
{
const T* opt_init = static_cast<const T*>(other.option(opt_key));
const T* opt_cur = static_cast<const T*>(this_c.option(opt_key));
int opt_init_max_id = opt_init->values.size() - 1;
for (int i = 0; i < opt_cur->values.size(); i++)
{
int init_id = i <= opt_init_max_id ? i : 0;
if (opt_cur->values[i] != opt_init->values[init_id])
vec.emplace_back(opt_key + "#" + std::to_string(i));
}
}
// Use deep_diff to correct return of changed options, considering individual options for each extruder.
inline t_config_option_keys deep_diff(const ConfigBase &config_this, const ConfigBase &config_other)
{
t_config_option_keys diff;
for (const t_config_option_key &opt_key : config_this.keys()) {
const ConfigOption *this_opt = config_this.option(opt_key);
const ConfigOption *other_opt = config_other.option(opt_key);
if (this_opt != nullptr && other_opt != nullptr && *this_opt != *other_opt)
{
if (opt_key == "bed_shape" || opt_key == "thumbnails" || opt_key == "compatible_prints" || opt_key == "compatible_printers") {
diff.emplace_back(opt_key);
continue;
}
switch (other_opt->type())
{
case coInts: add_correct_opts_to_diff<ConfigOptionInts >(opt_key, diff, config_other, config_this); break;
case coBools: add_correct_opts_to_diff<ConfigOptionBools >(opt_key, diff, config_other, config_this); break;
case coFloats: add_correct_opts_to_diff<ConfigOptionFloats >(opt_key, diff, config_other, config_this); break;
case coStrings: add_correct_opts_to_diff<ConfigOptionStrings >(opt_key, diff, config_other, config_this); break;
case coPercents:add_correct_opts_to_diff<ConfigOptionPercents >(opt_key, diff, config_other, config_this); break;
case coPoints: add_correct_opts_to_diff<ConfigOptionPoints >(opt_key, diff, config_other, config_this); break;
default: diff.emplace_back(opt_key); break;
}
}
}
return diff;
}
std::vector<std::string> PresetCollection::dirty_options(const Preset *edited, const Preset *reference, const bool deep_compare /*= false*/)
{
std::vector<std::string> changed;
if (edited != nullptr && reference != nullptr) {
changed = deep_compare ?
deep_diff(edited->config, reference->config) :
reference->config.diff(edited->config);
// The "compatible_printers" option key is handled differently from the others:
// It is not mandatory. If the key is missing, it means it is compatible with any printer.
// If the key exists and it is empty, it means it is compatible with no printer.
std::initializer_list<const char*> optional_keys { "compatible_prints", "compatible_printers" };
for (auto &opt_key : optional_keys) {
if (reference->config.has(opt_key) != edited->config.has(opt_key))
changed.emplace_back(opt_key);
}
}
return changed;
}
// Select a new preset. This resets all the edits done to the currently selected preset.
// If the preset with index idx does not exist, a first visible preset is selected.
Preset& PresetCollection::select_preset(size_t idx)
{
for (Preset &preset : m_presets)
preset.is_dirty = false;
if (idx >= m_presets.size())
idx = first_visible_idx();
m_idx_selected = idx;
m_edited_preset = m_presets[idx];
bool default_visible = ! m_default_suppressed || m_idx_selected < m_num_default_presets;
for (size_t i = 0; i < m_num_default_presets; ++i)
m_presets[i].is_visible = default_visible;
return m_presets[idx];
}
bool PresetCollection::select_preset_by_name(const std::string &name_w_suffix, bool force)
{
std::string name = Preset::remove_suffix_modified(name_w_suffix);
// 1) Try to find the preset by its name.
auto it = this->find_preset_internal(name);
size_t idx = 0;
if (it != m_presets.end() && it->name == name && it->is_visible)
// Preset found by its name and it is visible.
idx = it - m_presets.begin();
else {
// Find the first visible preset.
for (size_t i = m_default_suppressed ? m_num_default_presets : 0; i < m_presets.size(); ++ i)
if (m_presets[i].is_visible) {
idx = i;
break;
}
// If the first visible preset was not found, return the 0th element, which is the default preset.
}
// 2) Select the new preset.
if (m_idx_selected != idx || force) {
this->select_preset(idx);
return true;
}
return false;
}
bool PresetCollection::select_preset_by_name_strict(const std::string &name)
{
// 1) Try to find the preset by its name.
auto it = this->find_preset_internal(name);
size_t idx = (size_t)-1;
if (it != m_presets.end() && it->name == name && it->is_visible)
// Preset found by its name.
idx = it - m_presets.begin();
// 2) Select the new preset.
if (idx != (size_t)-1) {
this->select_preset(idx);
return true;
}
m_idx_selected = idx;
return false;
}
// Merge one vendor's presets with the other vendor's presets, report duplicates.
std::vector<std::string> PresetCollection::merge_presets(PresetCollection &&other, const VendorMap &new_vendors)
{
std::vector<std::string> duplicates;
for (Preset &preset : other.m_presets) {
if (preset.is_default || preset.is_external)
continue;
Preset key(m_type, preset.name);
auto it = std::lower_bound(m_presets.begin() + m_num_default_presets, m_presets.end(), key);
if (it == m_presets.end() || it->name != preset.name) {
if (preset.vendor != nullptr) {
// Re-assign a pointer to the vendor structure in the new PresetBundle.
auto it = new_vendors.find(preset.vendor->id);
assert(it != new_vendors.end());
preset.vendor = &it->second;
}
this->m_presets.emplace(it, std::move(preset));
} else
duplicates.emplace_back(std::move(preset.name));
}
return duplicates;
}
void PresetCollection::update_map_alias_to_profile_name()
{
m_map_alias_to_profile_name.clear();
for (const Preset &preset : m_presets)
m_map_alias_to_profile_name.emplace_back(preset.alias, preset.name);
std::sort(m_map_alias_to_profile_name.begin(), m_map_alias_to_profile_name.end(), [](auto &l, auto &r) { return l.first < r.first; });
}
void PresetCollection::update_map_system_profile_renamed()
{
m_map_system_profile_renamed.clear();
for (Preset &preset : m_presets)
for (const std::string &renamed_from : preset.renamed_from) {
const auto [it, success] = m_map_system_profile_renamed.insert(std::pair<std::string, std::string>(renamed_from, preset.name));
if (! success)
BOOST_LOG_TRIVIAL(error) << boost::format("Preset name \"%1%\" was marked as renamed from \"%2%\", though preset name \"%3%\" was marked as renamed from \"%2%\" as well.") % preset.name % renamed_from % it->second;
}
}
std::string PresetCollection::name() const
{
switch (this->type()) {
case Preset::TYPE_PRINT: return L("print");
case Preset::TYPE_FILAMENT: return L("filament");
case Preset::TYPE_SLA_PRINT: return L("SLA print");
case Preset::TYPE_SLA_MATERIAL: return L("SLA material");
case Preset::TYPE_PRINTER: return L("printer");
default: return "invalid";
}
}
std::string PresetCollection::section_name() const
{
switch (this->type()) {
case Preset::TYPE_PRINT: return "print";
case Preset::TYPE_FILAMENT: return "filament";
case Preset::TYPE_SLA_PRINT: return "sla_print";
case Preset::TYPE_SLA_MATERIAL: return "sla_material";
case Preset::TYPE_PRINTER: return "printer";
default: return "invalid";
}
}
std::vector<std::string> PresetCollection::system_preset_names() const
{
size_t num = 0;
for (const Preset &preset : m_presets)
if (preset.is_system)
++ num;
std::vector<std::string> out;
out.reserve(num);
for (const Preset &preset : m_presets)
if (preset.is_system)
out.emplace_back(preset.name);
std::sort(out.begin(), out.end());
return out;
}
// Generate a file path from a profile name. Add the ".ini" suffix if it is missing.
std::string PresetCollection::path_from_name(const std::string &new_name) const
{
std::string file_name = boost::iends_with(new_name, ".ini") ? new_name : (new_name + ".ini");
return (boost::filesystem::path(m_dir_path) / file_name).make_preferred().string();
}
void PresetCollection::clear_bitmap_cache()
{
m_bitmap_cache->clear();
}
wxString PresetCollection::separator(const std::string &label)
{
return wxString::FromUTF8(PresetCollection::separator_head()) + _(label) + wxString::FromUTF8(PresetCollection::separator_tail());
}
const Preset& PrinterPresetCollection::default_preset_for(const DynamicPrintConfig &config) const
{
const ConfigOptionEnumGeneric *opt_printer_technology = config.opt<ConfigOptionEnumGeneric>("printer_technology");
return this->default_preset((opt_printer_technology == nullptr || opt_printer_technology->value == ptFFF) ? 0 : 1);
}
const Preset* PrinterPresetCollection::find_by_model_id(const std::string &model_id) const
{
if (model_id.empty()) { return nullptr; }
const auto it = std::find_if(cbegin(), cend(), [&](const Preset &preset) {
return preset.config.opt_string("printer_model") == model_id;
});
return it != cend() ? &*it : nullptr;
}
namespace PresetUtils {
const VendorProfile::PrinterModel* system_printer_model(const Preset &preset)
{
const VendorProfile::PrinterModel *out = nullptr;
if (preset.vendor != nullptr) {
auto *printer_model = preset.config.opt<ConfigOptionString>("printer_model");
if (printer_model != nullptr && ! printer_model->value.empty()) {
auto it = std::find_if(preset.vendor->models.begin(), preset.vendor->models.end(), [printer_model](const VendorProfile::PrinterModel &pm) { return pm.id == printer_model->value; });
if (it != preset.vendor->models.end())
out = &(*it);
}
}
return out;
}
} // namespace PresetUtils
} // namespace Slic3r
|
//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is emits an assembly printer for the current target.
// Note that this is currently fairly skeletal, but will grow over time.
//
//===----------------------------------------------------------------------===//
#include "AsmWriterEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <algorithm>
#include <ostream>
using namespace llvm;
static bool isIdentChar(char C) {
return (C >= 'a' && C <= 'z') ||
(C >= 'A' && C <= 'Z') ||
(C >= '0' && C <= '9') ||
C == '_';
}
namespace {
struct AsmWriterOperand {
enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
/// Str - For isLiteralTextOperand, this IS the literal text. For
/// isMachineInstrOperand, this is the PrinterMethodName for the operand.
std::string Str;
/// MiOpNo - For isMachineInstrOperand, this is the operand number of the
/// machine instruction.
unsigned MIOpNo;
AsmWriterOperand(const std::string &LitStr)
: OperandType(isLiteralTextOperand), Str(LitStr) {}
AsmWriterOperand(const std::string &Printer, unsigned OpNo)
: OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
bool operator!=(const AsmWriterOperand &Other) const {
if (OperandType != Other.OperandType || Str != Other.Str) return true;
if (OperandType == isMachineInstrOperand)
return MIOpNo != Other.MIOpNo;
return false;
}
bool operator==(const AsmWriterOperand &Other) const {
return !operator!=(Other);
}
void EmitCode(std::ostream &OS) const;
};
struct AsmWriterInst {
std::vector<AsmWriterOperand> Operands;
const CodeGenInstruction *CGI;
AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
/// MatchesAllButOneOp - If this instruction is exactly identical to the
/// specified instruction except for one differing operand, return the
/// differing operand number. Otherwise return ~0.
unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
private:
void AddLiteralString(const std::string &Str) {
// If the last operand was already a literal text string, append this to
// it, otherwise add a new operand.
if (!Operands.empty() &&
Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
Operands.back().Str.append(Str);
else
Operands.push_back(AsmWriterOperand(Str));
}
};
}
void AsmWriterOperand::EmitCode(std::ostream &OS) const {
if (OperandType == isLiteralTextOperand)
OS << "O << \"" << Str << "\"; ";
else
OS << Str << "(MI, " << MIOpNo << "); ";
}
/// ParseAsmString - Parse the specified Instruction's AsmString into this
/// AsmWriterInst.
///
AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
this->CGI = &CGI;
bool inVariant = false; // True if we are inside a {.|.|.} region.
const std::string &AsmString = CGI.AsmString;
std::string::size_type LastEmitted = 0;
while (LastEmitted != AsmString.size()) {
std::string::size_type DollarPos =
AsmString.find_first_of("${|}", LastEmitted);
if (DollarPos == std::string::npos) DollarPos = AsmString.size();
// Emit a constant string fragment.
if (DollarPos != LastEmitted) {
// TODO: this should eventually handle escaping.
AddLiteralString(std::string(AsmString.begin()+LastEmitted,
AsmString.begin()+DollarPos));
LastEmitted = DollarPos;
} else if (AsmString[DollarPos] == '{') {
if (inVariant)
throw "Nested variants found for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = DollarPos+1;
inVariant = true; // We are now inside of the variant!
for (unsigned i = 0; i != Variant; ++i) {
// Skip over all of the text for an irrelevant variant here. The
// next variant starts at |, or there may not be text for this
// variant if we see a }.
std::string::size_type NP =
AsmString.find_first_of("|}", LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = NP+1;
if (AsmString[NP] == '}') {
inVariant = false; // No text for this variant.
break;
}
}
} else if (AsmString[DollarPos] == '|') {
if (!inVariant)
throw "'|' character found outside of a variant in instruction '"
+ CGI.TheDef->getName() + "'!";
// Move to the end of variant list.
std::string::size_type NP = AsmString.find('}', LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = NP+1;
inVariant = false;
} else if (AsmString[DollarPos] == '}') {
if (!inVariant)
throw "'}' character found outside of a variant in instruction '"
+ CGI.TheDef->getName() + "'!";
LastEmitted = DollarPos+1;
inVariant = false;
} else if (DollarPos+1 != AsmString.size() &&
AsmString[DollarPos+1] == '$') {
AddLiteralString("$"); // "$$" -> $
LastEmitted = DollarPos+2;
} else {
// Get the name of the variable.
std::string::size_type VarEnd = DollarPos+1;
// handle ${foo}bar as $foo by detecting whether the character following
// the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
// so the variable name does not contain the leading curly brace.
bool hasCurlyBraces = false;
if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
hasCurlyBraces = true;
++DollarPos;
++VarEnd;
}
while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
++VarEnd;
std::string VarName(AsmString.begin()+DollarPos+1,
AsmString.begin()+VarEnd);
// In order to avoid starting the next string at the terminating curly
// brace, advance the end position past it if we found an opening curly
// brace.
if (hasCurlyBraces) {
if (VarEnd >= AsmString.size())
throw "Reached end of string before terminating curly brace in '"
+ CGI.TheDef->getName() + "'";
if (AsmString[VarEnd] != '}')
throw "Variant name beginning with '{' did not end with '}' in '"
+ CGI.TheDef->getName() + "'";
++VarEnd;
}
if (VarName.empty())
throw "Stray '$' in '" + CGI.TheDef->getName() +
"' asm string, maybe you want $$?";
unsigned OpNo = CGI.getOperandNamed(VarName);
CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
// If this is a two-address instruction and we are not accessing the
// 0th operand, remove an operand.
unsigned MIOp = OpInfo.MIOperandNo;
if (CGI.isTwoAddress && MIOp != 0) {
if (MIOp == 1)
throw "Should refer to operand #0 instead of #1 for two-address"
" instruction '" + CGI.TheDef->getName() + "'!";
--MIOp;
}
Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
LastEmitted = VarEnd;
}
}
AddLiteralString("\\n");
}
/// MatchesAllButOneOp - If this instruction is exactly identical to the
/// specified instruction except for one differing operand, return the differing
/// operand number. If more than one operand mismatches, return ~1, otherwise
/// if the instructions are identical return ~0.
unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
if (Operands.size() != Other.Operands.size()) return ~1;
unsigned MismatchOperand = ~0U;
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
if (Operands[i] != Other.Operands[i])
if (MismatchOperand != ~0U) // Already have one mismatch?
return ~1U;
else
MismatchOperand = i;
}
return MismatchOperand;
}
static void PrintCases(std::vector<std::pair<std::string,
AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
O << " case " << OpsToPrint.back().first << ": ";
AsmWriterOperand TheOp = OpsToPrint.back().second;
OpsToPrint.pop_back();
// Check to see if any other operands are identical in this list, and if so,
// emit a case label for them.
for (unsigned i = OpsToPrint.size(); i != 0; --i)
if (OpsToPrint[i-1].second == TheOp) {
O << "\n case " << OpsToPrint[i-1].first << ": ";
OpsToPrint.erase(OpsToPrint.begin()+i-1);
}
// Finally, emit the code.
TheOp.EmitCode(O);
O << "break;\n";
}
/// EmitInstructions - Emit the last instruction in the vector and any other
/// instructions that are suitably similar to it.
static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
std::ostream &O) {
AsmWriterInst FirstInst = Insts.back();
Insts.pop_back();
std::vector<AsmWriterInst> SimilarInsts;
unsigned DifferingOperand = ~0;
for (unsigned i = Insts.size(); i != 0; --i) {
unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
if (DiffOp != ~1U) {
if (DifferingOperand == ~0U) // First match!
DifferingOperand = DiffOp;
// If this differs in the same operand as the rest of the instructions in
// this class, move it to the SimilarInsts list.
if (DifferingOperand == DiffOp || DiffOp == ~0U) {
SimilarInsts.push_back(Insts[i-1]);
Insts.erase(Insts.begin()+i-1);
}
}
}
std::string Namespace = FirstInst.CGI->Namespace;
O << " case " << Namespace << "::"
<< FirstInst.CGI->TheDef->getName() << ":\n";
for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
O << " case " << Namespace << "::"
<< SimilarInsts[i].CGI->TheDef->getName() << ":\n";
for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
if (i != DifferingOperand) {
// If the operand is the same for all instructions, just print it.
O << " ";
FirstInst.Operands[i].EmitCode(O);
} else {
// If this is the operand that varies between all of the instructions,
// emit a switch for just this operand now.
O << " switch (MI->getOpcode()) {\n";
std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
FirstInst.CGI->TheDef->getName(),
FirstInst.Operands[i]));
for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
AsmWriterInst &AWI = SimilarInsts[si];
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
AWI.CGI->TheDef->getName(),
AWI.Operands[i]));
}
std::reverse(OpsToPrint.begin(), OpsToPrint.end());
while (!OpsToPrint.empty())
PrintCases(OpsToPrint, O);
O << " }";
}
O << "\n";
}
O << " break;\n";
}
void AsmWriterEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Assembly Writer Source Fragment", O);
CodeGenTarget Target;
Record *AsmWriter = Target.getAsmWriter();
std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
unsigned Variant = AsmWriter->getValueAsInt("Variant");
O <<
"/// printInstruction - This method is automatically generated by tablegen\n"
"/// from the instruction set description. This method returns true if the\n"
"/// machine instruction was sufficiently described to print it, otherwise\n"
"/// it returns false.\n"
"bool " << Target.getName() << ClassName
<< "::printInstruction(const MachineInstr *MI) {\n";
std::string Namespace = Target.inst_begin()->second.Namespace;
std::vector<AsmWriterInst> Instructions;
for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
E = Target.inst_end(); I != E; ++I)
if (!I->second.AsmString.empty())
Instructions.push_back(AsmWriterInst(I->second, Variant));
// If all of the instructions start with a constant string (a very very common
// occurance), emit all of the constant strings as a big table lookup instead
// of requiring a switch for them.
bool AllStartWithString = true;
for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
if (Instructions[i].Operands.empty() ||
Instructions[i].Operands[0].OperandType !=
AsmWriterOperand::isLiteralTextOperand) {
AllStartWithString = false;
break;
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
if (AllStartWithString) {
// Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
// all machine instructions are necessarily being printed, so there may be
// target instructions not in this map.
std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
// Emit a table of constant strings.
O << " static const char * const OpStrs[] = {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
if (AWI == 0) {
// Something not handled by the asmwriter printer.
O << " 0,\t// ";
} else {
O << " \"" << AWI->Operands[0].Str << "\",\t// ";
// Nuke the string from the operand list. It is now handled!
AWI->Operands.erase(AWI->Operands.begin());
}
O << NumberedInstructions[i]->TheDef->getName() << "\n";
}
O << " };\n\n"
<< " // Emit the opcode for the instruction.\n"
<< " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
<< " O << AsmStr;\n\n";
}
// Because this is a vector we want to emit from the end. Reverse all of the
// elements in the vector.
std::reverse(Instructions.begin(), Instructions.end());
// Find the opcode # of inline asm
O << " switch (MI->getOpcode()) {\n"
" default: return false;\n"
" case " << NumberedInstructions.back()->Namespace
<< "::INLINEASM: printInlineAsm(MI); break;\n";
while (!Instructions.empty())
EmitInstructions(Instructions, O);
O << " }\n"
" return true;\n"
"}\n";
}
add a note, ya knoe
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@25880 91177308-0d34-0410-b5e6-96231b3b80d8
//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is emits an assembly printer for the current target.
// Note that this is currently fairly skeletal, but will grow over time.
//
//===----------------------------------------------------------------------===//
#include "AsmWriterEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <algorithm>
#include <ostream>
using namespace llvm;
static bool isIdentChar(char C) {
return (C >= 'a' && C <= 'z') ||
(C >= 'A' && C <= 'Z') ||
(C >= '0' && C <= '9') ||
C == '_';
}
namespace {
struct AsmWriterOperand {
enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
/// Str - For isLiteralTextOperand, this IS the literal text. For
/// isMachineInstrOperand, this is the PrinterMethodName for the operand.
std::string Str;
/// MiOpNo - For isMachineInstrOperand, this is the operand number of the
/// machine instruction.
unsigned MIOpNo;
AsmWriterOperand(const std::string &LitStr)
: OperandType(isLiteralTextOperand), Str(LitStr) {}
AsmWriterOperand(const std::string &Printer, unsigned OpNo)
: OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
bool operator!=(const AsmWriterOperand &Other) const {
if (OperandType != Other.OperandType || Str != Other.Str) return true;
if (OperandType == isMachineInstrOperand)
return MIOpNo != Other.MIOpNo;
return false;
}
bool operator==(const AsmWriterOperand &Other) const {
return !operator!=(Other);
}
void EmitCode(std::ostream &OS) const;
};
struct AsmWriterInst {
std::vector<AsmWriterOperand> Operands;
const CodeGenInstruction *CGI;
AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
/// MatchesAllButOneOp - If this instruction is exactly identical to the
/// specified instruction except for one differing operand, return the
/// differing operand number. Otherwise return ~0.
unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
private:
void AddLiteralString(const std::string &Str) {
// If the last operand was already a literal text string, append this to
// it, otherwise add a new operand.
if (!Operands.empty() &&
Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
Operands.back().Str.append(Str);
else
Operands.push_back(AsmWriterOperand(Str));
}
};
}
void AsmWriterOperand::EmitCode(std::ostream &OS) const {
if (OperandType == isLiteralTextOperand)
OS << "O << \"" << Str << "\"; ";
else
OS << Str << "(MI, " << MIOpNo << "); ";
}
/// ParseAsmString - Parse the specified Instruction's AsmString into this
/// AsmWriterInst.
///
AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
this->CGI = &CGI;
bool inVariant = false; // True if we are inside a {.|.|.} region.
// NOTE: Any extensions to this code need to be mirrored in the
// AsmPrinter::printInlineAsm code that executes as compile time (assuming
// that inline asm strings should also get the new feature)!
const std::string &AsmString = CGI.AsmString;
std::string::size_type LastEmitted = 0;
while (LastEmitted != AsmString.size()) {
std::string::size_type DollarPos =
AsmString.find_first_of("${|}", LastEmitted);
if (DollarPos == std::string::npos) DollarPos = AsmString.size();
// Emit a constant string fragment.
if (DollarPos != LastEmitted) {
// TODO: this should eventually handle escaping.
AddLiteralString(std::string(AsmString.begin()+LastEmitted,
AsmString.begin()+DollarPos));
LastEmitted = DollarPos;
} else if (AsmString[DollarPos] == '{') {
if (inVariant)
throw "Nested variants found for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = DollarPos+1;
inVariant = true; // We are now inside of the variant!
for (unsigned i = 0; i != Variant; ++i) {
// Skip over all of the text for an irrelevant variant here. The
// next variant starts at |, or there may not be text for this
// variant if we see a }.
std::string::size_type NP =
AsmString.find_first_of("|}", LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = NP+1;
if (AsmString[NP] == '}') {
inVariant = false; // No text for this variant.
break;
}
}
} else if (AsmString[DollarPos] == '|') {
if (!inVariant)
throw "'|' character found outside of a variant in instruction '"
+ CGI.TheDef->getName() + "'!";
// Move to the end of variant list.
std::string::size_type NP = AsmString.find('}', LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" +
CGI.TheDef->getName() + "'!";
LastEmitted = NP+1;
inVariant = false;
} else if (AsmString[DollarPos] == '}') {
if (!inVariant)
throw "'}' character found outside of a variant in instruction '"
+ CGI.TheDef->getName() + "'!";
LastEmitted = DollarPos+1;
inVariant = false;
} else if (DollarPos+1 != AsmString.size() &&
AsmString[DollarPos+1] == '$') {
AddLiteralString("$"); // "$$" -> $
LastEmitted = DollarPos+2;
} else {
// Get the name of the variable.
std::string::size_type VarEnd = DollarPos+1;
// handle ${foo}bar as $foo by detecting whether the character following
// the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
// so the variable name does not contain the leading curly brace.
bool hasCurlyBraces = false;
if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
hasCurlyBraces = true;
++DollarPos;
++VarEnd;
}
while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
++VarEnd;
std::string VarName(AsmString.begin()+DollarPos+1,
AsmString.begin()+VarEnd);
// In order to avoid starting the next string at the terminating curly
// brace, advance the end position past it if we found an opening curly
// brace.
if (hasCurlyBraces) {
if (VarEnd >= AsmString.size())
throw "Reached end of string before terminating curly brace in '"
+ CGI.TheDef->getName() + "'";
if (AsmString[VarEnd] != '}')
throw "Variant name beginning with '{' did not end with '}' in '"
+ CGI.TheDef->getName() + "'";
++VarEnd;
}
if (VarName.empty())
throw "Stray '$' in '" + CGI.TheDef->getName() +
"' asm string, maybe you want $$?";
unsigned OpNo = CGI.getOperandNamed(VarName);
CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
// If this is a two-address instruction and we are not accessing the
// 0th operand, remove an operand.
unsigned MIOp = OpInfo.MIOperandNo;
if (CGI.isTwoAddress && MIOp != 0) {
if (MIOp == 1)
throw "Should refer to operand #0 instead of #1 for two-address"
" instruction '" + CGI.TheDef->getName() + "'!";
--MIOp;
}
Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
LastEmitted = VarEnd;
}
}
AddLiteralString("\\n");
}
/// MatchesAllButOneOp - If this instruction is exactly identical to the
/// specified instruction except for one differing operand, return the differing
/// operand number. If more than one operand mismatches, return ~1, otherwise
/// if the instructions are identical return ~0.
unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
if (Operands.size() != Other.Operands.size()) return ~1;
unsigned MismatchOperand = ~0U;
for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
if (Operands[i] != Other.Operands[i])
if (MismatchOperand != ~0U) // Already have one mismatch?
return ~1U;
else
MismatchOperand = i;
}
return MismatchOperand;
}
static void PrintCases(std::vector<std::pair<std::string,
AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
O << " case " << OpsToPrint.back().first << ": ";
AsmWriterOperand TheOp = OpsToPrint.back().second;
OpsToPrint.pop_back();
// Check to see if any other operands are identical in this list, and if so,
// emit a case label for them.
for (unsigned i = OpsToPrint.size(); i != 0; --i)
if (OpsToPrint[i-1].second == TheOp) {
O << "\n case " << OpsToPrint[i-1].first << ": ";
OpsToPrint.erase(OpsToPrint.begin()+i-1);
}
// Finally, emit the code.
TheOp.EmitCode(O);
O << "break;\n";
}
/// EmitInstructions - Emit the last instruction in the vector and any other
/// instructions that are suitably similar to it.
static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
std::ostream &O) {
AsmWriterInst FirstInst = Insts.back();
Insts.pop_back();
std::vector<AsmWriterInst> SimilarInsts;
unsigned DifferingOperand = ~0;
for (unsigned i = Insts.size(); i != 0; --i) {
unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
if (DiffOp != ~1U) {
if (DifferingOperand == ~0U) // First match!
DifferingOperand = DiffOp;
// If this differs in the same operand as the rest of the instructions in
// this class, move it to the SimilarInsts list.
if (DifferingOperand == DiffOp || DiffOp == ~0U) {
SimilarInsts.push_back(Insts[i-1]);
Insts.erase(Insts.begin()+i-1);
}
}
}
std::string Namespace = FirstInst.CGI->Namespace;
O << " case " << Namespace << "::"
<< FirstInst.CGI->TheDef->getName() << ":\n";
for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
O << " case " << Namespace << "::"
<< SimilarInsts[i].CGI->TheDef->getName() << ":\n";
for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
if (i != DifferingOperand) {
// If the operand is the same for all instructions, just print it.
O << " ";
FirstInst.Operands[i].EmitCode(O);
} else {
// If this is the operand that varies between all of the instructions,
// emit a switch for just this operand now.
O << " switch (MI->getOpcode()) {\n";
std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
FirstInst.CGI->TheDef->getName(),
FirstInst.Operands[i]));
for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
AsmWriterInst &AWI = SimilarInsts[si];
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
AWI.CGI->TheDef->getName(),
AWI.Operands[i]));
}
std::reverse(OpsToPrint.begin(), OpsToPrint.end());
while (!OpsToPrint.empty())
PrintCases(OpsToPrint, O);
O << " }";
}
O << "\n";
}
O << " break;\n";
}
void AsmWriterEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Assembly Writer Source Fragment", O);
CodeGenTarget Target;
Record *AsmWriter = Target.getAsmWriter();
std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
unsigned Variant = AsmWriter->getValueAsInt("Variant");
O <<
"/// printInstruction - This method is automatically generated by tablegen\n"
"/// from the instruction set description. This method returns true if the\n"
"/// machine instruction was sufficiently described to print it, otherwise\n"
"/// it returns false.\n"
"bool " << Target.getName() << ClassName
<< "::printInstruction(const MachineInstr *MI) {\n";
std::string Namespace = Target.inst_begin()->second.Namespace;
std::vector<AsmWriterInst> Instructions;
for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
E = Target.inst_end(); I != E; ++I)
if (!I->second.AsmString.empty())
Instructions.push_back(AsmWriterInst(I->second, Variant));
// If all of the instructions start with a constant string (a very very common
// occurance), emit all of the constant strings as a big table lookup instead
// of requiring a switch for them.
bool AllStartWithString = true;
for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
if (Instructions[i].Operands.empty() ||
Instructions[i].Operands[0].OperandType !=
AsmWriterOperand::isLiteralTextOperand) {
AllStartWithString = false;
break;
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
if (AllStartWithString) {
// Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
// all machine instructions are necessarily being printed, so there may be
// target instructions not in this map.
std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
// Emit a table of constant strings.
O << " static const char * const OpStrs[] = {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
if (AWI == 0) {
// Something not handled by the asmwriter printer.
O << " 0,\t// ";
} else {
O << " \"" << AWI->Operands[0].Str << "\",\t// ";
// Nuke the string from the operand list. It is now handled!
AWI->Operands.erase(AWI->Operands.begin());
}
O << NumberedInstructions[i]->TheDef->getName() << "\n";
}
O << " };\n\n"
<< " // Emit the opcode for the instruction.\n"
<< " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
<< " O << AsmStr;\n\n";
}
// Because this is a vector we want to emit from the end. Reverse all of the
// elements in the vector.
std::reverse(Instructions.begin(), Instructions.end());
// Find the opcode # of inline asm
O << " switch (MI->getOpcode()) {\n"
" default: return false;\n"
" case " << NumberedInstructions.back()->Namespace
<< "::INLINEASM: printInlineAsm(MI); break;\n";
while (!Instructions.empty())
EmitInstructions(Instructions, O);
O << " }\n"
" return true;\n"
"}\n";
}
|
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sfx2.hxx"
#ifdef WNT
// necessary to include system headers without warnings
#ifdef _MSC_VER
#pragma warning(disable:4668 4917)
#endif
// Support Windows 95 too
#undef WINVER
#define WINVER 0x0400
#define USE_APP_SHORTCUTS
//
// the systray icon is only available on windows
//
#include <unotools/moduleoptions.hxx>
#include <unotools/dynamicmenuoptions.hxx>
#include "shutdownicon.hxx"
#include "app.hrc"
#include <shlobj.h>
#include <objidl.h>
#include <stdio.h>
#include <io.h>
#include <osl/thread.h>
#include <setup_native/qswin32.h>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/task/XJob.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <set>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::osl;
#define EXECUTER_WINDOWCLASS "SO Executer Class"
#define EXECUTER_WINDOWNAME "SO Executer Window"
#define ID_QUICKSTART 1
#define IDM_EXIT 2
#if defined(USE_APP_SHORTCUTS)
# define IDM_OPEN 3
# define IDM_WRITER 4
# define IDM_CALC 5
# define IDM_IMPRESS 6
# define IDM_DRAW 7
# define IDM_BASE 8
# define IDM_TEMPLATE 9
# define IDM_MATH 12
#endif
#define IDM_INSTALL 10
#define IDM_UNINSTALL 11
#define ICON_SO_DEFAULT 1
#define ICON_TEXT_DOCUMENT 2
#define ICON_TEXT_TEMPLATE 3
#define ICON_SPREADSHEET_DOCUMENT 4
#define ICON_SPREADSHEET_TEMPLATE 5
#define ICON_DRAWING_DOCUMENT 6
#define ICON_DRAWING_TEMPLATE 7
#define ICON_PRESENTATION_DOCUMENT 8
#define ICON_PRESENTATION_TEMPLATE 9
#define ICON_PRESENTATION_COMPRESSED 10
#define ICON_GLOBAL_DOCUMENT 11
#define ICON_HTML_DOCUMENT 12
#define ICON_CHART_DOCUMENT 13
#define ICON_DATABASE_DOCUMENT 14
#define ICON_MATH_DOCUMENT 15
#define ICON_TEMPLATE 16
#define ICON_MACROLIBRARY 17
#define ICON_CONFIGURATION 18
#define ICON_OPEN 19
#define ICON_SETUP 500
#define SFX_TASKBAR_NOTIFICATION WM_USER+1
static HWND aListenerWindow = NULL;
static HWND aExecuterWindow = NULL;
static HMENU popupMenu = NULL;
static void OnMeasureItem(HWND hwnd, LPMEASUREITEMSTRUCT lpmis);
static void OnDrawItem(HWND hwnd, LPDRAWITEMSTRUCT lpdis);
typedef struct tagMYITEM
{
OUString text;
UINT iconId;
} MYITEM;
// -------------------------------
static bool isNT()
{
static bool bInitialized = false;
static bool bWnt = false;
if( !bInitialized )
{
bInitialized = true;
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) )
{
if ( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
bWnt = true;
}
}
return bWnt;
}
// -------------------------------
static void addMenuItem( HMENU hMenu, UINT id, UINT iconId, const OUString& text, int& pos, int bOwnerdraw )
{
MENUITEMINFOW mi;
memset( &mi, 0, sizeof( MENUITEMINFOW ) );
mi.cbSize = sizeof( MENUITEMINFOW );
if( id == -1 )
{
mi.fMask=MIIM_TYPE;
mi.fType=MFT_SEPARATOR;
}
else
{
if( bOwnerdraw )
{
mi.fMask=MIIM_TYPE | MIIM_STATE | MIIM_ID | MIIM_DATA;
mi.fType=MFT_OWNERDRAW;
mi.fState=MFS_ENABLED;
mi.wID = id;
MYITEM *pMyItem = new MYITEM;
pMyItem->text = text;
pMyItem->iconId = iconId;
mi.dwItemData = (DWORD) pMyItem;
}
else
{
mi.fMask=MIIM_TYPE | MIIM_STATE | MIIM_ID | MIIM_DATA;
mi.fType=MFT_STRING;
mi.fState=MFS_ENABLED;
mi.wID = id;
mi.dwTypeData = (LPWSTR) text.getStr();
mi.cch = text.getLength();
}
#if defined(USE_APP_SHORTCUTS)
if ( IDM_TEMPLATE == id )
mi.fState |= MFS_DEFAULT;
#endif
}
InsertMenuItemW( hMenu, pos++, TRUE, &mi );
}
// -------------------------------
static HMENU createSystrayMenu( )
{
SvtModuleOptions aModuleOptions;
HMENU hMenu = CreatePopupMenu();
int pos=0;
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
OSL_ENSURE( pShutdownIcon, "ShutdownIcon instance empty!");
if( !pShutdownIcon )
return NULL;
#if defined(USE_APP_SHORTCUTS)
// collect the URLs of the entries in the File/New menu
::std::set< ::rtl::OUString > aFileNewAppsAvailable;
SvtDynamicMenuOptions aOpt;
Sequence < Sequence < PropertyValue > > aNewMenu = aOpt.GetMenu( E_NEWMENU );
const ::rtl::OUString sURLKey( RTL_CONSTASCII_USTRINGPARAM( "URL" ) );
const Sequence< PropertyValue >* pNewMenu = aNewMenu.getConstArray();
const Sequence< PropertyValue >* pNewMenuEnd = aNewMenu.getConstArray() + aNewMenu.getLength();
for ( ; pNewMenu != pNewMenuEnd; ++pNewMenu )
{
::comphelper::SequenceAsHashMap aEntryItems( *pNewMenu );
::rtl::OUString sURL( aEntryItems.getUnpackedValueOrDefault( sURLKey, ::rtl::OUString() ) );
if ( sURL.getLength() )
aFileNewAppsAvailable.insert( sURL );
}
// describe the menu entries for launching the applications
struct MenuEntryDescriptor
{
SvtModuleOptions::EModule eModuleIdentifier;
UINT nMenuItemID;
UINT nMenuIconID;
const char* pAsciiURLDescription;
} aMenuItems[] =
{
{ SvtModuleOptions::E_SWRITER, IDM_WRITER, ICON_TEXT_DOCUMENT, WRITER_URL },
{ SvtModuleOptions::E_SCALC, IDM_CALC, ICON_SPREADSHEET_DOCUMENT, CALC_URL },
{ SvtModuleOptions::E_SIMPRESS, IDM_IMPRESS,ICON_PRESENTATION_DOCUMENT, IMPRESS_WIZARD_URL },
{ SvtModuleOptions::E_SDRAW, IDM_DRAW, ICON_DRAWING_DOCUMENT, DRAW_URL },
{ SvtModuleOptions::E_SDATABASE, IDM_BASE, ICON_DATABASE_DOCUMENT, BASE_URL },
{ SvtModuleOptions::E_SMATH, IDM_MATH, ICON_MATH_DOCUMENT, MATH_URL },
};
// insert the menu entries for launching the applications
for ( size_t i = 0; i < sizeof( aMenuItems ) / sizeof( aMenuItems[0] ); ++i )
{
if ( !aModuleOptions.IsModuleInstalled( aMenuItems[i].eModuleIdentifier ) )
// the complete application is not even installed
continue;
::rtl::OUString sURL( ::rtl::OUString::createFromAscii( aMenuItems[i].pAsciiURLDescription ) );
if ( aFileNewAppsAvailable.find( sURL ) == aFileNewAppsAvailable.end() )
// the application is installed, but the entry has been configured to *not* appear in the File/New
// menu => also let not appear it in the quickstarter
continue;
addMenuItem( hMenu, aMenuItems[i].nMenuItemID, aMenuItems[i].nMenuIconID,
pShutdownIcon->GetUrlDescription( sURL ), pos, true );
}
// insert the remaining menu entries
addMenuItem( hMenu, IDM_TEMPLATE, ICON_TEMPLATE,
pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE ), pos, true);
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false );
addMenuItem( hMenu, IDM_OPEN, ICON_OPEN, pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ), pos, true );
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false );
#endif
addMenuItem( hMenu, IDM_INSTALL,0, pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH ), pos, false );
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false );
addMenuItem( hMenu, IDM_EXIT, 0, pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ), pos, false );
// indicate status of autostart folder
CheckMenuItem( hMenu, IDM_INSTALL, MF_BYCOMMAND | (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
return hMenu;
}
// -------------------------------
static void deleteSystrayMenu( HMENU hMenu )
{
if( !hMenu || !IsMenu( hMenu ))
return;
MENUITEMINFOW mi;
MYITEM *pMyItem;
int pos=0;
memset( &mi, 0, sizeof( mi ) );
mi.cbSize = sizeof( mi );
mi.fMask = MIIM_DATA;
while( GetMenuItemInfoW( hMenu, pos++, true, &mi ) )
{
pMyItem = (MYITEM*) mi.dwItemData;
if( pMyItem )
{
pMyItem->text = OUString();
delete pMyItem;
}
mi.fMask = MIIM_DATA;
}
}
// -------------------------------
static void addTaskbarIcon( HWND hWnd )
{
OUString strTip;
if( ShutdownIcon::getInstance() )
strTip = ShutdownIcon::getInstance()->GetResString( STR_QUICKSTART_TIP );
// add taskbar icon
NOTIFYICONDATAA nid;
nid.hIcon = (HICON)LoadImageA( GetModuleHandle( NULL ), MAKEINTRESOURCE( ICON_SO_DEFAULT ),
IMAGE_ICON, GetSystemMetrics( SM_CXSMICON ), GetSystemMetrics( SM_CYSMICON ),
LR_DEFAULTCOLOR | LR_SHARED );
// better use unicode wrapper here ?
strncpy( nid.szTip, ( OUStringToOString(strTip, osl_getThreadTextEncoding()).getStr() ), 64 );
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
nid.uCallbackMessage = SFX_TASKBAR_NOTIFICATION;
nid.uFlags = NIF_MESSAGE|NIF_TIP|NIF_ICON;
Shell_NotifyIconA(NIM_ADD, &nid);
}
// -------------------------------
/*
static void removeTaskbarIcon()
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
OSL_ENSURE( pShutdownIcon, "ShutdownIcon instance empty!");
if( !pShutdownIcon )
return;
if ( IsWindow( aListenerWindow ))
{
deleteSystrayMenu( popupMenu );
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = aListenerWindow;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
}
}
*/
// -------------------------------
LRESULT CALLBACK listenerWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static UINT s_uTaskbarRestart = 0;
static UINT s_uMsgKillTray = 0;
switch (uMsg)
{
case WM_NCCREATE:
return TRUE;
case WM_CREATE:
{
// request notfication when taskbar is recreated
// we then have to add our icon again
s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
s_uMsgKillTray = RegisterWindowMessage( SHUTDOWN_QUICKSTART_MESSAGE );
// create the menu
if( !popupMenu )
if( (popupMenu = createSystrayMenu( )) == NULL )
return -1;
// and the icon
addTaskbarIcon( hWnd );
// disable shutdown
ShutdownIcon::getInstance()->SetVeto( true );
ShutdownIcon::getInstance()->addTerminateListener();
}
return 0;
case WM_MEASUREITEM:
OnMeasureItem(hWnd, (LPMEASUREITEMSTRUCT) lParam);
return TRUE;
case WM_DRAWITEM:
OnDrawItem(hWnd, (LPDRAWITEMSTRUCT) lParam);
return TRUE;
case SFX_TASKBAR_NOTIFICATION:
switch( lParam )
{
case WM_LBUTTONDBLCLK:
#if defined(USE_APP_SHORTCUTS)
PostMessage( aExecuterWindow, WM_COMMAND, IDM_TEMPLATE, (LPARAM)hWnd );
#endif
break;
case WM_RBUTTONDOWN:
{
POINT pt;
GetCursorPos(&pt);
SetForegroundWindow( hWnd );
// update status before showing menu, could have been changed from option page
CheckMenuItem( popupMenu, IDM_INSTALL, MF_BYCOMMAND| (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
EnableMenuItem( popupMenu, IDM_EXIT, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
#if defined(USE_APP_SHORTCUTS)
EnableMenuItem( popupMenu, IDM_OPEN, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
EnableMenuItem( popupMenu, IDM_TEMPLATE, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
#endif
int m = TrackPopupMenuEx( popupMenu, TPM_RETURNCMD|TPM_LEFTALIGN|TPM_RIGHTBUTTON,
pt.x, pt.y, hWnd, NULL );
// BUGFIX: See Q135788 (PRB: Menus for Notification Icons Don't Work Correctly)
PostMessage( hWnd, NULL, 0, 0 );
switch( m )
{
#if defined(USE_APP_SHORTCUTS)
case IDM_OPEN:
case IDM_WRITER:
case IDM_CALC:
case IDM_IMPRESS:
case IDM_DRAW:
case IDM_TEMPLATE:
case IDM_BASE:
case IDM_MATH:
break;
#endif
case IDM_INSTALL:
CheckMenuItem( popupMenu, IDM_INSTALL, MF_BYCOMMAND| (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
break;
case IDM_EXIT:
// delete taskbar icon
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
break;
}
PostMessage( aExecuterWindow, WM_COMMAND, m, (LPARAM)hWnd );
}
break;
}
break;
case WM_DESTROY:
deleteSystrayMenu( popupMenu );
// We don't need the Systray Thread anymore
PostQuitMessage( 0 );
return DefWindowProc(hWnd, uMsg, wParam, lParam);
default:
if( uMsg == s_uTaskbarRestart )
{
// re-create taskbar icon
addTaskbarIcon( hWnd );
}
else if ( uMsg == s_uMsgKillTray )
{
// delete taskbar icon
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
PostMessage( aExecuterWindow, WM_COMMAND, IDM_EXIT, (LPARAM)hWnd );
}
else
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
// -------------------------------
static sal_Bool checkOEM() {
Reference<XMultiServiceFactory> rFactory = ::comphelper::getProcessServiceFactory();
Reference<XJob> rOemJob(rFactory->createInstance(
OUString::createFromAscii("com.sun.star.office.OEMPreloadJob")),
UNO_QUERY );
Sequence<NamedValue> args;
sal_Bool bResult = sal_False;
if (rOemJob.is())
{
Any aResult = rOemJob->execute(args);
aResult >>= bResult;
} else bResult = sal_True;
return bResult;
}
LRESULT CALLBACK executerWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_NCCREATE:
return TRUE;
case WM_CREATE:
return 0;
case WM_COMMAND:
switch( LOWORD(wParam) )
{
#if defined(USE_APP_SHORTCUTS)
case IDM_OPEN:
if ( !ShutdownIcon::bModalMode && checkOEM() )
ShutdownIcon::FileOpen();
break;
case IDM_WRITER:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( WRITER_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_CALC:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( CALC_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_IMPRESS:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( IMPRESS_WIZARD_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_DRAW:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( DRAW_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_BASE:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( BASE_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_MATH:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( MATH_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_TEMPLATE:
if ( !ShutdownIcon::bModalMode && checkOEM())
ShutdownIcon::FromTemplate();
break;
#endif
case IDM_INSTALL:
ShutdownIcon::SetAutostart( !ShutdownIcon::GetAutostart() );
break;
case IDM_EXIT:
// remove listener and
// terminate office if running in background
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::terminateDesktop();
break;
}
break;
case WM_DESTROY:
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
// -------------------------------
DWORD WINAPI SystrayThread( LPVOID /*lpParam*/ )
{
aListenerWindow = CreateWindowExA(0,
QUICKSTART_CLASSNAME, // registered class name
QUICKSTART_WINDOWNAME, // window name
0, // window style
CW_USEDEFAULT, // horizontal position of window
CW_USEDEFAULT, // vertical position of window
CW_USEDEFAULT, // window width
CW_USEDEFAULT, // window height
(HWND) NULL, // handle to parent or owner window
NULL, // menu handle or child identifier
(HINSTANCE) GetModuleHandle( NULL ), // handle to application instance
NULL // window-creation data
);
MSG msg;
while ( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return msg.wParam; // Exit code of WM_QUIT
}
// -------------------------------
void win32_init_sys_tray()
{
if ( ShutdownIcon::IsQuickstarterInstalled() )
{
WNDCLASSEXA listenerClass;
listenerClass.cbSize = sizeof(WNDCLASSEX);
listenerClass.style = 0;
listenerClass.lpfnWndProc = listenerWndProc;
listenerClass.cbClsExtra = 0;
listenerClass.cbWndExtra = 0;
listenerClass.hInstance = (HINSTANCE) GetModuleHandle( NULL );
listenerClass.hIcon = NULL;
listenerClass.hCursor = NULL;
listenerClass.hbrBackground = NULL;
listenerClass.lpszMenuName = NULL;
listenerClass.lpszClassName = QUICKSTART_CLASSNAME;
listenerClass.hIconSm = NULL;
RegisterClassExA(&listenerClass);
WNDCLASSEXA executerClass;
executerClass.cbSize = sizeof(WNDCLASSEX);
executerClass.style = 0;
executerClass.lpfnWndProc = executerWndProc;
executerClass.cbClsExtra = 0;
executerClass.cbWndExtra = 0;
executerClass.hInstance = (HINSTANCE) GetModuleHandle( NULL );
executerClass.hIcon = NULL;
executerClass.hCursor = NULL;
executerClass.hbrBackground = NULL;
executerClass.lpszMenuName = NULL;
executerClass.lpszClassName = EXECUTER_WINDOWCLASS;
executerClass.hIconSm = NULL;
RegisterClassExA( &executerClass );
aExecuterWindow = CreateWindowExA(0,
EXECUTER_WINDOWCLASS, // registered class name
EXECUTER_WINDOWNAME, // window name
0, // window style
CW_USEDEFAULT, // horizontal position of window
CW_USEDEFAULT, // vertical position of window
CW_USEDEFAULT, // window width
CW_USEDEFAULT, // window height
(HWND) NULL, // handle to parent or owner window
NULL, // menu handle or child identifier
(HINSTANCE) GetModuleHandle( NULL ), // handle to application instance
NULL // window-creation data
);
DWORD dwThreadId;
CreateThread( NULL, 0, SystrayThread, NULL, 0, &dwThreadId );
}
}
// -------------------------------
void win32_shutdown_sys_tray()
{
if ( ShutdownIcon::IsQuickstarterInstalled() )
{
if( IsWindow( aListenerWindow ) )
{
DestroyWindow( aListenerWindow );
aListenerWindow = NULL;
DestroyWindow( aExecuterWindow );
aExecuterWindow = NULL;
}
UnregisterClassA( QUICKSTART_CLASSNAME, GetModuleHandle( NULL ) );
UnregisterClassA( EXECUTER_WINDOWCLASS, GetModuleHandle( NULL ) );
}
}
// -------------------------------
void OnMeasureItem(HWND hwnd, LPMEASUREITEMSTRUCT lpmis)
{
MYITEM *pMyItem = (MYITEM *) lpmis->itemData;
HDC hdc = GetDC(hwnd);
SIZE size;
NONCLIENTMETRICS ncm;
memset(&ncm, 0, sizeof(ncm));
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID) &ncm, 0);
// Assume every menu item can be default and printed bold
ncm.lfMenuFont.lfWeight = FW_BOLD;
HFONT hfntOld = (HFONT) SelectObject(hdc, (HFONT) CreateFontIndirect( &ncm.lfMenuFont ));
GetTextExtentPoint32W(hdc, reinterpret_cast<LPCWSTR>(pMyItem->text.getStr()),
pMyItem->text.getLength(), &size);
lpmis->itemWidth = size.cx + 4 + GetSystemMetrics( SM_CXSMICON );
lpmis->itemHeight = (size.cy > GetSystemMetrics( SM_CYSMICON )) ? size.cy : GetSystemMetrics( SM_CYSMICON );
lpmis->itemHeight += 4;
DeleteObject( SelectObject(hdc, hfntOld) );
ReleaseDC(hwnd, hdc);
}
void OnDrawItem(HWND /*hwnd*/, LPDRAWITEMSTRUCT lpdis)
{
MYITEM *pMyItem = (MYITEM *) lpdis->itemData;
COLORREF clrPrevText, clrPrevBkgnd;
HFONT hfntOld;
HBRUSH hbrOld;
int x, y;
BOOL fSelected = lpdis->itemState & ODS_SELECTED;
BOOL fDisabled = lpdis->itemState & (ODS_DISABLED | ODS_GRAYED);
// Set the appropriate foreground and background colors.
RECT aRect = lpdis->rcItem;
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_MENU) );
if ( fDisabled )
clrPrevText = SetTextColor( lpdis->hDC, GetSysColor( COLOR_GRAYTEXT ) );
else
clrPrevText = SetTextColor( lpdis->hDC, GetSysColor( fSelected ? COLOR_HIGHLIGHTTEXT : COLOR_MENUTEXT ) );
if ( fSelected )
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_HIGHLIGHT) );
else
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_MENU) );
hbrOld = (HBRUSH)SelectObject( lpdis->hDC, CreateSolidBrush( GetBkColor( lpdis->hDC ) ) );
// Fill background
PatBlt(lpdis->hDC, aRect.left, aRect.top, aRect.right-aRect.left, aRect.bottom-aRect.top, PATCOPY);
int height = aRect.bottom-aRect.top;
x = aRect.left;
y = aRect.top;
int cx = GetSystemMetrics( SM_CXSMICON );
int cy = GetSystemMetrics( SM_CYSMICON );
HICON hIcon = (HICON) LoadImageA( GetModuleHandle( NULL ), MAKEINTRESOURCE( pMyItem->iconId ),
IMAGE_ICON, cx, cy,
LR_DEFAULTCOLOR | LR_SHARED );
// DrawIconEx( lpdis->hDC, x, y+(height-cy)/2, hIcon, cx, cy, 0, NULL, DI_NORMAL );
HBRUSH hbrIcon = CreateSolidBrush( GetSysColor( COLOR_GRAYTEXT ) );
DrawStateW( lpdis->hDC, (HBRUSH)hbrIcon, (DRAWSTATEPROC)NULL, (LPARAM)hIcon, (WPARAM)0, x, y+(height-cy)/2, 0, 0, DST_ICON | (fDisabled ? (fSelected ? DSS_MONO : DSS_DISABLED) : DSS_NORMAL) );
DeleteObject( hbrIcon );
x += cx + 4; // space for icon
aRect.left = x;
NONCLIENTMETRICS ncm;
memset(&ncm, 0, sizeof(ncm));
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID) &ncm, 0);
// Print default menu entry with bold font
if ( lpdis->itemState & ODS_DEFAULT )
ncm.lfMenuFont.lfWeight = FW_BOLD;
hfntOld = (HFONT) SelectObject(lpdis->hDC, (HFONT) CreateFontIndirect( &ncm.lfMenuFont ));
SIZE size;
GetTextExtentPointW( lpdis->hDC, reinterpret_cast<LPCWSTR>(pMyItem->text.getStr()), pMyItem->text.getLength(), &size );
DrawStateW( lpdis->hDC, (HBRUSH)NULL, (DRAWSTATEPROC)NULL, (LPARAM)pMyItem->text.getStr(), (WPARAM)0, aRect.left, aRect.top + (height - size.cy)/2, 0, 0, DST_TEXT | (fDisabled && !fSelected ? DSS_DISABLED : DSS_NORMAL) );
// Restore the original font and colors.
DeleteObject( SelectObject( lpdis->hDC, hbrOld ) );
DeleteObject( SelectObject( lpdis->hDC, hfntOld) );
SetTextColor(lpdis->hDC, clrPrevText);
SetBkColor(lpdis->hDC, clrPrevBkgnd);
}
// -------------------------------
// code from setup2 project
// -------------------------------
void _SHFree( void *pv )
{
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pv );
pMalloc->Release();
}
}
#define ALLOC(type, n) ((type *) HeapAlloc(GetProcessHeap(), 0, sizeof(type) * n ))
#define FREE(p) HeapFree(GetProcessHeap(), 0, p)
static OUString _SHGetSpecialFolder( int nFolderID )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
OUString aFolder;
if( hHdl == NOERROR )
{
WCHAR *lpFolderA;
lpFolderA = ALLOC( WCHAR, 16000 );
SHGetPathFromIDListW( pidl, lpFolderA );
aFolder = OUString( reinterpret_cast<const sal_Unicode*>(lpFolderA) );
FREE( lpFolderA );
_SHFree( pidl );
}
return aFolder;
}
OUString ShutdownIcon::GetAutostartFolderNameW32()
{
return _SHGetSpecialFolder(CSIDL_STARTUP);
}
static HRESULT WINAPI SHCoCreateInstance( LPVOID lpszReserved, REFCLSID clsid, LPUNKNOWN pUnkUnknown, REFIID iid, LPVOID *ppv )
{
HRESULT hResult = E_NOTIMPL;
HMODULE hModShell = GetModuleHandle( "SHELL32" );
if ( hModShell != NULL )
{
typedef HRESULT (WINAPI *SHCoCreateInstance_PROC)( LPVOID lpszReserved, REFCLSID clsid, LPUNKNOWN pUnkUnknwon, REFIID iid, LPVOID *ppv );
SHCoCreateInstance_PROC lpfnSHCoCreateInstance = (SHCoCreateInstance_PROC)GetProcAddress( hModShell, MAKEINTRESOURCE(102) );
if ( lpfnSHCoCreateInstance )
hResult = lpfnSHCoCreateInstance( lpszReserved, clsid, pUnkUnknown, iid, ppv );
}
return hResult;
}
BOOL CreateShortcut( const OUString& rAbsObject, const OUString& rAbsObjectPath,
const OUString& rAbsShortcut, const OUString& rDescription, const OUString& rParameter )
{
HRESULT hres;
IShellLink* psl;
CLSID clsid_ShellLink = CLSID_ShellLink;
CLSID clsid_IShellLink = IID_IShellLink;
hres = CoCreateInstance( clsid_ShellLink, NULL, CLSCTX_INPROC_SERVER,
clsid_IShellLink, (void**)&psl );
if( FAILED(hres) )
hres = SHCoCreateInstance( NULL, clsid_ShellLink, NULL, clsid_IShellLink, (void**)&psl );
if( SUCCEEDED(hres) )
{
IPersistFile* ppf;
psl->SetPath( OUStringToOString(rAbsObject, osl_getThreadTextEncoding()).getStr() );
psl->SetWorkingDirectory( OUStringToOString(rAbsObjectPath, osl_getThreadTextEncoding()).getStr() );
psl->SetDescription( OUStringToOString(rDescription, osl_getThreadTextEncoding()).getStr() );
if( rParameter.getLength() )
psl->SetArguments( OUStringToOString(rParameter, osl_getThreadTextEncoding()).getStr() );
CLSID clsid_IPersistFile = IID_IPersistFile;
hres = psl->QueryInterface( clsid_IPersistFile, (void**)&ppf );
if( SUCCEEDED(hres) )
{
hres = ppf->Save( reinterpret_cast<LPCOLESTR>(rAbsShortcut.getStr()), TRUE );
ppf->Release();
} else return FALSE;
psl->Release();
} else return FALSE;
return TRUE;
}
// ------------------
// install/uninstall
static bool FileExistsW( LPCWSTR lpPath )
{
bool bExists = false;
WIN32_FIND_DATAW aFindData;
HANDLE hFind = FindFirstFileW( lpPath, &aFindData );
if ( INVALID_HANDLE_VALUE != hFind )
{
bExists = true;
FindClose( hFind );
}
return bExists;
}
bool ShutdownIcon::IsQuickstarterInstalled()
{
wchar_t aPath[_MAX_PATH];
if( isNT() )
{
GetModuleFileNameW( NULL, aPath, _MAX_PATH-1);
}
else
{
char szPathA[_MAX_PATH];
GetModuleFileNameA( NULL, szPathA, _MAX_PATH-1);
// calc the string wcstr len
int nNeededWStrBuffSize = MultiByteToWideChar( CP_ACP, 0, szPathA, -1, NULL, 0 );
// copy the string if necessary
if ( nNeededWStrBuffSize > 0 )
MultiByteToWideChar( CP_ACP, 0, szPathA, -1, aPath, nNeededWStrBuffSize );
}
OUString aOfficepath( reinterpret_cast<const sal_Unicode*>(aPath) );
int i = aOfficepath.lastIndexOf((sal_Char) '\\');
if( i != -1 )
aOfficepath = aOfficepath.copy(0, i);
OUString quickstartExe(aOfficepath);
quickstartExe += OUString( RTL_CONSTASCII_USTRINGPARAM( "\\quickstart.exe" ) );
return FileExistsW( reinterpret_cast<LPCWSTR>(quickstartExe.getStr()) );
}
void ShutdownIcon::EnableAutostartW32( const rtl::OUString &aShortcut )
{
wchar_t aPath[_MAX_PATH];
if( isNT() )
GetModuleFileNameW( NULL, aPath, _MAX_PATH-1);
else
{
char szPathA[_MAX_PATH];
GetModuleFileNameA( NULL, szPathA, _MAX_PATH-1);
// calc the string wcstr len
int nNeededWStrBuffSize = MultiByteToWideChar( CP_ACP, 0, szPathA, -1, NULL, 0 );
// copy the string if necessary
if ( nNeededWStrBuffSize > 0 )
MultiByteToWideChar( CP_ACP, 0, szPathA, -1, aPath, nNeededWStrBuffSize );
}
OUString aOfficepath( reinterpret_cast<const sal_Unicode*>(aPath) );
int i = aOfficepath.lastIndexOf((sal_Char) '\\');
if( i != -1 )
aOfficepath = aOfficepath.copy(0, i);
OUString quickstartExe(aOfficepath);
quickstartExe += OUString( RTL_CONSTASCII_USTRINGPARAM( "\\quickstart.exe" ) );
CreateShortcut( quickstartExe, aOfficepath, aShortcut, OUString(), OUString() );
}
#endif // WNT
nativea: #161787# Use folder icon from Windows shell library
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sfx2.hxx"
#ifdef WNT
// necessary to include system headers without warnings
#ifdef _MSC_VER
#pragma warning(disable:4668 4917)
#endif
// Support Windows 95 too
#undef WINVER
#define WINVER 0x0400
#define USE_APP_SHORTCUTS
//
// the systray icon is only available on windows
//
#include <unotools/moduleoptions.hxx>
#include <unotools/dynamicmenuoptions.hxx>
#include "shutdownicon.hxx"
#include "app.hrc"
#include <shlobj.h>
#include <objidl.h>
#include <stdio.h>
#include <io.h>
#include <osl/thread.h>
#include <setup_native/qswin32.h>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/task/XJob.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <set>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::osl;
#define EXECUTER_WINDOWCLASS "SO Executer Class"
#define EXECUTER_WINDOWNAME "SO Executer Window"
#define ID_QUICKSTART 1
#define IDM_EXIT 2
#if defined(USE_APP_SHORTCUTS)
# define IDM_OPEN 3
# define IDM_WRITER 4
# define IDM_CALC 5
# define IDM_IMPRESS 6
# define IDM_DRAW 7
# define IDM_BASE 8
# define IDM_TEMPLATE 9
# define IDM_MATH 12
#endif
#define IDM_INSTALL 10
#define IDM_UNINSTALL 11
#define ICON_SO_DEFAULT 1
#define ICON_TEXT_DOCUMENT 2
#define ICON_TEXT_TEMPLATE 3
#define ICON_SPREADSHEET_DOCUMENT 4
#define ICON_SPREADSHEET_TEMPLATE 5
#define ICON_DRAWING_DOCUMENT 6
#define ICON_DRAWING_TEMPLATE 7
#define ICON_PRESENTATION_DOCUMENT 8
#define ICON_PRESENTATION_TEMPLATE 9
#define ICON_PRESENTATION_COMPRESSED 10
#define ICON_GLOBAL_DOCUMENT 11
#define ICON_HTML_DOCUMENT 12
#define ICON_CHART_DOCUMENT 13
#define ICON_DATABASE_DOCUMENT 14
#define ICON_MATH_DOCUMENT 15
#define ICON_TEMPLATE 16
#define ICON_MACROLIBRARY 17
#define ICON_CONFIGURATION 18
#define ICON_OPEN 5 // See index of open folder icon in shell32.dll
#define ICON_SETUP 500
#define SFX_TASKBAR_NOTIFICATION WM_USER+1
static HWND aListenerWindow = NULL;
static HWND aExecuterWindow = NULL;
static HMENU popupMenu = NULL;
static void OnMeasureItem(HWND hwnd, LPMEASUREITEMSTRUCT lpmis);
static void OnDrawItem(HWND hwnd, LPDRAWITEMSTRUCT lpdis);
typedef struct tagMYITEM
{
OUString text;
OUString module;
UINT iconId;
} MYITEM;
// -------------------------------
static bool isNT()
{
static bool bInitialized = false;
static bool bWnt = false;
if( !bInitialized )
{
bInitialized = true;
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) )
{
if ( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
bWnt = true;
}
}
return bWnt;
}
// -------------------------------
static void addMenuItem( HMENU hMenu, UINT id, UINT iconId, const OUString& text, int& pos, int bOwnerdraw, const OUString& module )
{
MENUITEMINFOW mi;
memset( &mi, 0, sizeof( MENUITEMINFOW ) );
mi.cbSize = sizeof( MENUITEMINFOW );
if( id == -1 )
{
mi.fMask=MIIM_TYPE;
mi.fType=MFT_SEPARATOR;
}
else
{
if( bOwnerdraw )
{
mi.fMask=MIIM_TYPE | MIIM_STATE | MIIM_ID | MIIM_DATA;
mi.fType=MFT_OWNERDRAW;
mi.fState=MFS_ENABLED;
mi.wID = id;
MYITEM *pMyItem = new MYITEM;
pMyItem->text = text;
pMyItem->iconId = iconId;
pMyItem->module = module;
mi.dwItemData = (DWORD) pMyItem;
}
else
{
mi.fMask=MIIM_TYPE | MIIM_STATE | MIIM_ID | MIIM_DATA;
mi.fType=MFT_STRING;
mi.fState=MFS_ENABLED;
mi.wID = id;
mi.dwTypeData = (LPWSTR) text.getStr();
mi.cch = text.getLength();
}
#if defined(USE_APP_SHORTCUTS)
if ( IDM_TEMPLATE == id )
mi.fState |= MFS_DEFAULT;
#endif
}
InsertMenuItemW( hMenu, pos++, TRUE, &mi );
}
// -------------------------------
static HMENU createSystrayMenu( )
{
SvtModuleOptions aModuleOptions;
HMENU hMenu = CreatePopupMenu();
int pos=0;
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
OSL_ENSURE( pShutdownIcon, "ShutdownIcon instance empty!");
if( !pShutdownIcon )
return NULL;
#if defined(USE_APP_SHORTCUTS)
// collect the URLs of the entries in the File/New menu
::std::set< ::rtl::OUString > aFileNewAppsAvailable;
SvtDynamicMenuOptions aOpt;
Sequence < Sequence < PropertyValue > > aNewMenu = aOpt.GetMenu( E_NEWMENU );
const ::rtl::OUString sURLKey( RTL_CONSTASCII_USTRINGPARAM( "URL" ) );
const Sequence< PropertyValue >* pNewMenu = aNewMenu.getConstArray();
const Sequence< PropertyValue >* pNewMenuEnd = aNewMenu.getConstArray() + aNewMenu.getLength();
for ( ; pNewMenu != pNewMenuEnd; ++pNewMenu )
{
::comphelper::SequenceAsHashMap aEntryItems( *pNewMenu );
::rtl::OUString sURL( aEntryItems.getUnpackedValueOrDefault( sURLKey, ::rtl::OUString() ) );
if ( sURL.getLength() )
aFileNewAppsAvailable.insert( sURL );
}
// describe the menu entries for launching the applications
struct MenuEntryDescriptor
{
SvtModuleOptions::EModule eModuleIdentifier;
UINT nMenuItemID;
UINT nMenuIconID;
const char* pAsciiURLDescription;
} aMenuItems[] =
{
{ SvtModuleOptions::E_SWRITER, IDM_WRITER, ICON_TEXT_DOCUMENT, WRITER_URL },
{ SvtModuleOptions::E_SCALC, IDM_CALC, ICON_SPREADSHEET_DOCUMENT, CALC_URL },
{ SvtModuleOptions::E_SIMPRESS, IDM_IMPRESS,ICON_PRESENTATION_DOCUMENT, IMPRESS_WIZARD_URL },
{ SvtModuleOptions::E_SDRAW, IDM_DRAW, ICON_DRAWING_DOCUMENT, DRAW_URL },
{ SvtModuleOptions::E_SDATABASE, IDM_BASE, ICON_DATABASE_DOCUMENT, BASE_URL },
{ SvtModuleOptions::E_SMATH, IDM_MATH, ICON_MATH_DOCUMENT, MATH_URL },
};
OUString aEmpty;
// insert the menu entries for launching the applications
for ( size_t i = 0; i < sizeof( aMenuItems ) / sizeof( aMenuItems[0] ); ++i )
{
if ( !aModuleOptions.IsModuleInstalled( aMenuItems[i].eModuleIdentifier ) )
// the complete application is not even installed
continue;
::rtl::OUString sURL( ::rtl::OUString::createFromAscii( aMenuItems[i].pAsciiURLDescription ) );
if ( aFileNewAppsAvailable.find( sURL ) == aFileNewAppsAvailable.end() )
// the application is installed, but the entry has been configured to *not* appear in the File/New
// menu => also let not appear it in the quickstarter
continue;
addMenuItem( hMenu, aMenuItems[i].nMenuItemID, aMenuItems[i].nMenuIconID,
pShutdownIcon->GetUrlDescription( sURL ), pos, true, aEmpty );
}
// insert the remaining menu entries
addMenuItem( hMenu, IDM_TEMPLATE, ICON_TEMPLATE,
pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE ), pos, true, aEmpty);
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false, aEmpty );
addMenuItem( hMenu, IDM_OPEN, ICON_OPEN, pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ), pos, true, OUString::createFromAscii( "shell32" ));
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false, aEmpty );
#endif
addMenuItem( hMenu, IDM_INSTALL,0, pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH ), pos, false, aEmpty );
addMenuItem( hMenu, static_cast< UINT >( -1 ), 0, OUString(), pos, false, aEmpty );
addMenuItem( hMenu, IDM_EXIT, 0, pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ), pos, false, aEmpty );
// indicate status of autostart folder
CheckMenuItem( hMenu, IDM_INSTALL, MF_BYCOMMAND | (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
return hMenu;
}
// -------------------------------
static void deleteSystrayMenu( HMENU hMenu )
{
if( !hMenu || !IsMenu( hMenu ))
return;
MENUITEMINFOW mi;
MYITEM *pMyItem;
int pos=0;
memset( &mi, 0, sizeof( mi ) );
mi.cbSize = sizeof( mi );
mi.fMask = MIIM_DATA;
while( GetMenuItemInfoW( hMenu, pos++, true, &mi ) )
{
pMyItem = (MYITEM*) mi.dwItemData;
if( pMyItem )
{
pMyItem->text = OUString();
delete pMyItem;
}
mi.fMask = MIIM_DATA;
}
}
// -------------------------------
static void addTaskbarIcon( HWND hWnd )
{
OUString strTip;
if( ShutdownIcon::getInstance() )
strTip = ShutdownIcon::getInstance()->GetResString( STR_QUICKSTART_TIP );
// add taskbar icon
NOTIFYICONDATAA nid;
nid.hIcon = (HICON)LoadImageA( GetModuleHandle( NULL ), MAKEINTRESOURCE( ICON_SO_DEFAULT ),
IMAGE_ICON, GetSystemMetrics( SM_CXSMICON ), GetSystemMetrics( SM_CYSMICON ),
LR_DEFAULTCOLOR | LR_SHARED );
// better use unicode wrapper here ?
strncpy( nid.szTip, ( OUStringToOString(strTip, osl_getThreadTextEncoding()).getStr() ), 64 );
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
nid.uCallbackMessage = SFX_TASKBAR_NOTIFICATION;
nid.uFlags = NIF_MESSAGE|NIF_TIP|NIF_ICON;
Shell_NotifyIconA(NIM_ADD, &nid);
}
// -------------------------------
/*
static void removeTaskbarIcon()
{
ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
OSL_ENSURE( pShutdownIcon, "ShutdownIcon instance empty!");
if( !pShutdownIcon )
return;
if ( IsWindow( aListenerWindow ))
{
deleteSystrayMenu( popupMenu );
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = aListenerWindow;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
}
}
*/
// -------------------------------
LRESULT CALLBACK listenerWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static UINT s_uTaskbarRestart = 0;
static UINT s_uMsgKillTray = 0;
switch (uMsg)
{
case WM_NCCREATE:
return TRUE;
case WM_CREATE:
{
// request notfication when taskbar is recreated
// we then have to add our icon again
s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
s_uMsgKillTray = RegisterWindowMessage( SHUTDOWN_QUICKSTART_MESSAGE );
// create the menu
if( !popupMenu )
if( (popupMenu = createSystrayMenu( )) == NULL )
return -1;
// and the icon
addTaskbarIcon( hWnd );
// disable shutdown
ShutdownIcon::getInstance()->SetVeto( true );
ShutdownIcon::getInstance()->addTerminateListener();
}
return 0;
case WM_MEASUREITEM:
OnMeasureItem(hWnd, (LPMEASUREITEMSTRUCT) lParam);
return TRUE;
case WM_DRAWITEM:
OnDrawItem(hWnd, (LPDRAWITEMSTRUCT) lParam);
return TRUE;
case SFX_TASKBAR_NOTIFICATION:
switch( lParam )
{
case WM_LBUTTONDBLCLK:
#if defined(USE_APP_SHORTCUTS)
PostMessage( aExecuterWindow, WM_COMMAND, IDM_TEMPLATE, (LPARAM)hWnd );
#endif
break;
case WM_RBUTTONDOWN:
{
POINT pt;
GetCursorPos(&pt);
SetForegroundWindow( hWnd );
// update status before showing menu, could have been changed from option page
CheckMenuItem( popupMenu, IDM_INSTALL, MF_BYCOMMAND| (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
EnableMenuItem( popupMenu, IDM_EXIT, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
#if defined(USE_APP_SHORTCUTS)
EnableMenuItem( popupMenu, IDM_OPEN, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
EnableMenuItem( popupMenu, IDM_TEMPLATE, MF_BYCOMMAND | (ShutdownIcon::bModalMode ? MF_GRAYED : MF_ENABLED) );
#endif
int m = TrackPopupMenuEx( popupMenu, TPM_RETURNCMD|TPM_LEFTALIGN|TPM_RIGHTBUTTON,
pt.x, pt.y, hWnd, NULL );
// BUGFIX: See Q135788 (PRB: Menus for Notification Icons Don't Work Correctly)
PostMessage( hWnd, NULL, 0, 0 );
switch( m )
{
#if defined(USE_APP_SHORTCUTS)
case IDM_OPEN:
case IDM_WRITER:
case IDM_CALC:
case IDM_IMPRESS:
case IDM_DRAW:
case IDM_TEMPLATE:
case IDM_BASE:
case IDM_MATH:
break;
#endif
case IDM_INSTALL:
CheckMenuItem( popupMenu, IDM_INSTALL, MF_BYCOMMAND| (ShutdownIcon::GetAutostart() ? MF_CHECKED : MF_UNCHECKED) );
break;
case IDM_EXIT:
// delete taskbar icon
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
break;
}
PostMessage( aExecuterWindow, WM_COMMAND, m, (LPARAM)hWnd );
}
break;
}
break;
case WM_DESTROY:
deleteSystrayMenu( popupMenu );
// We don't need the Systray Thread anymore
PostQuitMessage( 0 );
return DefWindowProc(hWnd, uMsg, wParam, lParam);
default:
if( uMsg == s_uTaskbarRestart )
{
// re-create taskbar icon
addTaskbarIcon( hWnd );
}
else if ( uMsg == s_uMsgKillTray )
{
// delete taskbar icon
NOTIFYICONDATAA nid;
nid.cbSize=sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = ID_QUICKSTART;
Shell_NotifyIconA(NIM_DELETE, &nid);
PostMessage( aExecuterWindow, WM_COMMAND, IDM_EXIT, (LPARAM)hWnd );
}
else
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
// -------------------------------
static sal_Bool checkOEM() {
Reference<XMultiServiceFactory> rFactory = ::comphelper::getProcessServiceFactory();
Reference<XJob> rOemJob(rFactory->createInstance(
OUString::createFromAscii("com.sun.star.office.OEMPreloadJob")),
UNO_QUERY );
Sequence<NamedValue> args;
sal_Bool bResult = sal_False;
if (rOemJob.is())
{
Any aResult = rOemJob->execute(args);
aResult >>= bResult;
} else bResult = sal_True;
return bResult;
}
LRESULT CALLBACK executerWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_NCCREATE:
return TRUE;
case WM_CREATE:
return 0;
case WM_COMMAND:
switch( LOWORD(wParam) )
{
#if defined(USE_APP_SHORTCUTS)
case IDM_OPEN:
if ( !ShutdownIcon::bModalMode && checkOEM() )
ShutdownIcon::FileOpen();
break;
case IDM_WRITER:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( WRITER_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_CALC:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( CALC_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_IMPRESS:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( IMPRESS_WIZARD_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_DRAW:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( DRAW_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_BASE:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( BASE_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_MATH:
if (checkOEM())
ShutdownIcon::OpenURL( OUString( RTL_CONSTASCII_USTRINGPARAM( MATH_URL ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
break;
case IDM_TEMPLATE:
if ( !ShutdownIcon::bModalMode && checkOEM())
ShutdownIcon::FromTemplate();
break;
#endif
case IDM_INSTALL:
ShutdownIcon::SetAutostart( !ShutdownIcon::GetAutostart() );
break;
case IDM_EXIT:
// remove listener and
// terminate office if running in background
if ( !ShutdownIcon::bModalMode )
ShutdownIcon::terminateDesktop();
break;
}
break;
case WM_DESTROY:
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
// -------------------------------
DWORD WINAPI SystrayThread( LPVOID /*lpParam*/ )
{
aListenerWindow = CreateWindowExA(0,
QUICKSTART_CLASSNAME, // registered class name
QUICKSTART_WINDOWNAME, // window name
0, // window style
CW_USEDEFAULT, // horizontal position of window
CW_USEDEFAULT, // vertical position of window
CW_USEDEFAULT, // window width
CW_USEDEFAULT, // window height
(HWND) NULL, // handle to parent or owner window
NULL, // menu handle or child identifier
(HINSTANCE) GetModuleHandle( NULL ), // handle to application instance
NULL // window-creation data
);
MSG msg;
while ( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return msg.wParam; // Exit code of WM_QUIT
}
// -------------------------------
void win32_init_sys_tray()
{
if ( ShutdownIcon::IsQuickstarterInstalled() )
{
WNDCLASSEXA listenerClass;
listenerClass.cbSize = sizeof(WNDCLASSEX);
listenerClass.style = 0;
listenerClass.lpfnWndProc = listenerWndProc;
listenerClass.cbClsExtra = 0;
listenerClass.cbWndExtra = 0;
listenerClass.hInstance = (HINSTANCE) GetModuleHandle( NULL );
listenerClass.hIcon = NULL;
listenerClass.hCursor = NULL;
listenerClass.hbrBackground = NULL;
listenerClass.lpszMenuName = NULL;
listenerClass.lpszClassName = QUICKSTART_CLASSNAME;
listenerClass.hIconSm = NULL;
RegisterClassExA(&listenerClass);
WNDCLASSEXA executerClass;
executerClass.cbSize = sizeof(WNDCLASSEX);
executerClass.style = 0;
executerClass.lpfnWndProc = executerWndProc;
executerClass.cbClsExtra = 0;
executerClass.cbWndExtra = 0;
executerClass.hInstance = (HINSTANCE) GetModuleHandle( NULL );
executerClass.hIcon = NULL;
executerClass.hCursor = NULL;
executerClass.hbrBackground = NULL;
executerClass.lpszMenuName = NULL;
executerClass.lpszClassName = EXECUTER_WINDOWCLASS;
executerClass.hIconSm = NULL;
RegisterClassExA( &executerClass );
aExecuterWindow = CreateWindowExA(0,
EXECUTER_WINDOWCLASS, // registered class name
EXECUTER_WINDOWNAME, // window name
0, // window style
CW_USEDEFAULT, // horizontal position of window
CW_USEDEFAULT, // vertical position of window
CW_USEDEFAULT, // window width
CW_USEDEFAULT, // window height
(HWND) NULL, // handle to parent or owner window
NULL, // menu handle or child identifier
(HINSTANCE) GetModuleHandle( NULL ), // handle to application instance
NULL // window-creation data
);
DWORD dwThreadId;
CreateThread( NULL, 0, SystrayThread, NULL, 0, &dwThreadId );
}
}
// -------------------------------
void win32_shutdown_sys_tray()
{
if ( ShutdownIcon::IsQuickstarterInstalled() )
{
if( IsWindow( aListenerWindow ) )
{
DestroyWindow( aListenerWindow );
aListenerWindow = NULL;
DestroyWindow( aExecuterWindow );
aExecuterWindow = NULL;
}
UnregisterClassA( QUICKSTART_CLASSNAME, GetModuleHandle( NULL ) );
UnregisterClassA( EXECUTER_WINDOWCLASS, GetModuleHandle( NULL ) );
}
}
// -------------------------------
void OnMeasureItem(HWND hwnd, LPMEASUREITEMSTRUCT lpmis)
{
MYITEM *pMyItem = (MYITEM *) lpmis->itemData;
HDC hdc = GetDC(hwnd);
SIZE size;
NONCLIENTMETRICS ncm;
memset(&ncm, 0, sizeof(ncm));
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID) &ncm, 0);
// Assume every menu item can be default and printed bold
ncm.lfMenuFont.lfWeight = FW_BOLD;
HFONT hfntOld = (HFONT) SelectObject(hdc, (HFONT) CreateFontIndirect( &ncm.lfMenuFont ));
GetTextExtentPoint32W(hdc, reinterpret_cast<LPCWSTR>(pMyItem->text.getStr()),
pMyItem->text.getLength(), &size);
lpmis->itemWidth = size.cx + 4 + GetSystemMetrics( SM_CXSMICON );
lpmis->itemHeight = (size.cy > GetSystemMetrics( SM_CYSMICON )) ? size.cy : GetSystemMetrics( SM_CYSMICON );
lpmis->itemHeight += 4;
DeleteObject( SelectObject(hdc, hfntOld) );
ReleaseDC(hwnd, hdc);
}
void OnDrawItem(HWND /*hwnd*/, LPDRAWITEMSTRUCT lpdis)
{
MYITEM *pMyItem = (MYITEM *) lpdis->itemData;
COLORREF clrPrevText, clrPrevBkgnd;
HFONT hfntOld;
HBRUSH hbrOld;
int x, y;
BOOL fSelected = lpdis->itemState & ODS_SELECTED;
BOOL fDisabled = lpdis->itemState & (ODS_DISABLED | ODS_GRAYED);
// Set the appropriate foreground and background colors.
RECT aRect = lpdis->rcItem;
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_MENU) );
if ( fDisabled )
clrPrevText = SetTextColor( lpdis->hDC, GetSysColor( COLOR_GRAYTEXT ) );
else
clrPrevText = SetTextColor( lpdis->hDC, GetSysColor( fSelected ? COLOR_HIGHLIGHTTEXT : COLOR_MENUTEXT ) );
if ( fSelected )
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_HIGHLIGHT) );
else
clrPrevBkgnd = SetBkColor( lpdis->hDC, GetSysColor(COLOR_MENU) );
hbrOld = (HBRUSH)SelectObject( lpdis->hDC, CreateSolidBrush( GetBkColor( lpdis->hDC ) ) );
// Fill background
PatBlt(lpdis->hDC, aRect.left, aRect.top, aRect.right-aRect.left, aRect.bottom-aRect.top, PATCOPY);
int height = aRect.bottom-aRect.top;
x = aRect.left;
y = aRect.top;
int cx = GetSystemMetrics( SM_CXSMICON );
int cy = GetSystemMetrics( SM_CYSMICON );
HICON hIcon( 0 );
if ( pMyItem->module.getLength() > 0 )
hIcon = (HICON) LoadImageA( GetModuleHandleW( reinterpret_cast<LPCWSTR>( pMyItem->module.getStr() )),
MAKEINTRESOURCE( pMyItem->iconId ),
IMAGE_ICON, cx, cy,
LR_DEFAULTCOLOR | LR_SHARED );
else
hIcon = (HICON) LoadImageA( GetModuleHandle( NULL ), MAKEINTRESOURCE( pMyItem->iconId ),
IMAGE_ICON, cx, cy,
LR_DEFAULTCOLOR | LR_SHARED );
// DrawIconEx( lpdis->hDC, x, y+(height-cy)/2, hIcon, cx, cy, 0, NULL, DI_NORMAL );
HBRUSH hbrIcon = CreateSolidBrush( GetSysColor( COLOR_GRAYTEXT ) );
DrawStateW( lpdis->hDC, (HBRUSH)hbrIcon, (DRAWSTATEPROC)NULL, (LPARAM)hIcon, (WPARAM)0, x, y+(height-cy)/2, 0, 0, DST_ICON | (fDisabled ? (fSelected ? DSS_MONO : DSS_DISABLED) : DSS_NORMAL) );
DeleteObject( hbrIcon );
x += cx + 4; // space for icon
aRect.left = x;
NONCLIENTMETRICS ncm;
memset(&ncm, 0, sizeof(ncm));
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, (PVOID) &ncm, 0);
// Print default menu entry with bold font
if ( lpdis->itemState & ODS_DEFAULT )
ncm.lfMenuFont.lfWeight = FW_BOLD;
hfntOld = (HFONT) SelectObject(lpdis->hDC, (HFONT) CreateFontIndirect( &ncm.lfMenuFont ));
SIZE size;
GetTextExtentPointW( lpdis->hDC, reinterpret_cast<LPCWSTR>(pMyItem->text.getStr()), pMyItem->text.getLength(), &size );
DrawStateW( lpdis->hDC, (HBRUSH)NULL, (DRAWSTATEPROC)NULL, (LPARAM)pMyItem->text.getStr(), (WPARAM)0, aRect.left, aRect.top + (height - size.cy)/2, 0, 0, DST_TEXT | (fDisabled && !fSelected ? DSS_DISABLED : DSS_NORMAL) );
// Restore the original font and colors.
DeleteObject( SelectObject( lpdis->hDC, hbrOld ) );
DeleteObject( SelectObject( lpdis->hDC, hfntOld) );
SetTextColor(lpdis->hDC, clrPrevText);
SetBkColor(lpdis->hDC, clrPrevBkgnd);
}
// -------------------------------
// code from setup2 project
// -------------------------------
void _SHFree( void *pv )
{
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pv );
pMalloc->Release();
}
}
#define ALLOC(type, n) ((type *) HeapAlloc(GetProcessHeap(), 0, sizeof(type) * n ))
#define FREE(p) HeapFree(GetProcessHeap(), 0, p)
static OUString _SHGetSpecialFolder( int nFolderID )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
OUString aFolder;
if( hHdl == NOERROR )
{
WCHAR *lpFolderA;
lpFolderA = ALLOC( WCHAR, 16000 );
SHGetPathFromIDListW( pidl, lpFolderA );
aFolder = OUString( reinterpret_cast<const sal_Unicode*>(lpFolderA) );
FREE( lpFolderA );
_SHFree( pidl );
}
return aFolder;
}
OUString ShutdownIcon::GetAutostartFolderNameW32()
{
return _SHGetSpecialFolder(CSIDL_STARTUP);
}
static HRESULT WINAPI SHCoCreateInstance( LPVOID lpszReserved, REFCLSID clsid, LPUNKNOWN pUnkUnknown, REFIID iid, LPVOID *ppv )
{
HRESULT hResult = E_NOTIMPL;
HMODULE hModShell = GetModuleHandle( "SHELL32" );
if ( hModShell != NULL )
{
typedef HRESULT (WINAPI *SHCoCreateInstance_PROC)( LPVOID lpszReserved, REFCLSID clsid, LPUNKNOWN pUnkUnknwon, REFIID iid, LPVOID *ppv );
SHCoCreateInstance_PROC lpfnSHCoCreateInstance = (SHCoCreateInstance_PROC)GetProcAddress( hModShell, MAKEINTRESOURCE(102) );
if ( lpfnSHCoCreateInstance )
hResult = lpfnSHCoCreateInstance( lpszReserved, clsid, pUnkUnknown, iid, ppv );
}
return hResult;
}
BOOL CreateShortcut( const OUString& rAbsObject, const OUString& rAbsObjectPath,
const OUString& rAbsShortcut, const OUString& rDescription, const OUString& rParameter )
{
HRESULT hres;
IShellLink* psl;
CLSID clsid_ShellLink = CLSID_ShellLink;
CLSID clsid_IShellLink = IID_IShellLink;
hres = CoCreateInstance( clsid_ShellLink, NULL, CLSCTX_INPROC_SERVER,
clsid_IShellLink, (void**)&psl );
if( FAILED(hres) )
hres = SHCoCreateInstance( NULL, clsid_ShellLink, NULL, clsid_IShellLink, (void**)&psl );
if( SUCCEEDED(hres) )
{
IPersistFile* ppf;
psl->SetPath( OUStringToOString(rAbsObject, osl_getThreadTextEncoding()).getStr() );
psl->SetWorkingDirectory( OUStringToOString(rAbsObjectPath, osl_getThreadTextEncoding()).getStr() );
psl->SetDescription( OUStringToOString(rDescription, osl_getThreadTextEncoding()).getStr() );
if( rParameter.getLength() )
psl->SetArguments( OUStringToOString(rParameter, osl_getThreadTextEncoding()).getStr() );
CLSID clsid_IPersistFile = IID_IPersistFile;
hres = psl->QueryInterface( clsid_IPersistFile, (void**)&ppf );
if( SUCCEEDED(hres) )
{
hres = ppf->Save( reinterpret_cast<LPCOLESTR>(rAbsShortcut.getStr()), TRUE );
ppf->Release();
} else return FALSE;
psl->Release();
} else return FALSE;
return TRUE;
}
// ------------------
// install/uninstall
static bool FileExistsW( LPCWSTR lpPath )
{
bool bExists = false;
WIN32_FIND_DATAW aFindData;
HANDLE hFind = FindFirstFileW( lpPath, &aFindData );
if ( INVALID_HANDLE_VALUE != hFind )
{
bExists = true;
FindClose( hFind );
}
return bExists;
}
bool ShutdownIcon::IsQuickstarterInstalled()
{
wchar_t aPath[_MAX_PATH];
if( isNT() )
{
GetModuleFileNameW( NULL, aPath, _MAX_PATH-1);
}
else
{
char szPathA[_MAX_PATH];
GetModuleFileNameA( NULL, szPathA, _MAX_PATH-1);
// calc the string wcstr len
int nNeededWStrBuffSize = MultiByteToWideChar( CP_ACP, 0, szPathA, -1, NULL, 0 );
// copy the string if necessary
if ( nNeededWStrBuffSize > 0 )
MultiByteToWideChar( CP_ACP, 0, szPathA, -1, aPath, nNeededWStrBuffSize );
}
OUString aOfficepath( reinterpret_cast<const sal_Unicode*>(aPath) );
int i = aOfficepath.lastIndexOf((sal_Char) '\\');
if( i != -1 )
aOfficepath = aOfficepath.copy(0, i);
OUString quickstartExe(aOfficepath);
quickstartExe += OUString( RTL_CONSTASCII_USTRINGPARAM( "\\quickstart.exe" ) );
return FileExistsW( reinterpret_cast<LPCWSTR>(quickstartExe.getStr()) );
}
void ShutdownIcon::EnableAutostartW32( const rtl::OUString &aShortcut )
{
wchar_t aPath[_MAX_PATH];
if( isNT() )
GetModuleFileNameW( NULL, aPath, _MAX_PATH-1);
else
{
char szPathA[_MAX_PATH];
GetModuleFileNameA( NULL, szPathA, _MAX_PATH-1);
// calc the string wcstr len
int nNeededWStrBuffSize = MultiByteToWideChar( CP_ACP, 0, szPathA, -1, NULL, 0 );
// copy the string if necessary
if ( nNeededWStrBuffSize > 0 )
MultiByteToWideChar( CP_ACP, 0, szPathA, -1, aPath, nNeededWStrBuffSize );
}
OUString aOfficepath( reinterpret_cast<const sal_Unicode*>(aPath) );
int i = aOfficepath.lastIndexOf((sal_Char) '\\');
if( i != -1 )
aOfficepath = aOfficepath.copy(0, i);
OUString quickstartExe(aOfficepath);
quickstartExe += OUString( RTL_CONSTASCII_USTRINGPARAM( "\\quickstart.exe" ) );
CreateShortcut( quickstartExe, aOfficepath, aShortcut, OUString(), OUString() );
}
#endif // WNT
|
//===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits subtarget enumerations.
//
//===----------------------------------------------------------------------===//
#include "SubtargetEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <set>
using namespace llvm;
//
// Convenience types.
//
typedef std::vector<Record*> RecordList;
typedef std::vector<Record*>::iterator RecordListIter;
//
// Record sort by name function.
//
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
//
// Record sort by field "Name" function.
//
struct LessRecordFieldName {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
}
};
//
// Enumeration - Emit the specified class as an enumeration.
//
void SubtargetEmitter::Enumeration(std::ostream &OS,
const char *ClassName,
bool isBits) {
RecordList Defs = Records.getAllDerivedDefinitions(ClassName);
sort(Defs.begin(), Defs.end(), LessRecord());
int i = 0;
OS << "enum {\n";
for (RecordListIter RI = Defs.begin(), E = Defs.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
OS << " "
<< Instance;
if (isBits) {
OS << " = "
<< " 1 << " << i++;
}
OS << ((RI != E) ? ",\n" : "\n");
}
OS << "};\n";
}
//
// FeatureKeyValues - Emit data of all the subtarget features. Used by command
// line.
//
void SubtargetEmitter::FeatureKeyValues(std::ostream &OS) {
RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature");
sort(Features.begin(), Features.end(), LessRecord());
OS << "// Sorted (by key) array of values for CPU features.\n"
<< "static llvm::SubtargetFeatureKV FeatureKV[] = {\n";
for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
std::string Name = R->getValueAsString("Name");
std::string Desc = R->getValueAsString("Desc");
OS << " { "
<< "\"" << Name << "\", "
<< "\"" << Desc << "\", "
<< Instance
<< ((RI != E) ? " },\n" : " }\n");
}
OS << "};\n";
OS<<"\nenum {\n";
OS<<" FeatureKVSize = sizeof(FeatureKV)/sizeof(llvm::SubtargetFeatureKV)\n";
OS<<"};\n";
}
//
// CPUKeyValues - Emit data of all the subtarget processors. Used by command
// line.
//
void SubtargetEmitter::CPUKeyValues(std::ostream &OS) {
RecordList Processors = Records.getAllDerivedDefinitions("Processor");
sort(Processors.begin(), Processors.end(), LessRecordFieldName());
OS << "// Sorted (by key) array of values for CPU subtype.\n"
<< "static const llvm::SubtargetFeatureKV SubTypeKV[] = {\n";
for (RecordListIter RI = Processors.begin(), E = Processors.end();
RI != E;) {
Record *R = *RI++;
std::string Name = R->getValueAsString("Name");
Record *ProcItin = R->getValueAsDef("ProcItin");
ListInit *Features = R->getValueAsListInit("Features");
unsigned N = Features->getSize();
OS << " { "
<< "\"" << Name << "\", "
<< "\"Select the " << Name << " processor\", ";
if (N == 0) {
OS << "0";
} else {
for (unsigned i = 0; i < N; ) {
if (DefInit *DI = dynamic_cast<DefInit*>(Features->getElement(i++))) {
Record *Feature = DI->getDef();
std::string Name = Feature->getName();
OS << Name;
if (i != N) OS << " | ";
} else {
throw "Feature: " + Name +
" expected feature in processor feature list!";
}
}
}
OS << ((RI != E) ? " },\n" : " }\n");
}
OS << "};\n";
OS<<"\nenum {\n";
OS<<" SubTypeKVSize = sizeof(SubTypeKV)/sizeof(llvm::SubtargetFeatureKV)\n";
OS<<"};\n";
}
//
// ParseFeaturesFunction - Produces a subtarget specific function for parsing
// the subtarget features string.
//
void SubtargetEmitter::ParseFeaturesFunction(std::ostream &OS) {
RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature");
sort(Features.begin(), Features.end(), LessRecord());
OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
"// subtarget options.\n"
"void llvm::";
OS << Target;
OS << "Subtarget::ParseSubtargetFeatures(const std::string &FS,\n"
" const std::string &CPU) {\n"
" SubtargetFeatures Features(FS);\n"
" Features.setCPUIfNone(CPU);\n"
" uint32_t Bits = Features.getBits(SubTypeKV, SubTypeKVSize,\n"
" FeatureKV, FeatureKVSize);\n";
for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
std::string Name = R->getValueAsString("Name");
std::string Type = R->getValueAsString("Type");
std::string Attribute = R->getValueAsString("Attribute");
OS << " " << Attribute << " = (Bits & " << Instance << ") != 0;\n";
}
OS << "}\n";
}
//
// SubtargetEmitter::run - Main subtarget enumeration emitter.
//
void SubtargetEmitter::run(std::ostream &OS) {
std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
if (Targets.size() == 0)
throw std::string("ERROR: No 'Target' subclasses defined!");
if (Targets.size() != 1)
throw std::string("ERROR: Multiple subclasses of Target defined!");
Target = Targets[0]->getName();
EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
OS << "#include \"llvm/Target/SubtargetFeature.h\"\n\n";
Enumeration(OS, "FuncUnit", true);
OS<<"\n";
Enumeration(OS, "InstrItinClass", false);
OS<<"\n";
Enumeration(OS, "SubtargetFeature", true);
OS<<"\n";
FeatureKeyValues(OS);
OS<<"\n";
CPUKeyValues(OS);
OS<<"\n";
ParseFeaturesFunction(OS);
}
Simplify.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@24015 91177308-0d34-0410-b5e6-96231b3b80d8
//===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits subtarget enumerations.
//
//===----------------------------------------------------------------------===//
#include "SubtargetEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <set>
using namespace llvm;
//
// Convenience types.
//
typedef std::vector<Record*> RecordList;
typedef std::vector<Record*>::iterator RecordListIter;
//
// Record sort by name function.
//
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
//
// Record sort by field "Name" function.
//
struct LessRecordFieldName {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
}
};
//
// Enumeration - Emit the specified class as an enumeration.
//
void SubtargetEmitter::Enumeration(std::ostream &OS,
const char *ClassName,
bool isBits) {
RecordList Defs = Records.getAllDerivedDefinitions(ClassName);
sort(Defs.begin(), Defs.end(), LessRecord());
int i = 0;
OS << "enum {\n";
for (RecordListIter RI = Defs.begin(), E = Defs.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
OS << " "
<< Instance;
if (isBits) {
OS << " = "
<< " 1 << " << i++;
}
OS << ((RI != E) ? ",\n" : "\n");
}
OS << "};\n";
}
//
// FeatureKeyValues - Emit data of all the subtarget features. Used by command
// line.
//
void SubtargetEmitter::FeatureKeyValues(std::ostream &OS) {
RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature");
sort(Features.begin(), Features.end(), LessRecord());
OS << "// Sorted (by key) array of values for CPU features.\n"
<< "static llvm::SubtargetFeatureKV FeatureKV[] = {\n";
for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
std::string Name = R->getValueAsString("Name");
std::string Desc = R->getValueAsString("Desc");
OS << " { "
<< "\"" << Name << "\", "
<< "\"" << Desc << "\", "
<< Instance
<< ((RI != E) ? " },\n" : " }\n");
}
OS << "};\n";
OS<<"\nenum {\n";
OS<<" FeatureKVSize = sizeof(FeatureKV)/sizeof(llvm::SubtargetFeatureKV)\n";
OS<<"};\n";
}
//
// CPUKeyValues - Emit data of all the subtarget processors. Used by command
// line.
//
void SubtargetEmitter::CPUKeyValues(std::ostream &OS) {
RecordList Processors = Records.getAllDerivedDefinitions("Processor");
sort(Processors.begin(), Processors.end(), LessRecordFieldName());
OS << "// Sorted (by key) array of values for CPU subtype.\n"
<< "static const llvm::SubtargetFeatureKV SubTypeKV[] = {\n";
for (RecordListIter RI = Processors.begin(), E = Processors.end();
RI != E;) {
Record *R = *RI++;
std::string Name = R->getValueAsString("Name");
Record *ProcItin = R->getValueAsDef("ProcItin");
ListInit *Features = R->getValueAsListInit("Features");
unsigned N = Features->getSize();
OS << " { "
<< "\"" << Name << "\", "
<< "\"Select the " << Name << " processor\", ";
if (N == 0) {
OS << "0";
} else {
for (unsigned i = 0; i < N; ) {
if (DefInit *DI = dynamic_cast<DefInit*>(Features->getElement(i++))) {
Record *Feature = DI->getDef();
std::string Name = Feature->getName();
OS << Name;
if (i != N) OS << " | ";
} else {
throw "Feature: " + Name +
" expected feature in processor feature list!";
}
}
}
OS << ((RI != E) ? " },\n" : " }\n");
}
OS << "};\n";
OS<<"\nenum {\n";
OS<<" SubTypeKVSize = sizeof(SubTypeKV)/sizeof(llvm::SubtargetFeatureKV)\n";
OS<<"};\n";
}
//
// ParseFeaturesFunction - Produces a subtarget specific function for parsing
// the subtarget features string.
//
void SubtargetEmitter::ParseFeaturesFunction(std::ostream &OS) {
RecordList Features = Records.getAllDerivedDefinitions("SubtargetFeature");
sort(Features.begin(), Features.end(), LessRecord());
OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
"// subtarget options.\n"
"void llvm::";
OS << Target;
OS << "Subtarget::ParseSubtargetFeatures(const std::string &FS,\n"
" const std::string &CPU) {\n"
" SubtargetFeatures Features(FS);\n"
" Features.setCPUIfNone(CPU);\n"
" uint32_t Bits = Features.getBits(SubTypeKV, SubTypeKVSize,\n"
" FeatureKV, FeatureKVSize);\n";
for (RecordListIter RI = Features.begin(), E = Features.end(); RI != E;) {
Record *R = *RI++;
std::string Instance = R->getName();
std::string Name = R->getValueAsString("Name");
std::string Type = R->getValueAsString("Type");
std::string Attribute = R->getValueAsString("Attribute");
OS << " " << Attribute << " = (Bits & " << Instance << ") != 0;\n";
}
OS << "}\n";
}
//
// SubtargetEmitter::run - Main subtarget enumeration emitter.
//
void SubtargetEmitter::run(std::ostream &OS) {
Target = CodeGenTarget().getName();
EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
OS << "#include \"llvm/Target/SubtargetFeature.h\"\n\n";
Enumeration(OS, "FuncUnit", true);
OS<<"\n";
Enumeration(OS, "InstrItinClass", false);
OS<<"\n";
Enumeration(OS, "SubtargetFeature", true);
OS<<"\n";
FeatureKeyValues(OS);
OS<<"\n";
CPUKeyValues(OS);
OS<<"\n";
ParseFeaturesFunction(OS);
}
|
/*************************************************************************
*
* $RCSfile: filedlghelper.cxx,v $
*
* $Revision: 1.62 $
*
* last change: $Author: fs $ $Date: 2001-10-12 13:53:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _LIST_
#include <list>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include "filedlghelper.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
#ifndef _SVT_HELPID_HRC
#include <svtools/helpid.hrc>
#endif
#ifndef _SFXAPP_HXX
#include "app.hxx"
#endif
#ifndef _SFXDOCFILE_HXX
#include "docfile.hxx"
#endif
#ifndef _SFX_OBJFAC_HXX
#include "docfac.hxx"
#endif
#ifndef _SFX_FCONTNR_HXX
#include "fcontnr.hxx"
#endif
#ifndef _SFX_OPENFLAG_HXX
#include "openflag.hxx"
#endif
#ifndef _SFX_PASSWD_HXX
#include <passwd.hxx>
#endif
#ifndef _SFX_SFXRESID_HXX
#include "sfxresid.hxx"
#endif
#ifndef _SFXSIDS_HRC
#include "sfxsids.hrc"
#endif
#ifndef _SFX_EXPLORER_HRC
#include "explorer.hrc"
#endif
#ifndef _SFX_FILEDLGHELPER_HRC
#include "filedlghelper.hrc"
#endif
#ifndef SFX2_FILTERGROUPING_HXX
#include "filtergrouping.hxx"
#endif
#ifndef _VECTOR_
#include <vector>
#endif
//-----------------------------------------------------------------------------
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
#define IODLG_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Save"))
#define IMPGRF_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Graph"))
#define USERITEM_NAME OUString::createFromAscii( "UserItem" )
//-----------------------------------------------------------------------------
namespace sfx2 {
String EncodeSpaces_Impl( const String& rSource );
String DecodeSpaces_Impl( const String& rSource );
// ------------------------------------------------------------------------
class FileDialogHelper_Impl : public WeakImplHelper1< XFilePickerListener >
{
friend class FileDialogHelper;
Reference < XFilePicker > mxFileDlg;
static ::std::vector< Reference < XFilePicker > >
maDialogQueue;
SfxFilterMatcher *mpMatcher;
GraphicFilter *mpGraphicFilter;
OUString maPath;
OUString maCurFilter;
OUString maSelectFilter;
Timer maPreViewTimer;
Graphic maGraphic;
FileDialogHelper* mpParent;
const short m_nDialogType;
ErrCode mnError;
sal_Bool mbHasPassword : 1;
sal_Bool mbIsPwdEnabled : 1;
sal_Bool m_bHaveFilterOptions : 1;
sal_Bool mbHasVersions : 1;
sal_Bool mbHasAutoExt : 1;
sal_Bool mbHasLink : 1;
sal_Bool mbHasPreview : 1;
sal_Bool mbShowPreview : 1;
sal_Bool mbIsSaveDlg : 1;
sal_Bool mbDeleteMatcher : 1;
sal_Bool mbInsert : 1;
sal_Bool mbSystemPicker : 1;
private:
void addFilters( sal_uInt32 nFlags,
const SfxObjectFactory& rFactory );
void addFilter( const OUString& rFilterName,
const OUString& rExtension );
void addGraphicFilter();
void enablePasswordBox();
void updateFilterOptionsBox();
void updateVersions();
void dispose();
void loadConfig();
void saveConfig();
const SfxFilter* getCurentSfxFilter();
sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable );
ErrCode getGraphic( const OUString& rURL, Graphic& rGraphic ) const;
void setDefaultValues();
void preExecute();
void postExecute();
sal_Int16 implDoExecute();
void pushBackPicker();
void popPicker();
DECL_LINK( TimeOutHdl_Impl, Timer* );
DECL_LINK( HandleEvent, FileDialogHelper* );
public:
// XFilePickerListener methods
virtual void SAL_CALL fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual OUString SAL_CALL helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL dialogSizeChanged() throw ( RuntimeException );
// XEventListener methods
virtual void SAL_CALL disposing( const EventObject& Source ) throw ( RuntimeException );
// handle XFilePickerListener events
void handleFileSelectionChanged( const FilePickerEvent& aEvent );
void handleDirectoryChanged( const FilePickerEvent& aEvent );
OUString handleHelpRequested( const FilePickerEvent& aEvent );
void handleControlStateChanged( const FilePickerEvent& aEvent );
void handleDialogSizeChanged();
// Own methods
FileDialogHelper_Impl( FileDialogHelper* pParent,
const short nDialogType,
sal_uInt32 nFlags );
~FileDialogHelper_Impl();
ErrCode execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter );
ErrCode execute();
void setPath( const OUString& rPath );
void setFilter( const OUString& rFilter );
OUString getPath() const;
OUString getFilter() const;
OUString getRealFilter() const;
ErrCode getGraphic( Graphic& rGraphic ) const;
static Reference< XFilePicker > getTopMostFilePicker( );
};
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
::std::vector< Reference < XFilePicker > > FileDialogHelper_Impl::maDialogQueue;
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->FileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->DirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper_Impl::helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return mpParent->HelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->ControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogSizeChanged() throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->DialogSizeChanged();
}
// ------------------------------------------------------------------------
// handle XFilePickerListener events
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleFileSelectionChanged( const FilePickerEvent& aEvent )
{
if ( mbHasVersions )
updateVersions();
if ( mbShowPreview )
maPreViewTimer.Start();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDirectoryChanged( const FilePickerEvent& aEvent )
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::handleHelpRequested( const FilePickerEvent& aEvent )
{
//!!! todo: cache the help strings (here or TRA)
ULONG nHelpId = 0;
// mapping from element id -> help id
switch ( aEvent.ElementId )
{
case ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION :
nHelpId = HID_FILESAVE_AUTOEXTENSION;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PASSWORD :
nHelpId = HID_FILESAVE_SAVEWITHPASSWORD;
break;
case ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS :
nHelpId = HID_FILESAVE_CUSTOMIZEFILTER;
break;
case ExtendedFilePickerElementIds::CHECKBOX_READONLY :
nHelpId = HID_FILEOPEN_READONLY;
break;
case ExtendedFilePickerElementIds::CHECKBOX_LINK :
nHelpId = HID_FILEDLG_LINK_CB;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW :
nHelpId = HID_FILEDLG_PREVIEW_CB;
break;
case ExtendedFilePickerElementIds::PUSHBUTTON_PLAY :
nHelpId = HID_FILESAVE_DOPLAY;
break;
case ExtendedFilePickerElementIds::LISTBOX_VERSION_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_VERSION :
nHelpId = HID_FILEOPEN_VERSION;
break;
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE :
nHelpId = HID_FILESAVE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE :
nHelpId = HID_FILEOPEN_IMAGE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::CHECKBOX_SELECTION :
nHelpId = HID_FILESAVE_SELECTION;
break;
default:
DBG_ERRORFILE( "invalid element id" );
}
OUString aHelpText;
Help* pHelp = Application::GetHelp();
if ( pHelp )
aHelpText = String( pHelp->GetHelpText( nHelpId, NULL ) );
return aHelpText;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleControlStateChanged( const FilePickerEvent& aEvent )
{
switch ( aEvent.ElementId )
{
case CommonFilePickerElementIds::LISTBOX_FILTER:
updateFilterOptionsBox();
enablePasswordBox();
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW:
if ( mbHasPreview )
{
Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a preview
if ( xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
sal_Bool bShowPreview = sal_False;
if ( aValue >>= bShowPreview )
{
mbShowPreview = bShowPreview;
TimeOutHdl_Impl( NULL );
}
}
catch( Exception )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::controlStateChanged: caught an exception!" );
}
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDialogSizeChanged()
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
// XEventListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::disposing( const EventObject& Source ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
dispose();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::dispose()
{
if ( mxFileDlg.is() )
{
// remove the event listener
Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
if ( xNotifier.is() )
xNotifier->removeFilePickerListener( this );
mxFileDlg.clear();
}
}
// ------------------------------------------------------------------------
const SfxFilter* FileDialogHelper_Impl::getCurentSfxFilter()
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
::rtl::OUString aFilterName = xFltMgr->getCurrentFilter();
const SfxFilter* pFilter = NULL;
if ( mpMatcher )
pFilter = mpMatcher->GetFilter4UIName( aFilterName, 0, SFX_FILTER_NOTINFILEDLG );
return pFilter;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable )
{
sal_Bool bIsEnabled = sal_False;
Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
try
{
xCtrlAccess->enableControl( _nExtendedControlId, _bEnable );
bIsEnabled = _bEnable;
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::updateExtendedControl: caught an exception!" );
}
}
return bIsEnabled;
}
// ------------------------------------------------------------------------
struct CheckFilterOptionsCapability
{
sal_Bool operator() ( const SfxFilter* _pFilter )
{
return _pFilter
&& ( 0 != ( _pFilter->GetFilterFlags() & SFX_FILTER_USESOPTIONS ) );
}
};
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateFilterOptionsBox()
{
if ( !m_bHaveFilterOptions )
return;
updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS,
CheckFilterOptionsCapability()( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
struct CheckPasswordCapability
{
sal_Bool operator() ( const SfxFilter* _pFilter )
{
return _pFilter
&& _pFilter->UsesStorage()
&& ( SOFFICE_FILEFORMAT_60 <= _pFilter->GetVersion() );
}
};
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::enablePasswordBox()
{
if ( ! mbHasPassword )
return;
mbIsPwdEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_PASSWORD,
CheckPasswordCapability()( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateVersions()
{
Sequence < OUString > aEntries;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
INetURLObject aObj( aPathSeq[0] );
if ( ( aObj.GetProtocol() == INET_PROT_FILE ) &&
( utl::UCBContentHelper::IsDocument( aObj.GetMainURL( INetURLObject::NO_DECODE ) ) ) )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ),
SFX_STREAM_READONLY_MAKECOPY, TRUE );
const SfxVersionTableDtor* pVerTable = aMed.GetVersionList();
if ( pVerTable )
{
SvStringsDtor* pVersions = pVerTable->GetVersions();
aEntries.realloc( pVersions->Count() + 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
for ( USHORT i = 0; i < pVersions->Count(); i++ )
aEntries[ i + 1 ] = OUString( *(pVersions->GetObject(i)) );
delete pVersions;
}
else if ( aMed.GetStorage() )
{
SfxFilterFlags nMust = SFX_FILTER_IMPORT | SFX_FILTER_OWN, nDont = SFX_FILTER_NOTINSTALLED | SFX_FILTER_STARONEFILTER;
if ( SFX_APP()->GetFilterMatcher().GetFilter4ClipBoardId( aMed.GetStorage()->GetFormat(), nMust, nDont ) )
{
aEntries.realloc( 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
}
}
}
}
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::DELETE_ITEMS, aValue );
}
catch( IllegalArgumentException ){}
sal_Int32 nCount = aEntries.getLength();
if ( nCount )
{
try
{
aValue <<= aEntries;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::ADD_ITEMS, aValue );
Any aPos;
aPos <<= (sal_Int32) 0;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::SET_SELECT_ITEM, aPos );
}
catch( IllegalArgumentException ){}
}
}
// -----------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, TimeOutHdl_Impl, Timer*, EMPTYARG )
{
if ( !mbHasPreview )
return 0;
maGraphic.Clear();
Any aAny;
Reference < XFilePreview > xFilePicker( mxFileDlg, UNO_QUERY );
if ( ! xFilePicker.is() )
return 0;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( mbShowPreview && ( aPathSeq.getLength() == 1 ) )
{
OUString aURL = aPathSeq[0];
if ( ERRCODE_NONE == getGraphic( aURL, maGraphic ) )
{
Bitmap aBmp = maGraphic.GetBitmap();
// scale the bitmap to the correct size
sal_Int32 nOutWidth = xFilePicker->getAvailableWidth();
sal_Int32 nOutHeight = xFilePicker->getAvailableHeight();
sal_Int32 nBmpWidth = aBmp.GetSizePixel().Width();
sal_Int32 nBmpHeight = aBmp.GetSizePixel().Height();
double nXRatio = (double) nOutWidth / nBmpWidth;
double nYRatio = (double) nOutHeight / nBmpHeight;
if ( nXRatio < nYRatio )
aBmp.Scale( nXRatio, nXRatio );
else
aBmp.Scale( nYRatio, nYRatio );
nBmpWidth = aBmp.GetSizePixel().Width();
nBmpHeight = aBmp.GetSizePixel().Height();
sal_Int32 nMidX = ( nOutWidth - nBmpWidth ) / 2;
sal_Int32 nMidY = ( nOutHeight - nBmpHeight ) / 2;
Rectangle aSrcRect( 0, 0, nBmpWidth, nBmpHeight );
Rectangle aDstRect( nMidX, nMidY, nMidX + nBmpWidth, nMidY + nBmpHeight );
// #92765# Have to conserve bitmap palette. There is no method setting it explicitely,
// thus doing it this way. Performance penalty is low, as bitmap is refcounted.
Bitmap aScaledBmp( aBmp );
aScaledBmp.SetSizePixel( Size(nOutWidth, nOutHeight) );
aScaledBmp.Erase( Color( COL_WHITE ) );
aScaledBmp.CopyPixel( aDstRect, aSrcRect, &aBmp );
// and copy it into the Any
SvMemoryStream aData;
aData << aScaledBmp;
Sequence < sal_Int8 > aBuffer( (sal_Int8*) aData.GetData(), aData.GetSize() );
aAny <<= aBuffer;
}
}
try
{
// clear the preview window
xFilePicker->setImage( FilePreviewImageFormats::BITMAP, aAny );
}
catch( IllegalArgumentException ){}
return 0;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( const OUString& rURL,
Graphic& rGraphic ) const
{
if ( utl::UCBContentHelper::IsFolder( rURL ) )
return ERRCODE_IO_NOTAFILE;
if ( !mpGraphicFilter )
return ERRCODE_IO_NOTSUPPORTED;
// select graphic filter from dialog filter selection
OUString aCurFilter( getFilter() );
sal_uInt16 nFilter = aCurFilter.getLength() && mpGraphicFilter->GetImportFormatCount()
? mpGraphicFilter->GetImportFormatNumber( aCurFilter )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURLObj( rURL );
if ( aURLObj.HasError() || INET_PROT_NOT_VALID == aURLObj.GetProtocol() )
{
aURLObj.SetSmartProtocol( INET_PROT_FILE );
aURLObj.SetSmartURL( rURL );
}
ErrCode nRet = ERRCODE_NONE;
sal_uInt32 nFilterImportFlags = GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
// non-local?
if ( INET_PROT_FILE != aURLObj.GetProtocol() )
{
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( rURL, STREAM_READ );
if( pStream )
nRet = mpGraphicFilter->ImportGraphic( rGraphic, rURL, *pStream, nFilter, NULL, nFilterImportFlags );
else
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
delete pStream;
}
else
{
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
}
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( Graphic& rGraphic ) const
{
ErrCode nRet = ERRCODE_NONE;
if ( ! maGraphic )
{
OUString aPath;;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
if ( aPath.getLength() )
nRet = getGraphic( aPath, rGraphic );
else
nRet = ERRCODE_IO_GENERAL;
}
else
rGraphic = maGraphic;
return nRet;
}
// ------------------------------------------------------------------------
sal_Bool lcl_isSystemFilePicker( const Reference< XFilePicker >& _rxFP )
{
try
{
Reference< XServiceInfo > xSI( _rxFP, UNO_QUERY );
if ( xSI.is() && xSI->supportsService( ::rtl::OUString::createFromAscii( "com.sun.star.ui.dialogs.SystemFilePicker" ) ) )
return sal_True;
}
catch( const Exception& )
{
}
return sal_False;
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper_Impl::FileDialogHelper_Impl( FileDialogHelper* pParent,
const short nDialogType,
sal_uInt32 nFlags )
:m_nDialogType( nDialogType )
{
OUString aService( RTL_CONSTASCII_USTRINGPARAM( FILE_OPEN_SERVICE_NAME ) );
Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
// create the file open dialog
// the flags can be SFXWB_INSERT or SFXWB_MULTISELECTION
mpParent = pParent;
mnError = ERRCODE_NONE;
mbHasAutoExt = sal_False;
mbHasPassword = sal_False;
m_bHaveFilterOptions = sal_False;
mbIsPwdEnabled = sal_True;
mbHasVersions = sal_False;
mbHasPreview = sal_False;
mbShowPreview = sal_False;
mbHasLink = sal_False;
mbDeleteMatcher = sal_False;
mbInsert = SFXWB_INSERT == ( nFlags & SFXWB_INSERT );
mbIsSaveDlg = sal_False;
mpMatcher = NULL;
mpGraphicFilter = NULL;
mxFileDlg = Reference < XFilePicker > ( xFactory->createInstance( aService ), UNO_QUERY );
mbSystemPicker = lcl_isSystemFilePicker( mxFileDlg );
Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
Reference< XInitialization > xInit( mxFileDlg, UNO_QUERY );
if ( ! mxFileDlg.is() || ! xNotifier.is() )
{
mnError = ERRCODE_ABORT;
return;
}
Sequence < Any > aServiceType(1);
switch ( m_nDialogType ) {
case FILEOPEN_SIMPLE:
aServiceType[0] <<= TemplateDescription::FILEOPEN_SIMPLE;
break;
case FILESAVE_SIMPLE:
aServiceType[0] <<= TemplateDescription::FILESAVE_SIMPLE;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD;
mbHasPassword = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS;
mbHasPassword = sal_True;
m_bHaveFilterOptions = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_SELECTION:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_TEMPLATE:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_TEMPLATE;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
aServiceType[0] <<= TemplateDescription::FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILEOPEN_PLAY:
aServiceType[0] <<= TemplateDescription::FILEOPEN_PLAY;
break;
case FILEOPEN_READONLY_VERSION:
aServiceType[0] <<= TemplateDescription::FILEOPEN_READONLY_VERSION;
mbHasVersions = sal_True;
break;
case FILEOPEN_LINK_PREVIEW:
aServiceType[0] <<= TemplateDescription::FILEOPEN_LINK_PREVIEW;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILESAVE_AUTOEXTENSION:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
default:
aServiceType[0] <<= TemplateDescription::FILEOPEN_SIMPLE;
DBG_ERRORFILE( "FileDialogHelper::ctor with unknown type" );
}
if ( xInit.is() )
xInit->initialize( aServiceType );
// set multiselection mode
if ( nFlags & SFXWB_MULTISELECTION )
mxFileDlg->setMultiSelectionMode( sal_True );
if ( mbHasLink ) // generate graphic filter only on demand
addGraphicFilter();
// the "insert file" dialog needs another title
if ( mbInsert )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_INSERT ) ) ) );
Reference < XFilePickerControlAccess > xExtDlg( mxFileDlg, UNO_QUERY );
if ( xExtDlg.is() )
{
try
{
xExtDlg->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK,
OUString( String( SfxResId( STR_SFX_EXPLORERFILE_BUTTONINSERT ) ) ) );
}
catch( IllegalArgumentException ){}
}
}
// add the event listener
xNotifier->addFilePickerListener( this );
}
// ------------------------------------------------------------------------
FileDialogHelper_Impl::~FileDialogHelper_Impl()
{
delete mpGraphicFilter;
if ( mbDeleteMatcher )
delete mpMatcher;
maPreViewTimer.SetTimeoutHdl( Link() );
}
#define nMagic (sal_Int16) 0xFFFF
class PickerThread_Impl : public ::vos::OThread
{
Reference < XFilePicker > mxPicker;
::vos::OMutex maMutex;
virtual void SAL_CALL run();
sal_Int16 mnRet;
public:
PickerThread_Impl( const Reference < XFilePicker >& rPicker )
: mxPicker( rPicker ), mnRet(nMagic) {}
sal_Int16 GetReturnValue()
{ ::vos::OGuard aGuard( maMutex ); return mnRet; }
void SetReturnValue( sal_Int16 aRetValue )
{ ::vos::OGuard aGuard( maMutex ); mnRet = aRetValue; }
};
void SAL_CALL PickerThread_Impl::run()
{
try
{
sal_Int16 n = mxPicker->execute();
SetReturnValue( n );
}
catch( RuntimeException& )
{
SetReturnValue( ExecutableDialogResults::CANCEL );
DBG_ERRORFILE( "RuntimeException caught" );
}
}
// ------------------------------------------------------------------------
Reference< XFilePicker > FileDialogHelper_Impl::getTopMostFilePicker( )
{
Reference< XFilePicker > xReturn;
DBG_ASSERT( !maDialogQueue.empty(), "FileDialogHelper_Impl::popPicker: no active picker!" );
if ( !maDialogQueue.empty() )
xReturn = *maDialogQueue.begin();
return xReturn;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::pushBackPicker()
{
DBG_ASSERT( mxFileDlg.is(), "FileDialogHelper_Impl::pushBackPicker: have no picker!" );
maDialogQueue.push_back( mxFileDlg );
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::popPicker()
{
DBG_ASSERT( !maDialogQueue.empty(), "FileDialogHelper_Impl::popPicker: no picker pushed!" );
if ( !maDialogQueue.empty() )
{
DBG_ASSERT( maDialogQueue.begin()->get() == mxFileDlg.get(), "FileDialogHelper_Impl::popPicker: invalid top-most queue element!" );
maDialogQueue.pop_back();
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::preExecute()
{
loadConfig();
setDefaultValues();
enablePasswordBox();
updateFilterOptionsBox();
pushBackPicker();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::postExecute()
{
popPicker();
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper_Impl::implDoExecute()
{
preExecute();
sal_Int16 nRet = ExecutableDialogResults::CANCEL;
if ( mbSystemPicker )
{
PickerThread_Impl* pThread = new PickerThread_Impl( mxFileDlg );
pThread->create();
while ( pThread->GetReturnValue() == nMagic )
Application::Yield();
pThread->join();
nRet = pThread->GetReturnValue();
delete pThread;
}
else
{
try
{
nRet = mxFileDlg->execute();
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
postExecute();
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
rpSet = NULL;
rpURLList = NULL;
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
if ( ExecutableDialogResults::CANCEL != implDoExecute() )
{
saveConfig();
// create an itemset
rpSet = new SfxAllItemSet( SFX_APP()->GetPool() );
Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a password box
if ( mbHasPassword && mbIsPwdEnabled && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
if ( ( aValue >>= bPassWord ) && bPassWord )
{
// ask for the password
SfxPasswordDialog aPasswordDlg( NULL );
aPasswordDlg.ShowExtras( SHOWEXTRAS_CONFIRM );
BOOL bOK = FALSE;
short nRet = aPasswordDlg.Execute();
if ( RET_OK == nRet )
{
String aPasswd = aPasswordDlg.GetPassword();
rpSet->Put( SfxStringItem( SID_PASSWORD, aPasswd ) );
}
else
return ERRCODE_ABORT;
}
}
catch( IllegalArgumentException ){}
}
// set the read-only flag. When inserting a file, this flag is always set
if ( mbInsert )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
else
{
if ( ( FILEOPEN_READONLY_VERSION == m_nDialogType ) && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_READONLY, 0 );
sal_Bool bReadOnly = sal_False;
if ( ( aValue >>= bReadOnly ) && bReadOnly )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, bReadOnly ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
}
if ( mbHasVersions && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::GET_SELECTED_ITEM );
sal_Int16 nVersion = 0;
if ( aValue >>= nVersion )
rpSet->Put( SfxInt16Item( SID_VERSION, nVersion ) );
}
catch( IllegalArgumentException ){}
}
// set the filter
rFilter = getRealFilter();
// fill the rpURLList
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() )
{
rpURLList = new SvStringsDtor;
if ( aPathSeq.getLength() == 1 )
{
OUString aFileURL( aPathSeq[0] );
String* pURL = new String( aFileURL );
rpURLList->Insert( pURL, 0 );
}
else
{
INetURLObject aPath( aPathSeq[0] );
aPath.setFinalSlash();
for ( USHORT i = 1; i < aPathSeq.getLength(); ++i )
{
if ( i == 1 )
aPath.Append( aPathSeq[i] );
else
aPath.setName( aPathSeq[i] );
String* pURL = new String( aPath.GetMainURL( INetURLObject::NO_DECODE ) );
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
return ERRCODE_NONE;
}
else
return ERRCODE_ABORT;
}
else
return ERRCODE_ABORT;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute()
{
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
sal_Int16 nRet = implDoExecute();
maPath = mxFileDlg->getDisplayDirectory();
if ( ExecutableDialogResults::CANCEL == nRet )
return ERRCODE_ABORT;
else
{
saveConfig();
return ERRCODE_NONE;
}
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getPath() const
{
OUString aPath;
if ( mxFileDlg.is() )
aPath = mxFileDlg->getDisplayDirectory();
if ( !aPath.getLength() )
aPath = maPath;
return aPath;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getFilter() const
{
OUString aFilter;
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( xFltMgr.is() )
aFilter = xFltMgr->getCurrentFilter();
else
aFilter = maCurFilter;
return aFilter;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getRealFilter() const
{
OUString aFilter;
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( xFltMgr.is() )
aFilter = xFltMgr->getCurrentFilter();
if ( ! aFilter.getLength() )
aFilter = maCurFilter;
if ( aFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter4UIName(
aFilter, 0, SFX_FILTER_NOTINFILEDLG );
if ( pFilter )
aFilter = pFilter->GetName();
}
return aFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setPath( const OUString& rPath )
{
// We check wether the path points to a dirctory or not
//
// We set the display directory only, when it is on a local / remote(?)
// filesystem
if ( ! rPath.getLength() )
return;
/* if (! utl::LocalFileHelper::IsLocalFile( rPath ) )
{
return;
}*/
OUString aName;
OUString aPath;
INetURLObject aObj( rPath );
// if the given path isn't a folder, we cut off the last part
// and take it as filename and the rest of the path should be
// the folder
if ( ! utl::UCBContentHelper::IsFolder( rPath ) )
{
aName = aObj.GetName( INetURLObject::DECODE_WITH_CHARSET );
aObj.removeSegment();
}
aPath = aObj.GetMainURL( INetURLObject::NO_DECODE );
if ( ! utl::UCBContentHelper::IsFolder( aPath ) )
return;
else
maPath = aPath;
// set the path
if ( mxFileDlg.is() )
{
try
{
if ( maPath.getLength() )
mxFileDlg->setDisplayDirectory( maPath );
if ( aName.getLength() )
mxFileDlg->setDefaultName( aName );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFilter( const OUString& rFilter )
{
maCurFilter = rFilter;
if ( rFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter(
rFilter, 0, SFX_FILTER_NOTINFILEDLG );
if ( pFilter )
maCurFilter = pFilter->GetUIName();
}
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( maCurFilter.getLength() && xFltMgr.is() )
{
try
{
xFltMgr->setCurrentFilter( maCurFilter );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilters( sal_uInt32 nFlags,
const SfxObjectFactory& rFactory )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
if ( !&rFactory )
{
SfxApplication *pSfxApp = SFX_APP();
mpMatcher = &pSfxApp->GetFilterMatcher();
mbDeleteMatcher = sal_False;
}
else
{
mpMatcher = new SfxFilterMatcher( rFactory.GetFilterContainer() );
mbDeleteMatcher = sal_True;
}
USHORT nFilterFlags = SFX_FILTER_EXPORT;
if( WB_OPEN == ( nFlags & WB_OPEN ) )
nFilterFlags = SFX_FILTER_IMPORT;
sal_Bool bHasAll = sal_False;
SfxFilterMatcherIter aIter( mpMatcher, nFilterFlags, SFX_FILTER_INTERNAL | SFX_FILTER_NOTINFILEDLG );
// append the filters
::rtl::OUString sFirstFilter;
if ( WB_OPEN == ( nFlags & WB_OPEN ) )
::sfx2::appendFiltersForOpen( aIter, xFltMgr, sFirstFilter );
else
::sfx2::appendFilters( aIter, xFltMgr, sFirstFilter );
// set our initial selected filter (if we do not already have one)
if ( maSelectFilter.getLength() )
maSelectFilter = sFirstFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilter( const OUString& rFilterName,
const OUString& rExtension )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
try
{
xFltMgr->appendFilter( rFilterName, rExtension );
if ( !maSelectFilter.getLength() )
maSelectFilter = rFilterName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( rFilterName ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addGraphicFilter()
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
mpGraphicFilter = new GraphicFilter;
USHORT i, j, nCount = mpGraphicFilter->GetImportFormatCount();
// compute the extension string for all known import filters
String aExtensions;
for ( i = 0; i < nCount; i++ )
{
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
}
#if defined(WIN) || defined(WNT)
if ( aExtensions.Len() > 240 )
aExtensions = String::CreateFromAscii( FILEDIALOG_FILTER_ALL );
#endif
try
{
OUString aAllFilterName = String( SfxResId( STR_SFX_IMPORT_ALL ) );
xFltMgr->appendFilter( aAllFilterName, aExtensions );
maSelectFilter = aAllFilterName;
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
// Now add the filter
for ( i = 0; i < nCount; i++ )
{
String aName = mpGraphicFilter->GetImportFormatName( i );
String aExtensions;
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
try
{
xFltMgr->appendFilter( aName, aExtensions );
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
}
}
// ------------------------------------------------------------------------
#define GRF_CONFIG_STR " "
#define STD_CONFIG_STR "1 "
void FileDialogHelper_Impl::saveConfig()
{
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aDlgOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData = String::CreateFromAscii( GRF_CONFIG_STR );
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
sal_Bool bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 1, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
INetURLObject aObj( getPath() );
if ( aObj.GetProtocol() == INET_PROT_FILE )
aUserData.SetToken( 2, ' ', aObj.GetMainURL( INetURLObject::NO_DECODE ) );
String aFilter = getFilter();
aFilter = EncodeSpaces_Impl( aFilter );
aUserData.SetToken( 3, ' ', aFilter );
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
catch( IllegalArgumentException ){}
}
else
{
sal_Bool bWriteConfig = sal_False;
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData = String::CreateFromAscii( STD_CONFIG_STR );
if ( aDlgOpt.Exists() )
{
Any aUserItem = aDlgOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( mbHasAutoExt )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 );
sal_Bool bAutoExt = sal_True;
aValue >>= bAutoExt;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bAutoExt ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( ! mbIsSaveDlg )
{
OUString aPath = getPath();
if ( aPath.getLength() &&
utl::LocalFileHelper::IsLocalFile( aPath ) )
{
aUserData.SetToken( 1, ' ', aPath );
bWriteConfig = sal_True;
}
}
if ( bWriteConfig )
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
SfxApplication *pSfxApp = SFX_APP();
pSfxApp->SetLastDir_Impl( getPath() );
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::loadConfig()
{
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aViewOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( aUserData.Len() > 0 )
{
try
{
// respect the last "insert as link" state
sal_Bool bLink = (sal_Bool) aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= bLink;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aValue );
// respect the last "show preview" state
sal_Bool bShowPreview = (sal_Bool) aUserData.GetToken( 1, ' ' ).ToInt32();
aValue <<= bShowPreview;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0, aValue );
if ( ! maPath.getLength() )
{
SfxApplication *pSfxApp = SFX_APP();
OUString aPath = pSfxApp->GetLastDir_Impl();
if ( !aPath.getLength() )
aPath = aUserData.GetToken( 2, ' ' );
setPath( aPath );
}
if ( ! maCurFilter.getLength() )
{
String aFilter = aUserData.GetToken( 3, ' ' );
aFilter = DecodeSpaces_Impl( aFilter );
setFilter( aFilter );
}
// set the member so we know that we have to show the preview
mbShowPreview = bShowPreview;
}
catch( IllegalArgumentException ){}
}
}
else
{
SvtViewOptions aViewOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( ! aUserData.Len() )
aUserData = String::CreateFromAscii( STD_CONFIG_STR );
if ( ! maPath.getLength() )
{
SfxApplication *pSfxApp = SFX_APP();
OUString aPath = pSfxApp->GetLastDir_Impl();
if ( !aPath.getLength() )
aPath = aUserData.GetToken( 1, ' ' );
setPath( aPath );
}
if ( mbHasAutoExt )
{
sal_Int32 nFlag = aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setDefaultValues()
{
// when no filter is set, we set the curentFilter to <all>
if ( !maCurFilter.getLength() && maSelectFilter.getLength() )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
try
{
xFltMgr->setCurrentFilter( maSelectFilter );
}
catch( IllegalArgumentException )
{}
}
// when no path is set, we use the standard 'work' folder
if ( ! maPath.getLength() )
{
OUString aWorkFolder = SvtPathOptions().GetWorkPath();
mxFileDlg->setDisplayDirectory( aWorkFolder );
// INetURLObject aStdDirObj( SvtPathOptions().GetWorkPath() );
//SetStandardDir( aStdDirObj.GetMainURL( INetURLObject::NO_DECODE ) );
}
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_uInt32 nFlags,
const SfxObjectFactory& rFact )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, rFact );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_uInt32 nFlags )
{
const short nDialogType = getDialogType( nFlags );
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( const short nDialogType,
sal_uInt32 nFlags,
const SfxObjectFactory& rFact )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, rFact );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( const short nDialogType,
sal_uInt32 nFlags )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::~FileDialogHelper()
{
mpImp->dispose();
mxImp.clear();
}
// ------------------------------------------------------------------------
Reference< XFilePicker > FileDialogHelper::GetTopMostFilePicker( )
{
return FileDialogHelper_Impl::getTopMostFilePicker();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( const String& rPath,
SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
SetDisplayDirectory( rPath );
return mpImp->execute( rpURLList, rpSet, rFilter );
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute()
{
return mpImp->execute();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( SfxItemSet *& rpSet,
String& rFilter)
{
ErrCode nRet;
SvStringsDtor* pURLList;
nRet = mpImp->execute( pURLList, rpSet, rFilter );
delete pURLList;
return nRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetTitle( const String& rNewTitle )
{
if ( mpImp->mxFileDlg.is() )
mpImp->mxFileDlg->setTitle( rNewTitle );
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetPath() const
{
OUString aPath;
if ( mpImp->mxFileDlg.is() )
{
Sequence < OUString > aPathSeq = mpImp->mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
}
return aPath;
}
// ------------------------------------------------------------------------
Sequence < OUString > FileDialogHelper::GetMPath() const
{
if ( mpImp->mxFileDlg.is() )
return mpImp->mxFileDlg->getFiles();
else
{
Sequence < OUString > aEmpty;
return aEmpty;
}
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetDisplayDirectory() const
{
return mpImp->getPath();
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetCurrentFilter() const
{
return mpImp->getFilter();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::GetGraphic( Graphic& rGraphic ) const
{
return mpImp->getGraphic( rGraphic );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetDisplayDirectory( const String& rPath )
{
mpImp->setPath( rPath );
}
// ------------------------------------------------------------------------
void FileDialogHelper::AddFilter( const String& rFilterName,
const String& rExtension )
{
mpImp->addFilter( rFilterName, rExtension );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetCurrentFilter( const String& rFilter )
{
mpImp->setFilter( rFilter );
}
// ------------------------------------------------------------------------
Reference < XFilePicker > FileDialogHelper::GetFilePicker() const
{
return mpImp->mxFileDlg;
}
// ------------------------------------------------------------------------
const short FileDialogHelper::getDialogType( sal_uInt32 nFlags ) const
{
short nDialogType = FILEOPEN_SIMPLE;
if ( nFlags & WB_SAVEAS )
{
if ( nFlags & SFXWB_PASSWORD )
nDialogType = FILESAVE_AUTOEXTENSION_PASSWORD;
else
nDialogType = FILESAVE_SIMPLE;
}
else if ( nFlags & SFXWB_GRAPHIC )
{
if ( nFlags & SFXWB_SHOWSTYLES )
nDialogType = FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
else
nDialogType = FILEOPEN_LINK_PREVIEW;
}
else if ( SFXWB_INSERT != ( nFlags & SFXWB_INSERT ) )
nDialogType = FILEOPEN_READONLY_VERSION;
return nDialogType;
}
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::FileSelectionChanged( const FilePickerEvent& aEvent )
{
mpImp->handleFileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DirectoryChanged( const FilePickerEvent& aEvent )
{
mpImp->handleDirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper::HelpRequested( const FilePickerEvent& aEvent )
{
return mpImp->handleHelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::ControlStateChanged( const FilePickerEvent& aEvent )
{
mpImp->handleControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogSizeChanged()
{
mpImp->handleDialogSizeChanged();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
ErrCode FileOpenDialog_Impl( sal_uInt32 nFlags,
const SfxObjectFactory& rFact,
SvStringsDtor *& rpURLList,
String& rFilter,
SfxItemSet *& rpSet,
String aPath )
{
ErrCode nRet;
FileDialogHelper aDialog( nFlags, rFact );
nRet = aDialog.Execute( aPath, rpURLList, rpSet, rFilter );
aPath = aDialog.GetDisplayDirectory();
return nRet;
}
// ------------------------------------------------------------------------
String EncodeSpaces_Impl( const String& rSource )
{
String aRet( rSource );
aRet.SearchAndReplaceAll( String::CreateFromAscii( " " ),
String::CreateFromAscii( "%20" ) );
return aRet;
}
// ------------------------------------------------------------------------
String DecodeSpaces_Impl( const String& rSource )
{
String aRet( rSource );
aRet.SearchAndReplaceAll( String::CreateFromAscii( "%20" ),
String::CreateFromAscii( " " ) );
return aRet;
}
// ------------------------------------------------------------------------
} // end of namespace sfx2
#93187# don't set a non-existent or not accessible path
/*************************************************************************
*
* $RCSfile: filedlghelper.cxx,v $
*
* $Revision: 1.63 $
*
* last change: $Author: fs $ $Date: 2001-10-25 11:20:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _LIST_
#include <list>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include "filedlghelper.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBHELPER_HXX
#include <unotools/ucbhelper.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
#ifndef _SVT_HELPID_HRC
#include <svtools/helpid.hrc>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _SFXAPP_HXX
#include "app.hxx"
#endif
#ifndef _SFXDOCFILE_HXX
#include "docfile.hxx"
#endif
#ifndef _SFX_OBJFAC_HXX
#include "docfac.hxx"
#endif
#ifndef _SFX_FCONTNR_HXX
#include "fcontnr.hxx"
#endif
#ifndef _SFX_OPENFLAG_HXX
#include "openflag.hxx"
#endif
#ifndef _SFX_PASSWD_HXX
#include <passwd.hxx>
#endif
#ifndef _SFX_SFXRESID_HXX
#include "sfxresid.hxx"
#endif
#ifndef _SFXSIDS_HRC
#include "sfxsids.hrc"
#endif
#ifndef _SFX_EXPLORER_HRC
#include "explorer.hrc"
#endif
#ifndef _SFX_FILEDLGHELPER_HRC
#include "filedlghelper.hrc"
#endif
#ifndef SFX2_FILTERGROUPING_HXX
#include "filtergrouping.hxx"
#endif
#ifndef _VECTOR_
#include <vector>
#endif
//-----------------------------------------------------------------------------
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
#define IODLG_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Save"))
#define IMPGRF_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Graph"))
#define USERITEM_NAME OUString::createFromAscii( "UserItem" )
//-----------------------------------------------------------------------------
namespace sfx2 {
String EncodeSpaces_Impl( const String& rSource );
String DecodeSpaces_Impl( const String& rSource );
// ------------------------------------------------------------------------
class FileDialogHelper_Impl : public WeakImplHelper1< XFilePickerListener >
{
friend class FileDialogHelper;
Reference < XFilePicker > mxFileDlg;
static ::std::vector< Reference < XFilePicker > >
maDialogQueue;
SfxFilterMatcher *mpMatcher;
GraphicFilter *mpGraphicFilter;
OUString maPath;
OUString maCurFilter;
OUString maSelectFilter;
Timer maPreViewTimer;
Graphic maGraphic;
FileDialogHelper* mpParent;
const short m_nDialogType;
ErrCode mnError;
sal_Bool mbHasPassword : 1;
sal_Bool mbIsPwdEnabled : 1;
sal_Bool m_bHaveFilterOptions : 1;
sal_Bool mbHasVersions : 1;
sal_Bool mbHasAutoExt : 1;
sal_Bool mbHasLink : 1;
sal_Bool mbHasPreview : 1;
sal_Bool mbShowPreview : 1;
sal_Bool mbIsSaveDlg : 1;
sal_Bool mbDeleteMatcher : 1;
sal_Bool mbInsert : 1;
sal_Bool mbSystemPicker : 1;
private:
void addFilters( sal_uInt32 nFlags,
const SfxObjectFactory& rFactory );
void addFilter( const OUString& rFilterName,
const OUString& rExtension );
void addGraphicFilter();
void enablePasswordBox();
void updateFilterOptionsBox();
void updateVersions();
void dispose();
void loadConfig();
void saveConfig();
const SfxFilter* getCurentSfxFilter();
sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable );
ErrCode getGraphic( const OUString& rURL, Graphic& rGraphic ) const;
void setDefaultValues();
void preExecute();
void postExecute();
sal_Int16 implDoExecute();
void pushBackPicker();
void popPicker();
DECL_LINK( TimeOutHdl_Impl, Timer* );
DECL_LINK( HandleEvent, FileDialogHelper* );
public:
// XFilePickerListener methods
virtual void SAL_CALL fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual OUString SAL_CALL helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException );
virtual void SAL_CALL dialogSizeChanged() throw ( RuntimeException );
// XEventListener methods
virtual void SAL_CALL disposing( const EventObject& Source ) throw ( RuntimeException );
// handle XFilePickerListener events
void handleFileSelectionChanged( const FilePickerEvent& aEvent );
void handleDirectoryChanged( const FilePickerEvent& aEvent );
OUString handleHelpRequested( const FilePickerEvent& aEvent );
void handleControlStateChanged( const FilePickerEvent& aEvent );
void handleDialogSizeChanged();
// Own methods
FileDialogHelper_Impl( FileDialogHelper* pParent,
const short nDialogType,
sal_uInt32 nFlags );
~FileDialogHelper_Impl();
ErrCode execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter );
ErrCode execute();
void setPath( const OUString& rPath );
void setFilter( const OUString& rFilter );
OUString getPath() const;
OUString getFilter() const;
OUString getRealFilter() const;
ErrCode getGraphic( Graphic& rGraphic ) const;
static Reference< XFilePicker > getTopMostFilePicker( );
};
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
::std::vector< Reference < XFilePicker > > FileDialogHelper_Impl::maDialogQueue;
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->FileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->DirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper_Impl::helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return mpParent->HelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->ControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogSizeChanged() throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpParent->DialogSizeChanged();
}
// ------------------------------------------------------------------------
// handle XFilePickerListener events
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleFileSelectionChanged( const FilePickerEvent& aEvent )
{
if ( mbHasVersions )
updateVersions();
if ( mbShowPreview )
maPreViewTimer.Start();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDirectoryChanged( const FilePickerEvent& aEvent )
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::handleHelpRequested( const FilePickerEvent& aEvent )
{
//!!! todo: cache the help strings (here or TRA)
ULONG nHelpId = 0;
// mapping from element id -> help id
switch ( aEvent.ElementId )
{
case ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION :
nHelpId = HID_FILESAVE_AUTOEXTENSION;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PASSWORD :
nHelpId = HID_FILESAVE_SAVEWITHPASSWORD;
break;
case ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS :
nHelpId = HID_FILESAVE_CUSTOMIZEFILTER;
break;
case ExtendedFilePickerElementIds::CHECKBOX_READONLY :
nHelpId = HID_FILEOPEN_READONLY;
break;
case ExtendedFilePickerElementIds::CHECKBOX_LINK :
nHelpId = HID_FILEDLG_LINK_CB;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW :
nHelpId = HID_FILEDLG_PREVIEW_CB;
break;
case ExtendedFilePickerElementIds::PUSHBUTTON_PLAY :
nHelpId = HID_FILESAVE_DOPLAY;
break;
case ExtendedFilePickerElementIds::LISTBOX_VERSION_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_VERSION :
nHelpId = HID_FILEOPEN_VERSION;
break;
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE :
nHelpId = HID_FILESAVE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE :
nHelpId = HID_FILEOPEN_IMAGE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::CHECKBOX_SELECTION :
nHelpId = HID_FILESAVE_SELECTION;
break;
default:
DBG_ERRORFILE( "invalid element id" );
}
OUString aHelpText;
Help* pHelp = Application::GetHelp();
if ( pHelp )
aHelpText = String( pHelp->GetHelpText( nHelpId, NULL ) );
return aHelpText;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleControlStateChanged( const FilePickerEvent& aEvent )
{
switch ( aEvent.ElementId )
{
case CommonFilePickerElementIds::LISTBOX_FILTER:
updateFilterOptionsBox();
enablePasswordBox();
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW:
if ( mbHasPreview )
{
Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a preview
if ( xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
sal_Bool bShowPreview = sal_False;
if ( aValue >>= bShowPreview )
{
mbShowPreview = bShowPreview;
TimeOutHdl_Impl( NULL );
}
}
catch( Exception )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::controlStateChanged: caught an exception!" );
}
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDialogSizeChanged()
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
// XEventListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::disposing( const EventObject& Source ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
dispose();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::dispose()
{
if ( mxFileDlg.is() )
{
// remove the event listener
Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
if ( xNotifier.is() )
xNotifier->removeFilePickerListener( this );
mxFileDlg.clear();
}
}
// ------------------------------------------------------------------------
const SfxFilter* FileDialogHelper_Impl::getCurentSfxFilter()
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
::rtl::OUString aFilterName = xFltMgr->getCurrentFilter();
const SfxFilter* pFilter = NULL;
if ( mpMatcher )
pFilter = mpMatcher->GetFilter4UIName( aFilterName, 0, SFX_FILTER_NOTINFILEDLG );
return pFilter;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable )
{
sal_Bool bIsEnabled = sal_False;
Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
try
{
xCtrlAccess->enableControl( _nExtendedControlId, _bEnable );
bIsEnabled = _bEnable;
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::updateExtendedControl: caught an exception!" );
}
}
return bIsEnabled;
}
// ------------------------------------------------------------------------
struct CheckFilterOptionsCapability
{
sal_Bool operator() ( const SfxFilter* _pFilter )
{
return _pFilter
&& ( 0 != ( _pFilter->GetFilterFlags() & SFX_FILTER_USESOPTIONS ) );
}
};
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateFilterOptionsBox()
{
if ( !m_bHaveFilterOptions )
return;
updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS,
CheckFilterOptionsCapability()( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
struct CheckPasswordCapability
{
sal_Bool operator() ( const SfxFilter* _pFilter )
{
return _pFilter
&& _pFilter->UsesStorage()
&& ( SOFFICE_FILEFORMAT_60 <= _pFilter->GetVersion() );
}
};
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::enablePasswordBox()
{
if ( ! mbHasPassword )
return;
mbIsPwdEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_PASSWORD,
CheckPasswordCapability()( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateVersions()
{
Sequence < OUString > aEntries;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
INetURLObject aObj( aPathSeq[0] );
if ( ( aObj.GetProtocol() == INET_PROT_FILE ) &&
( utl::UCBContentHelper::IsDocument( aObj.GetMainURL( INetURLObject::NO_DECODE ) ) ) )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ),
SFX_STREAM_READONLY_MAKECOPY, TRUE );
const SfxVersionTableDtor* pVerTable = aMed.GetVersionList();
if ( pVerTable )
{
SvStringsDtor* pVersions = pVerTable->GetVersions();
aEntries.realloc( pVersions->Count() + 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
for ( USHORT i = 0; i < pVersions->Count(); i++ )
aEntries[ i + 1 ] = OUString( *(pVersions->GetObject(i)) );
delete pVersions;
}
else if ( aMed.GetStorage() )
{
SfxFilterFlags nMust = SFX_FILTER_IMPORT | SFX_FILTER_OWN, nDont = SFX_FILTER_NOTINSTALLED | SFX_FILTER_STARONEFILTER;
if ( SFX_APP()->GetFilterMatcher().GetFilter4ClipBoardId( aMed.GetStorage()->GetFormat(), nMust, nDont ) )
{
aEntries.realloc( 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
}
}
}
}
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::DELETE_ITEMS, aValue );
}
catch( IllegalArgumentException ){}
sal_Int32 nCount = aEntries.getLength();
if ( nCount )
{
try
{
aValue <<= aEntries;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::ADD_ITEMS, aValue );
Any aPos;
aPos <<= (sal_Int32) 0;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::SET_SELECT_ITEM, aPos );
}
catch( IllegalArgumentException ){}
}
}
// -----------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, TimeOutHdl_Impl, Timer*, EMPTYARG )
{
if ( !mbHasPreview )
return 0;
maGraphic.Clear();
Any aAny;
Reference < XFilePreview > xFilePicker( mxFileDlg, UNO_QUERY );
if ( ! xFilePicker.is() )
return 0;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( mbShowPreview && ( aPathSeq.getLength() == 1 ) )
{
OUString aURL = aPathSeq[0];
if ( ERRCODE_NONE == getGraphic( aURL, maGraphic ) )
{
Bitmap aBmp = maGraphic.GetBitmap();
// scale the bitmap to the correct size
sal_Int32 nOutWidth = xFilePicker->getAvailableWidth();
sal_Int32 nOutHeight = xFilePicker->getAvailableHeight();
sal_Int32 nBmpWidth = aBmp.GetSizePixel().Width();
sal_Int32 nBmpHeight = aBmp.GetSizePixel().Height();
double nXRatio = (double) nOutWidth / nBmpWidth;
double nYRatio = (double) nOutHeight / nBmpHeight;
if ( nXRatio < nYRatio )
aBmp.Scale( nXRatio, nXRatio );
else
aBmp.Scale( nYRatio, nYRatio );
nBmpWidth = aBmp.GetSizePixel().Width();
nBmpHeight = aBmp.GetSizePixel().Height();
sal_Int32 nMidX = ( nOutWidth - nBmpWidth ) / 2;
sal_Int32 nMidY = ( nOutHeight - nBmpHeight ) / 2;
Rectangle aSrcRect( 0, 0, nBmpWidth, nBmpHeight );
Rectangle aDstRect( nMidX, nMidY, nMidX + nBmpWidth, nMidY + nBmpHeight );
// #92765# Have to conserve bitmap palette. There is no method setting it explicitely,
// thus doing it this way. Performance penalty is low, as bitmap is refcounted.
Bitmap aScaledBmp( aBmp );
aScaledBmp.SetSizePixel( Size(nOutWidth, nOutHeight) );
aScaledBmp.Erase( Color( COL_WHITE ) );
aScaledBmp.CopyPixel( aDstRect, aSrcRect, &aBmp );
// and copy it into the Any
SvMemoryStream aData;
aData << aScaledBmp;
Sequence < sal_Int8 > aBuffer( (sal_Int8*) aData.GetData(), aData.GetSize() );
aAny <<= aBuffer;
}
}
try
{
// clear the preview window
xFilePicker->setImage( FilePreviewImageFormats::BITMAP, aAny );
}
catch( IllegalArgumentException ){}
return 0;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( const OUString& rURL,
Graphic& rGraphic ) const
{
if ( utl::UCBContentHelper::IsFolder( rURL ) )
return ERRCODE_IO_NOTAFILE;
if ( !mpGraphicFilter )
return ERRCODE_IO_NOTSUPPORTED;
// select graphic filter from dialog filter selection
OUString aCurFilter( getFilter() );
sal_uInt16 nFilter = aCurFilter.getLength() && mpGraphicFilter->GetImportFormatCount()
? mpGraphicFilter->GetImportFormatNumber( aCurFilter )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURLObj( rURL );
if ( aURLObj.HasError() || INET_PROT_NOT_VALID == aURLObj.GetProtocol() )
{
aURLObj.SetSmartProtocol( INET_PROT_FILE );
aURLObj.SetSmartURL( rURL );
}
ErrCode nRet = ERRCODE_NONE;
sal_uInt32 nFilterImportFlags = GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
// non-local?
if ( INET_PROT_FILE != aURLObj.GetProtocol() )
{
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( rURL, STREAM_READ );
if( pStream )
nRet = mpGraphicFilter->ImportGraphic( rGraphic, rURL, *pStream, nFilter, NULL, nFilterImportFlags );
else
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
delete pStream;
}
else
{
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
}
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( Graphic& rGraphic ) const
{
ErrCode nRet = ERRCODE_NONE;
if ( ! maGraphic )
{
OUString aPath;;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
if ( aPath.getLength() )
nRet = getGraphic( aPath, rGraphic );
else
nRet = ERRCODE_IO_GENERAL;
}
else
rGraphic = maGraphic;
return nRet;
}
// ------------------------------------------------------------------------
sal_Bool lcl_isSystemFilePicker( const Reference< XFilePicker >& _rxFP )
{
try
{
Reference< XServiceInfo > xSI( _rxFP, UNO_QUERY );
if ( xSI.is() && xSI->supportsService( ::rtl::OUString::createFromAscii( "com.sun.star.ui.dialogs.SystemFilePicker" ) ) )
return sal_True;
}
catch( const Exception& )
{
}
return sal_False;
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper_Impl::FileDialogHelper_Impl( FileDialogHelper* pParent,
const short nDialogType,
sal_uInt32 nFlags )
:m_nDialogType( nDialogType )
{
OUString aService( RTL_CONSTASCII_USTRINGPARAM( FILE_OPEN_SERVICE_NAME ) );
Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
// create the file open dialog
// the flags can be SFXWB_INSERT or SFXWB_MULTISELECTION
mpParent = pParent;
mnError = ERRCODE_NONE;
mbHasAutoExt = sal_False;
mbHasPassword = sal_False;
m_bHaveFilterOptions = sal_False;
mbIsPwdEnabled = sal_True;
mbHasVersions = sal_False;
mbHasPreview = sal_False;
mbShowPreview = sal_False;
mbHasLink = sal_False;
mbDeleteMatcher = sal_False;
mbInsert = SFXWB_INSERT == ( nFlags & SFXWB_INSERT );
mbIsSaveDlg = sal_False;
mpMatcher = NULL;
mpGraphicFilter = NULL;
mxFileDlg = Reference < XFilePicker > ( xFactory->createInstance( aService ), UNO_QUERY );
mbSystemPicker = lcl_isSystemFilePicker( mxFileDlg );
Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
Reference< XInitialization > xInit( mxFileDlg, UNO_QUERY );
if ( ! mxFileDlg.is() || ! xNotifier.is() )
{
mnError = ERRCODE_ABORT;
return;
}
Sequence < Any > aServiceType(1);
switch ( m_nDialogType ) {
case FILEOPEN_SIMPLE:
aServiceType[0] <<= TemplateDescription::FILEOPEN_SIMPLE;
break;
case FILESAVE_SIMPLE:
aServiceType[0] <<= TemplateDescription::FILESAVE_SIMPLE;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD;
mbHasPassword = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS;
mbHasPassword = sal_True;
m_bHaveFilterOptions = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_SELECTION:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_TEMPLATE:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION_TEMPLATE;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
aServiceType[0] <<= TemplateDescription::FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILEOPEN_PLAY:
aServiceType[0] <<= TemplateDescription::FILEOPEN_PLAY;
break;
case FILEOPEN_READONLY_VERSION:
aServiceType[0] <<= TemplateDescription::FILEOPEN_READONLY_VERSION;
mbHasVersions = sal_True;
break;
case FILEOPEN_LINK_PREVIEW:
aServiceType[0] <<= TemplateDescription::FILEOPEN_LINK_PREVIEW;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILESAVE_AUTOEXTENSION:
aServiceType[0] <<= TemplateDescription::FILESAVE_AUTOEXTENSION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
default:
aServiceType[0] <<= TemplateDescription::FILEOPEN_SIMPLE;
DBG_ERRORFILE( "FileDialogHelper::ctor with unknown type" );
}
if ( xInit.is() )
xInit->initialize( aServiceType );
// set multiselection mode
if ( nFlags & SFXWB_MULTISELECTION )
mxFileDlg->setMultiSelectionMode( sal_True );
if ( mbHasLink ) // generate graphic filter only on demand
addGraphicFilter();
// the "insert file" dialog needs another title
if ( mbInsert )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_INSERT ) ) ) );
Reference < XFilePickerControlAccess > xExtDlg( mxFileDlg, UNO_QUERY );
if ( xExtDlg.is() )
{
try
{
xExtDlg->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK,
OUString( String( SfxResId( STR_SFX_EXPLORERFILE_BUTTONINSERT ) ) ) );
}
catch( IllegalArgumentException ){}
}
}
// add the event listener
xNotifier->addFilePickerListener( this );
}
// ------------------------------------------------------------------------
FileDialogHelper_Impl::~FileDialogHelper_Impl()
{
delete mpGraphicFilter;
if ( mbDeleteMatcher )
delete mpMatcher;
maPreViewTimer.SetTimeoutHdl( Link() );
}
#define nMagic (sal_Int16) 0xFFFF
class PickerThread_Impl : public ::vos::OThread
{
Reference < XFilePicker > mxPicker;
::vos::OMutex maMutex;
virtual void SAL_CALL run();
sal_Int16 mnRet;
public:
PickerThread_Impl( const Reference < XFilePicker >& rPicker )
: mxPicker( rPicker ), mnRet(nMagic) {}
sal_Int16 GetReturnValue()
{ ::vos::OGuard aGuard( maMutex ); return mnRet; }
void SetReturnValue( sal_Int16 aRetValue )
{ ::vos::OGuard aGuard( maMutex ); mnRet = aRetValue; }
};
void SAL_CALL PickerThread_Impl::run()
{
try
{
sal_Int16 n = mxPicker->execute();
SetReturnValue( n );
}
catch( RuntimeException& )
{
SetReturnValue( ExecutableDialogResults::CANCEL );
DBG_ERRORFILE( "RuntimeException caught" );
}
}
// ------------------------------------------------------------------------
Reference< XFilePicker > FileDialogHelper_Impl::getTopMostFilePicker( )
{
Reference< XFilePicker > xReturn;
DBG_ASSERT( !maDialogQueue.empty(), "FileDialogHelper_Impl::popPicker: no active picker!" );
if ( !maDialogQueue.empty() )
xReturn = *maDialogQueue.begin();
return xReturn;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::pushBackPicker()
{
DBG_ASSERT( mxFileDlg.is(), "FileDialogHelper_Impl::pushBackPicker: have no picker!" );
maDialogQueue.push_back( mxFileDlg );
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::popPicker()
{
DBG_ASSERT( !maDialogQueue.empty(), "FileDialogHelper_Impl::popPicker: no picker pushed!" );
if ( !maDialogQueue.empty() )
{
DBG_ASSERT( maDialogQueue.begin()->get() == mxFileDlg.get(), "FileDialogHelper_Impl::popPicker: invalid top-most queue element!" );
maDialogQueue.pop_back();
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::preExecute()
{
loadConfig();
setDefaultValues();
enablePasswordBox();
updateFilterOptionsBox();
pushBackPicker();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::postExecute()
{
popPicker();
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper_Impl::implDoExecute()
{
preExecute();
sal_Int16 nRet = ExecutableDialogResults::CANCEL;
if ( mbSystemPicker )
{
PickerThread_Impl* pThread = new PickerThread_Impl( mxFileDlg );
pThread->create();
while ( pThread->GetReturnValue() == nMagic )
Application::Yield();
pThread->join();
nRet = pThread->GetReturnValue();
delete pThread;
}
else
{
try
{
nRet = mxFileDlg->execute();
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
postExecute();
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
rpSet = NULL;
rpURLList = NULL;
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
if ( ExecutableDialogResults::CANCEL != implDoExecute() )
{
saveConfig();
// create an itemset
rpSet = new SfxAllItemSet( SFX_APP()->GetPool() );
Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a password box
if ( mbHasPassword && mbIsPwdEnabled && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
if ( ( aValue >>= bPassWord ) && bPassWord )
{
// ask for the password
SfxPasswordDialog aPasswordDlg( NULL );
aPasswordDlg.ShowExtras( SHOWEXTRAS_CONFIRM );
BOOL bOK = FALSE;
short nRet = aPasswordDlg.Execute();
if ( RET_OK == nRet )
{
String aPasswd = aPasswordDlg.GetPassword();
rpSet->Put( SfxStringItem( SID_PASSWORD, aPasswd ) );
}
else
return ERRCODE_ABORT;
}
}
catch( IllegalArgumentException ){}
}
// set the read-only flag. When inserting a file, this flag is always set
if ( mbInsert )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
else
{
if ( ( FILEOPEN_READONLY_VERSION == m_nDialogType ) && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_READONLY, 0 );
sal_Bool bReadOnly = sal_False;
if ( ( aValue >>= bReadOnly ) && bReadOnly )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, bReadOnly ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
}
if ( mbHasVersions && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ListboxControlActions::GET_SELECTED_ITEM );
sal_Int16 nVersion = 0;
if ( aValue >>= nVersion )
rpSet->Put( SfxInt16Item( SID_VERSION, nVersion ) );
}
catch( IllegalArgumentException ){}
}
// set the filter
rFilter = getRealFilter();
// fill the rpURLList
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() )
{
rpURLList = new SvStringsDtor;
if ( aPathSeq.getLength() == 1 )
{
OUString aFileURL( aPathSeq[0] );
String* pURL = new String( aFileURL );
rpURLList->Insert( pURL, 0 );
}
else
{
INetURLObject aPath( aPathSeq[0] );
aPath.setFinalSlash();
for ( USHORT i = 1; i < aPathSeq.getLength(); ++i )
{
if ( i == 1 )
aPath.Append( aPathSeq[i] );
else
aPath.setName( aPathSeq[i] );
String* pURL = new String( aPath.GetMainURL( INetURLObject::NO_DECODE ) );
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
return ERRCODE_NONE;
}
else
return ERRCODE_ABORT;
}
else
return ERRCODE_ABORT;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute()
{
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
sal_Int16 nRet = implDoExecute();
maPath = mxFileDlg->getDisplayDirectory();
if ( ExecutableDialogResults::CANCEL == nRet )
return ERRCODE_ABORT;
else
{
saveConfig();
return ERRCODE_NONE;
}
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getPath() const
{
OUString aPath;
if ( mxFileDlg.is() )
aPath = mxFileDlg->getDisplayDirectory();
if ( !aPath.getLength() )
aPath = maPath;
return aPath;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getFilter() const
{
OUString aFilter;
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( xFltMgr.is() )
aFilter = xFltMgr->getCurrentFilter();
else
aFilter = maCurFilter;
return aFilter;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getRealFilter() const
{
OUString aFilter;
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( xFltMgr.is() )
aFilter = xFltMgr->getCurrentFilter();
if ( ! aFilter.getLength() )
aFilter = maCurFilter;
if ( aFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter4UIName(
aFilter, 0, SFX_FILTER_NOTINFILEDLG );
if ( pFilter )
aFilter = pFilter->GetName();
}
return aFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setPath( const OUString& rPath )
{
// We check wether the path points to a dirctory or not
//
// We set the display directory only, when it is on a local / remote(?)
// filesystem
if ( ! rPath.getLength() )
return;
/* if (! utl::LocalFileHelper::IsLocalFile( rPath ) )
{
return;
}*/
OUString aName;
OUString aPath;
INetURLObject aObj( rPath );
// if the given path isn't a folder, we cut off the last part
// and take it as filename and the rest of the path should be
// the folder
if ( ! utl::UCBContentHelper::IsFolder( rPath ) )
{
aName = aObj.GetName( INetURLObject::DECODE_WITH_CHARSET );
aObj.removeSegment();
}
aPath = aObj.GetMainURL( INetURLObject::NO_DECODE );
if ( ! utl::UCBContentHelper::IsFolder( aPath ) )
return;
else
maPath = aPath;
// set the path
if ( mxFileDlg.is() )
{
try
{
if ( maPath.getLength() )
mxFileDlg->setDisplayDirectory( maPath );
if ( aName.getLength() )
mxFileDlg->setDefaultName( aName );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFilter( const OUString& rFilter )
{
maCurFilter = rFilter;
if ( rFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter(
rFilter, 0, SFX_FILTER_NOTINFILEDLG );
if ( pFilter )
maCurFilter = pFilter->GetUIName();
}
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( maCurFilter.getLength() && xFltMgr.is() )
{
try
{
xFltMgr->setCurrentFilter( maCurFilter );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilters( sal_uInt32 nFlags,
const SfxObjectFactory& rFactory )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
if ( !&rFactory )
{
SfxApplication *pSfxApp = SFX_APP();
mpMatcher = &pSfxApp->GetFilterMatcher();
mbDeleteMatcher = sal_False;
}
else
{
mpMatcher = new SfxFilterMatcher( rFactory.GetFilterContainer() );
mbDeleteMatcher = sal_True;
}
USHORT nFilterFlags = SFX_FILTER_EXPORT;
if( WB_OPEN == ( nFlags & WB_OPEN ) )
nFilterFlags = SFX_FILTER_IMPORT;
sal_Bool bHasAll = sal_False;
SfxFilterMatcherIter aIter( mpMatcher, nFilterFlags, SFX_FILTER_INTERNAL | SFX_FILTER_NOTINFILEDLG );
// append the filters
::rtl::OUString sFirstFilter;
if ( WB_OPEN == ( nFlags & WB_OPEN ) )
::sfx2::appendFiltersForOpen( aIter, xFltMgr, sFirstFilter );
else
::sfx2::appendFilters( aIter, xFltMgr, sFirstFilter );
// set our initial selected filter (if we do not already have one)
if ( maSelectFilter.getLength() )
maSelectFilter = sFirstFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilter( const OUString& rFilterName,
const OUString& rExtension )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
try
{
xFltMgr->appendFilter( rFilterName, rExtension );
if ( !maSelectFilter.getLength() )
maSelectFilter = rFilterName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( rFilterName ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addGraphicFilter()
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
mpGraphicFilter = new GraphicFilter;
USHORT i, j, nCount = mpGraphicFilter->GetImportFormatCount();
// compute the extension string for all known import filters
String aExtensions;
for ( i = 0; i < nCount; i++ )
{
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
}
#if defined(WIN) || defined(WNT)
if ( aExtensions.Len() > 240 )
aExtensions = String::CreateFromAscii( FILEDIALOG_FILTER_ALL );
#endif
try
{
OUString aAllFilterName = String( SfxResId( STR_SFX_IMPORT_ALL ) );
xFltMgr->appendFilter( aAllFilterName, aExtensions );
maSelectFilter = aAllFilterName;
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
// Now add the filter
for ( i = 0; i < nCount; i++ )
{
String aName = mpGraphicFilter->GetImportFormatName( i );
String aExtensions;
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
try
{
xFltMgr->appendFilter( aName, aExtensions );
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
}
}
// ------------------------------------------------------------------------
#define GRF_CONFIG_STR " "
#define STD_CONFIG_STR "1 "
void FileDialogHelper_Impl::saveConfig()
{
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aDlgOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData = String::CreateFromAscii( GRF_CONFIG_STR );
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
sal_Bool bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 1, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
INetURLObject aObj( getPath() );
if ( aObj.GetProtocol() == INET_PROT_FILE )
aUserData.SetToken( 2, ' ', aObj.GetMainURL( INetURLObject::NO_DECODE ) );
String aFilter = getFilter();
aFilter = EncodeSpaces_Impl( aFilter );
aUserData.SetToken( 3, ' ', aFilter );
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
catch( IllegalArgumentException ){}
}
else
{
sal_Bool bWriteConfig = sal_False;
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData = String::CreateFromAscii( STD_CONFIG_STR );
if ( aDlgOpt.Exists() )
{
Any aUserItem = aDlgOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( mbHasAutoExt )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 );
sal_Bool bAutoExt = sal_True;
aValue >>= bAutoExt;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bAutoExt ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( ! mbIsSaveDlg )
{
OUString aPath = getPath();
if ( aPath.getLength() &&
utl::LocalFileHelper::IsLocalFile( aPath ) )
{
aUserData.SetToken( 1, ' ', aPath );
bWriteConfig = sal_True;
}
}
if ( bWriteConfig )
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
SfxApplication *pSfxApp = SFX_APP();
pSfxApp->SetLastDir_Impl( getPath() );
}
// ------------------------------------------------------------------------
namespace
{
static ::rtl::OUString getInitPath( const String& _rFallback, const xub_StrLen _nFallbackToken )
{
SfxApplication *pSfxApp = SFX_APP();
String sPath = pSfxApp->GetLastDir_Impl();
if ( !sPath.Len() )
sPath = _rFallback.GetToken( _nFallbackToken, ' ' );
// check if the path points to a valid (accessible) directory
sal_Bool bValid = sal_False;
if ( sPath.Len() )
{
String sPathCheck( sPath );
if ( sPathCheck.GetBuffer()[ sPathCheck.Len() - 1 ] != '/' )
sPathCheck += '/';
sPathCheck += '.';
try
{
::ucb::Content aContent( sPathCheck, Reference< ::com::sun::star::ucb::XCommandEnvironment >() );
bValid = aContent.isFolder();
}
catch( const Exception& e )
{
e; // make compiler happy
}
}
if ( !bValid )
sPath.Erase();
return sPath;
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::loadConfig()
{
Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aViewOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( aUserData.Len() > 0 )
{
try
{
// respect the last "insert as link" state
sal_Bool bLink = (sal_Bool) aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= bLink;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aValue );
// respect the last "show preview" state
sal_Bool bShowPreview = (sal_Bool) aUserData.GetToken( 1, ' ' ).ToInt32();
aValue <<= bShowPreview;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0, aValue );
if ( ! maPath.getLength() )
setPath( getInitPath( aUserData, 2 ) );
if ( ! maCurFilter.getLength() )
{
String aFilter = aUserData.GetToken( 3, ' ' );
aFilter = DecodeSpaces_Impl( aFilter );
setFilter( aFilter );
}
// set the member so we know that we have to show the preview
mbShowPreview = bShowPreview;
}
catch( IllegalArgumentException ){}
}
}
else
{
SvtViewOptions aViewOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( ! aUserData.Len() )
aUserData = String::CreateFromAscii( STD_CONFIG_STR );
if ( ! maPath.getLength() )
setPath( getInitPath( aUserData, 1 ) );
if ( mbHasAutoExt )
{
sal_Int32 nFlag = aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setDefaultValues()
{
// when no filter is set, we set the curentFilter to <all>
if ( !maCurFilter.getLength() && maSelectFilter.getLength() )
{
Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
try
{
xFltMgr->setCurrentFilter( maSelectFilter );
}
catch( IllegalArgumentException )
{}
}
// when no path is set, we use the standard 'work' folder
if ( ! maPath.getLength() )
{
OUString aWorkFolder = SvtPathOptions().GetWorkPath();
mxFileDlg->setDisplayDirectory( aWorkFolder );
// INetURLObject aStdDirObj( SvtPathOptions().GetWorkPath() );
//SetStandardDir( aStdDirObj.GetMainURL( INetURLObject::NO_DECODE ) );
}
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_uInt32 nFlags,
const SfxObjectFactory& rFact )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, rFact );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_uInt32 nFlags )
{
const short nDialogType = getDialogType( nFlags );
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( const short nDialogType,
sal_uInt32 nFlags,
const SfxObjectFactory& rFact )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, rFact );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( const short nDialogType,
sal_uInt32 nFlags )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::~FileDialogHelper()
{
mpImp->dispose();
mxImp.clear();
}
// ------------------------------------------------------------------------
Reference< XFilePicker > FileDialogHelper::GetTopMostFilePicker( )
{
return FileDialogHelper_Impl::getTopMostFilePicker();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( const String& rPath,
SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
SetDisplayDirectory( rPath );
return mpImp->execute( rpURLList, rpSet, rFilter );
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute()
{
return mpImp->execute();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( SfxItemSet *& rpSet,
String& rFilter)
{
ErrCode nRet;
SvStringsDtor* pURLList;
nRet = mpImp->execute( pURLList, rpSet, rFilter );
delete pURLList;
return nRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetTitle( const String& rNewTitle )
{
if ( mpImp->mxFileDlg.is() )
mpImp->mxFileDlg->setTitle( rNewTitle );
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetPath() const
{
OUString aPath;
if ( mpImp->mxFileDlg.is() )
{
Sequence < OUString > aPathSeq = mpImp->mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
}
return aPath;
}
// ------------------------------------------------------------------------
Sequence < OUString > FileDialogHelper::GetMPath() const
{
if ( mpImp->mxFileDlg.is() )
return mpImp->mxFileDlg->getFiles();
else
{
Sequence < OUString > aEmpty;
return aEmpty;
}
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetDisplayDirectory() const
{
return mpImp->getPath();
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetCurrentFilter() const
{
return mpImp->getFilter();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::GetGraphic( Graphic& rGraphic ) const
{
return mpImp->getGraphic( rGraphic );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetDisplayDirectory( const String& rPath )
{
mpImp->setPath( rPath );
}
// ------------------------------------------------------------------------
void FileDialogHelper::AddFilter( const String& rFilterName,
const String& rExtension )
{
mpImp->addFilter( rFilterName, rExtension );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetCurrentFilter( const String& rFilter )
{
mpImp->setFilter( rFilter );
}
// ------------------------------------------------------------------------
Reference < XFilePicker > FileDialogHelper::GetFilePicker() const
{
return mpImp->mxFileDlg;
}
// ------------------------------------------------------------------------
const short FileDialogHelper::getDialogType( sal_uInt32 nFlags ) const
{
short nDialogType = FILEOPEN_SIMPLE;
if ( nFlags & WB_SAVEAS )
{
if ( nFlags & SFXWB_PASSWORD )
nDialogType = FILESAVE_AUTOEXTENSION_PASSWORD;
else
nDialogType = FILESAVE_SIMPLE;
}
else if ( nFlags & SFXWB_GRAPHIC )
{
if ( nFlags & SFXWB_SHOWSTYLES )
nDialogType = FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
else
nDialogType = FILEOPEN_LINK_PREVIEW;
}
else if ( SFXWB_INSERT != ( nFlags & SFXWB_INSERT ) )
nDialogType = FILEOPEN_READONLY_VERSION;
return nDialogType;
}
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::FileSelectionChanged( const FilePickerEvent& aEvent )
{
mpImp->handleFileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DirectoryChanged( const FilePickerEvent& aEvent )
{
mpImp->handleDirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper::HelpRequested( const FilePickerEvent& aEvent )
{
return mpImp->handleHelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::ControlStateChanged( const FilePickerEvent& aEvent )
{
mpImp->handleControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogSizeChanged()
{
mpImp->handleDialogSizeChanged();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
ErrCode FileOpenDialog_Impl( sal_uInt32 nFlags,
const SfxObjectFactory& rFact,
SvStringsDtor *& rpURLList,
String& rFilter,
SfxItemSet *& rpSet,
String aPath )
{
ErrCode nRet;
FileDialogHelper aDialog( nFlags, rFact );
nRet = aDialog.Execute( aPath, rpURLList, rpSet, rFilter );
aPath = aDialog.GetDisplayDirectory();
return nRet;
}
// ------------------------------------------------------------------------
String EncodeSpaces_Impl( const String& rSource )
{
String aRet( rSource );
aRet.SearchAndReplaceAll( String::CreateFromAscii( " " ),
String::CreateFromAscii( "%20" ) );
return aRet;
}
// ------------------------------------------------------------------------
String DecodeSpaces_Impl( const String& rSource )
{
String aRet( rSource );
aRet.SearchAndReplaceAll( String::CreateFromAscii( "%20" ),
String::CreateFromAscii( " " ) );
return aRet;
}
// ------------------------------------------------------------------------
} // end of namespace sfx2
|
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sfx2.hxx"
#include <sfx2/filedlghelper.hxx>
#include <sal/types.h>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#include <com/sun/star/ui/dialogs/ControlActions.hpp>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#include <com/sun/star/ui/dialogs/XControlInformation.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#include <com/sun/star/ui/dialogs/XFilePicker2.hpp>
#include <com/sun/star/ui/dialogs/XAsynchronousExecutableDialog.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XContainerQuery.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#include <comphelper/processfactory.hxx>
#include <comphelper/types.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/stillreadwriteinteraction.hxx>
#include <tools/urlobj.hxx>
#include <vcl/help.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/ucbhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <vos/thread.hxx>
#include <vos/mutex.hxx>
#include <vos/security.hxx>
#include <vcl/cvtgrf.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/mnemonic.hxx>
#include <unotools/pathoptions.hxx>
#include <unotools/securityoptions.hxx>
#include <svl/itemset.hxx>
#include <svl/eitem.hxx>
#include <svl/intitem.hxx>
#include <svl/stritem.hxx>
#include <svtools/filter.hxx>
#include <unotools/viewoptions.hxx>
#include <unotools/moduleoptions.hxx>
#include <svtools/helpid.hrc>
#include <svl/pickerhelper.hxx>
#include <comphelper/docpasswordrequest.hxx>
#include <comphelper/docpasswordhelper.hxx>
#include <ucbhelper/content.hxx>
#include <ucbhelper/commandenvironment.hxx>
#include <comphelper/storagehelper.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/app.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfac.hxx>
#include "openflag.hxx"
#include <sfx2/passwd.hxx>
#include "sfxresid.hxx"
#include <sfx2/sfxsids.hrc>
#include "filedlghelper.hrc"
#include "filtergrouping.hxx"
#include <sfx2/request.hxx>
#include "filedlgimpl.hxx"
#include <sfxlocal.hrc>
//-----------------------------------------------------------------------------
using namespace ::com::sun::star;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::ui::dialogs::TemplateDescription;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
#define IODLG_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Save"))
#define IMPGRF_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Graph"))
#define USERITEM_NAME ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "UserItem" ))
//-----------------------------------------------------------------------------
namespace sfx2
{
const OUString* GetLastFilterConfigId( FileDialogHelper::Context _eContext )
{
static const OUString aSD_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SdExportLastFilter" ) );
static const OUString aSI_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SiExportLastFilter" ) );
static const OUString aSW_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SwExportLastFilter" ) );
const OUString* pRet = NULL;
switch( _eContext )
{
case FileDialogHelper::SD_EXPORT: pRet = &aSD_EXPORT_IDENTIFIER; break;
case FileDialogHelper::SI_EXPORT: pRet = &aSI_EXPORT_IDENTIFIER; break;
case FileDialogHelper::SW_EXPORT: pRet = &aSW_EXPORT_IDENTIFIER; break;
default: break;
}
return pRet;
}
String EncodeSpaces_Impl( const String& rSource );
String DecodeSpaces_Impl( const String& rSource );
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->FileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper_Impl::helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return mpAntiImpl->HelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->ControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogSizeChanged() throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DialogSizeChanged();
}
// ------------------------------------------------------------------------
// XDialogClosedListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogClosed( const DialogClosedEvent& _rEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DialogClosed( _rEvent );
postExecute( _rEvent.DialogResult );
}
// ------------------------------------------------------------------------
// handle XFilePickerListener events
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleFileSelectionChanged( const FilePickerEvent& )
{
if ( mbHasVersions )
updateVersions();
if ( mbShowPreview )
maPreViewTimer.Start();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDirectoryChanged( const FilePickerEvent& )
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::handleHelpRequested( const FilePickerEvent& aEvent )
{
//!!! todo: cache the help strings (here or TRA)
rtl::OString sHelpId;
// mapping from element id -> help id
switch ( aEvent.ElementId )
{
case ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION :
sHelpId = HID_FILESAVE_AUTOEXTENSION;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PASSWORD :
sHelpId = HID_FILESAVE_SAVEWITHPASSWORD;
break;
case ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS :
sHelpId = HID_FILESAVE_CUSTOMIZEFILTER;
break;
case ExtendedFilePickerElementIds::CHECKBOX_READONLY :
sHelpId = HID_FILEOPEN_READONLY;
break;
case ExtendedFilePickerElementIds::CHECKBOX_LINK :
sHelpId = HID_FILEDLG_LINK_CB;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW :
sHelpId = HID_FILEDLG_PREVIEW_CB;
break;
case ExtendedFilePickerElementIds::PUSHBUTTON_PLAY :
sHelpId = HID_FILESAVE_DOPLAY;
break;
case ExtendedFilePickerElementIds::LISTBOX_VERSION_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_VERSION :
sHelpId = HID_FILEOPEN_VERSION;
break;
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE :
sHelpId = HID_FILESAVE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE :
sHelpId = HID_FILEOPEN_IMAGE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::CHECKBOX_SELECTION :
sHelpId = HID_FILESAVE_SELECTION;
break;
default:
DBG_ERRORFILE( "invalid element id" );
}
OUString aHelpText;
Help* pHelp = Application::GetHelp();
if ( pHelp )
aHelpText = String( pHelp->GetHelpText( String( ByteString(sHelpId), RTL_TEXTENCODING_UTF8), NULL ) );
return aHelpText;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleControlStateChanged( const FilePickerEvent& aEvent )
{
switch ( aEvent.ElementId )
{
case CommonFilePickerElementIds::LISTBOX_FILTER:
updateFilterOptionsBox();
enablePasswordBox( sal_False );
updateSelectionBox();
// only use it for export and with our own dialog
if ( mbExport && !mbSystemPicker )
updateExportButton();
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW:
updatePreviewState();
break;
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDialogSizeChanged()
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
// XEventListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::disposing( const EventObject& ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
dispose();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::dispose()
{
if ( mxFileDlg.is() )
{
// remove the event listener
uno::Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
if ( xNotifier.is() )
xNotifier->removeFilePickerListener( this );
::comphelper::disposeComponent( mxFileDlg );
mxFileDlg.clear();
}
}
// ------------------------------------------------------------------------
String FileDialogHelper_Impl::getCurrentFilterUIName() const
{
String aFilterName;
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if( xFltMgr.is() )
{
aFilterName = xFltMgr->getCurrentFilter();
if ( aFilterName.Len() && isShowFilterExtensionEnabled() )
aFilterName = getFilterName( aFilterName );
}
return aFilterName;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::LoadLastUsedFilter( const OUString& _rContextIdentifier )
{
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
if( aDlgOpt.Exists() )
{
OUString aLastFilter;
if( aDlgOpt.GetUserItem( _rContextIdentifier ) >>= aLastFilter )
setFilter( aLastFilter );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::SaveLastUsedFilter( const OUString& _rContextIdentifier )
{
SvtViewOptions( E_DIALOG, IODLG_CONFIGNAME ).SetUserItem( _rContextIdentifier,
makeAny( getFilterWithExtension( getFilter() ) ) );
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::SaveLastUsedFilter( void )
{
const OUString* pConfigId = GetLastFilterConfigId( meContext );
if( pConfigId )
SaveLastUsedFilter( *pConfigId );
}
// ------------------------------------------------------------------------
const SfxFilter* FileDialogHelper_Impl::getCurentSfxFilter()
{
String aFilterName = getCurrentFilterUIName();
const SfxFilter* pFilter = NULL;
if ( mpMatcher && aFilterName.Len() )
pFilter = mpMatcher->GetFilter4UIName( aFilterName, m_nMustFlags, m_nDontFlags );
return pFilter;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable )
{
sal_Bool bIsEnabled = sal_False;
uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
try
{
xCtrlAccess->enableControl( _nExtendedControlId, _bEnable );
bIsEnabled = _bEnable;
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::updateExtendedControl: caught an exception!" );
}
}
return bIsEnabled;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::CheckFilterOptionsCapability( const SfxFilter* _pFilter )
{
sal_Bool bResult = sal_False;
if( mxFilterCFG.is() && _pFilter )
{
try {
Sequence < PropertyValue > aProps;
Any aAny = mxFilterCFG->getByName( _pFilter->GetName() );
if ( aAny >>= aProps )
{
::rtl::OUString aServiceName;
sal_Int32 nPropertyCount = aProps.getLength();
for( sal_Int32 nProperty=0; nProperty < nPropertyCount; ++nProperty )
{
if( aProps[nProperty].Name.equals( DEFINE_CONST_OUSTRING( "UIComponent") ) )
{
aProps[nProperty].Value >>= aServiceName;
if( aServiceName.getLength() )
bResult = sal_True;
}
}
}
}
catch( Exception& )
{
}
}
return bResult;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::isInOpenMode() const
{
sal_Bool bRet = sal_False;
switch ( m_nDialogType )
{
case FILEOPEN_SIMPLE:
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
case FILEOPEN_PLAY:
case FILEOPEN_READONLY_VERSION:
case FILEOPEN_LINK_PREVIEW:
bRet = sal_True;
}
return bRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateFilterOptionsBox()
{
if ( !m_bHaveFilterOptions )
return;
updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS,
CheckFilterOptionsCapability( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateExportButton()
{
uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
OUString sEllipses( RTL_CONSTASCII_USTRINGPARAM( "..." ) );
OUString sOldLabel( xCtrlAccess->getLabel( CommonFilePickerElementIds::PUSHBUTTON_OK ) );
// initialize button label; we need the label with the mnemonic char
if ( !maButtonLabel.getLength() || maButtonLabel.indexOf( MNEMONIC_CHAR ) == -1 )
{
// cut the ellipses, if necessary
sal_Int32 nIndex = sOldLabel.indexOf( sEllipses );
if ( -1 == nIndex )
nIndex = sOldLabel.getLength();
maButtonLabel = sOldLabel.copy( 0, nIndex );
}
OUString sLabel = maButtonLabel;
// filter with options -> append ellipses on export button label
if ( CheckFilterOptionsCapability( getCurentSfxFilter() ) )
sLabel += OUString( RTL_CONSTASCII_USTRINGPARAM( "..." ) );
if ( sOldLabel != sLabel )
{
try
{
xCtrlAccess->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK, sLabel );
}
catch( const IllegalArgumentException& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::updateExportButton: caught an exception!" );
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateSelectionBox()
{
if ( !mbHasSelectionBox )
return;
// Does the selection box exist?
sal_Bool bSelectionBoxFound = sal_False;
uno::Reference< XControlInformation > xCtrlInfo( mxFileDlg, UNO_QUERY );
if ( xCtrlInfo.is() )
{
Sequence< ::rtl::OUString > aCtrlList = xCtrlInfo->getSupportedControls();
sal_uInt32 nCount = aCtrlList.getLength();
for ( sal_uInt32 nCtrl = 0; nCtrl < nCount; ++nCtrl )
if ( aCtrlList[ nCtrl ].equalsAscii("SelectionBox") )
{
bSelectionBoxFound = sal_False;
break;
}
}
if ( bSelectionBoxFound )
{
const SfxFilter* pFilter = getCurentSfxFilter();
mbSelectionFltrEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_SELECTION,
( mbSelectionEnabled && pFilter && ( pFilter->GetFilterFlags() & SFX_FILTER_SUPPORTSSELECTION ) != 0 ) );
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0, makeAny( (sal_Bool)mbSelection ) );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::enablePasswordBox( sal_Bool bInit )
{
if ( ! mbHasPassword )
return;
sal_Bool bWasEnabled = mbIsPwdEnabled;
const SfxFilter* pCurrentFilter = getCurentSfxFilter();
mbIsPwdEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_PASSWORD,
pCurrentFilter && ( pCurrentFilter->GetFilterFlags() & SFX_FILTER_ENCRYPTION )
);
if( bInit )
{
// in case of inintialization previous state is not interesting
if( mbIsPwdEnabled )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if( mbPwdCheckBoxState )
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_True ) );
}
}
else if( !bWasEnabled && mbIsPwdEnabled )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if( mbPwdCheckBoxState )
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_True ) );
}
else if( bWasEnabled && !mbIsPwdEnabled )
{
// remember user settings until checkbox is enabled
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
mbPwdCheckBoxState = ( aValue >>= bPassWord ) && bPassWord;
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_False ) );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updatePreviewState( sal_Bool _bUpdatePreviewWindow )
{
if ( mbHasPreview )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a preview
if ( xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
sal_Bool bShowPreview = sal_False;
if ( aValue >>= bShowPreview )
{
mbShowPreview = bShowPreview;
// #97633
// setShowState has currently no effect for the
// OpenOffice FilePicker (see svtools/source/filepicker/iodlg.cxx)
uno::Reference< XFilePreview > xFilePreview( mxFileDlg, UNO_QUERY );
if ( xFilePreview.is() )
xFilePreview->setShowState( mbShowPreview );
if ( _bUpdatePreviewWindow )
TimeOutHdl_Impl( NULL );
}
}
catch( Exception )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::updatePreviewState: caught an exception!" );
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateVersions()
{
Sequence < OUString > aEntries;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
INetURLObject aObj( aPathSeq[0] );
if ( ( aObj.GetProtocol() == INET_PROT_FILE ) &&
( utl::UCBContentHelper::IsDocument( aObj.GetMainURL( INetURLObject::NO_DECODE ) ) ) )
{
try
{
uno::Reference< embed::XStorage > xStorage = ::comphelper::OStorageHelper::GetStorageFromURL(
aObj.GetMainURL( INetURLObject::NO_DECODE ),
embed::ElementModes::READ );
DBG_ASSERT( xStorage.is(), "The method must return the storage or throw an exception!" );
if ( !xStorage.is() )
throw uno::RuntimeException();
uno::Sequence < util::RevisionTag > xVersions = SfxMedium::GetVersionList( xStorage );
aEntries.realloc( xVersions.getLength() + 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
for ( sal_Int32 i=0; i<xVersions.getLength(); i++ )
aEntries[ i + 1 ] = xVersions[i].Identifier;
// TODO/LATER: not sure that this information must be shown in future ( binfilter? )
//REMOVE else
//REMOVE {
//REMOVE SfxFilterFlags nMust = SFX_FILTER_IMPORT | SFX_FILTER_OWN;
//REMOVE SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED | SFX_FILTER_STARONEFILTER;
//REMOVE if ( SFX_APP()->GetFilterMatcher().GetFilter4ClipBoardId( pStor->GetFormat(), nMust, nDont ) )
//REMOVE {
//REMOVE aEntries.realloc( 1 );
//REMOVE aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
//REMOVE }
//REMOVE }
}
catch( uno::Exception& )
{
}
}
}
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::DELETE_ITEMS, aValue );
}
catch( IllegalArgumentException ){}
sal_Int32 nCount = aEntries.getLength();
if ( nCount )
{
try
{
aValue <<= aEntries;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::ADD_ITEMS, aValue );
Any aPos;
aPos <<= (sal_Int32) 0;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::SET_SELECT_ITEM, aPos );
}
catch( IllegalArgumentException ){}
}
}
// -----------------------------------------------------------------------
class OReleaseSolarMutex
{
private:
const sal_Int32 m_nAquireCount;
public:
OReleaseSolarMutex( )
:m_nAquireCount( Application::ReleaseSolarMutex() )
{
}
~OReleaseSolarMutex( )
{
Application::AcquireSolarMutex( m_nAquireCount );
}
};
// -----------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, TimeOutHdl_Impl, Timer*, EMPTYARG )
{
if ( !mbHasPreview )
return 0;
maGraphic.Clear();
Any aAny;
uno::Reference < XFilePreview > xFilePicker( mxFileDlg, UNO_QUERY );
if ( ! xFilePicker.is() )
return 0;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( mbShowPreview && ( aPathSeq.getLength() == 1 ) )
{
OUString aURL = aPathSeq[0];
if ( ERRCODE_NONE == getGraphic( aURL, maGraphic ) )
{
// #89491
// changed the code slightly;
// before: the bitmap was scaled and
// surrounded a white frame
// now: the bitmap will only be scaled
// and the filepicker implementation
// is responsible for placing it at its
// proper position and painting a frame
Bitmap aBmp = maGraphic.GetBitmap();
// scale the bitmap to the correct size
sal_Int32 nOutWidth = xFilePicker->getAvailableWidth();
sal_Int32 nOutHeight = xFilePicker->getAvailableHeight();
sal_Int32 nBmpWidth = aBmp.GetSizePixel().Width();
sal_Int32 nBmpHeight = aBmp.GetSizePixel().Height();
double nXRatio = (double) nOutWidth / nBmpWidth;
double nYRatio = (double) nOutHeight / nBmpHeight;
if ( nXRatio < nYRatio )
aBmp.Scale( nXRatio, nXRatio );
else
aBmp.Scale( nYRatio, nYRatio );
// #94505# Convert to true color, to allow CopyPixel
aBmp.Convert( BMP_CONVERSION_24BIT );
// and copy it into the Any
SvMemoryStream aData;
aData << aBmp;
const Sequence < sal_Int8 > aBuffer(
static_cast< const sal_Int8* >(aData.GetData()),
aData.GetEndOfData() );
aAny <<= aBuffer;
}
}
try
{
OReleaseSolarMutex aReleaseForCallback;
// clear the preview window
xFilePicker->setImage( FilePreviewImageFormats::BITMAP, aAny );
}
catch( IllegalArgumentException )
{
}
return 0;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( const OUString& rURL,
Graphic& rGraphic ) const
{
if ( utl::UCBContentHelper::IsFolder( rURL ) )
return ERRCODE_IO_NOTAFILE;
if ( !mpGraphicFilter )
return ERRCODE_IO_NOTSUPPORTED;
// select graphic filter from dialog filter selection
OUString aCurFilter( getFilter() );
sal_uInt16 nFilter = aCurFilter.getLength() && mpGraphicFilter->GetImportFormatCount()
? mpGraphicFilter->GetImportFormatNumber( aCurFilter )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURLObj( rURL );
if ( aURLObj.HasError() || INET_PROT_NOT_VALID == aURLObj.GetProtocol() )
{
aURLObj.SetSmartProtocol( INET_PROT_FILE );
aURLObj.SetSmartURL( rURL );
}
ErrCode nRet = ERRCODE_NONE;
sal_uInt32 nFilterImportFlags = GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
// non-local?
if ( INET_PROT_FILE != aURLObj.GetProtocol() )
{
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( rURL, STREAM_READ );
if( pStream )
nRet = mpGraphicFilter->ImportGraphic( rGraphic, rURL, *pStream, nFilter, NULL, nFilterImportFlags );
else
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
delete pStream;
}
else
{
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
}
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( Graphic& rGraphic ) const
{
ErrCode nRet = ERRCODE_NONE;
if ( ! maGraphic )
{
OUString aPath;;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
if ( aPath.getLength() )
nRet = getGraphic( aPath, rGraphic );
else
nRet = ERRCODE_IO_GENERAL;
}
else
rGraphic = maGraphic;
return nRet;
}
// ------------------------------------------------------------------------
sal_Bool lcl_isSystemFilePicker( const uno::Reference< XFilePicker >& _rxFP )
{
try
{
uno::Reference< XServiceInfo > xSI( _rxFP, UNO_QUERY );
if ( xSI.is() && xSI->supportsService( DEFINE_CONST_OUSTRING( "com.sun.star.ui.dialogs.SystemFilePicker" ) ) )
return sal_True;
}
catch( const Exception& )
{
}
return sal_False;
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper_Impl::FileDialogHelper_Impl(
FileDialogHelper* _pAntiImpl,
sal_Int16 nDialogType,
sal_Int64 nFlags,
sal_Int16 nDialog,
Window* _pPreferredParentWindow,
const String& sStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList
)
:m_nDialogType ( nDialogType )
,meContext ( FileDialogHelper::UNKNOWN_CONTEXT )
{
const char* pServiceName=0;
if ( nDialog == SFX2_IMPL_DIALOG_SYSTEM )
pServiceName = FILE_OPEN_SERVICE_NAME_OOO;
else if ( nDialog == SFX2_IMPL_DIALOG_OOO )
pServiceName = FILE_OPEN_SERVICE_NAME_OOO;
else
pServiceName = FILE_OPEN_SERVICE_NAME;
OUString aService = ::rtl::OUString::createFromAscii( pServiceName );
uno::Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
// create the file open dialog
// the flags can be SFXWB_INSERT or SFXWB_MULTISELECTION
mpPreferredParentWindow = _pPreferredParentWindow;
mpAntiImpl = _pAntiImpl;
mnError = ERRCODE_NONE;
mbHasAutoExt = sal_False;
mbHasPassword = sal_False;
m_bHaveFilterOptions = sal_False;
mbIsPwdEnabled = sal_True;
mbHasVersions = sal_False;
mbHasPreview = sal_False;
mbShowPreview = sal_False;
mbHasLink = sal_False;
mbDeleteMatcher = sal_False;
mbInsert = SFXWB_INSERT == ( nFlags & SFXWB_INSERT );
mbExport = SFXWB_EXPORT == ( nFlags & SFXWB_EXPORT );
mbIsSaveDlg = sal_False;
mbPwdCheckBoxState = sal_False;
mbSelection = sal_False;
mbSelectionEnabled = sal_True;
mbHasSelectionBox = sal_False;
mbSelectionFltrEnabled = sal_False;
// default settings
m_nDontFlags = SFX_FILTER_INTERNAL | SFX_FILTER_NOTINFILEDLG | SFX_FILTER_NOTINSTALLED;
if( WB_OPEN == ( nFlags & WB_OPEN ) )
m_nMustFlags = SFX_FILTER_IMPORT;
else
m_nMustFlags = SFX_FILTER_EXPORT;
mpMatcher = NULL;
mpGraphicFilter = NULL;
mnPostUserEventId = 0;
// create the picker component
mxFileDlg = mxFileDlg.query( xFactory->createInstance( aService ) );
mbSystemPicker = lcl_isSystemFilePicker( mxFileDlg );
uno::Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
uno::Reference< XInitialization > xInit( mxFileDlg, UNO_QUERY );
if ( ! mxFileDlg.is() || ! xNotifier.is() )
{
mnError = ERRCODE_ABORT;
return;
}
if ( xInit.is() )
{
sal_Int16 nTemplateDescription = TemplateDescription::FILEOPEN_SIMPLE;
switch ( m_nDialogType )
{
case FILEOPEN_SIMPLE:
nTemplateDescription = TemplateDescription::FILEOPEN_SIMPLE;
break;
case FILESAVE_SIMPLE:
nTemplateDescription = TemplateDescription::FILESAVE_SIMPLE;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD;
mbHasPassword = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS;
mbHasPassword = sal_True;
m_bHaveFilterOptions = sal_True;
if( xFactory.is() )
{
mxFilterCFG = uno::Reference< XNameAccess >(
xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.document.FilterFactory" ) ),
UNO_QUERY );
}
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_SELECTION:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
mbHasSelectionBox = sal_True;
if ( mbExport && !mxFilterCFG.is() && xFactory.is() )
{
mxFilterCFG = uno::Reference< XNameAccess >(
xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.document.FilterFactory" ) ),
UNO_QUERY );
}
break;
case FILESAVE_AUTOEXTENSION_TEMPLATE:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_TEMPLATE;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
nTemplateDescription = TemplateDescription::FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILEOPEN_PLAY:
nTemplateDescription = TemplateDescription::FILEOPEN_PLAY;
break;
case FILEOPEN_READONLY_VERSION:
nTemplateDescription = TemplateDescription::FILEOPEN_READONLY_VERSION;
mbHasVersions = sal_True;
break;
case FILEOPEN_LINK_PREVIEW:
nTemplateDescription = TemplateDescription::FILEOPEN_LINK_PREVIEW;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILESAVE_AUTOEXTENSION:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
default:
DBG_ERRORFILE( "FileDialogHelper::ctor with unknown type" );
break;
}
//Sequence < Any > aInitArguments( mbSystemPicker || !mpPreferredParentWindow ? 1 : 3 );
Sequence < Any > aInitArguments( !mpPreferredParentWindow ? 3 : 4 );
// This is a hack. We currently know that the internal file picker implementation
// supports the extended arguments as specified below.
// TODO:
// a) adjust the service description so that it includes the TemplateDescription and ParentWindow args
// b) adjust the implementation of the system file picker to that it recognizes it
if ( mbSystemPicker )
{
aInitArguments[0] <<= nTemplateDescription;
}
else
{
aInitArguments[0] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TemplateDescription" ) ),
makeAny( nTemplateDescription )
);
::rtl::OUString sStandardDirTemp = ::rtl::OUString( sStandardDir );
aInitArguments[1] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StandardDir" ) ),
makeAny( sStandardDirTemp )
);
aInitArguments[2] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BlackList" ) ),
makeAny( rBlackList )
);
if ( mpPreferredParentWindow )
aInitArguments[3] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ParentWindow" ) ),
makeAny( VCLUnoHelper::GetInterface( mpPreferredParentWindow ) )
);
}
try
{
xInit->initialize( aInitArguments );
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::FileDialogHelper_Impl: could not initialize the picker!" );
}
}
// set multiselection mode
if ( nFlags & SFXWB_MULTISELECTION )
mxFileDlg->setMultiSelectionMode( sal_True );
if ( mbHasLink ) // generate graphic filter only on demand
addGraphicFilter();
// Export dialog
if ( mbExport )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_EXPORT ) ) ) );
try {
com::sun::star::uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY_THROW );
xCtrlAccess->enableControl( ExtendedFilePickerElementIds::LISTBOX_FILTER_SELECTOR, sal_True );
}
catch( const Exception & ) { }
}
// the "insert file" dialog needs another title
if ( mbInsert )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_INSERT ) ) ) );
uno::Reference < XFilePickerControlAccess > xExtDlg( mxFileDlg, UNO_QUERY );
if ( xExtDlg.is() )
{
try
{
xExtDlg->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK,
OUString( String( SfxResId( STR_SFX_EXPLORERFILE_BUTTONINSERT ) ) ) );
}
catch( IllegalArgumentException ){}
}
}
// add the event listener
xNotifier->addFilePickerListener( this );
}
// ------------------------------------------------------------------------
FileDialogHelper_Impl::~FileDialogHelper_Impl()
{
// Remove user event if we haven't received it yet
if ( mnPostUserEventId )
Application::RemoveUserEvent( mnPostUserEventId );
mnPostUserEventId = 0;
delete mpGraphicFilter;
if ( mbDeleteMatcher )
delete mpMatcher;
maPreViewTimer.SetTimeoutHdl( Link() );
::comphelper::disposeComponent( mxFileDlg );
}
#define nMagic -1
class PickerThread_Impl : public ::vos::OThread
{
uno::Reference < XFilePicker > mxPicker;
::vos::OMutex maMutex;
virtual void SAL_CALL run();
sal_Int16 mnRet;
public:
PickerThread_Impl( const uno::Reference < XFilePicker >& rPicker )
: mxPicker( rPicker ), mnRet(nMagic) {}
sal_Int16 GetReturnValue()
{ ::vos::OGuard aGuard( maMutex ); return mnRet; }
void SetReturnValue( sal_Int16 aRetValue )
{ ::vos::OGuard aGuard( maMutex ); mnRet = aRetValue; }
};
void SAL_CALL PickerThread_Impl::run()
{
try
{
sal_Int16 n = mxPicker->execute();
SetReturnValue( n );
}
catch( RuntimeException& )
{
SetReturnValue( ExecutableDialogResults::CANCEL );
DBG_ERRORFILE( "RuntimeException caught" );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setControlHelpIds( const sal_Int16* _pControlId, const char** _pHelpId )
{
DBG_ASSERT( _pControlId && _pHelpId, "FileDialogHelper_Impl::setControlHelpIds: invalid array pointers!" );
if ( !_pControlId || !_pHelpId )
return;
// forward these ids to the file picker
try
{
const ::rtl::OUString sHelpIdPrefix( RTL_CONSTASCII_USTRINGPARAM( INET_HID_SCHEME ) );
// the ids for the single controls
uno::Reference< XFilePickerControlAccess > xControlAccess( mxFileDlg, UNO_QUERY );
if ( xControlAccess.is() )
{
while ( *_pControlId )
{
DBG_ASSERT( INetURLObject( rtl::OStringToOUString( *_pHelpId, RTL_TEXTENCODING_UTF8 ) ).GetProtocol() == INET_PROT_NOT_VALID, "Wrong HelpId!" );
::rtl::OUString sId( sHelpIdPrefix );
sId += ::rtl::OUString( *_pHelpId, strlen( *_pHelpId ), RTL_TEXTENCODING_UTF8 );
xControlAccess->setValue( *_pControlId, ControlActions::SET_HELP_URL, makeAny( sId ) );
++_pControlId; ++_pHelpId;
}
}
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::setControlHelpIds: caught an exception while setting the help ids!" );
}
}
// ------------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, InitControls, void*, NOTINTERESTEDIN )
{
(void)NOTINTERESTEDIN;
mnPostUserEventId = 0;
enablePasswordBox( sal_True );
updateFilterOptionsBox( );
updateSelectionBox( );
return 0L;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::preExecute()
{
loadConfig( );
setDefaultValues( );
updatePreviewState( sal_False );
implInitializeFileName( );
// #106079# / 2002-12-09 / fs@openoffice.org
#if !(defined(MACOSX) && defined(QUARTZ)) && !defined(WNT)
// allow for dialog implementations which need to be executed before they return valid values for
// current filter and such
// On Vista (at least SP1) it's the same as on MacOSX, the modal dialog won't let message pass
// through before it returns from execution
mnPostUserEventId = Application::PostUserEvent( LINK( this, FileDialogHelper_Impl, InitControls ) );
#else
// However, the Mac OS X implementation's pickers run modally in execute and so the event doesn't
// get through in time... so we call the methods directly
enablePasswordBox( sal_True );
updateFilterOptionsBox( );
updateSelectionBox( );
#endif
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::postExecute( sal_Int16 _nResult )
{
if ( ExecutableDialogResults::CANCEL != _nResult )
saveConfig();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implInitializeFileName( )
{
if ( maFileName.getLength() )
{
INetURLObject aObj( maPath );
aObj.Append( maFileName );
// in case we're operating as save dialog, and "auto extension" is checked,
// cut the extension from the name
// #106079# / 2002-12-09 / fs@openoffice.org
if ( mbIsSaveDlg && mbHasAutoExt )
{
try
{
sal_Bool bAutoExtChecked = sal_False;
uno::Reference < XFilePickerControlAccess > xControlAccess( mxFileDlg, UNO_QUERY );
if ( xControlAccess.is()
&& ( xControlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 )
>>= bAutoExtChecked
)
)
{
if ( bAutoExtChecked )
{ // cut the extension
aObj.removeExtension( );
mxFileDlg->setDefaultName( aObj.GetName( INetURLObject::DECODE_WITH_CHARSET ) );
}
}
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::implInitializeFileName: could not ask for the auto-extension current-value!" );
}
}
}
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper_Impl::implDoExecute()
{
preExecute();
sal_Int16 nRet = ExecutableDialogResults::CANCEL;
//On MacOSX the native file picker has to run in the primordial thread because of drawing issues
//On Linux the native gtk file picker, when backed by gnome-vfs2, needs to be run in the same
//primordial thread as the ucb gnome-vfs2 provider was initialized in.
/*
#ifdef WNT
if ( mbSystemPicker )
{
PickerThread_Impl* pThread = new PickerThread_Impl( mxFileDlg );
pThread->create();
while ( pThread->GetReturnValue() == nMagic )
Application::Yield();
pThread->join();
nRet = pThread->GetReturnValue();
delete pThread;
}
else
#endif
*/
{
try
{
#ifdef WNT
if ( mbSystemPicker )
{
OReleaseSolarMutex aSolarMutex;
nRet = mxFileDlg->execute();
}
else
#endif
nRet = mxFileDlg->execute();
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
postExecute( nRet );
return nRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implStartExecute()
{
DBG_ASSERT( mxFileDlg.is(), "invalid file dialog" );
preExecute();
if ( mbSystemPicker )
{
}
else
{
try
{
uno::Reference< XAsynchronousExecutableDialog > xAsyncDlg( mxFileDlg, UNO_QUERY );
if ( xAsyncDlg.is() )
xAsyncDlg->startExecuteModal( this );
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
String FileDialogHelper_Impl::implEnsureURLExtension(const String& sURL,
const String& /*sExtension*/)
{
return sURL;
/*
// This feature must be active for file save/export only !
if (
(! mbIsSaveDlg) &&
(! mbExport )
)
return sURL;
// no extension available (because "ALL *.*" was selected) ?
// Nod idea what else should happen here .-)
if (sExtension.Len() < 1)
return sURL;
// Some FilePicker implementations already add the right extension ...
// or might be the user used the right one already ...
// Dont create duplicate extension.
INetURLObject aURL(sURL);
if (aURL.getExtension().equals(sExtension))
return sURL;
// Ignore any other extension set by the user.
// Make sure suitable extension is used always.
// e.g. "test.bla.odt" for "ODT"
::rtl::OUStringBuffer sNewURL(256);
sNewURL.append (sURL );
sNewURL.appendAscii("." );
sNewURL.append (sExtension);
return sNewURL.makeStringAndClear();
*/
}
// ------------------------------------------------------------------------
void lcl_saveLastURLs(SvStringsDtor*& rpURLList ,
::comphelper::SequenceAsVector< ::rtl::OUString >& lLastURLs )
{
lLastURLs.clear();
USHORT c = rpURLList->Count();
USHORT i = 0;
for (i=0; i<c; ++i)
lLastURLs.push_back(*(rpURLList->GetObject(i)));
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implGetAndCacheFiles(const uno::Reference< XInterface >& xPicker ,
SvStringsDtor*& rpURLList,
const SfxFilter* pFilter )
{
rpURLList = NULL;
String sExtension;
if (pFilter)
{
sExtension = pFilter->GetDefaultExtension ();
sExtension.EraseAllChars( '*' );
sExtension.EraseAllChars( '.' );
}
// a) the new way (optional!)
uno::Reference< XFilePicker2 > xPickNew(xPicker, UNO_QUERY);
if (xPickNew.is())
{
rpURLList = new SvStringsDtor;
Sequence< OUString > lFiles = xPickNew->getSelectedFiles();
::sal_Int32 nFiles = lFiles.getLength();
for (::sal_Int32 i = 0; i < nFiles; i++)
{
String* pURL = new String(implEnsureURLExtension(lFiles[i], sExtension));
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
// b) the olde way ... non optional.
else
{
uno::Reference< XFilePicker > xPickOld(xPicker, UNO_QUERY_THROW);
Sequence< OUString > lFiles = xPickOld->getFiles();
::sal_Int32 nFiles = lFiles.getLength();
if ( nFiles == 1 )
{
rpURLList = new SvStringsDtor;
String* pURL = new String(implEnsureURLExtension(lFiles[0], sExtension));
rpURLList->Insert( pURL, 0 );
}
else
if ( nFiles > 1 )
{
rpURLList = new SvStringsDtor;
INetURLObject aPath( lFiles[0] );
aPath.setFinalSlash();
for (::sal_Int32 i = 1; i < nFiles; i++)
{
if (i == 1)
aPath.Append( lFiles[i] );
else
aPath.setName( lFiles[i] );
String* pURL = new String(implEnsureURLExtension(aPath.GetMainURL( INetURLObject::NO_DECODE ), sExtension) );
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
}
lcl_saveLastURLs(rpURLList, mlLastURLs);
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
// rFilter is a pure output parameter, it shouldn't be used for anything else
// changing this would surely break code
// rpSet is in/out parameter, usually just a media-descriptor that can be changed by dialog
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// retrieves parameters from rpSet
// for now only Password is used
if ( rpSet )
{
// check password checkbox if the document had password before
if( mbHasPassword )
{
SFX_ITEMSET_ARG( rpSet, pPassItem, SfxStringItem, SID_PASSWORD, FALSE );
mbPwdCheckBoxState = ( pPassItem != NULL );
// in case the document has password to modify, the dialog should be shown
SFX_ITEMSET_ARG( rpSet, pPassToModifyItem, SfxUnoAnyItem, SID_MODIFYPASSWORDINFO, FALSE );
mbPwdCheckBoxState |= ( pPassToModifyItem && pPassToModifyItem->GetValue().hasValue() );
}
SFX_ITEMSET_ARG( rpSet, pSelectItem, SfxBoolItem, SID_SELECTION, FALSE );
if ( pSelectItem )
mbSelection = pSelectItem->GetValue();
else
mbSelectionEnabled = sal_False;
// the password will be set in case user decide so
rpSet->ClearItem( SID_PASSWORD );
rpSet->ClearItem( SID_RECOMMENDREADONLY );
rpSet->ClearItem( SID_MODIFYPASSWORDINFO );
}
if ( mbHasPassword && !mbPwdCheckBoxState )
{
SvtSecurityOptions aSecOpt;
mbPwdCheckBoxState = (
aSecOpt.IsOptionSet( SvtSecurityOptions::E_DOCWARN_RECOMMENDPASSWORD ) );
}
rpURLList = NULL;
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
if ( ExecutableDialogResults::CANCEL != implDoExecute() )
{
// create an itemset if there is no
if( !rpSet )
rpSet = new SfxAllItemSet( SFX_APP()->GetPool() );
// the item should remain only if it was set by the dialog
rpSet->ClearItem( SID_SELECTION );
if( mbExport )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 );
sal_Bool bSelection = sal_False;
if ( aValue >>= bSelection )
rpSet->Put( SfxBoolItem( SID_SELECTION, bSelection ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
// set the read-only flag. When inserting a file, this flag is always set
if ( mbInsert )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
else
{
if ( ( FILEOPEN_READONLY_VERSION == m_nDialogType ) && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_READONLY, 0 );
sal_Bool bReadOnly = sal_False;
if ( ( aValue >>= bReadOnly ) && bReadOnly )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, bReadOnly ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
}
if ( mbHasVersions && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::GET_SELECTED_ITEM_INDEX );
sal_Int32 nVersion = 0;
if ( ( aValue >>= nVersion ) && nVersion > 0 )
// open a special version; 0 == current version
rpSet->Put( SfxInt16Item( SID_VERSION, (short)nVersion ) );
}
catch( IllegalArgumentException ){}
}
// set the filter
getRealFilter( rFilter );
const SfxFilter* pCurrentFilter = getCurentSfxFilter();
// fill the rpURLList
implGetAndCacheFiles( mxFileDlg, rpURLList, pCurrentFilter );
if ( rpURLList == NULL || rpURLList->GetObject(0) == NULL )
return ERRCODE_ABORT;
// check, wether or not we have to display a password box
if ( pCurrentFilter && mbHasPassword && mbIsPwdEnabled && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
if ( ( aValue >>= bPassWord ) && bPassWord )
{
// ask for a password
uno::Reference < ::com::sun::star::task::XInteractionHandler > xInteractionHandler( ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.comp.uui.UUIInteractionHandler")), UNO_QUERY );
if( xInteractionHandler.is() )
{
// TODO: need a save way to distinguish MS filters from other filters
// for now MS-filters are the only alien filters that support encryption
sal_Bool bMSType = !pCurrentFilter->IsOwnFormat();
::comphelper::DocPasswordRequestType eType = bMSType ?
::comphelper::DocPasswordRequestType_MS :
::comphelper::DocPasswordRequestType_STANDARD;
::rtl::Reference< ::comphelper::DocPasswordRequest > pPasswordRequest( new ::comphelper::DocPasswordRequest( eType, ::com::sun::star::task::PasswordRequestMode_PASSWORD_CREATE, *(rpURLList->GetObject(0)), ( pCurrentFilter->GetFilterFlags() & SFX_FILTER_PASSWORDTOMODIFY ) != 0 ) );
uno::Reference< com::sun::star::task::XInteractionRequest > rRequest( pPasswordRequest.get() );
xInteractionHandler->handle( rRequest );
if ( pPasswordRequest->isPassword() )
{
if ( pPasswordRequest->getPassword().getLength() )
rpSet->Put( SfxStringItem( SID_PASSWORD, pPasswordRequest->getPassword() ) );
if ( pPasswordRequest->getRecommendReadOnly() )
rpSet->Put( SfxBoolItem( SID_RECOMMENDREADONLY, sal_True ) );
if ( bMSType )
{
// the empty password has 0 as Hash
sal_Int32 nHash = SfxMedium::CreatePasswordToModifyHash( pPasswordRequest->getPasswordToModify(), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.text.TextDocument" ) ).equals( pCurrentFilter->GetServiceName() ) );
if ( nHash )
rpSet->Put( SfxUnoAnyItem( SID_MODIFYPASSWORDINFO, uno::makeAny( nHash ) ) );
}
else
{
uno::Sequence< beans::PropertyValue > aModifyPasswordInfo = ::comphelper::DocPasswordHelper::GenerateNewModifyPasswordInfo( pPasswordRequest->getPasswordToModify() );
if ( aModifyPasswordInfo.getLength() )
rpSet->Put( SfxUnoAnyItem( SID_MODIFYPASSWORDINFO, uno::makeAny( aModifyPasswordInfo ) ) );
}
}
else
return ERRCODE_ABORT;
}
}
}
catch( IllegalArgumentException ){}
}
SaveLastUsedFilter();
return ERRCODE_NONE;
}
else
return ERRCODE_ABORT;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute()
{
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
sal_Int16 nRet = implDoExecute();
maPath = mxFileDlg->getDisplayDirectory();
if ( ExecutableDialogResults::CANCEL == nRet )
return ERRCODE_ABORT;
else
{
return ERRCODE_NONE;
}
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getPath() const
{
OUString aPath;
if ( mxFileDlg.is() )
aPath = mxFileDlg->getDisplayDirectory();
if ( !aPath.getLength() )
aPath = maPath;
return aPath;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getFilter() const
{
String aFilter = getCurrentFilterUIName();
if( !aFilter.Len() )
aFilter = maCurFilter;
return aFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::getRealFilter( String& _rFilter ) const
{
_rFilter = getCurrentFilterUIName();
if ( !_rFilter.Len() )
_rFilter = maCurFilter;
if ( _rFilter.Len() && mpMatcher )
{
const SfxFilter* pFilter =
mpMatcher->GetFilter4UIName( _rFilter, m_nMustFlags, m_nDontFlags );
_rFilter = pFilter ? pFilter->GetFilterName() : _rFilter.Erase();
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::displayFolder( const ::rtl::OUString& _rPath )
{
if ( ! _rPath.getLength() )
// nothing to do
return;
/*
if ( !::utl::UCBContentHelper::IsFolder( _rPath ) )
// only valid folders accepted here
return;
*/
maPath = _rPath;
if ( mxFileDlg.is() )
{
try
{
mxFileDlg->setDisplayDirectory( maPath );
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::displayFolder: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFileName( const ::rtl::OUString& _rFile )
{
maFileName = _rFile;
if ( mxFileDlg.is() )
{
try
{
mxFileDlg->setDefaultName( maFileName );
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::setFileName: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFilter( const OUString& rFilter )
{
DBG_ASSERT( rFilter.indexOf(':') == -1, "Old filter name used!");
maCurFilter = rFilter;
if ( rFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter4FilterName(
rFilter, m_nMustFlags, m_nDontFlags );
if ( pFilter )
maCurFilter = pFilter->GetUIName();
}
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( maCurFilter.getLength() && xFltMgr.is() )
{
try
{
xFltMgr->setCurrentFilter( maCurFilter );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::createMatcher( const String& rFactory )
{
mpMatcher = new SfxFilterMatcher( SfxObjectShell::GetServiceNameFromFactory(rFactory) );
mbDeleteMatcher = sal_True;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilters( sal_Int64 nFlags,
const String& rFactory,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// we still need a matcher to convert UI names to filter names
if ( !rFactory.Len() )
{
SfxApplication *pSfxApp = SFX_APP();
mpMatcher = &pSfxApp->GetFilterMatcher();
mbDeleteMatcher = sal_False;
}
else
{
mpMatcher = new SfxFilterMatcher( rFactory );
mbDeleteMatcher = sal_True;
}
uno::Reference< XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();
uno::Reference< XContainerQuery > xFilterCont(
xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.document.FilterFactory")),
UNO_QUERY);
if ( ! xFilterCont.is() )
return;
m_nMustFlags |= nMust;
m_nDontFlags |= nDont;
// create the list of filters
::rtl::OUStringBuffer sQuery(256);
sQuery.appendAscii("getSortedFilterList()");
sQuery.appendAscii(":module=" );
sQuery.append (rFactory ); // use long name here !
sQuery.appendAscii(":iflags=" );
sQuery.append (::rtl::OUString::valueOf((sal_Int32)m_nMustFlags));
sQuery.appendAscii(":eflags=" );
sQuery.append (::rtl::OUString::valueOf((sal_Int32)m_nDontFlags));
uno::Reference< XEnumeration > xResult = xFilterCont->createSubSetEnumerationByQuery(sQuery.makeStringAndClear());
TSortedFilterList aIter (xResult);
// no matcher any longer used ...
mbDeleteMatcher = sal_False;
// append the filters
::rtl::OUString sFirstFilter;
if ( WB_OPEN == ( nFlags & WB_OPEN ) )
::sfx2::appendFiltersForOpen( aIter, xFltMgr, sFirstFilter, *this );
else if ( mbExport )
::sfx2::appendExportFilters( aIter, xFltMgr, sFirstFilter, *this );
else
::sfx2::appendFiltersForSave( aIter, xFltMgr, sFirstFilter, *this, rFactory );
// set our initial selected filter (if we do not already have one)
if ( !maSelectFilter.getLength() )
maSelectFilter = sFirstFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilter( const OUString& rFilterName,
const OUString& rExtension )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
try
{
xFltMgr->appendFilter( rFilterName, rExtension );
if ( !maSelectFilter.getLength() )
maSelectFilter = rFilterName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( rFilterName ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addGraphicFilter()
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
mpGraphicFilter = new GraphicFilter;
USHORT i, j, nCount = mpGraphicFilter->GetImportFormatCount();
// compute the extension string for all known import filters
String aExtensions;
for ( i = 0; i < nCount; i++ )
{
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
}
#if defined(WIN) || defined(WNT)
if ( aExtensions.Len() > 240 )
aExtensions = DEFINE_CONST_UNICODE( FILEDIALOG_FILTER_ALL );
#endif
sal_Bool bIsInOpenMode = isInOpenMode();
try
{
OUString aAllFilterName = String( SfxResId( STR_SFX_IMPORT_ALL ) );
aAllFilterName = ::sfx2::addExtension( aAllFilterName, aExtensions, bIsInOpenMode, *this );
xFltMgr->appendFilter( aAllFilterName, aExtensions );
maSelectFilter = aAllFilterName;
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
// Now add the filter
for ( i = 0; i < nCount; i++ )
{
String aName = mpGraphicFilter->GetImportFormatName( i );
String aExt;
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExt.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExt.Len() )
aExt += sal_Unicode(';');
aExt += sWildcard;
}
}
aName = ::sfx2::addExtension( aName, aExt, bIsInOpenMode, *this );
try
{
xFltMgr->appendFilter( aName, aExt );
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
}
}
// ------------------------------------------------------------------------
#define GRF_CONFIG_STR " "
#define STD_CONFIG_STR "1 "
void FileDialogHelper_Impl::saveConfig()
{
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aDlgOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData = DEFINE_CONST_UNICODE( GRF_CONFIG_STR );
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
sal_Bool bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 1, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
INetURLObject aObj( getPath() );
if ( aObj.GetProtocol() == INET_PROT_FILE )
aUserData.SetToken( 2, ' ', aObj.GetMainURL( INetURLObject::NO_DECODE ) );
String aFilter = getFilter();
aFilter = EncodeSpaces_Impl( aFilter );
aUserData.SetToken( 3, ' ', aFilter );
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
catch( IllegalArgumentException ){}
}
else
{
sal_Bool bWriteConfig = sal_False;
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData = DEFINE_CONST_UNICODE( STD_CONFIG_STR );
if ( aDlgOpt.Exists() )
{
Any aUserItem = aDlgOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( mbHasAutoExt )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 );
sal_Bool bAutoExt = sal_True;
aValue >>= bAutoExt;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bAutoExt ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( ! mbIsSaveDlg )
{
OUString aPath = getPath();
if ( aPath.getLength() &&
utl::LocalFileHelper::IsLocalFile( aPath ) )
{
aUserData.SetToken( 1, ' ', aPath );
bWriteConfig = sal_True;
}
}
if( mbHasSelectionBox && mbSelectionFltrEnabled )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 );
sal_Bool bSelection = sal_True;
aValue >>= bSelection;
if ( aUserData.GetTokenCount(' ') < 3 )
aUserData.Append(' ');
aUserData.SetToken( 2, ' ', String::CreateFromInt32( (sal_Int32) bSelection ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( bWriteConfig )
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
SfxApplication *pSfxApp = SFX_APP();
pSfxApp->SetLastDir_Impl( getPath() );
}
// ------------------------------------------------------------------------
namespace
{
static ::rtl::OUString getInitPath( const String& _rFallback, const xub_StrLen _nFallbackToken )
{
SfxApplication *pSfxApp = SFX_APP();
String sPath = pSfxApp->GetLastDir_Impl();
if ( !sPath.Len() )
sPath = _rFallback.GetToken( _nFallbackToken, ' ' );
// check if the path points to a valid (accessible) directory
sal_Bool bValid = sal_False;
if ( sPath.Len() )
{
String sPathCheck( sPath );
if ( sPathCheck.GetBuffer()[ sPathCheck.Len() - 1 ] != '/' )
sPathCheck += '/';
sPathCheck += '.';
try
{
::ucbhelper::Content aContent( sPathCheck, uno::Reference< ucb::XCommandEnvironment >() );
bValid = aContent.isFolder();
}
catch( Exception& ) {}
}
if ( !bValid )
sPath.Erase();
return sPath;
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::loadConfig()
{
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aViewOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( aUserData.Len() > 0 )
{
try
{
// respect the last "insert as link" state
sal_Bool bLink = (sal_Bool) aUserData.GetToken( 0, ' ' ).ToInt32();
if ( !xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 ).hasValue() )
{
aValue <<= bLink;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aValue );
}
// respect the last "show preview" state
sal_Bool bShowPreview = (sal_Bool) aUserData.GetToken( 1, ' ' ).ToInt32();
if ( !xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 ).hasValue() )
{
aValue <<= bShowPreview;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0, aValue );
}
if ( !maPath.getLength() )
displayFolder( getInitPath( aUserData, 2 ) );
if ( ! maCurFilter.getLength() )
{
String aFilter = aUserData.GetToken( 3, ' ' );
aFilter = DecodeSpaces_Impl( aFilter );
setFilter( aFilter );
}
// set the member so we know that we have to show the preview
mbShowPreview = bShowPreview;
}
catch( IllegalArgumentException ){}
}
if ( !maPath.getLength() )
displayFolder( SvtPathOptions().GetGraphicPath() );
}
else
{
SvtViewOptions aViewOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( ! aUserData.Len() )
aUserData = DEFINE_CONST_UNICODE( STD_CONFIG_STR );
if ( ! maPath.getLength() )
displayFolder( getInitPath( aUserData, 1 ) );
if ( mbHasAutoExt )
{
sal_Int32 nFlag = aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
if( mbHasSelectionBox )
{
sal_Int32 nFlag = aUserData.GetToken( 2, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
if ( !maPath.getLength() )
displayFolder( SvtPathOptions().GetWorkPath() );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setDefaultValues()
{
// when no filter is set, we set the curentFilter to <all>
if ( !maCurFilter.getLength() && maSelectFilter.getLength() )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
try
{
xFltMgr->setCurrentFilter( maSelectFilter );
}
catch( IllegalArgumentException )
{}
}
// when no path is set, we use the standard 'work' folder
if ( ! maPath.getLength() )
{
OUString aWorkFolder = SvtPathOptions().GetWorkPath();
try
{
mxFileDlg->setDisplayDirectory( aWorkFolder );
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::setDefaultValues: caught an exception while setting the display directory!" );
}
// INetURLObject aStdDirObj( SvtPathOptions().GetWorkPath() );
//SetStandardDir( aStdDirObj.GetMainURL( INetURLObject::NO_DECODE ) );
}
}
sal_Bool FileDialogHelper_Impl::isShowFilterExtensionEnabled() const
{
return !maFilters.empty();
}
void FileDialogHelper_Impl::addFilterPair( const OUString& rFilter,
const OUString& rFilterWithExtension )
{
maFilters.push_back( FilterPair( rFilter, rFilterWithExtension ) );
}
OUString FileDialogHelper_Impl::getFilterName( const OUString& rFilterWithExtension ) const
{
OUString sRet;
for( ::std::vector< FilterPair >::const_iterator pIter = maFilters.begin(); pIter != maFilters.end(); ++pIter )
{
if ( (*pIter).Second == rFilterWithExtension )
{
sRet = (*pIter).First;
break;
}
}
return sRet;
}
OUString FileDialogHelper_Impl::getFilterWithExtension( const OUString& rFilter ) const
{
OUString sRet;
for( ::std::vector< FilterPair >::const_iterator pIter = maFilters.begin(); pIter != maFilters.end(); ++pIter )
{
if ( (*pIter).First == rFilter )
{
sRet = (*pIter).Second;
break;
}
}
return sRet;
}
void FileDialogHelper_Impl::SetContext( FileDialogHelper::Context _eNewContext )
{
meContext = _eNewContext;
sal_Int32 nNewHelpId = 0;
OUString aConfigId;
switch( _eNewContext )
{
// #104952# dependency to SVX not allowed! When used again, another solution has to be found
// case FileDialogHelper::SW_INSERT_GRAPHIC:
// case FileDialogHelper::SC_INSERT_GRAPHIC:
// case FileDialogHelper::SD_INSERT_GRAPHIC: nNewHelpId = SID_INSERT_GRAPHIC; break;
case FileDialogHelper::SW_INSERT_SOUND:
case FileDialogHelper::SC_INSERT_SOUND:
case FileDialogHelper::SD_INSERT_SOUND: nNewHelpId = SID_INSERT_SOUND; break;
case FileDialogHelper::SW_INSERT_VIDEO:
case FileDialogHelper::SC_INSERT_VIDEO:
case FileDialogHelper::SD_INSERT_VIDEO: nNewHelpId = SID_INSERT_VIDEO; break;
default: break;
}
const OUString* pConfigId = GetLastFilterConfigId( _eNewContext );
if( pConfigId )
LoadLastUsedFilter( *pConfigId );
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList)
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags, nDialog, NULL , rStandardDir, rBlackList );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags, nDialog );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_Int64 nFlags )
{
sal_Int16 nDialogType = getDialogType( nFlags );
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const String& rFact,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList)
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, nDialog, NULL, rStandardDir, rBlackList );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
Window* _pPreferredParent )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, SFX2_IMPL_DIALOG_CONFIG, _pPreferredParent );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const ::rtl::OUString& aFilterUIName,
const ::rtl::OUString& aExtName,
const ::rtl::OUString& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList,
Window* _pPreferredParent )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, SFX2_IMPL_DIALOG_CONFIG, _pPreferredParent,rStandardDir, rBlackList );
mxImp = mpImp;
// the wildcard here is expected in form "*.extension"
::rtl::OUString aWildcard;
if ( aExtName.indexOf( (sal_Unicode)'*' ) != 0 )
{
if ( aExtName.getLength() && aExtName.indexOf( (sal_Unicode)'.' ) != 0 )
aWildcard = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
else
aWildcard = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*" ) );
}
aWildcard += aExtName;
::rtl::OUString aUIString =
::sfx2::addExtension( aFilterUIName, aWildcard, ( WB_OPEN == ( nFlags & WB_OPEN ) ), *mpImp );
AddFilter( aUIString, aWildcard );
}
// ------------------------------------------------------------------------
FileDialogHelper::~FileDialogHelper()
{
mpImp->dispose();
mxImp.clear();
}
// ------------------------------------------------------------------------
void FileDialogHelper::CreateMatcher( const String& rFactory )
{
mpImp->createMatcher( SfxObjectShell::GetServiceNameFromFactory(rFactory) );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetControlHelpIds( const sal_Int16* _pControlId, const char** _pHelpId )
{
mpImp->setControlHelpIds( _pControlId, _pHelpId );
}
void FileDialogHelper::SetContext( Context _eNewContext )
{
mpImp->SetContext( _eNewContext );
}
// ------------------------------------------------------------------------
IMPL_LINK( FileDialogHelper, ExecuteSystemFilePicker, void*, EMPTYARG )
{
m_nError = mpImp->execute();
if ( m_aDialogClosedLink.IsSet() )
m_aDialogClosedLink.Call( this );
return 0L;
}
// ------------------------------------------------------------------------
// rDirPath has to be a directory
ErrCode FileDialogHelper::Execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter,
const String& rDirPath )
{
SetDisplayFolder( rDirPath );
return mpImp->execute( rpURLList, rpSet, rFilter );
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute()
{
return mpImp->execute();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( SfxItemSet *& rpSet,
String& rFilter )
{
ErrCode nRet;
SvStringsDtor* pURLList;
nRet = mpImp->execute( pURLList, rpSet, rFilter );
delete pURLList;
return nRet;
}
void FileDialogHelper::StartExecuteModal( const Link& rEndDialogHdl )
{
m_aDialogClosedLink = rEndDialogHdl;
m_nError = ERRCODE_NONE;
if ( mpImp->isSystemFilePicker() )
Application::PostUserEvent( LINK( this, FileDialogHelper, ExecuteSystemFilePicker ) );
else
mpImp->implStartExecute();
}
// ------------------------------------------------------------------------
short FileDialogHelper::GetDialogType() const
{
return mpImp ? mpImp->m_nDialogType : 0;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper::IsPasswordEnabled() const
{
return mpImp ? mpImp->isPasswordEnabled() : sal_False;
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetRealFilter() const
{
String sFilter;
if ( mpImp )
mpImp->getRealFilter( sFilter );
return sFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetTitle( const String& rNewTitle )
{
if ( mpImp->mxFileDlg.is() )
mpImp->mxFileDlg->setTitle( rNewTitle );
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetPath() const
{
OUString aPath;
if ( mpImp->mlLastURLs.size() > 0)
return mpImp->mlLastURLs[0];
if ( mpImp->mxFileDlg.is() )
{
Sequence < OUString > aPathSeq = mpImp->mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
}
return aPath;
}
// ------------------------------------------------------------------------
Sequence < OUString > FileDialogHelper::GetMPath() const
{
if ( mpImp->mlLastURLs.size() > 0)
return mpImp->mlLastURLs.getAsConstList();
if ( mpImp->mxFileDlg.is() )
return mpImp->mxFileDlg->getFiles();
else
{
Sequence < OUString > aEmpty;
return aEmpty;
}
}
// ------------------------------------------------------------------------
Sequence< ::rtl::OUString > FileDialogHelper::GetSelectedFiles() const
{
// a) the new way (optional!)
uno::Sequence< ::rtl::OUString > aResultSeq;
uno::Reference< XFilePicker2 > xPickNew(mpImp->mxFileDlg, UNO_QUERY);
if (xPickNew.is())
{
aResultSeq = xPickNew->getSelectedFiles();
}
// b) the olde way ... non optional.
else
{
uno::Reference< XFilePicker > xPickOld(mpImp->mxFileDlg, UNO_QUERY_THROW);
Sequence< OUString > lFiles = xPickOld->getFiles();
::sal_Int32 nFiles = lFiles.getLength();
if ( nFiles > 1 )
{
aResultSeq = Sequence< ::rtl::OUString >( nFiles-1 );
INetURLObject aPath( lFiles[0] );
aPath.setFinalSlash();
for (::sal_Int32 i = 1; i < nFiles; i++)
{
if (i == 1)
aPath.Append( lFiles[i] );
else
aPath.setName( lFiles[i] );
aResultSeq[i-1] = ::rtl::OUString(aPath.GetMainURL( INetURLObject::NO_DECODE ));
}
}
else
aResultSeq = lFiles;
}
return aResultSeq;
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetDisplayDirectory() const
{
return mpImp->getPath();
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetCurrentFilter() const
{
return mpImp->getFilter();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::GetGraphic( Graphic& rGraphic ) const
{
return mpImp->getGraphic( rGraphic );
}
// ------------------------------------------------------------------------
static int impl_isFolder( const OUString& rPath )
{
uno::Reference< task::XInteractionHandler > xHandler;
try
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory(), uno::UNO_QUERY_THROW );
xHandler.set( xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.task.InteractionHandler" ) ),
uno::UNO_QUERY_THROW );
}
catch ( Exception const & )
{
}
::rtl::Reference< ::comphelper::StillReadWriteInteraction > aHandler = new ::comphelper::StillReadWriteInteraction( xHandler );
try
{
::ucbhelper::Content aContent(
rPath, new ::ucbhelper::CommandEnvironment( static_cast< task::XInteractionHandler* > ( aHandler.get() ), uno::Reference< ucb::XProgressHandler >() ) );
if ( aContent.isFolder() )
return 1;
return 0;
}
catch ( Exception const & )
{
}
return -1;
}
void FileDialogHelper::SetDisplayDirectory( const String& _rPath )
{
if ( !_rPath.Len() )
return;
// if the given path isn't a folder, we cut off the last part
// and take it as filename and the rest of the path should be
// the folder
INetURLObject aObj( _rPath );
::rtl::OUString sFileName = aObj.GetName( INetURLObject::DECODE_WITH_CHARSET );
aObj.removeSegment();
::rtl::OUString sPath = aObj.GetMainURL( INetURLObject::NO_DECODE );
int nIsFolder = impl_isFolder( _rPath );
if ( nIsFolder == 0 ||
( nIsFolder == -1 && impl_isFolder( sPath ) == 1 ) )
{
mpImp->setFileName( sFileName );
mpImp->displayFolder( sPath );
}
else
{
INetURLObject aObjPathName( _rPath );
::rtl::OUString sFolder( aObjPathName.GetMainURL( INetURLObject::NO_DECODE ) );
if ( sFolder.getLength() == 0 )
{
// _rPath is not a valid path -> fallback to home directory
NAMESPACE_VOS( OSecurity ) aSecurity;
aSecurity.getHomeDir( sFolder );
}
mpImp->displayFolder( sFolder );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetDisplayFolder( const String& _rURL )
{
mpImp->displayFolder( _rURL );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetFileName( const String& _rFileName )
{
mpImp->setFileName( _rFileName );
}
// ------------------------------------------------------------------------
void FileDialogHelper::AddFilter( const String& rFilterName,
const String& rExtension )
{
mpImp->addFilter( rFilterName, rExtension );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetCurrentFilter( const String& rFilter )
{
String sFilter( rFilter );
if ( mpImp->isShowFilterExtensionEnabled() )
sFilter = mpImp->getFilterWithExtension( rFilter );
mpImp->setFilter( sFilter );
}
// ------------------------------------------------------------------------
uno::Reference < XFilePicker > FileDialogHelper::GetFilePicker() const
{
return mpImp->mxFileDlg;
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper::getDialogType( sal_Int64 nFlags ) const
{
sal_Int16 nDialogType = FILEOPEN_SIMPLE;
if ( nFlags & WB_SAVEAS )
{
if ( nFlags & SFXWB_PASSWORD )
nDialogType = FILESAVE_AUTOEXTENSION_PASSWORD;
else
nDialogType = FILESAVE_SIMPLE;
}
else if ( nFlags & SFXWB_GRAPHIC )
{
if ( nFlags & SFXWB_SHOWSTYLES )
nDialogType = FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
else
nDialogType = FILEOPEN_LINK_PREVIEW;
}
else if ( SFXWB_INSERT != ( nFlags & SFXWB_INSERT ) )
nDialogType = FILEOPEN_READONLY_VERSION;
return nDialogType;
}
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::FileSelectionChanged( const FilePickerEvent& aEvent )
{
mpImp->handleFileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DirectoryChanged( const FilePickerEvent& aEvent )
{
mpImp->handleDirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper::HelpRequested( const FilePickerEvent& aEvent )
{
return mpImp->handleHelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::ControlStateChanged( const FilePickerEvent& aEvent )
{
mpImp->handleControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogSizeChanged()
{
mpImp->handleDialogSizeChanged();
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogClosed( const DialogClosedEvent& _rEvent )
{
m_nError = ( RET_OK == _rEvent.DialogResult ) ? ERRCODE_NONE : ERRCODE_ABORT;
if ( m_aDialogClosedLink.IsSet() )
m_aDialogClosedLink.Call( this );
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
ErrCode FileOpenDialog_Impl( sal_Int64 nFlags,
const String& rFact,
SvStringsDtor *& rpURLList,
String& rFilter,
SfxItemSet *& rpSet,
const String* pPath,
sal_Int16 nDialog,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList )
{
ErrCode nRet;
FileDialogHelper aDialog( nFlags, rFact, nDialog, 0, 0, rStandardDir, rBlackList );
String aPath;
if ( pPath )
aPath = *pPath;
nRet = aDialog.Execute( rpURLList, rpSet, rFilter, aPath );
DBG_ASSERT( rFilter.SearchAscii(": ") == STRING_NOTFOUND, "Old filter name used!");
return nRet;
}
// ------------------------------------------------------------------------
String EncodeSpaces_Impl( const String& rSource )
{
String sRet( rSource );
sRet.SearchAndReplaceAll( DEFINE_CONST_UNICODE( " " ), DEFINE_CONST_UNICODE( "%20" ) );
return sRet;
}
// ------------------------------------------------------------------------
String DecodeSpaces_Impl( const String& rSource )
{
String sRet( rSource );
sRet.SearchAndReplaceAll( DEFINE_CONST_UNICODE( "%20" ), DEFINE_CONST_UNICODE( " " ) );
return sRet;
}
// ------------------------------------------------------------------------
} // end of namespace sfx2
CWS changehid: #i111874#: pickerhelper.hxx removed
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_sfx2.hxx"
#include <sfx2/filedlghelper.hxx>
#include <sal/types.h>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#include <com/sun/star/ui/dialogs/ControlActions.hpp>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#include <com/sun/star/ui/dialogs/XControlInformation.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#include <com/sun/star/ui/dialogs/XFilePicker2.hpp>
#include <com/sun/star/ui/dialogs/XAsynchronousExecutableDialog.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XContainerQuery.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#include <comphelper/processfactory.hxx>
#include <comphelper/types.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/stillreadwriteinteraction.hxx>
#include <tools/urlobj.hxx>
#include <vcl/help.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/ucbhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <vos/thread.hxx>
#include <vos/mutex.hxx>
#include <vos/security.hxx>
#include <vcl/cvtgrf.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/mnemonic.hxx>
#include <unotools/pathoptions.hxx>
#include <unotools/securityoptions.hxx>
#include <svl/itemset.hxx>
#include <svl/eitem.hxx>
#include <svl/intitem.hxx>
#include <svl/stritem.hxx>
#include <svtools/filter.hxx>
#include <unotools/viewoptions.hxx>
#include <unotools/moduleoptions.hxx>
#include <svtools/helpid.hrc>
#include <comphelper/docpasswordrequest.hxx>
#include <comphelper/docpasswordhelper.hxx>
#include <ucbhelper/content.hxx>
#include <ucbhelper/commandenvironment.hxx>
#include <comphelper/storagehelper.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/app.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfac.hxx>
#include "openflag.hxx"
#include <sfx2/passwd.hxx>
#include "sfxresid.hxx"
#include <sfx2/sfxsids.hrc>
#include "filedlghelper.hrc"
#include "filtergrouping.hxx"
#include <sfx2/request.hxx>
#include "filedlgimpl.hxx"
#include <sfxlocal.hrc>
//-----------------------------------------------------------------------------
using namespace ::com::sun::star;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::ui::dialogs::TemplateDescription;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
#define IODLG_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Save"))
#define IMPGRF_CONFIGNAME String(DEFINE_CONST_UNICODE("FilePicker_Graph"))
#define USERITEM_NAME ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "UserItem" ))
//-----------------------------------------------------------------------------
namespace sfx2
{
const OUString* GetLastFilterConfigId( FileDialogHelper::Context _eContext )
{
static const OUString aSD_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SdExportLastFilter" ) );
static const OUString aSI_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SiExportLastFilter" ) );
static const OUString aSW_EXPORT_IDENTIFIER( RTL_CONSTASCII_USTRINGPARAM( "SwExportLastFilter" ) );
const OUString* pRet = NULL;
switch( _eContext )
{
case FileDialogHelper::SD_EXPORT: pRet = &aSD_EXPORT_IDENTIFIER; break;
case FileDialogHelper::SI_EXPORT: pRet = &aSI_EXPORT_IDENTIFIER; break;
case FileDialogHelper::SW_EXPORT: pRet = &aSW_EXPORT_IDENTIFIER; break;
default: break;
}
return pRet;
}
String EncodeSpaces_Impl( const String& rSource );
String DecodeSpaces_Impl( const String& rSource );
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::fileSelectionChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->FileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::directoryChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper_Impl::helpRequested( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return mpAntiImpl->HelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::controlStateChanged( const FilePickerEvent& aEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->ControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogSizeChanged() throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DialogSizeChanged();
}
// ------------------------------------------------------------------------
// XDialogClosedListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::dialogClosed( const DialogClosedEvent& _rEvent ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
mpAntiImpl->DialogClosed( _rEvent );
postExecute( _rEvent.DialogResult );
}
// ------------------------------------------------------------------------
// handle XFilePickerListener events
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleFileSelectionChanged( const FilePickerEvent& )
{
if ( mbHasVersions )
updateVersions();
if ( mbShowPreview )
maPreViewTimer.Start();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDirectoryChanged( const FilePickerEvent& )
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::handleHelpRequested( const FilePickerEvent& aEvent )
{
//!!! todo: cache the help strings (here or TRA)
rtl::OString sHelpId;
// mapping from element id -> help id
switch ( aEvent.ElementId )
{
case ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION :
sHelpId = HID_FILESAVE_AUTOEXTENSION;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PASSWORD :
sHelpId = HID_FILESAVE_SAVEWITHPASSWORD;
break;
case ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS :
sHelpId = HID_FILESAVE_CUSTOMIZEFILTER;
break;
case ExtendedFilePickerElementIds::CHECKBOX_READONLY :
sHelpId = HID_FILEOPEN_READONLY;
break;
case ExtendedFilePickerElementIds::CHECKBOX_LINK :
sHelpId = HID_FILEDLG_LINK_CB;
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW :
sHelpId = HID_FILEDLG_PREVIEW_CB;
break;
case ExtendedFilePickerElementIds::PUSHBUTTON_PLAY :
sHelpId = HID_FILESAVE_DOPLAY;
break;
case ExtendedFilePickerElementIds::LISTBOX_VERSION_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_VERSION :
sHelpId = HID_FILEOPEN_VERSION;
break;
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_TEMPLATE :
sHelpId = HID_FILESAVE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE_LABEL :
case ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE :
sHelpId = HID_FILEOPEN_IMAGE_TEMPLATE;
break;
case ExtendedFilePickerElementIds::CHECKBOX_SELECTION :
sHelpId = HID_FILESAVE_SELECTION;
break;
default:
DBG_ERRORFILE( "invalid element id" );
}
OUString aHelpText;
Help* pHelp = Application::GetHelp();
if ( pHelp )
aHelpText = String( pHelp->GetHelpText( String( ByteString(sHelpId), RTL_TEXTENCODING_UTF8), NULL ) );
return aHelpText;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleControlStateChanged( const FilePickerEvent& aEvent )
{
switch ( aEvent.ElementId )
{
case CommonFilePickerElementIds::LISTBOX_FILTER:
updateFilterOptionsBox();
enablePasswordBox( sal_False );
updateSelectionBox();
// only use it for export and with our own dialog
if ( mbExport && !mbSystemPicker )
updateExportButton();
break;
case ExtendedFilePickerElementIds::CHECKBOX_PREVIEW:
updatePreviewState();
break;
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::handleDialogSizeChanged()
{
if ( mbShowPreview )
TimeOutHdl_Impl( NULL );
}
// ------------------------------------------------------------------------
// XEventListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper_Impl::disposing( const EventObject& ) throw ( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
dispose();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::dispose()
{
if ( mxFileDlg.is() )
{
// remove the event listener
uno::Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
if ( xNotifier.is() )
xNotifier->removeFilePickerListener( this );
::comphelper::disposeComponent( mxFileDlg );
mxFileDlg.clear();
}
}
// ------------------------------------------------------------------------
String FileDialogHelper_Impl::getCurrentFilterUIName() const
{
String aFilterName;
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if( xFltMgr.is() )
{
aFilterName = xFltMgr->getCurrentFilter();
if ( aFilterName.Len() && isShowFilterExtensionEnabled() )
aFilterName = getFilterName( aFilterName );
}
return aFilterName;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::LoadLastUsedFilter( const OUString& _rContextIdentifier )
{
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
if( aDlgOpt.Exists() )
{
OUString aLastFilter;
if( aDlgOpt.GetUserItem( _rContextIdentifier ) >>= aLastFilter )
setFilter( aLastFilter );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::SaveLastUsedFilter( const OUString& _rContextIdentifier )
{
SvtViewOptions( E_DIALOG, IODLG_CONFIGNAME ).SetUserItem( _rContextIdentifier,
makeAny( getFilterWithExtension( getFilter() ) ) );
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::SaveLastUsedFilter( void )
{
const OUString* pConfigId = GetLastFilterConfigId( meContext );
if( pConfigId )
SaveLastUsedFilter( *pConfigId );
}
// ------------------------------------------------------------------------
const SfxFilter* FileDialogHelper_Impl::getCurentSfxFilter()
{
String aFilterName = getCurrentFilterUIName();
const SfxFilter* pFilter = NULL;
if ( mpMatcher && aFilterName.Len() )
pFilter = mpMatcher->GetFilter4UIName( aFilterName, m_nMustFlags, m_nDontFlags );
return pFilter;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable )
{
sal_Bool bIsEnabled = sal_False;
uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
try
{
xCtrlAccess->enableControl( _nExtendedControlId, _bEnable );
bIsEnabled = _bEnable;
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::updateExtendedControl: caught an exception!" );
}
}
return bIsEnabled;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::CheckFilterOptionsCapability( const SfxFilter* _pFilter )
{
sal_Bool bResult = sal_False;
if( mxFilterCFG.is() && _pFilter )
{
try {
Sequence < PropertyValue > aProps;
Any aAny = mxFilterCFG->getByName( _pFilter->GetName() );
if ( aAny >>= aProps )
{
::rtl::OUString aServiceName;
sal_Int32 nPropertyCount = aProps.getLength();
for( sal_Int32 nProperty=0; nProperty < nPropertyCount; ++nProperty )
{
if( aProps[nProperty].Name.equals( DEFINE_CONST_OUSTRING( "UIComponent") ) )
{
aProps[nProperty].Value >>= aServiceName;
if( aServiceName.getLength() )
bResult = sal_True;
}
}
}
}
catch( Exception& )
{
}
}
return bResult;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper_Impl::isInOpenMode() const
{
sal_Bool bRet = sal_False;
switch ( m_nDialogType )
{
case FILEOPEN_SIMPLE:
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
case FILEOPEN_PLAY:
case FILEOPEN_READONLY_VERSION:
case FILEOPEN_LINK_PREVIEW:
bRet = sal_True;
}
return bRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateFilterOptionsBox()
{
if ( !m_bHaveFilterOptions )
return;
updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS,
CheckFilterOptionsCapability( getCurentSfxFilter() )
);
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateExportButton()
{
uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if ( xCtrlAccess.is() )
{
OUString sEllipses( RTL_CONSTASCII_USTRINGPARAM( "..." ) );
OUString sOldLabel( xCtrlAccess->getLabel( CommonFilePickerElementIds::PUSHBUTTON_OK ) );
// initialize button label; we need the label with the mnemonic char
if ( !maButtonLabel.getLength() || maButtonLabel.indexOf( MNEMONIC_CHAR ) == -1 )
{
// cut the ellipses, if necessary
sal_Int32 nIndex = sOldLabel.indexOf( sEllipses );
if ( -1 == nIndex )
nIndex = sOldLabel.getLength();
maButtonLabel = sOldLabel.copy( 0, nIndex );
}
OUString sLabel = maButtonLabel;
// filter with options -> append ellipses on export button label
if ( CheckFilterOptionsCapability( getCurentSfxFilter() ) )
sLabel += OUString( RTL_CONSTASCII_USTRINGPARAM( "..." ) );
if ( sOldLabel != sLabel )
{
try
{
xCtrlAccess->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK, sLabel );
}
catch( const IllegalArgumentException& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::updateExportButton: caught an exception!" );
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateSelectionBox()
{
if ( !mbHasSelectionBox )
return;
// Does the selection box exist?
sal_Bool bSelectionBoxFound = sal_False;
uno::Reference< XControlInformation > xCtrlInfo( mxFileDlg, UNO_QUERY );
if ( xCtrlInfo.is() )
{
Sequence< ::rtl::OUString > aCtrlList = xCtrlInfo->getSupportedControls();
sal_uInt32 nCount = aCtrlList.getLength();
for ( sal_uInt32 nCtrl = 0; nCtrl < nCount; ++nCtrl )
if ( aCtrlList[ nCtrl ].equalsAscii("SelectionBox") )
{
bSelectionBoxFound = sal_False;
break;
}
}
if ( bSelectionBoxFound )
{
const SfxFilter* pFilter = getCurentSfxFilter();
mbSelectionFltrEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_SELECTION,
( mbSelectionEnabled && pFilter && ( pFilter->GetFilterFlags() & SFX_FILTER_SUPPORTSSELECTION ) != 0 ) );
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0, makeAny( (sal_Bool)mbSelection ) );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::enablePasswordBox( sal_Bool bInit )
{
if ( ! mbHasPassword )
return;
sal_Bool bWasEnabled = mbIsPwdEnabled;
const SfxFilter* pCurrentFilter = getCurentSfxFilter();
mbIsPwdEnabled = updateExtendedControl(
ExtendedFilePickerElementIds::CHECKBOX_PASSWORD,
pCurrentFilter && ( pCurrentFilter->GetFilterFlags() & SFX_FILTER_ENCRYPTION )
);
if( bInit )
{
// in case of inintialization previous state is not interesting
if( mbIsPwdEnabled )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if( mbPwdCheckBoxState )
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_True ) );
}
}
else if( !bWasEnabled && mbIsPwdEnabled )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
if( mbPwdCheckBoxState )
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_True ) );
}
else if( bWasEnabled && !mbIsPwdEnabled )
{
// remember user settings until checkbox is enabled
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
mbPwdCheckBoxState = ( aValue >>= bPassWord ) && bPassWord;
xCtrlAccess->setValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0, makeAny( sal_False ) );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updatePreviewState( sal_Bool _bUpdatePreviewWindow )
{
if ( mbHasPreview )
{
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// check, wether or not we have to display a preview
if ( xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
sal_Bool bShowPreview = sal_False;
if ( aValue >>= bShowPreview )
{
mbShowPreview = bShowPreview;
// #97633
// setShowState has currently no effect for the
// OpenOffice FilePicker (see svtools/source/filepicker/iodlg.cxx)
uno::Reference< XFilePreview > xFilePreview( mxFileDlg, UNO_QUERY );
if ( xFilePreview.is() )
xFilePreview->setShowState( mbShowPreview );
if ( _bUpdatePreviewWindow )
TimeOutHdl_Impl( NULL );
}
}
catch( Exception )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::updatePreviewState: caught an exception!" );
}
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::updateVersions()
{
Sequence < OUString > aEntries;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
INetURLObject aObj( aPathSeq[0] );
if ( ( aObj.GetProtocol() == INET_PROT_FILE ) &&
( utl::UCBContentHelper::IsDocument( aObj.GetMainURL( INetURLObject::NO_DECODE ) ) ) )
{
try
{
uno::Reference< embed::XStorage > xStorage = ::comphelper::OStorageHelper::GetStorageFromURL(
aObj.GetMainURL( INetURLObject::NO_DECODE ),
embed::ElementModes::READ );
DBG_ASSERT( xStorage.is(), "The method must return the storage or throw an exception!" );
if ( !xStorage.is() )
throw uno::RuntimeException();
uno::Sequence < util::RevisionTag > xVersions = SfxMedium::GetVersionList( xStorage );
aEntries.realloc( xVersions.getLength() + 1 );
aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
for ( sal_Int32 i=0; i<xVersions.getLength(); i++ )
aEntries[ i + 1 ] = xVersions[i].Identifier;
// TODO/LATER: not sure that this information must be shown in future ( binfilter? )
//REMOVE else
//REMOVE {
//REMOVE SfxFilterFlags nMust = SFX_FILTER_IMPORT | SFX_FILTER_OWN;
//REMOVE SfxFilterFlags nDont = SFX_FILTER_NOTINSTALLED | SFX_FILTER_STARONEFILTER;
//REMOVE if ( SFX_APP()->GetFilterMatcher().GetFilter4ClipBoardId( pStor->GetFormat(), nMust, nDont ) )
//REMOVE {
//REMOVE aEntries.realloc( 1 );
//REMOVE aEntries[0] = OUString( String ( SfxResId( STR_SFX_FILEDLG_ACTUALVERSION ) ) );
//REMOVE }
//REMOVE }
}
catch( uno::Exception& )
{
}
}
}
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::DELETE_ITEMS, aValue );
}
catch( IllegalArgumentException ){}
sal_Int32 nCount = aEntries.getLength();
if ( nCount )
{
try
{
aValue <<= aEntries;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::ADD_ITEMS, aValue );
Any aPos;
aPos <<= (sal_Int32) 0;
xDlg->setValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::SET_SELECT_ITEM, aPos );
}
catch( IllegalArgumentException ){}
}
}
// -----------------------------------------------------------------------
class OReleaseSolarMutex
{
private:
const sal_Int32 m_nAquireCount;
public:
OReleaseSolarMutex( )
:m_nAquireCount( Application::ReleaseSolarMutex() )
{
}
~OReleaseSolarMutex( )
{
Application::AcquireSolarMutex( m_nAquireCount );
}
};
// -----------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, TimeOutHdl_Impl, Timer*, EMPTYARG )
{
if ( !mbHasPreview )
return 0;
maGraphic.Clear();
Any aAny;
uno::Reference < XFilePreview > xFilePicker( mxFileDlg, UNO_QUERY );
if ( ! xFilePicker.is() )
return 0;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( mbShowPreview && ( aPathSeq.getLength() == 1 ) )
{
OUString aURL = aPathSeq[0];
if ( ERRCODE_NONE == getGraphic( aURL, maGraphic ) )
{
// #89491
// changed the code slightly;
// before: the bitmap was scaled and
// surrounded a white frame
// now: the bitmap will only be scaled
// and the filepicker implementation
// is responsible for placing it at its
// proper position and painting a frame
Bitmap aBmp = maGraphic.GetBitmap();
// scale the bitmap to the correct size
sal_Int32 nOutWidth = xFilePicker->getAvailableWidth();
sal_Int32 nOutHeight = xFilePicker->getAvailableHeight();
sal_Int32 nBmpWidth = aBmp.GetSizePixel().Width();
sal_Int32 nBmpHeight = aBmp.GetSizePixel().Height();
double nXRatio = (double) nOutWidth / nBmpWidth;
double nYRatio = (double) nOutHeight / nBmpHeight;
if ( nXRatio < nYRatio )
aBmp.Scale( nXRatio, nXRatio );
else
aBmp.Scale( nYRatio, nYRatio );
// #94505# Convert to true color, to allow CopyPixel
aBmp.Convert( BMP_CONVERSION_24BIT );
// and copy it into the Any
SvMemoryStream aData;
aData << aBmp;
const Sequence < sal_Int8 > aBuffer(
static_cast< const sal_Int8* >(aData.GetData()),
aData.GetEndOfData() );
aAny <<= aBuffer;
}
}
try
{
OReleaseSolarMutex aReleaseForCallback;
// clear the preview window
xFilePicker->setImage( FilePreviewImageFormats::BITMAP, aAny );
}
catch( IllegalArgumentException )
{
}
return 0;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( const OUString& rURL,
Graphic& rGraphic ) const
{
if ( utl::UCBContentHelper::IsFolder( rURL ) )
return ERRCODE_IO_NOTAFILE;
if ( !mpGraphicFilter )
return ERRCODE_IO_NOTSUPPORTED;
// select graphic filter from dialog filter selection
OUString aCurFilter( getFilter() );
sal_uInt16 nFilter = aCurFilter.getLength() && mpGraphicFilter->GetImportFormatCount()
? mpGraphicFilter->GetImportFormatNumber( aCurFilter )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURLObj( rURL );
if ( aURLObj.HasError() || INET_PROT_NOT_VALID == aURLObj.GetProtocol() )
{
aURLObj.SetSmartProtocol( INET_PROT_FILE );
aURLObj.SetSmartURL( rURL );
}
ErrCode nRet = ERRCODE_NONE;
sal_uInt32 nFilterImportFlags = GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
// non-local?
if ( INET_PROT_FILE != aURLObj.GetProtocol() )
{
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( rURL, STREAM_READ );
if( pStream )
nRet = mpGraphicFilter->ImportGraphic( rGraphic, rURL, *pStream, nFilter, NULL, nFilterImportFlags );
else
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
delete pStream;
}
else
{
nRet = mpGraphicFilter->ImportGraphic( rGraphic, aURLObj, nFilter, NULL, nFilterImportFlags );
}
return nRet;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::getGraphic( Graphic& rGraphic ) const
{
ErrCode nRet = ERRCODE_NONE;
if ( ! maGraphic )
{
OUString aPath;;
Sequence < OUString > aPathSeq = mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
if ( aPath.getLength() )
nRet = getGraphic( aPath, rGraphic );
else
nRet = ERRCODE_IO_GENERAL;
}
else
rGraphic = maGraphic;
return nRet;
}
// ------------------------------------------------------------------------
sal_Bool lcl_isSystemFilePicker( const uno::Reference< XFilePicker >& _rxFP )
{
try
{
uno::Reference< XServiceInfo > xSI( _rxFP, UNO_QUERY );
if ( xSI.is() && xSI->supportsService( DEFINE_CONST_OUSTRING( "com.sun.star.ui.dialogs.SystemFilePicker" ) ) )
return sal_True;
}
catch( const Exception& )
{
}
return sal_False;
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper_Impl ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper_Impl::FileDialogHelper_Impl(
FileDialogHelper* _pAntiImpl,
sal_Int16 nDialogType,
sal_Int64 nFlags,
sal_Int16 nDialog,
Window* _pPreferredParentWindow,
const String& sStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList
)
:m_nDialogType ( nDialogType )
,meContext ( FileDialogHelper::UNKNOWN_CONTEXT )
{
const char* pServiceName=0;
if ( nDialog == SFX2_IMPL_DIALOG_SYSTEM )
pServiceName = FILE_OPEN_SERVICE_NAME_OOO;
else if ( nDialog == SFX2_IMPL_DIALOG_OOO )
pServiceName = FILE_OPEN_SERVICE_NAME_OOO;
else
pServiceName = FILE_OPEN_SERVICE_NAME;
OUString aService = ::rtl::OUString::createFromAscii( pServiceName );
uno::Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
// create the file open dialog
// the flags can be SFXWB_INSERT or SFXWB_MULTISELECTION
mpPreferredParentWindow = _pPreferredParentWindow;
mpAntiImpl = _pAntiImpl;
mnError = ERRCODE_NONE;
mbHasAutoExt = sal_False;
mbHasPassword = sal_False;
m_bHaveFilterOptions = sal_False;
mbIsPwdEnabled = sal_True;
mbHasVersions = sal_False;
mbHasPreview = sal_False;
mbShowPreview = sal_False;
mbHasLink = sal_False;
mbDeleteMatcher = sal_False;
mbInsert = SFXWB_INSERT == ( nFlags & SFXWB_INSERT );
mbExport = SFXWB_EXPORT == ( nFlags & SFXWB_EXPORT );
mbIsSaveDlg = sal_False;
mbPwdCheckBoxState = sal_False;
mbSelection = sal_False;
mbSelectionEnabled = sal_True;
mbHasSelectionBox = sal_False;
mbSelectionFltrEnabled = sal_False;
// default settings
m_nDontFlags = SFX_FILTER_INTERNAL | SFX_FILTER_NOTINFILEDLG | SFX_FILTER_NOTINSTALLED;
if( WB_OPEN == ( nFlags & WB_OPEN ) )
m_nMustFlags = SFX_FILTER_IMPORT;
else
m_nMustFlags = SFX_FILTER_EXPORT;
mpMatcher = NULL;
mpGraphicFilter = NULL;
mnPostUserEventId = 0;
// create the picker component
mxFileDlg = mxFileDlg.query( xFactory->createInstance( aService ) );
mbSystemPicker = lcl_isSystemFilePicker( mxFileDlg );
uno::Reference< XFilePickerNotifier > xNotifier( mxFileDlg, UNO_QUERY );
uno::Reference< XInitialization > xInit( mxFileDlg, UNO_QUERY );
if ( ! mxFileDlg.is() || ! xNotifier.is() )
{
mnError = ERRCODE_ABORT;
return;
}
if ( xInit.is() )
{
sal_Int16 nTemplateDescription = TemplateDescription::FILEOPEN_SIMPLE;
switch ( m_nDialogType )
{
case FILEOPEN_SIMPLE:
nTemplateDescription = TemplateDescription::FILEOPEN_SIMPLE;
break;
case FILESAVE_SIMPLE:
nTemplateDescription = TemplateDescription::FILESAVE_SIMPLE;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD;
mbHasPassword = sal_True;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS;
mbHasPassword = sal_True;
m_bHaveFilterOptions = sal_True;
if( xFactory.is() )
{
mxFilterCFG = uno::Reference< XNameAccess >(
xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.document.FilterFactory" ) ),
UNO_QUERY );
}
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILESAVE_AUTOEXTENSION_SELECTION:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
mbHasSelectionBox = sal_True;
if ( mbExport && !mxFilterCFG.is() && xFactory.is() )
{
mxFilterCFG = uno::Reference< XNameAccess >(
xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.document.FilterFactory" ) ),
UNO_QUERY );
}
break;
case FILESAVE_AUTOEXTENSION_TEMPLATE:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION_TEMPLATE;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
case FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE:
nTemplateDescription = TemplateDescription::FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILEOPEN_PLAY:
nTemplateDescription = TemplateDescription::FILEOPEN_PLAY;
break;
case FILEOPEN_READONLY_VERSION:
nTemplateDescription = TemplateDescription::FILEOPEN_READONLY_VERSION;
mbHasVersions = sal_True;
break;
case FILEOPEN_LINK_PREVIEW:
nTemplateDescription = TemplateDescription::FILEOPEN_LINK_PREVIEW;
mbHasPreview = sal_True;
mbHasLink = sal_True;
// aPreviewTimer
maPreViewTimer.SetTimeout( 500 );
maPreViewTimer.SetTimeoutHdl( LINK( this, FileDialogHelper_Impl, TimeOutHdl_Impl ) );
break;
case FILESAVE_AUTOEXTENSION:
nTemplateDescription = TemplateDescription::FILESAVE_AUTOEXTENSION;
mbHasAutoExt = sal_True;
mbIsSaveDlg = sal_True;
break;
default:
DBG_ERRORFILE( "FileDialogHelper::ctor with unknown type" );
break;
}
//Sequence < Any > aInitArguments( mbSystemPicker || !mpPreferredParentWindow ? 1 : 3 );
Sequence < Any > aInitArguments( !mpPreferredParentWindow ? 3 : 4 );
// This is a hack. We currently know that the internal file picker implementation
// supports the extended arguments as specified below.
// TODO:
// a) adjust the service description so that it includes the TemplateDescription and ParentWindow args
// b) adjust the implementation of the system file picker to that it recognizes it
if ( mbSystemPicker )
{
aInitArguments[0] <<= nTemplateDescription;
}
else
{
aInitArguments[0] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TemplateDescription" ) ),
makeAny( nTemplateDescription )
);
::rtl::OUString sStandardDirTemp = ::rtl::OUString( sStandardDir );
aInitArguments[1] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StandardDir" ) ),
makeAny( sStandardDirTemp )
);
aInitArguments[2] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BlackList" ) ),
makeAny( rBlackList )
);
if ( mpPreferredParentWindow )
aInitArguments[3] <<= NamedValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ParentWindow" ) ),
makeAny( VCLUnoHelper::GetInterface( mpPreferredParentWindow ) )
);
}
try
{
xInit->initialize( aInitArguments );
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::FileDialogHelper_Impl: could not initialize the picker!" );
}
}
// set multiselection mode
if ( nFlags & SFXWB_MULTISELECTION )
mxFileDlg->setMultiSelectionMode( sal_True );
if ( mbHasLink ) // generate graphic filter only on demand
addGraphicFilter();
// Export dialog
if ( mbExport )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_EXPORT ) ) ) );
try {
com::sun::star::uno::Reference < XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY_THROW );
xCtrlAccess->enableControl( ExtendedFilePickerElementIds::LISTBOX_FILTER_SELECTOR, sal_True );
}
catch( const Exception & ) { }
}
// the "insert file" dialog needs another title
if ( mbInsert )
{
mxFileDlg->setTitle( OUString( String( SfxResId( STR_SFX_EXPLORERFILE_INSERT ) ) ) );
uno::Reference < XFilePickerControlAccess > xExtDlg( mxFileDlg, UNO_QUERY );
if ( xExtDlg.is() )
{
try
{
xExtDlg->setLabel( CommonFilePickerElementIds::PUSHBUTTON_OK,
OUString( String( SfxResId( STR_SFX_EXPLORERFILE_BUTTONINSERT ) ) ) );
}
catch( IllegalArgumentException ){}
}
}
// add the event listener
xNotifier->addFilePickerListener( this );
}
// ------------------------------------------------------------------------
FileDialogHelper_Impl::~FileDialogHelper_Impl()
{
// Remove user event if we haven't received it yet
if ( mnPostUserEventId )
Application::RemoveUserEvent( mnPostUserEventId );
mnPostUserEventId = 0;
delete mpGraphicFilter;
if ( mbDeleteMatcher )
delete mpMatcher;
maPreViewTimer.SetTimeoutHdl( Link() );
::comphelper::disposeComponent( mxFileDlg );
}
#define nMagic -1
class PickerThread_Impl : public ::vos::OThread
{
uno::Reference < XFilePicker > mxPicker;
::vos::OMutex maMutex;
virtual void SAL_CALL run();
sal_Int16 mnRet;
public:
PickerThread_Impl( const uno::Reference < XFilePicker >& rPicker )
: mxPicker( rPicker ), mnRet(nMagic) {}
sal_Int16 GetReturnValue()
{ ::vos::OGuard aGuard( maMutex ); return mnRet; }
void SetReturnValue( sal_Int16 aRetValue )
{ ::vos::OGuard aGuard( maMutex ); mnRet = aRetValue; }
};
void SAL_CALL PickerThread_Impl::run()
{
try
{
sal_Int16 n = mxPicker->execute();
SetReturnValue( n );
}
catch( RuntimeException& )
{
SetReturnValue( ExecutableDialogResults::CANCEL );
DBG_ERRORFILE( "RuntimeException caught" );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setControlHelpIds( const sal_Int16* _pControlId, const char** _pHelpId )
{
DBG_ASSERT( _pControlId && _pHelpId, "FileDialogHelper_Impl::setControlHelpIds: invalid array pointers!" );
if ( !_pControlId || !_pHelpId )
return;
// forward these ids to the file picker
try
{
const ::rtl::OUString sHelpIdPrefix( RTL_CONSTASCII_USTRINGPARAM( INET_HID_SCHEME ) );
// the ids for the single controls
uno::Reference< XFilePickerControlAccess > xControlAccess( mxFileDlg, UNO_QUERY );
if ( xControlAccess.is() )
{
while ( *_pControlId )
{
DBG_ASSERT( INetURLObject( rtl::OStringToOUString( *_pHelpId, RTL_TEXTENCODING_UTF8 ) ).GetProtocol() == INET_PROT_NOT_VALID, "Wrong HelpId!" );
::rtl::OUString sId( sHelpIdPrefix );
sId += ::rtl::OUString( *_pHelpId, strlen( *_pHelpId ), RTL_TEXTENCODING_UTF8 );
xControlAccess->setValue( *_pControlId, ControlActions::SET_HELP_URL, makeAny( sId ) );
++_pControlId; ++_pHelpId;
}
}
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::setControlHelpIds: caught an exception while setting the help ids!" );
}
}
// ------------------------------------------------------------------------
IMPL_LINK( FileDialogHelper_Impl, InitControls, void*, NOTINTERESTEDIN )
{
(void)NOTINTERESTEDIN;
mnPostUserEventId = 0;
enablePasswordBox( sal_True );
updateFilterOptionsBox( );
updateSelectionBox( );
return 0L;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::preExecute()
{
loadConfig( );
setDefaultValues( );
updatePreviewState( sal_False );
implInitializeFileName( );
// #106079# / 2002-12-09 / fs@openoffice.org
#if !(defined(MACOSX) && defined(QUARTZ)) && !defined(WNT)
// allow for dialog implementations which need to be executed before they return valid values for
// current filter and such
// On Vista (at least SP1) it's the same as on MacOSX, the modal dialog won't let message pass
// through before it returns from execution
mnPostUserEventId = Application::PostUserEvent( LINK( this, FileDialogHelper_Impl, InitControls ) );
#else
// However, the Mac OS X implementation's pickers run modally in execute and so the event doesn't
// get through in time... so we call the methods directly
enablePasswordBox( sal_True );
updateFilterOptionsBox( );
updateSelectionBox( );
#endif
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::postExecute( sal_Int16 _nResult )
{
if ( ExecutableDialogResults::CANCEL != _nResult )
saveConfig();
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implInitializeFileName( )
{
if ( maFileName.getLength() )
{
INetURLObject aObj( maPath );
aObj.Append( maFileName );
// in case we're operating as save dialog, and "auto extension" is checked,
// cut the extension from the name
// #106079# / 2002-12-09 / fs@openoffice.org
if ( mbIsSaveDlg && mbHasAutoExt )
{
try
{
sal_Bool bAutoExtChecked = sal_False;
uno::Reference < XFilePickerControlAccess > xControlAccess( mxFileDlg, UNO_QUERY );
if ( xControlAccess.is()
&& ( xControlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 )
>>= bAutoExtChecked
)
)
{
if ( bAutoExtChecked )
{ // cut the extension
aObj.removeExtension( );
mxFileDlg->setDefaultName( aObj.GetName( INetURLObject::DECODE_WITH_CHARSET ) );
}
}
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::implInitializeFileName: could not ask for the auto-extension current-value!" );
}
}
}
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper_Impl::implDoExecute()
{
preExecute();
sal_Int16 nRet = ExecutableDialogResults::CANCEL;
//On MacOSX the native file picker has to run in the primordial thread because of drawing issues
//On Linux the native gtk file picker, when backed by gnome-vfs2, needs to be run in the same
//primordial thread as the ucb gnome-vfs2 provider was initialized in.
/*
#ifdef WNT
if ( mbSystemPicker )
{
PickerThread_Impl* pThread = new PickerThread_Impl( mxFileDlg );
pThread->create();
while ( pThread->GetReturnValue() == nMagic )
Application::Yield();
pThread->join();
nRet = pThread->GetReturnValue();
delete pThread;
}
else
#endif
*/
{
try
{
#ifdef WNT
if ( mbSystemPicker )
{
OReleaseSolarMutex aSolarMutex;
nRet = mxFileDlg->execute();
}
else
#endif
nRet = mxFileDlg->execute();
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
postExecute( nRet );
return nRet;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implStartExecute()
{
DBG_ASSERT( mxFileDlg.is(), "invalid file dialog" );
preExecute();
if ( mbSystemPicker )
{
}
else
{
try
{
uno::Reference< XAsynchronousExecutableDialog > xAsyncDlg( mxFileDlg, UNO_QUERY );
if ( xAsyncDlg.is() )
xAsyncDlg->startExecuteModal( this );
}
catch( const Exception& )
{
DBG_ERRORFILE( "FileDialogHelper_Impl::implDoExecute: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
String FileDialogHelper_Impl::implEnsureURLExtension(const String& sURL,
const String& /*sExtension*/)
{
return sURL;
/*
// This feature must be active for file save/export only !
if (
(! mbIsSaveDlg) &&
(! mbExport )
)
return sURL;
// no extension available (because "ALL *.*" was selected) ?
// Nod idea what else should happen here .-)
if (sExtension.Len() < 1)
return sURL;
// Some FilePicker implementations already add the right extension ...
// or might be the user used the right one already ...
// Dont create duplicate extension.
INetURLObject aURL(sURL);
if (aURL.getExtension().equals(sExtension))
return sURL;
// Ignore any other extension set by the user.
// Make sure suitable extension is used always.
// e.g. "test.bla.odt" for "ODT"
::rtl::OUStringBuffer sNewURL(256);
sNewURL.append (sURL );
sNewURL.appendAscii("." );
sNewURL.append (sExtension);
return sNewURL.makeStringAndClear();
*/
}
// ------------------------------------------------------------------------
void lcl_saveLastURLs(SvStringsDtor*& rpURLList ,
::comphelper::SequenceAsVector< ::rtl::OUString >& lLastURLs )
{
lLastURLs.clear();
USHORT c = rpURLList->Count();
USHORT i = 0;
for (i=0; i<c; ++i)
lLastURLs.push_back(*(rpURLList->GetObject(i)));
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::implGetAndCacheFiles(const uno::Reference< XInterface >& xPicker ,
SvStringsDtor*& rpURLList,
const SfxFilter* pFilter )
{
rpURLList = NULL;
String sExtension;
if (pFilter)
{
sExtension = pFilter->GetDefaultExtension ();
sExtension.EraseAllChars( '*' );
sExtension.EraseAllChars( '.' );
}
// a) the new way (optional!)
uno::Reference< XFilePicker2 > xPickNew(xPicker, UNO_QUERY);
if (xPickNew.is())
{
rpURLList = new SvStringsDtor;
Sequence< OUString > lFiles = xPickNew->getSelectedFiles();
::sal_Int32 nFiles = lFiles.getLength();
for (::sal_Int32 i = 0; i < nFiles; i++)
{
String* pURL = new String(implEnsureURLExtension(lFiles[i], sExtension));
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
// b) the olde way ... non optional.
else
{
uno::Reference< XFilePicker > xPickOld(xPicker, UNO_QUERY_THROW);
Sequence< OUString > lFiles = xPickOld->getFiles();
::sal_Int32 nFiles = lFiles.getLength();
if ( nFiles == 1 )
{
rpURLList = new SvStringsDtor;
String* pURL = new String(implEnsureURLExtension(lFiles[0], sExtension));
rpURLList->Insert( pURL, 0 );
}
else
if ( nFiles > 1 )
{
rpURLList = new SvStringsDtor;
INetURLObject aPath( lFiles[0] );
aPath.setFinalSlash();
for (::sal_Int32 i = 1; i < nFiles; i++)
{
if (i == 1)
aPath.Append( lFiles[i] );
else
aPath.setName( lFiles[i] );
String* pURL = new String(implEnsureURLExtension(aPath.GetMainURL( INetURLObject::NO_DECODE ), sExtension) );
rpURLList->Insert( pURL, rpURLList->Count() );
}
}
}
lcl_saveLastURLs(rpURLList, mlLastURLs);
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter )
{
// rFilter is a pure output parameter, it shouldn't be used for anything else
// changing this would surely break code
// rpSet is in/out parameter, usually just a media-descriptor that can be changed by dialog
uno::Reference< XFilePickerControlAccess > xCtrlAccess( mxFileDlg, UNO_QUERY );
// retrieves parameters from rpSet
// for now only Password is used
if ( rpSet )
{
// check password checkbox if the document had password before
if( mbHasPassword )
{
SFX_ITEMSET_ARG( rpSet, pPassItem, SfxStringItem, SID_PASSWORD, FALSE );
mbPwdCheckBoxState = ( pPassItem != NULL );
// in case the document has password to modify, the dialog should be shown
SFX_ITEMSET_ARG( rpSet, pPassToModifyItem, SfxUnoAnyItem, SID_MODIFYPASSWORDINFO, FALSE );
mbPwdCheckBoxState |= ( pPassToModifyItem && pPassToModifyItem->GetValue().hasValue() );
}
SFX_ITEMSET_ARG( rpSet, pSelectItem, SfxBoolItem, SID_SELECTION, FALSE );
if ( pSelectItem )
mbSelection = pSelectItem->GetValue();
else
mbSelectionEnabled = sal_False;
// the password will be set in case user decide so
rpSet->ClearItem( SID_PASSWORD );
rpSet->ClearItem( SID_RECOMMENDREADONLY );
rpSet->ClearItem( SID_MODIFYPASSWORDINFO );
}
if ( mbHasPassword && !mbPwdCheckBoxState )
{
SvtSecurityOptions aSecOpt;
mbPwdCheckBoxState = (
aSecOpt.IsOptionSet( SvtSecurityOptions::E_DOCWARN_RECOMMENDPASSWORD ) );
}
rpURLList = NULL;
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
if ( ExecutableDialogResults::CANCEL != implDoExecute() )
{
// create an itemset if there is no
if( !rpSet )
rpSet = new SfxAllItemSet( SFX_APP()->GetPool() );
// the item should remain only if it was set by the dialog
rpSet->ClearItem( SID_SELECTION );
if( mbExport )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 );
sal_Bool bSelection = sal_False;
if ( aValue >>= bSelection )
rpSet->Put( SfxBoolItem( SID_SELECTION, bSelection ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
// set the read-only flag. When inserting a file, this flag is always set
if ( mbInsert )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
else
{
if ( ( FILEOPEN_READONLY_VERSION == m_nDialogType ) && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_READONLY, 0 );
sal_Bool bReadOnly = sal_False;
if ( ( aValue >>= bReadOnly ) && bReadOnly )
rpSet->Put( SfxBoolItem( SID_DOC_READONLY, bReadOnly ) );
}
catch( IllegalArgumentException )
{
DBG_ERROR( "FileDialogHelper_Impl::execute: caught an IllegalArgumentException!" );
}
}
}
if ( mbHasVersions && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::LISTBOX_VERSION,
ControlActions::GET_SELECTED_ITEM_INDEX );
sal_Int32 nVersion = 0;
if ( ( aValue >>= nVersion ) && nVersion > 0 )
// open a special version; 0 == current version
rpSet->Put( SfxInt16Item( SID_VERSION, (short)nVersion ) );
}
catch( IllegalArgumentException ){}
}
// set the filter
getRealFilter( rFilter );
const SfxFilter* pCurrentFilter = getCurentSfxFilter();
// fill the rpURLList
implGetAndCacheFiles( mxFileDlg, rpURLList, pCurrentFilter );
if ( rpURLList == NULL || rpURLList->GetObject(0) == NULL )
return ERRCODE_ABORT;
// check, wether or not we have to display a password box
if ( pCurrentFilter && mbHasPassword && mbIsPwdEnabled && xCtrlAccess.is() )
{
try
{
Any aValue = xCtrlAccess->getValue( ExtendedFilePickerElementIds::CHECKBOX_PASSWORD, 0 );
sal_Bool bPassWord = sal_False;
if ( ( aValue >>= bPassWord ) && bPassWord )
{
// ask for a password
uno::Reference < ::com::sun::star::task::XInteractionHandler > xInteractionHandler( ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.comp.uui.UUIInteractionHandler")), UNO_QUERY );
if( xInteractionHandler.is() )
{
// TODO: need a save way to distinguish MS filters from other filters
// for now MS-filters are the only alien filters that support encryption
sal_Bool bMSType = !pCurrentFilter->IsOwnFormat();
::comphelper::DocPasswordRequestType eType = bMSType ?
::comphelper::DocPasswordRequestType_MS :
::comphelper::DocPasswordRequestType_STANDARD;
::rtl::Reference< ::comphelper::DocPasswordRequest > pPasswordRequest( new ::comphelper::DocPasswordRequest( eType, ::com::sun::star::task::PasswordRequestMode_PASSWORD_CREATE, *(rpURLList->GetObject(0)), ( pCurrentFilter->GetFilterFlags() & SFX_FILTER_PASSWORDTOMODIFY ) != 0 ) );
uno::Reference< com::sun::star::task::XInteractionRequest > rRequest( pPasswordRequest.get() );
xInteractionHandler->handle( rRequest );
if ( pPasswordRequest->isPassword() )
{
if ( pPasswordRequest->getPassword().getLength() )
rpSet->Put( SfxStringItem( SID_PASSWORD, pPasswordRequest->getPassword() ) );
if ( pPasswordRequest->getRecommendReadOnly() )
rpSet->Put( SfxBoolItem( SID_RECOMMENDREADONLY, sal_True ) );
if ( bMSType )
{
// the empty password has 0 as Hash
sal_Int32 nHash = SfxMedium::CreatePasswordToModifyHash( pPasswordRequest->getPasswordToModify(), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.text.TextDocument" ) ).equals( pCurrentFilter->GetServiceName() ) );
if ( nHash )
rpSet->Put( SfxUnoAnyItem( SID_MODIFYPASSWORDINFO, uno::makeAny( nHash ) ) );
}
else
{
uno::Sequence< beans::PropertyValue > aModifyPasswordInfo = ::comphelper::DocPasswordHelper::GenerateNewModifyPasswordInfo( pPasswordRequest->getPasswordToModify() );
if ( aModifyPasswordInfo.getLength() )
rpSet->Put( SfxUnoAnyItem( SID_MODIFYPASSWORDINFO, uno::makeAny( aModifyPasswordInfo ) ) );
}
}
else
return ERRCODE_ABORT;
}
}
}
catch( IllegalArgumentException ){}
}
SaveLastUsedFilter();
return ERRCODE_NONE;
}
else
return ERRCODE_ABORT;
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper_Impl::execute()
{
if ( ! mxFileDlg.is() )
return ERRCODE_ABORT;
sal_Int16 nRet = implDoExecute();
maPath = mxFileDlg->getDisplayDirectory();
if ( ExecutableDialogResults::CANCEL == nRet )
return ERRCODE_ABORT;
else
{
return ERRCODE_NONE;
}
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getPath() const
{
OUString aPath;
if ( mxFileDlg.is() )
aPath = mxFileDlg->getDisplayDirectory();
if ( !aPath.getLength() )
aPath = maPath;
return aPath;
}
// ------------------------------------------------------------------------
OUString FileDialogHelper_Impl::getFilter() const
{
String aFilter = getCurrentFilterUIName();
if( !aFilter.Len() )
aFilter = maCurFilter;
return aFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::getRealFilter( String& _rFilter ) const
{
_rFilter = getCurrentFilterUIName();
if ( !_rFilter.Len() )
_rFilter = maCurFilter;
if ( _rFilter.Len() && mpMatcher )
{
const SfxFilter* pFilter =
mpMatcher->GetFilter4UIName( _rFilter, m_nMustFlags, m_nDontFlags );
_rFilter = pFilter ? pFilter->GetFilterName() : _rFilter.Erase();
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::displayFolder( const ::rtl::OUString& _rPath )
{
if ( ! _rPath.getLength() )
// nothing to do
return;
/*
if ( !::utl::UCBContentHelper::IsFolder( _rPath ) )
// only valid folders accepted here
return;
*/
maPath = _rPath;
if ( mxFileDlg.is() )
{
try
{
mxFileDlg->setDisplayDirectory( maPath );
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::displayFolder: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFileName( const ::rtl::OUString& _rFile )
{
maFileName = _rFile;
if ( mxFileDlg.is() )
{
try
{
mxFileDlg->setDefaultName( maFileName );
}
catch( const IllegalArgumentException& )
{
DBG_ERROR( "FileDialogHelper_Impl::setFileName: caught an exception!" );
}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setFilter( const OUString& rFilter )
{
DBG_ASSERT( rFilter.indexOf(':') == -1, "Old filter name used!");
maCurFilter = rFilter;
if ( rFilter.getLength() && mpMatcher )
{
const SfxFilter* pFilter = mpMatcher->GetFilter4FilterName(
rFilter, m_nMustFlags, m_nDontFlags );
if ( pFilter )
maCurFilter = pFilter->GetUIName();
}
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( maCurFilter.getLength() && xFltMgr.is() )
{
try
{
xFltMgr->setCurrentFilter( maCurFilter );
}
catch( IllegalArgumentException ){}
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::createMatcher( const String& rFactory )
{
mpMatcher = new SfxFilterMatcher( SfxObjectShell::GetServiceNameFromFactory(rFactory) );
mbDeleteMatcher = sal_True;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilters( sal_Int64 nFlags,
const String& rFactory,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// we still need a matcher to convert UI names to filter names
if ( !rFactory.Len() )
{
SfxApplication *pSfxApp = SFX_APP();
mpMatcher = &pSfxApp->GetFilterMatcher();
mbDeleteMatcher = sal_False;
}
else
{
mpMatcher = new SfxFilterMatcher( rFactory );
mbDeleteMatcher = sal_True;
}
uno::Reference< XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();
uno::Reference< XContainerQuery > xFilterCont(
xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.document.FilterFactory")),
UNO_QUERY);
if ( ! xFilterCont.is() )
return;
m_nMustFlags |= nMust;
m_nDontFlags |= nDont;
// create the list of filters
::rtl::OUStringBuffer sQuery(256);
sQuery.appendAscii("getSortedFilterList()");
sQuery.appendAscii(":module=" );
sQuery.append (rFactory ); // use long name here !
sQuery.appendAscii(":iflags=" );
sQuery.append (::rtl::OUString::valueOf((sal_Int32)m_nMustFlags));
sQuery.appendAscii(":eflags=" );
sQuery.append (::rtl::OUString::valueOf((sal_Int32)m_nDontFlags));
uno::Reference< XEnumeration > xResult = xFilterCont->createSubSetEnumerationByQuery(sQuery.makeStringAndClear());
TSortedFilterList aIter (xResult);
// no matcher any longer used ...
mbDeleteMatcher = sal_False;
// append the filters
::rtl::OUString sFirstFilter;
if ( WB_OPEN == ( nFlags & WB_OPEN ) )
::sfx2::appendFiltersForOpen( aIter, xFltMgr, sFirstFilter, *this );
else if ( mbExport )
::sfx2::appendExportFilters( aIter, xFltMgr, sFirstFilter, *this );
else
::sfx2::appendFiltersForSave( aIter, xFltMgr, sFirstFilter, *this, rFactory );
// set our initial selected filter (if we do not already have one)
if ( !maSelectFilter.getLength() )
maSelectFilter = sFirstFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addFilter( const OUString& rFilterName,
const OUString& rExtension )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
try
{
xFltMgr->appendFilter( rFilterName, rExtension );
if ( !maSelectFilter.getLength() )
maSelectFilter = rFilterName;
}
catch( IllegalArgumentException )
{
#ifdef DBG_UTIL
ByteString aMsg( "Could not append Filter" );
aMsg += ByteString( String( rFilterName ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::addGraphicFilter()
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
if ( ! xFltMgr.is() )
return;
// create the list of filters
mpGraphicFilter = new GraphicFilter;
USHORT i, j, nCount = mpGraphicFilter->GetImportFormatCount();
// compute the extension string for all known import filters
String aExtensions;
for ( i = 0; i < nCount; i++ )
{
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExtensions.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExtensions.Len() )
aExtensions += sal_Unicode(';');
aExtensions += sWildcard;
}
}
}
#if defined(WIN) || defined(WNT)
if ( aExtensions.Len() > 240 )
aExtensions = DEFINE_CONST_UNICODE( FILEDIALOG_FILTER_ALL );
#endif
sal_Bool bIsInOpenMode = isInOpenMode();
try
{
OUString aAllFilterName = String( SfxResId( STR_SFX_IMPORT_ALL ) );
aAllFilterName = ::sfx2::addExtension( aAllFilterName, aExtensions, bIsInOpenMode, *this );
xFltMgr->appendFilter( aAllFilterName, aExtensions );
maSelectFilter = aAllFilterName;
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
// Now add the filter
for ( i = 0; i < nCount; i++ )
{
String aName = mpGraphicFilter->GetImportFormatName( i );
String aExt;
j = 0;
String sWildcard;
while( TRUE )
{
sWildcard = mpGraphicFilter->GetImportWildcard( i, j++ );
if ( !sWildcard.Len() )
break;
if ( aExt.Search( sWildcard ) == STRING_NOTFOUND )
{
if ( aExt.Len() )
aExt += sal_Unicode(';');
aExt += sWildcard;
}
}
aName = ::sfx2::addExtension( aName, aExt, bIsInOpenMode, *this );
try
{
xFltMgr->appendFilter( aName, aExt );
}
catch( IllegalArgumentException )
{
DBG_ERRORFILE( "Could not append Filter" );
}
}
}
// ------------------------------------------------------------------------
#define GRF_CONFIG_STR " "
#define STD_CONFIG_STR "1 "
void FileDialogHelper_Impl::saveConfig()
{
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aDlgOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData = DEFINE_CONST_UNICODE( GRF_CONFIG_STR );
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
sal_Bool bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 );
bValue = sal_False;
aValue >>= bValue;
aUserData.SetToken( 1, ' ', String::CreateFromInt32( (sal_Int32) bValue ) );
INetURLObject aObj( getPath() );
if ( aObj.GetProtocol() == INET_PROT_FILE )
aUserData.SetToken( 2, ' ', aObj.GetMainURL( INetURLObject::NO_DECODE ) );
String aFilter = getFilter();
aFilter = EncodeSpaces_Impl( aFilter );
aUserData.SetToken( 3, ' ', aFilter );
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
catch( IllegalArgumentException ){}
}
else
{
sal_Bool bWriteConfig = sal_False;
SvtViewOptions aDlgOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData = DEFINE_CONST_UNICODE( STD_CONFIG_STR );
if ( aDlgOpt.Exists() )
{
Any aUserItem = aDlgOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( mbHasAutoExt )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0 );
sal_Bool bAutoExt = sal_True;
aValue >>= bAutoExt;
aUserData.SetToken( 0, ' ', String::CreateFromInt32( (sal_Int32) bAutoExt ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( ! mbIsSaveDlg )
{
OUString aPath = getPath();
if ( aPath.getLength() &&
utl::LocalFileHelper::IsLocalFile( aPath ) )
{
aUserData.SetToken( 1, ' ', aPath );
bWriteConfig = sal_True;
}
}
if( mbHasSelectionBox && mbSelectionFltrEnabled )
{
try
{
aValue = xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 );
sal_Bool bSelection = sal_True;
aValue >>= bSelection;
if ( aUserData.GetTokenCount(' ') < 3 )
aUserData.Append(' ');
aUserData.SetToken( 2, ' ', String::CreateFromInt32( (sal_Int32) bSelection ) );
bWriteConfig = sal_True;
}
catch( IllegalArgumentException ){}
}
if ( bWriteConfig )
aDlgOpt.SetUserItem( USERITEM_NAME, makeAny( OUString( aUserData ) ) );
}
SfxApplication *pSfxApp = SFX_APP();
pSfxApp->SetLastDir_Impl( getPath() );
}
// ------------------------------------------------------------------------
namespace
{
static ::rtl::OUString getInitPath( const String& _rFallback, const xub_StrLen _nFallbackToken )
{
SfxApplication *pSfxApp = SFX_APP();
String sPath = pSfxApp->GetLastDir_Impl();
if ( !sPath.Len() )
sPath = _rFallback.GetToken( _nFallbackToken, ' ' );
// check if the path points to a valid (accessible) directory
sal_Bool bValid = sal_False;
if ( sPath.Len() )
{
String sPathCheck( sPath );
if ( sPathCheck.GetBuffer()[ sPathCheck.Len() - 1 ] != '/' )
sPathCheck += '/';
sPathCheck += '.';
try
{
::ucbhelper::Content aContent( sPathCheck, uno::Reference< ucb::XCommandEnvironment >() );
bValid = aContent.isFolder();
}
catch( Exception& ) {}
}
if ( !bValid )
sPath.Erase();
return sPath;
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::loadConfig()
{
uno::Reference < XFilePickerControlAccess > xDlg( mxFileDlg, UNO_QUERY );
Any aValue;
if ( ! xDlg.is() )
return;
if ( mbHasPreview )
{
SvtViewOptions aViewOpt( E_DIALOG, IMPGRF_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( aUserData.Len() > 0 )
{
try
{
// respect the last "insert as link" state
sal_Bool bLink = (sal_Bool) aUserData.GetToken( 0, ' ' ).ToInt32();
if ( !xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 ).hasValue() )
{
aValue <<= bLink;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aValue );
}
// respect the last "show preview" state
sal_Bool bShowPreview = (sal_Bool) aUserData.GetToken( 1, ' ' ).ToInt32();
if ( !xDlg->getValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0 ).hasValue() )
{
aValue <<= bShowPreview;
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_PREVIEW, 0, aValue );
}
if ( !maPath.getLength() )
displayFolder( getInitPath( aUserData, 2 ) );
if ( ! maCurFilter.getLength() )
{
String aFilter = aUserData.GetToken( 3, ' ' );
aFilter = DecodeSpaces_Impl( aFilter );
setFilter( aFilter );
}
// set the member so we know that we have to show the preview
mbShowPreview = bShowPreview;
}
catch( IllegalArgumentException ){}
}
if ( !maPath.getLength() )
displayFolder( SvtPathOptions().GetGraphicPath() );
}
else
{
SvtViewOptions aViewOpt( E_DIALOG, IODLG_CONFIGNAME );
String aUserData;
if ( aViewOpt.Exists() )
{
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
OUString aTemp;
if ( aUserItem >>= aTemp )
aUserData = String( aTemp );
}
if ( ! aUserData.Len() )
aUserData = DEFINE_CONST_UNICODE( STD_CONFIG_STR );
if ( ! maPath.getLength() )
displayFolder( getInitPath( aUserData, 1 ) );
if ( mbHasAutoExt )
{
sal_Int32 nFlag = aUserData.GetToken( 0, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_AUTOEXTENSION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
if( mbHasSelectionBox )
{
sal_Int32 nFlag = aUserData.GetToken( 2, ' ' ).ToInt32();
aValue <<= (sal_Bool) nFlag;
try
{
xDlg->setValue( ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0, aValue );
}
catch( IllegalArgumentException ){}
}
if ( !maPath.getLength() )
displayFolder( SvtPathOptions().GetWorkPath() );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper_Impl::setDefaultValues()
{
// when no filter is set, we set the curentFilter to <all>
if ( !maCurFilter.getLength() && maSelectFilter.getLength() )
{
uno::Reference< XFilterManager > xFltMgr( mxFileDlg, UNO_QUERY );
try
{
xFltMgr->setCurrentFilter( maSelectFilter );
}
catch( IllegalArgumentException )
{}
}
// when no path is set, we use the standard 'work' folder
if ( ! maPath.getLength() )
{
OUString aWorkFolder = SvtPathOptions().GetWorkPath();
try
{
mxFileDlg->setDisplayDirectory( aWorkFolder );
}
catch( const Exception& )
{
DBG_ERROR( "FileDialogHelper_Impl::setDefaultValues: caught an exception while setting the display directory!" );
}
// INetURLObject aStdDirObj( SvtPathOptions().GetWorkPath() );
//SetStandardDir( aStdDirObj.GetMainURL( INetURLObject::NO_DECODE ) );
}
}
sal_Bool FileDialogHelper_Impl::isShowFilterExtensionEnabled() const
{
return !maFilters.empty();
}
void FileDialogHelper_Impl::addFilterPair( const OUString& rFilter,
const OUString& rFilterWithExtension )
{
maFilters.push_back( FilterPair( rFilter, rFilterWithExtension ) );
}
OUString FileDialogHelper_Impl::getFilterName( const OUString& rFilterWithExtension ) const
{
OUString sRet;
for( ::std::vector< FilterPair >::const_iterator pIter = maFilters.begin(); pIter != maFilters.end(); ++pIter )
{
if ( (*pIter).Second == rFilterWithExtension )
{
sRet = (*pIter).First;
break;
}
}
return sRet;
}
OUString FileDialogHelper_Impl::getFilterWithExtension( const OUString& rFilter ) const
{
OUString sRet;
for( ::std::vector< FilterPair >::const_iterator pIter = maFilters.begin(); pIter != maFilters.end(); ++pIter )
{
if ( (*pIter).First == rFilter )
{
sRet = (*pIter).Second;
break;
}
}
return sRet;
}
void FileDialogHelper_Impl::SetContext( FileDialogHelper::Context _eNewContext )
{
meContext = _eNewContext;
sal_Int32 nNewHelpId = 0;
OUString aConfigId;
switch( _eNewContext )
{
// #104952# dependency to SVX not allowed! When used again, another solution has to be found
// case FileDialogHelper::SW_INSERT_GRAPHIC:
// case FileDialogHelper::SC_INSERT_GRAPHIC:
// case FileDialogHelper::SD_INSERT_GRAPHIC: nNewHelpId = SID_INSERT_GRAPHIC; break;
case FileDialogHelper::SW_INSERT_SOUND:
case FileDialogHelper::SC_INSERT_SOUND:
case FileDialogHelper::SD_INSERT_SOUND: nNewHelpId = SID_INSERT_SOUND; break;
case FileDialogHelper::SW_INSERT_VIDEO:
case FileDialogHelper::SC_INSERT_VIDEO:
case FileDialogHelper::SD_INSERT_VIDEO: nNewHelpId = SID_INSERT_VIDEO; break;
default: break;
}
const OUString* pConfigId = GetLastFilterConfigId( _eNewContext );
if( pConfigId )
LoadLastUsedFilter( *pConfigId );
}
// ------------------------------------------------------------------------
// ----------- FileDialogHelper ---------------------------
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList)
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags, nDialog, NULL , rStandardDir, rBlackList );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
FileDialogHelper::FileDialogHelper(
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, getDialogType( nFlags ), nFlags, nDialog );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper( sal_Int64 nFlags )
{
sal_Int16 nDialogType = getDialogType( nFlags );
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const String& rFact,
SfxFilterFlags nMust,
SfxFilterFlags nDont )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const String& rFact,
sal_Int16 nDialog,
SfxFilterFlags nMust,
SfxFilterFlags nDont,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList)
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, nDialog, NULL, rStandardDir, rBlackList );
mxImp = mpImp;
// create the list of filters
mpImp->addFilters( nFlags, SfxObjectShell::GetServiceNameFromFactory(rFact), nMust, nDont );
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
Window* _pPreferredParent )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, SFX2_IMPL_DIALOG_CONFIG, _pPreferredParent );
mxImp = mpImp;
}
// ------------------------------------------------------------------------
FileDialogHelper::FileDialogHelper(
sal_Int16 nDialogType,
sal_Int64 nFlags,
const ::rtl::OUString& aFilterUIName,
const ::rtl::OUString& aExtName,
const ::rtl::OUString& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList,
Window* _pPreferredParent )
{
mpImp = new FileDialogHelper_Impl( this, nDialogType, nFlags, SFX2_IMPL_DIALOG_CONFIG, _pPreferredParent,rStandardDir, rBlackList );
mxImp = mpImp;
// the wildcard here is expected in form "*.extension"
::rtl::OUString aWildcard;
if ( aExtName.indexOf( (sal_Unicode)'*' ) != 0 )
{
if ( aExtName.getLength() && aExtName.indexOf( (sal_Unicode)'.' ) != 0 )
aWildcard = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
else
aWildcard = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*" ) );
}
aWildcard += aExtName;
::rtl::OUString aUIString =
::sfx2::addExtension( aFilterUIName, aWildcard, ( WB_OPEN == ( nFlags & WB_OPEN ) ), *mpImp );
AddFilter( aUIString, aWildcard );
}
// ------------------------------------------------------------------------
FileDialogHelper::~FileDialogHelper()
{
mpImp->dispose();
mxImp.clear();
}
// ------------------------------------------------------------------------
void FileDialogHelper::CreateMatcher( const String& rFactory )
{
mpImp->createMatcher( SfxObjectShell::GetServiceNameFromFactory(rFactory) );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetControlHelpIds( const sal_Int16* _pControlId, const char** _pHelpId )
{
mpImp->setControlHelpIds( _pControlId, _pHelpId );
}
void FileDialogHelper::SetContext( Context _eNewContext )
{
mpImp->SetContext( _eNewContext );
}
// ------------------------------------------------------------------------
IMPL_LINK( FileDialogHelper, ExecuteSystemFilePicker, void*, EMPTYARG )
{
m_nError = mpImp->execute();
if ( m_aDialogClosedLink.IsSet() )
m_aDialogClosedLink.Call( this );
return 0L;
}
// ------------------------------------------------------------------------
// rDirPath has to be a directory
ErrCode FileDialogHelper::Execute( SvStringsDtor*& rpURLList,
SfxItemSet *& rpSet,
String& rFilter,
const String& rDirPath )
{
SetDisplayFolder( rDirPath );
return mpImp->execute( rpURLList, rpSet, rFilter );
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute()
{
return mpImp->execute();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::Execute( SfxItemSet *& rpSet,
String& rFilter )
{
ErrCode nRet;
SvStringsDtor* pURLList;
nRet = mpImp->execute( pURLList, rpSet, rFilter );
delete pURLList;
return nRet;
}
void FileDialogHelper::StartExecuteModal( const Link& rEndDialogHdl )
{
m_aDialogClosedLink = rEndDialogHdl;
m_nError = ERRCODE_NONE;
if ( mpImp->isSystemFilePicker() )
Application::PostUserEvent( LINK( this, FileDialogHelper, ExecuteSystemFilePicker ) );
else
mpImp->implStartExecute();
}
// ------------------------------------------------------------------------
short FileDialogHelper::GetDialogType() const
{
return mpImp ? mpImp->m_nDialogType : 0;
}
// ------------------------------------------------------------------------
sal_Bool FileDialogHelper::IsPasswordEnabled() const
{
return mpImp ? mpImp->isPasswordEnabled() : sal_False;
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetRealFilter() const
{
String sFilter;
if ( mpImp )
mpImp->getRealFilter( sFilter );
return sFilter;
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetTitle( const String& rNewTitle )
{
if ( mpImp->mxFileDlg.is() )
mpImp->mxFileDlg->setTitle( rNewTitle );
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetPath() const
{
OUString aPath;
if ( mpImp->mlLastURLs.size() > 0)
return mpImp->mlLastURLs[0];
if ( mpImp->mxFileDlg.is() )
{
Sequence < OUString > aPathSeq = mpImp->mxFileDlg->getFiles();
if ( aPathSeq.getLength() == 1 )
{
aPath = aPathSeq[0];
}
}
return aPath;
}
// ------------------------------------------------------------------------
Sequence < OUString > FileDialogHelper::GetMPath() const
{
if ( mpImp->mlLastURLs.size() > 0)
return mpImp->mlLastURLs.getAsConstList();
if ( mpImp->mxFileDlg.is() )
return mpImp->mxFileDlg->getFiles();
else
{
Sequence < OUString > aEmpty;
return aEmpty;
}
}
// ------------------------------------------------------------------------
Sequence< ::rtl::OUString > FileDialogHelper::GetSelectedFiles() const
{
// a) the new way (optional!)
uno::Sequence< ::rtl::OUString > aResultSeq;
uno::Reference< XFilePicker2 > xPickNew(mpImp->mxFileDlg, UNO_QUERY);
if (xPickNew.is())
{
aResultSeq = xPickNew->getSelectedFiles();
}
// b) the olde way ... non optional.
else
{
uno::Reference< XFilePicker > xPickOld(mpImp->mxFileDlg, UNO_QUERY_THROW);
Sequence< OUString > lFiles = xPickOld->getFiles();
::sal_Int32 nFiles = lFiles.getLength();
if ( nFiles > 1 )
{
aResultSeq = Sequence< ::rtl::OUString >( nFiles-1 );
INetURLObject aPath( lFiles[0] );
aPath.setFinalSlash();
for (::sal_Int32 i = 1; i < nFiles; i++)
{
if (i == 1)
aPath.Append( lFiles[i] );
else
aPath.setName( lFiles[i] );
aResultSeq[i-1] = ::rtl::OUString(aPath.GetMainURL( INetURLObject::NO_DECODE ));
}
}
else
aResultSeq = lFiles;
}
return aResultSeq;
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetDisplayDirectory() const
{
return mpImp->getPath();
}
// ------------------------------------------------------------------------
String FileDialogHelper::GetCurrentFilter() const
{
return mpImp->getFilter();
}
// ------------------------------------------------------------------------
ErrCode FileDialogHelper::GetGraphic( Graphic& rGraphic ) const
{
return mpImp->getGraphic( rGraphic );
}
// ------------------------------------------------------------------------
static int impl_isFolder( const OUString& rPath )
{
uno::Reference< task::XInteractionHandler > xHandler;
try
{
uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory(), uno::UNO_QUERY_THROW );
xHandler.set( xFactory->createInstance( DEFINE_CONST_OUSTRING( "com.sun.star.task.InteractionHandler" ) ),
uno::UNO_QUERY_THROW );
}
catch ( Exception const & )
{
}
::rtl::Reference< ::comphelper::StillReadWriteInteraction > aHandler = new ::comphelper::StillReadWriteInteraction( xHandler );
try
{
::ucbhelper::Content aContent(
rPath, new ::ucbhelper::CommandEnvironment( static_cast< task::XInteractionHandler* > ( aHandler.get() ), uno::Reference< ucb::XProgressHandler >() ) );
if ( aContent.isFolder() )
return 1;
return 0;
}
catch ( Exception const & )
{
}
return -1;
}
void FileDialogHelper::SetDisplayDirectory( const String& _rPath )
{
if ( !_rPath.Len() )
return;
// if the given path isn't a folder, we cut off the last part
// and take it as filename and the rest of the path should be
// the folder
INetURLObject aObj( _rPath );
::rtl::OUString sFileName = aObj.GetName( INetURLObject::DECODE_WITH_CHARSET );
aObj.removeSegment();
::rtl::OUString sPath = aObj.GetMainURL( INetURLObject::NO_DECODE );
int nIsFolder = impl_isFolder( _rPath );
if ( nIsFolder == 0 ||
( nIsFolder == -1 && impl_isFolder( sPath ) == 1 ) )
{
mpImp->setFileName( sFileName );
mpImp->displayFolder( sPath );
}
else
{
INetURLObject aObjPathName( _rPath );
::rtl::OUString sFolder( aObjPathName.GetMainURL( INetURLObject::NO_DECODE ) );
if ( sFolder.getLength() == 0 )
{
// _rPath is not a valid path -> fallback to home directory
NAMESPACE_VOS( OSecurity ) aSecurity;
aSecurity.getHomeDir( sFolder );
}
mpImp->displayFolder( sFolder );
}
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetDisplayFolder( const String& _rURL )
{
mpImp->displayFolder( _rURL );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetFileName( const String& _rFileName )
{
mpImp->setFileName( _rFileName );
}
// ------------------------------------------------------------------------
void FileDialogHelper::AddFilter( const String& rFilterName,
const String& rExtension )
{
mpImp->addFilter( rFilterName, rExtension );
}
// ------------------------------------------------------------------------
void FileDialogHelper::SetCurrentFilter( const String& rFilter )
{
String sFilter( rFilter );
if ( mpImp->isShowFilterExtensionEnabled() )
sFilter = mpImp->getFilterWithExtension( rFilter );
mpImp->setFilter( sFilter );
}
// ------------------------------------------------------------------------
uno::Reference < XFilePicker > FileDialogHelper::GetFilePicker() const
{
return mpImp->mxFileDlg;
}
// ------------------------------------------------------------------------
sal_Int16 FileDialogHelper::getDialogType( sal_Int64 nFlags ) const
{
sal_Int16 nDialogType = FILEOPEN_SIMPLE;
if ( nFlags & WB_SAVEAS )
{
if ( nFlags & SFXWB_PASSWORD )
nDialogType = FILESAVE_AUTOEXTENSION_PASSWORD;
else
nDialogType = FILESAVE_SIMPLE;
}
else if ( nFlags & SFXWB_GRAPHIC )
{
if ( nFlags & SFXWB_SHOWSTYLES )
nDialogType = FILEOPEN_LINK_PREVIEW_IMAGE_TEMPLATE;
else
nDialogType = FILEOPEN_LINK_PREVIEW;
}
else if ( SFXWB_INSERT != ( nFlags & SFXWB_INSERT ) )
nDialogType = FILEOPEN_READONLY_VERSION;
return nDialogType;
}
// ------------------------------------------------------------------------
// XFilePickerListener Methods
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::FileSelectionChanged( const FilePickerEvent& aEvent )
{
mpImp->handleFileSelectionChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DirectoryChanged( const FilePickerEvent& aEvent )
{
mpImp->handleDirectoryChanged( aEvent );
}
// ------------------------------------------------------------------------
OUString SAL_CALL FileDialogHelper::HelpRequested( const FilePickerEvent& aEvent )
{
return mpImp->handleHelpRequested( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::ControlStateChanged( const FilePickerEvent& aEvent )
{
mpImp->handleControlStateChanged( aEvent );
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogSizeChanged()
{
mpImp->handleDialogSizeChanged();
}
// ------------------------------------------------------------------------
void SAL_CALL FileDialogHelper::DialogClosed( const DialogClosedEvent& _rEvent )
{
m_nError = ( RET_OK == _rEvent.DialogResult ) ? ERRCODE_NONE : ERRCODE_ABORT;
if ( m_aDialogClosedLink.IsSet() )
m_aDialogClosedLink.Call( this );
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
ErrCode FileOpenDialog_Impl( sal_Int64 nFlags,
const String& rFact,
SvStringsDtor *& rpURLList,
String& rFilter,
SfxItemSet *& rpSet,
const String* pPath,
sal_Int16 nDialog,
const String& rStandardDir,
const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rBlackList )
{
ErrCode nRet;
FileDialogHelper aDialog( nFlags, rFact, nDialog, 0, 0, rStandardDir, rBlackList );
String aPath;
if ( pPath )
aPath = *pPath;
nRet = aDialog.Execute( rpURLList, rpSet, rFilter, aPath );
DBG_ASSERT( rFilter.SearchAscii(": ") == STRING_NOTFOUND, "Old filter name used!");
return nRet;
}
// ------------------------------------------------------------------------
String EncodeSpaces_Impl( const String& rSource )
{
String sRet( rSource );
sRet.SearchAndReplaceAll( DEFINE_CONST_UNICODE( " " ), DEFINE_CONST_UNICODE( "%20" ) );
return sRet;
}
// ------------------------------------------------------------------------
String DecodeSpaces_Impl( const String& rSource )
{
String sRet( rSource );
sRet.SearchAndReplaceAll( DEFINE_CONST_UNICODE( "%20" ), DEFINE_CONST_UNICODE( " " ) );
return sRet;
}
// ------------------------------------------------------------------------
} // end of namespace sfx2
|
/*************************************************************************
*
* $RCSfile: eventsupplier.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: hr $ $Date: 2004-03-09 10:08:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//--------------------------------------------------------------------------------------------------------
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_UTL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif
#ifndef _SFX_APPUNO_HXX
#include <appuno.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <objsh.hxx>
#endif
#ifndef _SFX_SFXBASEMODEL_HXX_
#include <sfxbasemodel.hxx>
#endif
#ifndef _SFX_EVENTCONF_HXX
#include <evntconf.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _SFX_EVENTSUPPLIER_HXX_
#include "eventsupplier.hxx"
#endif
#include "app.hxx"
#include "sfxresid.hxx"
#include "sfxsids.hrc"
#include "sfxlocal.hrc"
#include "docfile.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
//--------------------------------------------------------------------------------------------------------
#define MACRO_PRFIX "macro://"
#define MACRO_POSTFIX "()"
//--------------------------------------------------------------------------------------------------------
#define PROPERTYVALUE ::com::sun::star::beans::PropertyValue
#define UNO_QUERY ::com::sun::star::uno::UNO_QUERY
//--------------------------------------------------------------------------------------------------------
// --- XNameReplace ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::replaceByName( const OUSTRING & aName, const ANY & rElement )
throw( ILLEGALARGUMENTEXCEPTION, NOSUCHELEMENTEXCEPTION,
WRAPPEDTARGETEXCEPTION, RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and replace the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
{
// check for correct type of the element
if ( ::getCppuType( (const SEQUENCE < PROPERTYVALUE > *)0 ) == rElement.getValueType() )
{
// create Configuration at first, creation might call this method also and that would overwrite everything
// we might have stored before!
USHORT nID = (USHORT) SfxEventConfiguration::GetEventId_Impl( aName );
if ( nID )
{
SfxEventConfigItem_Impl* pConfig =
mpObjShell ? mpObjShell->GetEventConfig_Impl(TRUE) : SFX_APP()->GetEventConfig()->GetAppEventConfig_Impl();
ANY aValue;
BlowUpMacro( rElement, aValue, mpObjShell );
// pConfig becomes the owner of the new SvxMacro
SvxMacro *pMacro = ConvertToMacro( aValue, mpObjShell, FALSE );
pConfig->ConfigureEvent( nID, pMacro );
maEventData[i] = aValue;
SEQUENCE < PROPERTYVALUE > aProperties;
if ( aValue >>= aProperties )
{
long nCount = aProperties.getLength();
for ( long nIndex = 0; nIndex < nCount; nIndex++ )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
{
::rtl::OUString aType;
aProperties[ nIndex ].Value >>= aType;
break;
}
}
}
}
}
else
throw ILLEGALARGUMENTEXCEPTION();
return;
}
}
throw NOSUCHELEMENTEXCEPTION();
}
//--------------------------------------------------------------------------------------------------------
// --- XNameAccess ---
//--------------------------------------------------------------------------------------------------------
ANY SAL_CALL SfxEvents_Impl::getByName( const OUSTRING& aName )
throw( NOSUCHELEMENTEXCEPTION, WRAPPEDTARGETEXCEPTION,
RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and return the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
return maEventData[i];
}
throw NOSUCHELEMENTEXCEPTION();
return ANY();
}
//--------------------------------------------------------------------------------------------------------
SEQUENCE< OUSTRING > SAL_CALL SfxEvents_Impl::getElementNames() throw ( RUNTIMEEXCEPTION )
{
return maEventNames;
}
//--------------------------------------------------------------------------------------------------------
sal_Bool SAL_CALL SfxEvents_Impl::hasByName( const OUSTRING& aName ) throw ( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and return the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------------------------------------------
// --- XElementAccess ( parent of XNameAccess ) ---
//--------------------------------------------------------------------------------------------------------
UNOTYPE SAL_CALL SfxEvents_Impl::getElementType() throw ( RUNTIMEEXCEPTION )
{
UNOTYPE aElementType = ::getCppuType( (const SEQUENCE < PROPERTYVALUE > *)0 );
return aElementType;
}
//--------------------------------------------------------------------------------------------------------
sal_Bool SAL_CALL SfxEvents_Impl::hasElements() throw ( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
if ( maEventNames.getLength() )
return sal_True;
else
return sal_False;
}
//--------------------------------------------------------------------------------------------------------
// --- ::document::XEventListener ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::notifyEvent( const DOCEVENTOBJECT& aEvent ) throw( RUNTIMEEXCEPTION )
{
::osl::ClearableMutexGuard aGuard( maMutex );
// get the event name, find the coresponding data, execute the data
OUSTRING aName = aEvent.EventName;
long nCount = maEventNames.getLength();
long nIndex = 0;
sal_Bool bFound = sal_False;
while ( !bFound && ( nIndex < nCount ) )
{
if ( maEventNames[nIndex] == aName )
bFound = sal_True;
else
nIndex += 1;
}
if ( !bFound )
return;
SEQUENCE < PROPERTYVALUE > aProperties;
ANY aEventData = maEventData[ nIndex ];
if ( aEventData >>= aProperties )
{
OUSTRING aPrefix = OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_PRFIX ) );
OUSTRING aType;
OUSTRING aScript;
OUSTRING aLibrary;
OUSTRING aMacroName;
nCount = aProperties.getLength();
if ( !nCount )
return;
nIndex = 0;
while ( nIndex < nCount )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
aProperties[ nIndex ].Value >>= aType;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
aProperties[ nIndex ].Value >>= aScript;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
aProperties[ nIndex ].Value >>= aLibrary;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
aProperties[ nIndex ].Value >>= aMacroName;
else
DBG_ERROR("Unknown property value!");
nIndex += 1;
}
if ( aType.compareToAscii( STAR_BASIC ) == 0 && aScript.getLength() )
{
aGuard.clear();
com::sun::star::uno::Any aAny;
SfxMacroLoader::loadMacro( aScript, aAny, mpObjShell );
}
else if ( aType.compareToAscii( "Service" ) == 0 || ( aType.compareToAscii( "Script" ) == 0 ) )
{
if ( aScript.getLength() )
{
SfxViewFrame* pView = mpObjShell ? SfxViewFrame::GetFirst( mpObjShell ) : SfxViewFrame::Current();
::com::sun::star::util::URL aURL;
aURL.Complete = aScript;
::com::sun::star::uno::Reference < ::com::sun::star::util::XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY );
xTrans->parseStrict( aURL );
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatchProvider > xProv( pView->GetFrame()->GetFrameInterface(), UNO_QUERY );
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDisp;
if ( xProv.is() )
xDisp = xProv->queryDispatch( aURL, ::rtl::OUString(), 0 );
if ( xDisp.is() )
{
//::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > aArgs(1);
//aArgs[0].Name = rtl::OUString::createFromAscii("Referer");
//aArs[0].Value <<= ::rtl::OUString( mpObjShell->GetMedium()->GetName() );
//xDisp->dispatch( aURL, aArgs );
xDisp->dispatch( aURL, ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >() );
}
}
}
else
{
DBG_ERRORFILE( "notifyEvent(): Unsupported event type" );
}
}
}
//--------------------------------------------------------------------------------------------------------
// --- ::lang::XEventListener ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::disposing( const EVENTOBJECT& Source ) throw( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
if ( mxBroadcaster.is() )
{
mxBroadcaster->removeEventListener( this );
mxBroadcaster = NULL;
}
}
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
SfxEvents_Impl::SfxEvents_Impl( SfxObjectShell* pShell,
REFERENCE< XEVENTBROADCASTER > xBroadcaster )
{
// get the list of supported events and store it
if ( pShell )
maEventNames = pShell->GetEventNames();
else
maEventNames = SfxObjectShell::GetEventNames_Impl();
maEventData = SEQUENCE < ANY > ( maEventNames.getLength() );
mpObjShell = pShell;
mxBroadcaster = xBroadcaster;
if ( mxBroadcaster.is() )
mxBroadcaster->addEventListener( this );
}
//--------------------------------------------------------------------------------------------------------
SfxEvents_Impl::~SfxEvents_Impl()
{
}
//--------------------------------------------------------------------------------------------------------
SvxMacro* SfxEvents_Impl::ConvertToMacro( const ANY& rElement, SfxObjectShell* pObjShell, BOOL bBlowUp )
{
SvxMacro* pMacro = NULL;
SEQUENCE < PROPERTYVALUE > aProperties;
ANY aAny;
if ( bBlowUp )
BlowUpMacro( rElement, aAny, pObjShell );
else
aAny = rElement;
if ( aAny >>= aProperties )
{
OUSTRING aType;
OUSTRING aScriptURL;
OUSTRING aLibrary;
OUSTRING aMacroName;
long nCount = aProperties.getLength();
long nIndex = 0;
if ( !nCount )
return pMacro;
while ( nIndex < nCount )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
aProperties[ nIndex ].Value >>= aType;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
aProperties[ nIndex ].Value >>= aScriptURL;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
aProperties[ nIndex ].Value >>= aLibrary;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
aProperties[ nIndex ].Value >>= aMacroName;
else
DBG_ERROR("Unknown propery value!");
nIndex += 1;
}
// Get the type
ScriptType eType( STARBASIC );
if ( aType.compareToAscii( STAR_BASIC ) == COMPARE_EQUAL )
eType = STARBASIC;
else if ( aType.compareToAscii( "Script" ) == COMPARE_EQUAL && aScriptURL.getLength() )
eType = EXTENDED_STYPE;
else if ( aType.compareToAscii( SVX_MACRO_LANGUAGE_JAVASCRIPT ) == COMPARE_EQUAL )
eType = JAVASCRIPT;
else
DBG_ERRORFILE( "ConvertToMacro: Unknown macro type" );
if ( aMacroName.getLength() )
{
if ( aLibrary.compareToAscii("application") == 0 )
aLibrary = SFX_APP()->GetName();
else
aLibrary = ::rtl::OUString();
pMacro = new SvxMacro( aMacroName, aLibrary, eType );
}
else if ( eType == EXTENDED_STYPE )
pMacro = new SvxMacro( aScriptURL, aType );
}
return pMacro;
}
void SfxEvents_Impl::BlowUpMacro( const ANY& rEvent, ANY& rRet, SfxObjectShell* pDoc )
{
if ( !pDoc )
pDoc = SfxObjectShell::Current();
SEQUENCE < PROPERTYVALUE > aInProps;
SEQUENCE < PROPERTYVALUE > aOutProps(2);
if ( !( rEvent >>= aInProps ) )
return;
sal_Int32 nCount = aInProps.getLength();
if ( !nCount )
return;
OUSTRING aType;
OUSTRING aScript;
OUSTRING aLibrary;
OUSTRING aMacroName;
sal_Int32 nIndex = 0;
while ( nIndex < nCount )
{
if ( aInProps[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
{
aInProps[nIndex].Value >>= aType;
aOutProps[0] = aInProps[nIndex];
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
{
aInProps[nIndex].Value >>= aScript;
aOutProps[1] = aInProps[nIndex];
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
{
aInProps[ nIndex ].Value >>= aLibrary;
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
{
aInProps[ nIndex ].Value >>= aMacroName;
}
nIndex += 1;
}
if ( aType.compareToAscii( STAR_BASIC ) == 0 )
{
aOutProps.realloc(4);
if ( aScript.getLength() )
{
if( ! aMacroName.getLength() || ! aLibrary.getLength() )
{
sal_Int32 nHashPos = aScript.indexOf( '/', 8 );
sal_Int32 nArgsPos = aScript.indexOf( '(' );
if ( ( nHashPos != STRING_NOTFOUND ) && ( nHashPos < nArgsPos ) )
{
OUSTRING aBasMgrName( INetURLObject::decode( aScript.copy( 8, nHashPos-8 ), INET_HEX_ESCAPE, INetURLObject::DECODE_WITH_CHARSET ) );
if ( aBasMgrName.compareToAscii(".") == 0 )
aLibrary = pDoc->GetTitle();
/*
else if ( aBasMgrName.getLength() )
aLibrary = aBasMgrName;
*/
else
aLibrary = SFX_APP()->GetName();
// Get the macro name
aMacroName = aScript.copy( nHashPos+1, nArgsPos - nHashPos - 1 );
}
else
{
DBG_ERRORFILE( "ConvertToMacro: Unknown macro url format" );
}
}
}
else if ( aMacroName.getLength() )
{
aScript = OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_PRFIX ) );
if ( aLibrary.compareTo( SFX_APP()->GetName() ) != 0 && aLibrary.compareToAscii("StarDesktop") != 0 && aLibrary.compareToAscii("application") != 0 )
aScript += OUSTRING('.');
aScript += OUSTRING('/');
aScript += aMacroName;
aScript += OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_POSTFIX ) );
}
else
// wrong properties
return;
if ( aLibrary.compareToAscii("document") != 0 )
{
if ( !aLibrary.getLength() || pDoc && ( String(aLibrary) == pDoc->GetTitle( SFX_TITLE_APINAME ) || String(aLibrary) == pDoc->GetTitle() ) )
aLibrary = String::CreateFromAscii("document");
else
aLibrary = String::CreateFromAscii("application");
}
aOutProps[1].Name = OUSTRING::createFromAscii( PROP_SCRIPT );
aOutProps[1].Value <<= aScript;
aOutProps[2].Name = OUSTRING::createFromAscii( PROP_LIBRARY );
aOutProps[2].Value <<= aLibrary;
aOutProps[3].Name = OUSTRING::createFromAscii( PROP_MACRO_NAME );
aOutProps[3].Value <<= aMacroName;
rRet <<= aOutProps;
}
else if ( aType.compareToAscii( SVX_MACRO_LANGUAGE_JAVASCRIPT ) == 0 )
{
aOutProps[1] = aInProps[1];
rRet <<= aOutProps;
}
else
{
rRet <<= aOutProps;
}
}
SFX_IMPL_XSERVICEINFO( SfxGlobalEvents_Impl, "com.sun.star.frame.GlobalEventBroadcaster", "com.sun.star.comp.sfx2.GlobalEventBroadcaster" )
SFX_IMPL_ONEINSTANCEFACTORY( SfxGlobalEvents_Impl );
SfxGlobalEvents_Impl::SfxGlobalEvents_Impl( const com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory >& xSmgr )
: m_aInterfaceContainer( m_aMutex )
{
m_refCount++;
pImp = new SfxEvents_Impl( NULL, this );
m_xEvents = pImp;
m_xJobsBinding = REFERENCE< XJOBEXECUTOR >(xSmgr->createInstance(OUSTRING::createFromAscii("com.sun.star.task.JobExecutor")), UNO_QUERY);
StartListening(*SFX_APP());
m_refCount--;
}
SfxGlobalEvents_Impl::~SfxGlobalEvents_Impl()
{
}
REFERENCE< XNAMEREPLACE > SAL_CALL SfxGlobalEvents_Impl::getEvents() throw( RUNTIMEEXCEPTION )
{
return m_xEvents;
}
void SAL_CALL SfxGlobalEvents_Impl::addEventListener( const REFERENCE< XDOCEVENTLISTENER >& xListener ) throw( RUNTIMEEXCEPTION )
{
m_aInterfaceContainer.addInterface( xListener );
}
void SAL_CALL SfxGlobalEvents_Impl::removeEventListener( const REFERENCE< XDOCEVENTLISTENER >& xListener ) throw( RUNTIMEEXCEPTION )
{
m_aInterfaceContainer.removeInterface( xListener );
}
void SfxGlobalEvents_Impl::Notify( SfxBroadcaster& aBC, const SfxHint& aHint )
{
SfxEventHint* pNamedHint = PTR_CAST( SfxEventHint, &aHint );
if ( pNamedHint )
{
OUSTRING aName = SfxEventConfiguration::GetEventName_Impl( pNamedHint->GetEventId() );
REFERENCE < XEVENTSSUPPLIER > xSup;
if ( pNamedHint->GetObjShell() )
xSup = REFERENCE < XEVENTSSUPPLIER >( pNamedHint->GetObjShell()->GetModel(), UNO_QUERY );
// else
// xSup = (XEVENTSSUPPLIER*) this;
DOCEVENTOBJECT aEvent( xSup, aName );
// Attention: This listener is a special one. It binds the global document events
// to the generic job execution framework. It's a loose binding (using weak references).
// So we hold this listener outside our normal listener container.
// The implementation behind this job executor can be replaced ...
// but we check for this undocumented interface!
REFERENCE< XDOCEVENTLISTENER > xJobExecutor(m_xJobsBinding.get(), UNO_QUERY);
if (xJobExecutor.is())
xJobExecutor->notifyEvent(aEvent);
::cppu::OInterfaceIteratorHelper aIt( m_aInterfaceContainer );
while( aIt.hasMoreElements() )
{
try
{
((XDOCEVENTLISTENER *)aIt.next())->notifyEvent( aEvent );
}
catch( RUNTIMEEXCEPTION& )
{
aIt.remove();
}
}
}
}
INTEGRATION: CWS scriptingf5 (1.22.36); FILE MERGED
2004/03/19 14:27:42 toconnor 1.22.36.2: RESYNC: (1.22-1.23); FILE MERGED
2004/02/26 17:44:15 toconnor 1.22.36.1: #i25859# - If there is no document shell available get XDispatchProvider
from Desktop service
/*************************************************************************
*
* $RCSfile: eventsupplier.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: svesik $ $Date: 2004-04-19 23:17:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//--------------------------------------------------------------------------------------------------------
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_UTL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SFXMACITEM_HXX
#include <svtools/macitem.hxx>
#endif
#ifndef _SFX_APPUNO_HXX
#include <appuno.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <objsh.hxx>
#endif
#ifndef _SFX_SFXBASEMODEL_HXX_
#include <sfxbasemodel.hxx>
#endif
#ifndef _SFX_EVENTCONF_HXX
#include <evntconf.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _SFX_EVENTSUPPLIER_HXX_
#include "eventsupplier.hxx"
#endif
#include "app.hxx"
#include "sfxresid.hxx"
#include "sfxsids.hrc"
#include "sfxlocal.hrc"
#include "docfile.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
//--------------------------------------------------------------------------------------------------------
#define MACRO_PRFIX "macro://"
#define MACRO_POSTFIX "()"
//--------------------------------------------------------------------------------------------------------
#define PROPERTYVALUE ::com::sun::star::beans::PropertyValue
#define UNO_QUERY ::com::sun::star::uno::UNO_QUERY
//--------------------------------------------------------------------------------------------------------
// --- XNameReplace ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::replaceByName( const OUSTRING & aName, const ANY & rElement )
throw( ILLEGALARGUMENTEXCEPTION, NOSUCHELEMENTEXCEPTION,
WRAPPEDTARGETEXCEPTION, RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and replace the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
{
// check for correct type of the element
if ( ::getCppuType( (const SEQUENCE < PROPERTYVALUE > *)0 ) == rElement.getValueType() )
{
// create Configuration at first, creation might call this method also and that would overwrite everything
// we might have stored before!
USHORT nID = (USHORT) SfxEventConfiguration::GetEventId_Impl( aName );
if ( nID )
{
SfxEventConfigItem_Impl* pConfig =
mpObjShell ? mpObjShell->GetEventConfig_Impl(TRUE) : SFX_APP()->GetEventConfig()->GetAppEventConfig_Impl();
ANY aValue;
BlowUpMacro( rElement, aValue, mpObjShell );
// pConfig becomes the owner of the new SvxMacro
SvxMacro *pMacro = ConvertToMacro( aValue, mpObjShell, FALSE );
pConfig->ConfigureEvent( nID, pMacro );
maEventData[i] = aValue;
SEQUENCE < PROPERTYVALUE > aProperties;
if ( aValue >>= aProperties )
{
long nCount = aProperties.getLength();
for ( long nIndex = 0; nIndex < nCount; nIndex++ )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
{
::rtl::OUString aType;
aProperties[ nIndex ].Value >>= aType;
break;
}
}
}
}
}
else
throw ILLEGALARGUMENTEXCEPTION();
return;
}
}
throw NOSUCHELEMENTEXCEPTION();
}
//--------------------------------------------------------------------------------------------------------
// --- XNameAccess ---
//--------------------------------------------------------------------------------------------------------
ANY SAL_CALL SfxEvents_Impl::getByName( const OUSTRING& aName )
throw( NOSUCHELEMENTEXCEPTION, WRAPPEDTARGETEXCEPTION,
RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and return the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
return maEventData[i];
}
throw NOSUCHELEMENTEXCEPTION();
return ANY();
}
//--------------------------------------------------------------------------------------------------------
SEQUENCE< OUSTRING > SAL_CALL SfxEvents_Impl::getElementNames() throw ( RUNTIMEEXCEPTION )
{
return maEventNames;
}
//--------------------------------------------------------------------------------------------------------
sal_Bool SAL_CALL SfxEvents_Impl::hasByName( const OUSTRING& aName ) throw ( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
// find the event in the list and return the data
long nCount = maEventNames.getLength();
for ( long i=0; i<nCount; i++ )
{
if ( maEventNames[i] == aName )
return sal_True;
}
return sal_False;
}
//--------------------------------------------------------------------------------------------------------
// --- XElementAccess ( parent of XNameAccess ) ---
//--------------------------------------------------------------------------------------------------------
UNOTYPE SAL_CALL SfxEvents_Impl::getElementType() throw ( RUNTIMEEXCEPTION )
{
UNOTYPE aElementType = ::getCppuType( (const SEQUENCE < PROPERTYVALUE > *)0 );
return aElementType;
}
//--------------------------------------------------------------------------------------------------------
sal_Bool SAL_CALL SfxEvents_Impl::hasElements() throw ( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
if ( maEventNames.getLength() )
return sal_True;
else
return sal_False;
}
//--------------------------------------------------------------------------------------------------------
// --- ::document::XEventListener ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::notifyEvent( const DOCEVENTOBJECT& aEvent ) throw( RUNTIMEEXCEPTION )
{
::osl::ClearableMutexGuard aGuard( maMutex );
// get the event name, find the coresponding data, execute the data
OUSTRING aName = aEvent.EventName;
long nCount = maEventNames.getLength();
long nIndex = 0;
sal_Bool bFound = sal_False;
while ( !bFound && ( nIndex < nCount ) )
{
if ( maEventNames[nIndex] == aName )
bFound = sal_True;
else
nIndex += 1;
}
if ( !bFound )
return;
SEQUENCE < PROPERTYVALUE > aProperties;
ANY aEventData = maEventData[ nIndex ];
if ( aEventData >>= aProperties )
{
OUSTRING aPrefix = OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_PRFIX ) );
OUSTRING aType;
OUSTRING aScript;
OUSTRING aLibrary;
OUSTRING aMacroName;
nCount = aProperties.getLength();
if ( !nCount )
return;
nIndex = 0;
while ( nIndex < nCount )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
aProperties[ nIndex ].Value >>= aType;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
aProperties[ nIndex ].Value >>= aScript;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
aProperties[ nIndex ].Value >>= aLibrary;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
aProperties[ nIndex ].Value >>= aMacroName;
else
DBG_ERROR("Unknown property value!");
nIndex += 1;
}
if ( aType.compareToAscii( STAR_BASIC ) == 0 && aScript.getLength() )
{
aGuard.clear();
com::sun::star::uno::Any aAny;
SfxMacroLoader::loadMacro( aScript, aAny, mpObjShell );
}
else if ( aType.compareToAscii( "Service" ) == 0 ||
aType.compareToAscii( "Script" ) == 0 )
{
if ( aScript.getLength() )
{
SfxViewFrame* pView = mpObjShell ?
SfxViewFrame::GetFirst( mpObjShell ) :
SfxViewFrame::Current();
::com::sun::star::uno::Reference
< ::com::sun::star::util::XURLTransformer > xTrans(
::comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString::createFromAscii(
"com.sun.star.util.URLTransformer" ) ),
UNO_QUERY );
::com::sun::star::util::URL aURL;
aURL.Complete = aScript;
xTrans->parseStrict( aURL );
::com::sun::star::uno::Reference
< ::com::sun::star::frame::XDispatchProvider > xProv;
if ( pView != NULL )
{
xProv = ::com::sun::star::uno::Reference
< ::com::sun::star::frame::XDispatchProvider > (
pView->GetFrame()->GetFrameInterface(), UNO_QUERY );
}
else
{
xProv = ::com::sun::star::uno::Reference
< ::com::sun::star::frame::XDispatchProvider > (
::comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString::createFromAscii(
"com.sun.star.frame.Desktop" ) ),
UNO_QUERY );
}
::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDisp;
if ( xProv.is() )
xDisp = xProv->queryDispatch( aURL, ::rtl::OUString(), 0 );
if ( xDisp.is() )
{
//::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > aArgs(1);
//aArgs[0].Name = rtl::OUString::createFromAscii("Referer");
//aArs[0].Value <<= ::rtl::OUString( mpObjShell->GetMedium()->GetName() );
//xDisp->dispatch( aURL, aArgs );
xDisp->dispatch( aURL, ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >() );
}
}
}
else
{
DBG_ERRORFILE( "notifyEvent(): Unsupported event type" );
}
}
}
//--------------------------------------------------------------------------------------------------------
// --- ::lang::XEventListener ---
//--------------------------------------------------------------------------------------------------------
void SAL_CALL SfxEvents_Impl::disposing( const EVENTOBJECT& Source ) throw( RUNTIMEEXCEPTION )
{
::osl::MutexGuard aGuard( maMutex );
if ( mxBroadcaster.is() )
{
mxBroadcaster->removeEventListener( this );
mxBroadcaster = NULL;
}
}
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
SfxEvents_Impl::SfxEvents_Impl( SfxObjectShell* pShell,
REFERENCE< XEVENTBROADCASTER > xBroadcaster )
{
// get the list of supported events and store it
if ( pShell )
maEventNames = pShell->GetEventNames();
else
maEventNames = SfxObjectShell::GetEventNames_Impl();
maEventData = SEQUENCE < ANY > ( maEventNames.getLength() );
mpObjShell = pShell;
mxBroadcaster = xBroadcaster;
if ( mxBroadcaster.is() )
mxBroadcaster->addEventListener( this );
}
//--------------------------------------------------------------------------------------------------------
SfxEvents_Impl::~SfxEvents_Impl()
{
}
//--------------------------------------------------------------------------------------------------------
SvxMacro* SfxEvents_Impl::ConvertToMacro( const ANY& rElement, SfxObjectShell* pObjShell, BOOL bBlowUp )
{
SvxMacro* pMacro = NULL;
SEQUENCE < PROPERTYVALUE > aProperties;
ANY aAny;
if ( bBlowUp )
BlowUpMacro( rElement, aAny, pObjShell );
else
aAny = rElement;
if ( aAny >>= aProperties )
{
OUSTRING aType;
OUSTRING aScriptURL;
OUSTRING aLibrary;
OUSTRING aMacroName;
long nCount = aProperties.getLength();
long nIndex = 0;
if ( !nCount )
return pMacro;
while ( nIndex < nCount )
{
if ( aProperties[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
aProperties[ nIndex ].Value >>= aType;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
aProperties[ nIndex ].Value >>= aScriptURL;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
aProperties[ nIndex ].Value >>= aLibrary;
else if ( aProperties[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
aProperties[ nIndex ].Value >>= aMacroName;
else
DBG_ERROR("Unknown propery value!");
nIndex += 1;
}
// Get the type
ScriptType eType( STARBASIC );
if ( aType.compareToAscii( STAR_BASIC ) == COMPARE_EQUAL )
eType = STARBASIC;
else if ( aType.compareToAscii( "Script" ) == COMPARE_EQUAL && aScriptURL.getLength() )
eType = EXTENDED_STYPE;
else if ( aType.compareToAscii( SVX_MACRO_LANGUAGE_JAVASCRIPT ) == COMPARE_EQUAL )
eType = JAVASCRIPT;
else
DBG_ERRORFILE( "ConvertToMacro: Unknown macro type" );
if ( aMacroName.getLength() )
{
if ( aLibrary.compareToAscii("application") == 0 )
aLibrary = SFX_APP()->GetName();
else
aLibrary = ::rtl::OUString();
pMacro = new SvxMacro( aMacroName, aLibrary, eType );
}
else if ( eType == EXTENDED_STYPE )
pMacro = new SvxMacro( aScriptURL, aType );
}
return pMacro;
}
void SfxEvents_Impl::BlowUpMacro( const ANY& rEvent, ANY& rRet, SfxObjectShell* pDoc )
{
if ( !pDoc )
pDoc = SfxObjectShell::Current();
SEQUENCE < PROPERTYVALUE > aInProps;
SEQUENCE < PROPERTYVALUE > aOutProps(2);
if ( !( rEvent >>= aInProps ) )
return;
sal_Int32 nCount = aInProps.getLength();
if ( !nCount )
return;
OUSTRING aType;
OUSTRING aScript;
OUSTRING aLibrary;
OUSTRING aMacroName;
sal_Int32 nIndex = 0;
while ( nIndex < nCount )
{
if ( aInProps[ nIndex ].Name.compareToAscii( PROP_EVENT_TYPE ) == 0 )
{
aInProps[nIndex].Value >>= aType;
aOutProps[0] = aInProps[nIndex];
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_SCRIPT ) == 0 )
{
aInProps[nIndex].Value >>= aScript;
aOutProps[1] = aInProps[nIndex];
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_LIBRARY ) == 0 )
{
aInProps[ nIndex ].Value >>= aLibrary;
}
else if ( aInProps[ nIndex ].Name.compareToAscii( PROP_MACRO_NAME ) == 0 )
{
aInProps[ nIndex ].Value >>= aMacroName;
}
nIndex += 1;
}
if ( aType.compareToAscii( STAR_BASIC ) == 0 )
{
aOutProps.realloc(4);
if ( aScript.getLength() )
{
if( ! aMacroName.getLength() || ! aLibrary.getLength() )
{
sal_Int32 nHashPos = aScript.indexOf( '/', 8 );
sal_Int32 nArgsPos = aScript.indexOf( '(' );
if ( ( nHashPos != STRING_NOTFOUND ) && ( nHashPos < nArgsPos ) )
{
OUSTRING aBasMgrName( INetURLObject::decode( aScript.copy( 8, nHashPos-8 ), INET_HEX_ESCAPE, INetURLObject::DECODE_WITH_CHARSET ) );
if ( aBasMgrName.compareToAscii(".") == 0 )
aLibrary = pDoc->GetTitle();
/*
else if ( aBasMgrName.getLength() )
aLibrary = aBasMgrName;
*/
else
aLibrary = SFX_APP()->GetName();
// Get the macro name
aMacroName = aScript.copy( nHashPos+1, nArgsPos - nHashPos - 1 );
}
else
{
DBG_ERRORFILE( "ConvertToMacro: Unknown macro url format" );
}
}
}
else if ( aMacroName.getLength() )
{
aScript = OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_PRFIX ) );
if ( aLibrary.compareTo( SFX_APP()->GetName() ) != 0 && aLibrary.compareToAscii("StarDesktop") != 0 && aLibrary.compareToAscii("application") != 0 )
aScript += OUSTRING('.');
aScript += OUSTRING('/');
aScript += aMacroName;
aScript += OUSTRING( RTL_CONSTASCII_USTRINGPARAM( MACRO_POSTFIX ) );
}
else
// wrong properties
return;
if ( aLibrary.compareToAscii("document") != 0 )
{
if ( !aLibrary.getLength() || pDoc && ( String(aLibrary) == pDoc->GetTitle( SFX_TITLE_APINAME ) || String(aLibrary) == pDoc->GetTitle() ) )
aLibrary = String::CreateFromAscii("document");
else
aLibrary = String::CreateFromAscii("application");
}
aOutProps[1].Name = OUSTRING::createFromAscii( PROP_SCRIPT );
aOutProps[1].Value <<= aScript;
aOutProps[2].Name = OUSTRING::createFromAscii( PROP_LIBRARY );
aOutProps[2].Value <<= aLibrary;
aOutProps[3].Name = OUSTRING::createFromAscii( PROP_MACRO_NAME );
aOutProps[3].Value <<= aMacroName;
rRet <<= aOutProps;
}
else if ( aType.compareToAscii( SVX_MACRO_LANGUAGE_JAVASCRIPT ) == 0 )
{
aOutProps[1] = aInProps[1];
rRet <<= aOutProps;
}
else
{
rRet <<= aOutProps;
}
}
SFX_IMPL_XSERVICEINFO( SfxGlobalEvents_Impl, "com.sun.star.frame.GlobalEventBroadcaster", "com.sun.star.comp.sfx2.GlobalEventBroadcaster" )
SFX_IMPL_ONEINSTANCEFACTORY( SfxGlobalEvents_Impl );
SfxGlobalEvents_Impl::SfxGlobalEvents_Impl( const com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory >& xSmgr )
: m_aInterfaceContainer( m_aMutex )
{
m_refCount++;
pImp = new SfxEvents_Impl( NULL, this );
m_xEvents = pImp;
m_xJobsBinding = REFERENCE< XJOBEXECUTOR >(xSmgr->createInstance(OUSTRING::createFromAscii("com.sun.star.task.JobExecutor")), UNO_QUERY);
StartListening(*SFX_APP());
m_refCount--;
}
SfxGlobalEvents_Impl::~SfxGlobalEvents_Impl()
{
}
REFERENCE< XNAMEREPLACE > SAL_CALL SfxGlobalEvents_Impl::getEvents() throw( RUNTIMEEXCEPTION )
{
return m_xEvents;
}
void SAL_CALL SfxGlobalEvents_Impl::addEventListener( const REFERENCE< XDOCEVENTLISTENER >& xListener ) throw( RUNTIMEEXCEPTION )
{
m_aInterfaceContainer.addInterface( xListener );
}
void SAL_CALL SfxGlobalEvents_Impl::removeEventListener( const REFERENCE< XDOCEVENTLISTENER >& xListener ) throw( RUNTIMEEXCEPTION )
{
m_aInterfaceContainer.removeInterface( xListener );
}
void SfxGlobalEvents_Impl::Notify( SfxBroadcaster& aBC, const SfxHint& aHint )
{
SfxEventHint* pNamedHint = PTR_CAST( SfxEventHint, &aHint );
if ( pNamedHint )
{
OUSTRING aName = SfxEventConfiguration::GetEventName_Impl( pNamedHint->GetEventId() );
REFERENCE < XEVENTSSUPPLIER > xSup;
if ( pNamedHint->GetObjShell() )
xSup = REFERENCE < XEVENTSSUPPLIER >( pNamedHint->GetObjShell()->GetModel(), UNO_QUERY );
// else
// xSup = (XEVENTSSUPPLIER*) this;
DOCEVENTOBJECT aEvent( xSup, aName );
// Attention: This listener is a special one. It binds the global document events
// to the generic job execution framework. It's a loose binding (using weak references).
// So we hold this listener outside our normal listener container.
// The implementation behind this job executor can be replaced ...
// but we check for this undocumented interface!
REFERENCE< XDOCEVENTLISTENER > xJobExecutor(m_xJobsBinding.get(), UNO_QUERY);
if (xJobExecutor.is())
xJobExecutor->notifyEvent(aEvent);
::cppu::OInterfaceIteratorHelper aIt( m_aInterfaceContainer );
while( aIt.hasMoreElements() )
{
try
{
((XDOCEVENTLISTENER *)aIt.next())->notifyEvent( aEvent );
}
catch( RUNTIMEEXCEPTION& )
{
aIt.remove();
}
}
}
}
|
/* Cycript - Inlining/Optimizing JavaScript Compiler
* Copyright (C) 2009 Jay Freeman (saurik)
*/
/* Modified BSD License {{{ */
/*
* Redistribution and use in source and binary
* forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse
* or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sqlite3.h>
#include "Internal.hpp"
#include <dlfcn.h>
#include <iconv.h>
#include "cycript.hpp"
#include "sig/parse.hpp"
#include "sig/ffi_type.hpp"
#include "Pooling.hpp"
#include <sys/mman.h>
#include <iostream>
#include <ext/stdio_filebuf.h>
#include <set>
#include <map>
#include <iomanip>
#include <sstream>
#include <cmath>
#include "Parser.hpp"
#include "Cycript.tab.hh"
#include "Error.hpp"
#include "JavaScript.hpp"
#include "String.hpp"
#ifdef __OBJC__
#define CYCatch_ \
catch (NSException *error) { \
CYThrow(context, error, exception); \
return NULL; \
}
#else
#define CYCatch_
#endif
char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
if (const unsigned char *value = sqlite3_column_text(stmt, n))
return apr_pstrdup(pool, (const char *) value);
else return NULL;
}
struct CYHooks *hooks_;
/* JavaScript Properties {{{ */
JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
CYThrow(context, exception);
return value;
}
JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
CYThrow(context, exception);
return value;
}
void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
JSValueRef exception(NULL);
JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
CYThrow(context, exception);
}
void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
JSValueRef exception(NULL);
JSObjectSetProperty(context, object, name, value, attributes, &exception);
CYThrow(context, exception);
}
/* }}} */
/* JavaScript Strings {{{ */
JSStringRef CYCopyJSString(const char *value) {
return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
}
JSStringRef CYCopyJSString(JSStringRef value) {
return value == NULL ? NULL : JSStringRetain(value);
}
JSStringRef CYCopyJSString(CYUTF8String value) {
// XXX: this is very wrong
return CYCopyJSString(value.data);
}
JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
if (JSValueIsNull(context, value))
return NULL;
JSValueRef exception(NULL);
JSStringRef string(JSValueToStringCopy(context, value, &exception));
CYThrow(context, exception);
return string;
}
static CYUTF16String CYCastUTF16String(JSStringRef value) {
return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
}
template <typename Type_>
_finline size_t iconv_(size_t (*iconv)(iconv_t, Type_, size_t *, char **, size_t *), iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft) {
return iconv(cd, const_cast<Type_>(inbuf), inbytesleft, outbuf, outbytesleft);
}
CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
_assert(pool != NULL);
CYUTF16String utf16(CYCastUTF16String(value));
const char *in(reinterpret_cast<const char *>(utf16.data));
#ifdef __GLIBC__
iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2")));
#else
iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
#endif
size_t size(JSStringGetMaximumUTF8CStringSize(value));
char *out(new(pool) char[size]);
CYUTF8String utf8(out, size);
size = utf16.size * 2;
_syscall(iconv_(&iconv, conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
*out = '\0';
utf8.size = out - utf8.data;
_syscall(iconv_close(conversion));
return utf8;
}
const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
_assert(memchr(utf8.data, '\0', utf8.size) == NULL);
return utf8.data;
}
const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
}
/* }}} */
/* Index Offsets {{{ */
size_t CYGetIndex(const CYUTF8String &value) {
if (value.data[0] != '0') {
size_t index(0);
for (size_t i(0); i != value.size; ++i) {
if (!DigitRange_[value.data[i]])
return _not(size_t);
index *= 10;
index += value.data[i] - '0';
}
return index;
} else if (value.size == 1)
return 0;
else
return _not(size_t);
}
size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
return CYGetIndex(CYPoolUTF8String(pool, context, value));
}
// XXX: this isn't actually right
bool CYGetOffset(const char *value, ssize_t &index) {
if (value[0] != '0') {
char *end;
index = strtol(value, &end, 10);
if (value + strlen(value) == end)
return true;
} else if (value[1] == '\0') {
index = 0;
return true;
}
return false;
}
/* }}} */
/* JavaScript *ify {{{ */
void CYStringify(std::ostringstream &str, const char *data, size_t size) {
unsigned quot(0), apos(0);
for (const char *value(data), *end(data + size); value != end; ++value)
if (*value == '"')
++quot;
else if (*value == '\'')
++apos;
bool single(quot > apos);
str << (single ? '\'' : '"');
for (const char *value(data), *end(data + size); value != end; ++value)
switch (*value) {
case '\\': str << "\\\\"; break;
case '\b': str << "\\b"; break;
case '\f': str << "\\f"; break;
case '\n': str << "\\n"; break;
case '\r': str << "\\r"; break;
case '\t': str << "\\t"; break;
case '\v': str << "\\v"; break;
case '"':
if (!single)
str << "\\\"";
else goto simple;
break;
case '\'':
if (single)
str << "\\'";
else goto simple;
break;
default:
// this test is designed to be "awewsome", generating neither warnings nor incorrect results
if (*value < 0x20 || *value >= 0x7f)
str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(uint8_t(*value));
else simple:
str << *value;
}
str << (single ? '\'' : '"');
}
void CYNumerify(std::ostringstream &str, double value) {
char string[32];
// XXX: I want this to print 1e3 rather than 1000
sprintf(string, "%.17g", value);
str << string;
}
bool CYIsKey(CYUTF8String value) {
const char *data(value.data);
size_t size(value.size);
if (size == 0)
return false;
if (DigitRange_[data[0]]) {
size_t index(CYGetIndex(value));
if (index == _not(size_t))
return false;
} else {
if (!WordStartRange_[data[0]])
return false;
for (size_t i(1); i != size; ++i)
if (!WordEndRange_[data[i]])
return false;
}
return true;
}
/* }}} */
static JSGlobalContextRef Context_;
static JSObjectRef System_;
static JSClassRef Functor_;
static JSClassRef Pointer_;
static JSClassRef Runtime_;
static JSClassRef Struct_;
static JSStringRef Result_;
JSObjectRef Array_;
JSObjectRef Error_;
JSObjectRef Function_;
JSObjectRef String_;
JSStringRef length_;
JSStringRef message_;
JSStringRef name_;
JSStringRef prototype_;
JSStringRef toCYON_;
JSStringRef toJSON_;
JSObjectRef Object_prototype_;
JSObjectRef Function_prototype_;
JSObjectRef Array_prototype_;
JSObjectRef Array_pop_;
JSObjectRef Array_push_;
JSObjectRef Array_splice_;
sqlite3 *Bridge_;
void CYFinalize(JSObjectRef object) {
delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
}
struct CStringMapLess :
std::binary_function<const char *, const char *, bool>
{
_finline bool operator ()(const char *lhs, const char *rhs) const {
return strcmp(lhs, rhs) < 0;
}
};
void Structor_(apr_pool_t *pool, sig::Type *&type) {
if (
type->primitive == sig::pointer_P &&
type->data.data.type != NULL &&
type->data.data.type->primitive == sig::struct_P &&
strcmp(type->data.data.type->name, "_objc_class") == 0
) {
type->primitive = sig::typename_P;
type->data.data.type = NULL;
return;
}
if (type->primitive != sig::struct_P || type->name == NULL)
return;
sqlite3_stmt *statement;
_sqlcall(sqlite3_prepare(Bridge_,
"select "
"\"bridge\".\"mode\", "
"\"bridge\".\"value\" "
"from \"bridge\" "
"where"
" \"bridge\".\"mode\" in (3, 4) and"
" \"bridge\".\"name\" = ?"
" limit 1"
, -1, &statement, NULL));
_sqlcall(sqlite3_bind_text(statement, 1, type->name, -1, SQLITE_STATIC));
int mode;
const char *value;
if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
mode = -1;
value = NULL;
} else {
mode = sqlite3_column_int(statement, 0);
value = sqlite3_column_pooled(pool, statement, 1);
}
_sqlcall(sqlite3_finalize(statement));
switch (mode) {
default:
_assert(false);
case -1:
break;
case 3: {
sig::Parse(pool, &type->data.signature, value, &Structor_);
} break;
case 4: {
sig::Signature signature;
sig::Parse(pool, &signature, value, &Structor_);
type = signature.elements[0].type;
} break;
}
}
JSClassRef Type_privateData::Class_;
struct Pointer :
CYOwned
{
Type_privateData *type_;
Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
CYOwned(value, context, owner),
type_(new(pool_) Type_privateData(type))
{
}
};
struct Struct_privateData :
CYOwned
{
Type_privateData *type_;
Struct_privateData(JSContextRef context, JSObjectRef owner) :
CYOwned(NULL, context, owner)
{
}
};
typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
static TypeMap Types_;
JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
Struct_privateData *internal(new Struct_privateData(context, owner));
apr_pool_t *pool(internal->pool_);
Type_privateData *typical(new(pool) Type_privateData(type, ffi));
internal->type_ = typical;
if (owner != NULL)
internal->value_ = data;
else {
size_t size(typical->GetFFI()->size);
void *copy(apr_palloc(internal->pool_, size));
memcpy(copy, data, size);
internal->value_ = copy;
}
return JSObjectMake(context, Struct_, internal);
}
JSValueRef CYCastJSValue(JSContextRef context, bool value) {
return JSValueMakeBoolean(context, value);
}
JSValueRef CYCastJSValue(JSContextRef context, double value) {
return JSValueMakeNumber(context, value);
}
#define CYCastJSValue_(Type_) \
JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
return JSValueMakeNumber(context, static_cast<double>(value)); \
}
CYCastJSValue_(int)
CYCastJSValue_(unsigned int)
CYCastJSValue_(long int)
CYCastJSValue_(long unsigned int)
CYCastJSValue_(long long int)
CYCastJSValue_(long long unsigned int)
JSValueRef CYJSUndefined(JSContextRef context) {
return JSValueMakeUndefined(context);
}
double CYCastDouble(const char *value, size_t size) {
char *end;
double number(strtod(value, &end));
if (end != value + size)
return NAN;
return number;
}
double CYCastDouble(const char *value) {
return CYCastDouble(value, strlen(value));
}
double CYCastDouble(JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
double number(JSValueToNumber(context, value, &exception));
CYThrow(context, exception);
return number;
}
bool CYCastBool(JSContextRef context, JSValueRef value) {
return JSValueToBoolean(context, value);
}
JSValueRef CYJSNull(JSContextRef context) {
return JSValueMakeNull(context);
}
JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
}
JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
return CYCastJSValue(context, CYJSString(value));
}
JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
JSObjectRef object(JSValueToObject(context, value, &exception));
CYThrow(context, exception);
return object;
}
JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
CYThrow(context, exception);
return value;
}
bool CYIsCallable(JSContextRef context, JSValueRef value) {
return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
}
static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count == 0)
printf("\n");
else {
CYPool pool;
printf("%s\n", CYPoolCString(pool, context, arguments[0]));
}
return CYJSUndefined(context);
} CYCatch }
static size_t Nonce_(0);
static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
CYPool pool;
const char *name(apr_psprintf(pool, "%s%"APR_SIZE_T_FMT"", CYPoolCString(pool, context, arguments[0]), Nonce_++));
return CYCastJSValue(context, name);
}
static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
JSGarbageCollect(context);
return CYJSUndefined(context);
}
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
switch (JSType type = JSValueGetType(context, value)) {
case kJSTypeUndefined:
return "undefined";
case kJSTypeNull:
return "null";
case kJSTypeBoolean:
return CYCastBool(context, value) ? "true" : "false";
case kJSTypeNumber: {
std::ostringstream str;
CYNumerify(str, CYCastDouble(context, value));
std::string value(str.str());
return apr_pstrmemdup(pool, value.c_str(), value.size());
} break;
case kJSTypeString: {
std::ostringstream str;
CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
CYStringify(str, string.data, string.size);
std::string value(str.str());
return apr_pstrmemdup(pool, value.c_str(), value.size());
} break;
case kJSTypeObject:
return CYPoolCCYON(pool, context, (JSObjectRef) value);
default:
throw CYJSError(context, "JSValueGetType() == 0x%x", type);
}
} CYCatch }
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
const char *cyon(CYPoolCCYON(pool, context, value, &exception));
CYThrow(context, exception);
return cyon;
}
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
if (CYIsCallable(context, toCYON)) {
JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
return CYPoolCString(pool, context, value);
}
JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
if (CYIsCallable(context, toJSON)) {
JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
JSValueRef exception(NULL);
const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
CYThrow(context, exception);
return cyon;
}
std::ostringstream str;
str << '{';
// XXX: this is, sadly, going to leak
JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
bool comma(false);
for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
JSValueRef value(CYGetProperty(context, object, name));
if (comma)
str << ',';
else
comma = true;
CYUTF8String string(CYPoolUTF8String(pool, context, name));
if (CYIsKey(string))
str << string.data;
else
CYStringify(str, string.data, string.size);
str << ':' << CYPoolCCYON(pool, context, value);
}
str << '}';
JSPropertyNameArrayRelease(names);
std::string string(str.str());
return apr_pstrmemdup(pool, string.c_str(), string.size());
}
static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYPool pool;
std::ostringstream str;
str << '[';
JSValueRef length(CYGetProperty(context, _this, length_));
bool comma(false);
for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
JSValueRef value(CYGetProperty(context, _this, index));
if (comma)
str << ',';
else
comma = true;
if (!JSValueIsUndefined(context, value))
str << CYPoolCCYON(pool, context, value);
else {
str << ',';
comma = false;
}
}
str << ']';
std::string value(str.str());
return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
} CYCatch }
JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
Pointer *internal(new Pointer(pointer, context, owner, type));
return JSObjectMake(context, Pointer_, internal);
}
static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
cy::Functor *internal(new cy::Functor(type, function));
return JSObjectMake(context, Functor_, internal);
}
static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
return CYGetOffset(CYPoolCString(pool, context, value), index);
}
void *CYCastPointer_(JSContextRef context, JSValueRef value) {
switch (JSValueGetType(context, value)) {
case kJSTypeNull:
return NULL;
/*case kJSTypeObject:
if (JSValueIsObjectOfClass(context, value, Pointer_)) {
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
return internal->value_;
}*/
default:
double number(CYCastDouble(context, value));
if (std::isnan(number))
throw CYJSError(context, "cannot convert value to pointer");
return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
}
}
void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
switch (type->primitive) {
case sig::boolean_P:
*reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
break;
#define CYPoolFFI_(primitive, native) \
case sig::primitive ## _P: \
*reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
break;
CYPoolFFI_(uchar, unsigned char)
CYPoolFFI_(char, char)
CYPoolFFI_(ushort, unsigned short)
CYPoolFFI_(short, short)
CYPoolFFI_(ulong, unsigned long)
CYPoolFFI_(long, long)
CYPoolFFI_(uint, unsigned int)
CYPoolFFI_(int, int)
CYPoolFFI_(ulonglong, unsigned long long)
CYPoolFFI_(longlong, long long)
CYPoolFFI_(float, float)
CYPoolFFI_(double, double)
case sig::pointer_P:
*reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
break;
case sig::string_P:
*reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
break;
case sig::struct_P: {
uint8_t *base(reinterpret_cast<uint8_t *>(data));
JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
for (size_t index(0); index != type->data.signature.count; ++index) {
sig::Element *element(&type->data.signature.elements[index]);
ffi_type *field(ffi->elements[index]);
JSValueRef rhs;
if (aggregate == NULL)
rhs = value;
else {
rhs = CYGetProperty(context, aggregate, index);
if (JSValueIsUndefined(context, rhs)) {
if (element->name != NULL)
rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
else
goto undefined;
if (JSValueIsUndefined(context, rhs)) undefined:
throw CYJSError(context, "unable to extract structure value");
}
}
CYPoolFFI(pool, context, element->type, field, base, rhs);
// XXX: alignment?
base += field->size;
}
} break;
case sig::void_P:
break;
default:
if (hooks_ != NULL && hooks_->PoolFFI != NULL)
if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
return;
fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
_assert(false);
}
}
JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
switch (type->primitive) {
case sig::boolean_P:
return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
#define CYFromFFI_(primitive, native) \
case sig::primitive ## _P: \
return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
CYFromFFI_(uchar, unsigned char)
CYFromFFI_(char, char)
CYFromFFI_(ushort, unsigned short)
CYFromFFI_(short, short)
CYFromFFI_(ulong, unsigned long)
CYFromFFI_(long, long)
CYFromFFI_(uint, unsigned int)
CYFromFFI_(int, int)
CYFromFFI_(ulonglong, unsigned long long)
CYFromFFI_(longlong, long long)
CYFromFFI_(float, float)
CYFromFFI_(double, double)
case sig::pointer_P:
if (void *pointer = *reinterpret_cast<void **>(data))
return CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
else goto null;
case sig::string_P:
if (char *utf8 = *reinterpret_cast<char **>(data))
return CYCastJSValue(context, utf8);
else goto null;
case sig::struct_P:
return CYMakeStruct(context, data, type, ffi, owner);
case sig::void_P:
return CYJSUndefined(context);
null:
return CYJSNull(context);
default:
if (hooks_ != NULL && hooks_->FromFFI != NULL)
if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
return value;
CYThrow("failed conversion from FFI format: '%c'\n", type->primitive);
}
}
static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
JSContextRef context(internal->context_);
size_t count(internal->cif_.nargs);
JSValueRef values[count];
for (size_t index(0); index != count; ++index)
values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
}
Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
// XXX: in case of exceptions this will leak
// XXX: in point of fact, this may /need/ to leak :(
Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
ffi_closure *closure((ffi_closure *) _syscall(mmap(
NULL, sizeof(ffi_closure),
PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
-1, 0
)));
ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
_assert(status == FFI_OK);
_syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
internal->value_ = closure;
return internal;
}
static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
return JSObjectMake(context, Functor_, internal);
}
static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
JSValueRef exception(NULL);
bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
CYThrow(context, exception);
if (function) {
JSObjectRef function(CYCastJSObject(context, value));
return CYMakeFunctor(context, function, type);
} else {
void (*function)()(CYCastPointer<void (*)()>(context, value));
return CYMakeFunctor(context, function, type);
}
}
static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
Type_privateData *typical(internal->type_);
sig::Type *type(typical->type_);
if (type == NULL)
return false;
const char *name(CYPoolCString(pool, context, property));
size_t length(strlen(name));
double number(CYCastDouble(name, length));
size_t count(type->data.signature.count);
if (std::isnan(number)) {
if (property == NULL)
return false;
sig::Element *elements(type->data.signature.elements);
for (size_t local(0); local != count; ++local) {
sig::Element *element(&elements[local]);
if (element->name != NULL && strcmp(name, element->name) == 0) {
index = local;
goto base;
}
}
return false;
} else {
index = static_cast<ssize_t>(number);
if (index != number || index < 0 || static_cast<size_t>(index) >= count)
return false;
}
base:
ffi_type **elements(typical->GetFFI()->elements);
base = reinterpret_cast<uint8_t *>(internal->value_);
for (ssize_t local(0); local != index; ++local)
base += elements[local]->size;
return true;
}
static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) { CYTry {
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ffi_type *ffi(typical->GetFFI());
uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
base += ffi->size * index;
JSObjectRef owner(internal->GetOwner() ?: object);
return CYFromFFI(context, typical->type_, ffi, base, false, owner);
} CYCatch }
static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
CYPool pool;
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
if (typical->type_ == NULL)
return NULL;
ssize_t offset;
if (!CYGetOffset(pool, context, property, offset))
return NULL;
return Pointer_getIndex(context, object, offset, exception);
}
static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
return Pointer_getIndex(context, object, 0, exception);
}
static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) { CYTry {
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ffi_type *ffi(typical->GetFFI());
uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
base += ffi->size * index;
CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
return true;
} CYCatch }
static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
CYPool pool;
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
if (typical->type_ == NULL)
return NULL;
ssize_t offset;
if (!CYGetOffset(pool, context, property, offset))
return NULL;
return Pointer_setIndex(context, object, offset, value, exception);
}
static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
return Pointer_setIndex(context, object, 0, value, exception);
}
static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
Type_privateData *typical(internal->type_);
return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
}
static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
CYPool pool;
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ssize_t index;
uint8_t *base;
if (!Index_(pool, context, internal, property, index, base))
return NULL;
JSObjectRef owner(internal->GetOwner() ?: object);
return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
} CYCatch }
static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
CYPool pool;
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ssize_t index;
uint8_t *base;
if (!Index_(pool, context, internal, property, index, base))
return false;
CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
return true;
} CYCatch }
static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
sig::Type *type(typical->type_);
if (type == NULL)
return;
size_t count(type->data.signature.count);
sig::Element *elements(type->data.signature.elements);
char number[32];
for (size_t index(0); index != count; ++index) {
const char *name;
name = elements[index].name;
if (name == NULL) {
sprintf(number, "%zu", index);
name = number;
}
JSPropertyNameAccumulatorAddName(names, CYJSString(name));
}
}
JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { CYTry {
if (setups + count != signature->count - 1)
throw CYJSError(context, "incorrect number of arguments to ffi function");
size_t size(setups + count);
void *values[size];
memcpy(values, setup, sizeof(void *) * setups);
for (size_t index(setups); index != size; ++index) {
sig::Element *element(&signature->elements[index + 1]);
ffi_type *ffi(cif->arg_types[index]);
// XXX: alignment?
values[index] = new(pool) uint8_t[ffi->size];
CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
}
uint8_t value[cif->rtype->size];
if (hooks_ != NULL && hooks_->CallFunction != NULL)
(*hooks_->CallFunction)(context, cif, function, value, values);
else
ffi_call(cif, function, value, values);
return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
} CYCatch }
static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
CYPool pool;
cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
}
static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
Type_privateData *internal(new Type_privateData(type));
return JSObjectMake(context, Type_privateData::Class_, internal);
}
static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
Type_privateData *internal(new Type_privateData(type));
return JSObjectMake(context, Type_privateData::Class_, internal);
}
static void *CYCastSymbol(const char *name) {
return dlsym(RTLD_DEFAULT, name);
}
static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
CYPool pool;
CYUTF8String name(CYPoolUTF8String(pool, context, property));
if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
return value;
sqlite3_stmt *statement;
_sqlcall(sqlite3_prepare(Bridge_,
"select "
"\"bridge\".\"mode\", "
"\"bridge\".\"value\" "
"from \"bridge\" "
"where"
" \"bridge\".\"name\" = ?"
" limit 1"
, -1, &statement, NULL));
_sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
int mode;
const char *value;
if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
mode = -1;
value = NULL;
} else {
mode = sqlite3_column_int(statement, 0);
value = sqlite3_column_pooled(pool, statement, 1);
}
_sqlcall(sqlite3_finalize(statement));
switch (mode) {
default:
_assert(false);
case -1:
return NULL;
case 0:
return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
case 1:
if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
return CYMakeFunctor(context, symbol, value);
else return NULL;
case 2:
if (void *symbol = CYCastSymbol(name.data)) {
// XXX: this is horrendously inefficient
sig::Signature signature;
sig::Parse(pool, &signature, value, &Structor_);
ffi_cif cif;
sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
} else return NULL;
// XXX: implement case 3
case 4:
return CYMakeType(context, value);
}
} CYCatch }
static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 2)
throw CYJSError(context, "incorrect number of arguments to Functor constructor");
CYPool pool;
void *value(CYCastPointer<void *>(context, arguments[0]));
const char *type(CYPoolCString(pool, context, arguments[1]));
sig::Signature signature;
sig::Parse(pool, &signature, type, &Structor_);
return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
} CYCatch }
static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 1)
throw CYJSError(context, "incorrect number of arguments to Type constructor");
CYPool pool;
const char *type(CYPoolCString(pool, context, arguments[0]));
return CYMakeType(context, type);
} CYCatch }
static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
sig::Type type;
if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
type.primitive = sig::pointer_P;
type.data.data.size = 0;
} else {
CYPool pool;
size_t index(CYGetIndex(pool, context, property));
if (index == _not(size_t))
return NULL;
type.primitive = sig::array_P;
type.data.data.size = index;
}
type.name = NULL;
type.flags = 0;
type.data.data.type = internal->type_;
return CYMakeType(context, &type);
} CYCatch }
static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
if (count != 1)
throw CYJSError(context, "incorrect number of arguments to type cast function");
sig::Type *type(internal->type_);
ffi_type *ffi(internal->GetFFI());
// XXX: alignment?
uint8_t value[ffi->size];
CYPool pool;
CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
return CYFromFFI(context, type, ffi, value);
} CYCatch }
static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 0)
throw CYJSError(context, "incorrect number of arguments to type cast function");
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
sig::Type *type(internal->type_);
size_t size;
if (type->primitive != sig::array_P)
size = 0;
else {
size = type->data.data.size;
type = type->data.data.type;
}
void *value(malloc(internal->GetFFI()->size));
return CYMakePointer(context, value, type, NULL, NULL);
} CYCatch }
static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 2)
throw CYJSError(context, "incorrect number of arguments to Functor constructor");
CYPool pool;
const char *type(CYPoolCString(pool, context, arguments[1]));
return CYMakeFunctor(context, arguments[0], type);
} CYCatch }
static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
} CYCatch }
static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
}
static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
char string[32];
sprintf(string, "%p", internal->value_);
return CYCastJSValue(context, string);
} CYCatch }
static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
CYPool pool;
const char *type(sig::Unparse(pool, internal->type_));
return CYCastJSValue(context, CYJSString(type));
} CYCatch }
static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
CYPool pool;
const char *type(sig::Unparse(pool, internal->type_));
size_t size(strlen(type));
char *cyon(new(pool) char[12 + size + 1]);
memcpy(cyon, "new Type(\"", 10);
cyon[12 + size] = '\0';
cyon[12 + size - 2] = '"';
cyon[12 + size - 1] = ')';
memcpy(cyon + 10, type, size);
return CYCastJSValue(context, CYJSString(cyon));
} CYCatch }
static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
}
static JSStaticValue Pointer_staticValues[2] = {
{"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, NULL, 0}
};
static JSStaticFunction Pointer_staticFunctions[4] = {
{"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSStaticFunction Struct_staticFunctions[2] = {
{"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSStaticFunction Functor_staticFunctions[4] = {
{"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
namespace cy {
JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
}
static JSStaticFunction Type_staticFunctions[4] = {
{"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
void CYSetArgs(int argc, const char *argv[]) {
JSContextRef context(CYGetJSContext());
JSValueRef args[argc];
for (int i(0); i != argc; ++i)
args[i] = CYCastJSValue(context, argv[i]);
JSObjectRef array;
if (JSObjectMakeArray$ != NULL) {
JSValueRef exception(NULL);
array = (*JSObjectMakeArray$)(context, argc, args, &exception);
CYThrow(context, exception);
} else {
JSValueRef value(CYCallAsFunction(context, Array_, NULL, argc, args));
array = CYCastJSObject(context, value);
}
CYSetProperty(context, System_, CYJSString("args"), array);
}
JSObjectRef CYGetGlobalObject(JSContextRef context) {
return JSContextGetGlobalObject(context);
}
const char *CYExecute(apr_pool_t *pool, const char *code) {
JSContextRef context(CYGetJSContext());
JSValueRef exception(NULL), result;
void *handle;
if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
handle = (*hooks_->ExecuteStart)(context);
else
handle = NULL;
const char *json;
try {
result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
} catch (const char *error) {
return error;
}
if (exception != NULL) { error:
result = exception;
exception = NULL;
}
if (JSValueIsUndefined(context, result))
return NULL;
try {
json = CYPoolCCYON(pool, context, result, &exception);
} catch (const char *error) {
return error;
}
if (exception != NULL)
goto error;
CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
(*hooks_->ExecuteEnd)(context, handle);
return json;
}
static apr_pool_t *Pool_;
static bool initialized_;
void CYInitialize() {
if (!initialized_)
initialized_ = true;
else return;
_aprcall(apr_initialize());
_aprcall(apr_pool_create(&Pool_, NULL));
_sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
}
apr_pool_t *CYGetGlobalPool() {
CYInitialize();
return Pool_;
}
void CYThrow(JSContextRef context, JSValueRef value) {
if (value != NULL)
throw CYJSError(context, value);
}
const char *CYJSError::PoolCString(apr_pool_t *pool) const {
return CYPoolCString(pool, context_, value_);
}
JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
// XXX: what if the context is different?
return value_;
}
void CYThrow(const char *format, ...) {
va_list args;
va_start (args, format);
throw CYPoolError(format, args);
// XXX: does this matter? :(
va_end (args);
}
const char *CYPoolError::PoolCString(apr_pool_t *pool) const {
return apr_pstrdup(pool, message_);
}
CYPoolError::CYPoolError(const char *format, ...) {
va_list args;
va_start (args, format);
message_ = apr_pvsprintf(pool_, format, args);
va_end (args);
}
CYPoolError::CYPoolError(const char *format, va_list args) {
message_ = apr_pvsprintf(pool_, format, args);
}
JSValueRef CYCastJSError(JSContextRef context, const char *message) {
JSValueRef arguments[1] = {CYCastJSValue(context, message)};
JSValueRef exception(NULL);
JSValueRef value(JSObjectCallAsConstructor(context, Error_, 1, arguments, &exception));
CYThrow(context, exception);
return value;
}
JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
return CYCastJSError(context, message_);
}
CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
if (context == NULL)
context = CYGetJSContext();
CYPool pool;
va_list args;
va_start (args, format);
const char *message(apr_pvsprintf(pool, format, args));
va_end (args);
value_ = CYCastJSError(context, message);
}
JSGlobalContextRef CYGetJSContext() {
CYInitialize();
if (Context_ == NULL) {
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = "Functor";
definition.staticFunctions = cy::Functor::StaticFunctions;
definition.callAsFunction = &Functor_callAsFunction;
definition.finalize = &CYFinalize;
Functor_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Pointer";
definition.staticValues = Pointer_staticValues;
definition.staticFunctions = Pointer_staticFunctions;
definition.getProperty = &Pointer_getProperty;
definition.setProperty = &Pointer_setProperty;
definition.finalize = &CYFinalize;
Pointer_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Struct";
definition.staticFunctions = Struct_staticFunctions;
definition.getProperty = &Struct_getProperty;
definition.setProperty = &Struct_setProperty;
definition.getPropertyNames = &Struct_getPropertyNames;
definition.finalize = &CYFinalize;
Struct_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Type";
definition.staticFunctions = Type_staticFunctions;
definition.getProperty = &Type_getProperty;
definition.callAsFunction = &Type_callAsFunction;
definition.callAsConstructor = &Type_callAsConstructor;
definition.finalize = &CYFinalize;
Type_privateData::Class_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Runtime";
definition.getProperty = &Runtime_getProperty;
Runtime_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
//definition.getProperty = &Global_getProperty;
JSClassRef Global(JSClassCreate(&definition));
JSGlobalContextRef context(JSGlobalContextCreate(Global));
Context_ = context;
JSObjectRef global(CYGetGlobalObject(context));
JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
JSValueProtect(context, Array_);
Error_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error")));
JSValueProtect(context, Error_);
Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
JSValueProtect(context, Function_);
String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
JSValueProtect(context, String_);
length_ = JSStringCreateWithUTF8CString("length");
message_ = JSStringCreateWithUTF8CString("message");
name_ = JSStringCreateWithUTF8CString("name");
prototype_ = JSStringCreateWithUTF8CString("prototype");
toCYON_ = JSStringCreateWithUTF8CString("toCYON");
toJSON_ = JSStringCreateWithUTF8CString("toJSON");
JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
JSValueProtect(context, Object_prototype_);
Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
JSValueProtect(context, Array_prototype_);
JSValueProtect(context, Array_pop_);
JSValueProtect(context, Array_push_);
JSValueProtect(context, Array_splice_);
JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
Function_prototype_ = (JSObjectRef) CYGetProperty(context, Function_, prototype_);
JSValueProtect(context, Function_prototype_);
JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), Function_prototype_);
CYSetProperty(context, global, CYJSString("Functor"), Functor);
CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
CYSetProperty(context, global, CYJSString("Cycript"), cycript);
CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
System_ = JSObjectMake(context, NULL, NULL);
JSValueProtect(context, System_);
CYSetProperty(context, global, CYJSString("system"), System_);
CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
//CYSetProperty(context, System_, CYJSString("global"), global);
CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
Result_ = JSStringCreateWithUTF8CString("_");
if (hooks_ != NULL && hooks_->SetupContext != NULL)
(*hooks_->SetupContext)(context);
}
return Context_;
}
Setup Pointer to emulate an Array.
/* Cycript - Inlining/Optimizing JavaScript Compiler
* Copyright (C) 2009 Jay Freeman (saurik)
*/
/* Modified BSD License {{{ */
/*
* Redistribution and use in source and binary
* forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse
* or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sqlite3.h>
#include "Internal.hpp"
#include <dlfcn.h>
#include <iconv.h>
#include "cycript.hpp"
#include "sig/parse.hpp"
#include "sig/ffi_type.hpp"
#include "Pooling.hpp"
#include <sys/mman.h>
#include <iostream>
#include <ext/stdio_filebuf.h>
#include <set>
#include <map>
#include <iomanip>
#include <sstream>
#include <cmath>
#include "Parser.hpp"
#include "Cycript.tab.hh"
#include "Error.hpp"
#include "JavaScript.hpp"
#include "String.hpp"
#ifdef __OBJC__
#define CYCatch_ \
catch (NSException *error) { \
CYThrow(context, error, exception); \
return NULL; \
}
#else
#define CYCatch_
#endif
char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
if (const unsigned char *value = sqlite3_column_text(stmt, n))
return apr_pstrdup(pool, (const char *) value);
else return NULL;
}
struct CYHooks *hooks_;
/* JavaScript Properties {{{ */
JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
CYThrow(context, exception);
return value;
}
JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
CYThrow(context, exception);
return value;
}
void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
JSValueRef exception(NULL);
JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
CYThrow(context, exception);
}
void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
JSValueRef exception(NULL);
JSObjectSetProperty(context, object, name, value, attributes, &exception);
CYThrow(context, exception);
}
/* }}} */
/* JavaScript Strings {{{ */
JSStringRef CYCopyJSString(const char *value) {
return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
}
JSStringRef CYCopyJSString(JSStringRef value) {
return value == NULL ? NULL : JSStringRetain(value);
}
JSStringRef CYCopyJSString(CYUTF8String value) {
// XXX: this is very wrong
return CYCopyJSString(value.data);
}
JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
if (JSValueIsNull(context, value))
return NULL;
JSValueRef exception(NULL);
JSStringRef string(JSValueToStringCopy(context, value, &exception));
CYThrow(context, exception);
return string;
}
static CYUTF16String CYCastUTF16String(JSStringRef value) {
return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
}
template <typename Type_>
_finline size_t iconv_(size_t (*iconv)(iconv_t, Type_, size_t *, char **, size_t *), iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft) {
return iconv(cd, const_cast<Type_>(inbuf), inbytesleft, outbuf, outbytesleft);
}
CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
_assert(pool != NULL);
CYUTF16String utf16(CYCastUTF16String(value));
const char *in(reinterpret_cast<const char *>(utf16.data));
#ifdef __GLIBC__
iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2")));
#else
iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
#endif
size_t size(JSStringGetMaximumUTF8CStringSize(value));
char *out(new(pool) char[size]);
CYUTF8String utf8(out, size);
size = utf16.size * 2;
_syscall(iconv_(&iconv, conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
*out = '\0';
utf8.size = out - utf8.data;
_syscall(iconv_close(conversion));
return utf8;
}
const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
_assert(memchr(utf8.data, '\0', utf8.size) == NULL);
return utf8.data;
}
const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
}
/* }}} */
/* Index Offsets {{{ */
size_t CYGetIndex(const CYUTF8String &value) {
if (value.data[0] != '0') {
size_t index(0);
for (size_t i(0); i != value.size; ++i) {
if (!DigitRange_[value.data[i]])
return _not(size_t);
index *= 10;
index += value.data[i] - '0';
}
return index;
} else if (value.size == 1)
return 0;
else
return _not(size_t);
}
size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
return CYGetIndex(CYPoolUTF8String(pool, context, value));
}
// XXX: this isn't actually right
bool CYGetOffset(const char *value, ssize_t &index) {
if (value[0] != '0') {
char *end;
index = strtol(value, &end, 10);
if (value + strlen(value) == end)
return true;
} else if (value[1] == '\0') {
index = 0;
return true;
}
return false;
}
/* }}} */
/* JavaScript *ify {{{ */
void CYStringify(std::ostringstream &str, const char *data, size_t size) {
unsigned quot(0), apos(0);
for (const char *value(data), *end(data + size); value != end; ++value)
if (*value == '"')
++quot;
else if (*value == '\'')
++apos;
bool single(quot > apos);
str << (single ? '\'' : '"');
for (const char *value(data), *end(data + size); value != end; ++value)
switch (*value) {
case '\\': str << "\\\\"; break;
case '\b': str << "\\b"; break;
case '\f': str << "\\f"; break;
case '\n': str << "\\n"; break;
case '\r': str << "\\r"; break;
case '\t': str << "\\t"; break;
case '\v': str << "\\v"; break;
case '"':
if (!single)
str << "\\\"";
else goto simple;
break;
case '\'':
if (single)
str << "\\'";
else goto simple;
break;
default:
// this test is designed to be "awewsome", generating neither warnings nor incorrect results
if (*value < 0x20 || *value >= 0x7f)
str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(uint8_t(*value));
else simple:
str << *value;
}
str << (single ? '\'' : '"');
}
void CYNumerify(std::ostringstream &str, double value) {
char string[32];
// XXX: I want this to print 1e3 rather than 1000
sprintf(string, "%.17g", value);
str << string;
}
bool CYIsKey(CYUTF8String value) {
const char *data(value.data);
size_t size(value.size);
if (size == 0)
return false;
if (DigitRange_[data[0]]) {
size_t index(CYGetIndex(value));
if (index == _not(size_t))
return false;
} else {
if (!WordStartRange_[data[0]])
return false;
for (size_t i(1); i != size; ++i)
if (!WordEndRange_[data[i]])
return false;
}
return true;
}
/* }}} */
static JSGlobalContextRef Context_;
static JSObjectRef System_;
static JSClassRef Functor_;
static JSClassRef Pointer_;
static JSClassRef Runtime_;
static JSClassRef Struct_;
static JSStringRef Result_;
JSObjectRef Array_;
JSObjectRef Error_;
JSObjectRef Function_;
JSObjectRef String_;
JSStringRef length_;
JSStringRef message_;
JSStringRef name_;
JSStringRef prototype_;
JSStringRef toCYON_;
JSStringRef toJSON_;
JSObjectRef Object_prototype_;
JSObjectRef Function_prototype_;
JSObjectRef Array_prototype_;
JSObjectRef Array_pop_;
JSObjectRef Array_push_;
JSObjectRef Array_splice_;
sqlite3 *Bridge_;
void CYFinalize(JSObjectRef object) {
delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
}
struct CStringMapLess :
std::binary_function<const char *, const char *, bool>
{
_finline bool operator ()(const char *lhs, const char *rhs) const {
return strcmp(lhs, rhs) < 0;
}
};
void Structor_(apr_pool_t *pool, sig::Type *&type) {
if (
type->primitive == sig::pointer_P &&
type->data.data.type != NULL &&
type->data.data.type->primitive == sig::struct_P &&
strcmp(type->data.data.type->name, "_objc_class") == 0
) {
type->primitive = sig::typename_P;
type->data.data.type = NULL;
return;
}
if (type->primitive != sig::struct_P || type->name == NULL)
return;
sqlite3_stmt *statement;
_sqlcall(sqlite3_prepare(Bridge_,
"select "
"\"bridge\".\"mode\", "
"\"bridge\".\"value\" "
"from \"bridge\" "
"where"
" \"bridge\".\"mode\" in (3, 4) and"
" \"bridge\".\"name\" = ?"
" limit 1"
, -1, &statement, NULL));
_sqlcall(sqlite3_bind_text(statement, 1, type->name, -1, SQLITE_STATIC));
int mode;
const char *value;
if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
mode = -1;
value = NULL;
} else {
mode = sqlite3_column_int(statement, 0);
value = sqlite3_column_pooled(pool, statement, 1);
}
_sqlcall(sqlite3_finalize(statement));
switch (mode) {
default:
_assert(false);
case -1:
break;
case 3: {
sig::Parse(pool, &type->data.signature, value, &Structor_);
} break;
case 4: {
sig::Signature signature;
sig::Parse(pool, &signature, value, &Structor_);
type = signature.elements[0].type;
} break;
}
}
JSClassRef Type_privateData::Class_;
struct Pointer :
CYOwned
{
Type_privateData *type_;
size_t length_;
Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type, size_t length = _not(size_t)) :
CYOwned(value, context, owner),
type_(new(pool_) Type_privateData(type)),
length_(length)
{
}
};
struct Struct_privateData :
CYOwned
{
Type_privateData *type_;
Struct_privateData(JSContextRef context, JSObjectRef owner) :
CYOwned(NULL, context, owner)
{
}
};
typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
static TypeMap Types_;
JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
Struct_privateData *internal(new Struct_privateData(context, owner));
apr_pool_t *pool(internal->pool_);
Type_privateData *typical(new(pool) Type_privateData(type, ffi));
internal->type_ = typical;
if (owner != NULL)
internal->value_ = data;
else {
size_t size(typical->GetFFI()->size);
void *copy(apr_palloc(internal->pool_, size));
memcpy(copy, data, size);
internal->value_ = copy;
}
return JSObjectMake(context, Struct_, internal);
}
JSValueRef CYCastJSValue(JSContextRef context, bool value) {
return JSValueMakeBoolean(context, value);
}
JSValueRef CYCastJSValue(JSContextRef context, double value) {
return JSValueMakeNumber(context, value);
}
#define CYCastJSValue_(Type_) \
JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
return JSValueMakeNumber(context, static_cast<double>(value)); \
}
CYCastJSValue_(int)
CYCastJSValue_(unsigned int)
CYCastJSValue_(long int)
CYCastJSValue_(long unsigned int)
CYCastJSValue_(long long int)
CYCastJSValue_(long long unsigned int)
JSValueRef CYJSUndefined(JSContextRef context) {
return JSValueMakeUndefined(context);
}
double CYCastDouble(const char *value, size_t size) {
char *end;
double number(strtod(value, &end));
if (end != value + size)
return NAN;
return number;
}
double CYCastDouble(const char *value) {
return CYCastDouble(value, strlen(value));
}
double CYCastDouble(JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
double number(JSValueToNumber(context, value, &exception));
CYThrow(context, exception);
return number;
}
bool CYCastBool(JSContextRef context, JSValueRef value) {
return JSValueToBoolean(context, value);
}
JSValueRef CYJSNull(JSContextRef context) {
return JSValueMakeNull(context);
}
JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
}
JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
return CYCastJSValue(context, CYJSString(value));
}
JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
JSObjectRef object(JSValueToObject(context, value, &exception));
CYThrow(context, exception);
return object;
}
JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
JSValueRef exception(NULL);
JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
CYThrow(context, exception);
return value;
}
bool CYIsCallable(JSContextRef context, JSValueRef value) {
return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
}
static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count == 0)
printf("\n");
else {
CYPool pool;
printf("%s\n", CYPoolCString(pool, context, arguments[0]));
}
return CYJSUndefined(context);
} CYCatch }
static size_t Nonce_(0);
static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
CYPool pool;
const char *name(apr_psprintf(pool, "%s%"APR_SIZE_T_FMT"", CYPoolCString(pool, context, arguments[0]), Nonce_++));
return CYCastJSValue(context, name);
}
static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
JSGarbageCollect(context);
return CYJSUndefined(context);
}
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
switch (JSType type = JSValueGetType(context, value)) {
case kJSTypeUndefined:
return "undefined";
case kJSTypeNull:
return "null";
case kJSTypeBoolean:
return CYCastBool(context, value) ? "true" : "false";
case kJSTypeNumber: {
std::ostringstream str;
CYNumerify(str, CYCastDouble(context, value));
std::string value(str.str());
return apr_pstrmemdup(pool, value.c_str(), value.size());
} break;
case kJSTypeString: {
std::ostringstream str;
CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
CYStringify(str, string.data, string.size);
std::string value(str.str());
return apr_pstrmemdup(pool, value.c_str(), value.size());
} break;
case kJSTypeObject:
return CYPoolCCYON(pool, context, (JSObjectRef) value);
default:
throw CYJSError(context, "JSValueGetType() == 0x%x", type);
}
} CYCatch }
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
JSValueRef exception(NULL);
const char *cyon(CYPoolCCYON(pool, context, value, &exception));
CYThrow(context, exception);
return cyon;
}
const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
if (CYIsCallable(context, toCYON)) {
JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
return CYPoolCString(pool, context, value);
}
JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
if (CYIsCallable(context, toJSON)) {
JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
JSValueRef exception(NULL);
const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
CYThrow(context, exception);
return cyon;
}
std::ostringstream str;
str << '{';
// XXX: this is, sadly, going to leak
JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
bool comma(false);
for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
JSValueRef value(CYGetProperty(context, object, name));
if (comma)
str << ',';
else
comma = true;
CYUTF8String string(CYPoolUTF8String(pool, context, name));
if (CYIsKey(string))
str << string.data;
else
CYStringify(str, string.data, string.size);
str << ':' << CYPoolCCYON(pool, context, value);
}
str << '}';
JSPropertyNameArrayRelease(names);
std::string string(str.str());
return apr_pstrmemdup(pool, string.c_str(), string.size());
}
static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYPool pool;
std::ostringstream str;
str << '[';
JSValueRef length(CYGetProperty(context, _this, length_));
bool comma(false);
for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
JSValueRef value(CYGetProperty(context, _this, index));
if (comma)
str << ',';
else
comma = true;
if (!JSValueIsUndefined(context, value))
str << CYPoolCCYON(pool, context, value);
else {
str << ',';
comma = false;
}
}
str << ']';
std::string value(str.str());
return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
} CYCatch }
JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
Pointer *internal(new Pointer(pointer, context, owner, type));
return JSObjectMake(context, Pointer_, internal);
}
static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
cy::Functor *internal(new cy::Functor(type, function));
return JSObjectMake(context, Functor_, internal);
}
static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
return CYGetOffset(CYPoolCString(pool, context, value), index);
}
void *CYCastPointer_(JSContextRef context, JSValueRef value) {
switch (JSValueGetType(context, value)) {
case kJSTypeNull:
return NULL;
/*case kJSTypeObject:
if (JSValueIsObjectOfClass(context, value, Pointer_)) {
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
return internal->value_;
}*/
default:
double number(CYCastDouble(context, value));
if (std::isnan(number))
throw CYJSError(context, "cannot convert value to pointer");
return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
}
}
void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
switch (type->primitive) {
case sig::boolean_P:
*reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
break;
#define CYPoolFFI_(primitive, native) \
case sig::primitive ## _P: \
*reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
break;
CYPoolFFI_(uchar, unsigned char)
CYPoolFFI_(char, char)
CYPoolFFI_(ushort, unsigned short)
CYPoolFFI_(short, short)
CYPoolFFI_(ulong, unsigned long)
CYPoolFFI_(long, long)
CYPoolFFI_(uint, unsigned int)
CYPoolFFI_(int, int)
CYPoolFFI_(ulonglong, unsigned long long)
CYPoolFFI_(longlong, long long)
CYPoolFFI_(float, float)
CYPoolFFI_(double, double)
case sig::pointer_P:
*reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
break;
case sig::string_P:
*reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
break;
case sig::struct_P: {
uint8_t *base(reinterpret_cast<uint8_t *>(data));
JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
for (size_t index(0); index != type->data.signature.count; ++index) {
sig::Element *element(&type->data.signature.elements[index]);
ffi_type *field(ffi->elements[index]);
JSValueRef rhs;
if (aggregate == NULL)
rhs = value;
else {
rhs = CYGetProperty(context, aggregate, index);
if (JSValueIsUndefined(context, rhs)) {
if (element->name != NULL)
rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
else
goto undefined;
if (JSValueIsUndefined(context, rhs)) undefined:
throw CYJSError(context, "unable to extract structure value");
}
}
CYPoolFFI(pool, context, element->type, field, base, rhs);
// XXX: alignment?
base += field->size;
}
} break;
case sig::void_P:
break;
default:
if (hooks_ != NULL && hooks_->PoolFFI != NULL)
if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
return;
fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
_assert(false);
}
}
JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
switch (type->primitive) {
case sig::boolean_P:
return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
#define CYFromFFI_(primitive, native) \
case sig::primitive ## _P: \
return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
CYFromFFI_(uchar, unsigned char)
CYFromFFI_(char, char)
CYFromFFI_(ushort, unsigned short)
CYFromFFI_(short, short)
CYFromFFI_(ulong, unsigned long)
CYFromFFI_(long, long)
CYFromFFI_(uint, unsigned int)
CYFromFFI_(int, int)
CYFromFFI_(ulonglong, unsigned long long)
CYFromFFI_(longlong, long long)
CYFromFFI_(float, float)
CYFromFFI_(double, double)
case sig::array_P:
if (void *pointer = data)
return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
else goto null;
case sig::pointer_P:
if (void *pointer = *reinterpret_cast<void **>(data))
return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
else goto null;
case sig::string_P:
if (char *utf8 = *reinterpret_cast<char **>(data))
return CYCastJSValue(context, utf8);
else goto null;
case sig::struct_P:
return CYMakeStruct(context, data, type, ffi, owner);
case sig::void_P:
return CYJSUndefined(context);
null:
return CYJSNull(context);
default:
if (hooks_ != NULL && hooks_->FromFFI != NULL)
if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
return value;
CYThrow("failed conversion from FFI format: '%c'\n", type->primitive);
}
}
static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
JSContextRef context(internal->context_);
size_t count(internal->cif_.nargs);
JSValueRef values[count];
for (size_t index(0); index != count; ++index)
values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
}
Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
// XXX: in case of exceptions this will leak
// XXX: in point of fact, this may /need/ to leak :(
Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
ffi_closure *closure((ffi_closure *) _syscall(mmap(
NULL, sizeof(ffi_closure),
PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
-1, 0
)));
ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
_assert(status == FFI_OK);
_syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
internal->value_ = closure;
return internal;
}
static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
return JSObjectMake(context, Functor_, internal);
}
static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
JSValueRef exception(NULL);
bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
CYThrow(context, exception);
if (function) {
JSObjectRef function(CYCastJSObject(context, value));
return CYMakeFunctor(context, function, type);
} else {
void (*function)()(CYCastPointer<void (*)()>(context, value));
return CYMakeFunctor(context, function, type);
}
}
static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
Type_privateData *typical(internal->type_);
sig::Type *type(typical->type_);
if (type == NULL)
return false;
const char *name(CYPoolCString(pool, context, property));
size_t length(strlen(name));
double number(CYCastDouble(name, length));
size_t count(type->data.signature.count);
if (std::isnan(number)) {
if (property == NULL)
return false;
sig::Element *elements(type->data.signature.elements);
for (size_t local(0); local != count; ++local) {
sig::Element *element(&elements[local]);
if (element->name != NULL && strcmp(name, element->name) == 0) {
index = local;
goto base;
}
}
return false;
} else {
index = static_cast<ssize_t>(number);
if (index != number || index < 0 || static_cast<size_t>(index) >= count)
return false;
}
base:
ffi_type **elements(typical->GetFFI()->elements);
base = reinterpret_cast<uint8_t *>(internal->value_);
for (ssize_t local(0); local != index; ++local)
base += elements[local]->size;
return true;
}
static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
CYPool pool;
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
if (JSStringIsEqual(property, length_))
return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
Type_privateData *typical(internal->type_);
if (typical->type_ == NULL)
return NULL;
ssize_t offset;
if (JSStringIsEqualToUTF8CString(property, "$cyi"))
offset = 0;
else if (!CYGetOffset(pool, context, property, offset))
return NULL;
ffi_type *ffi(typical->GetFFI());
uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
base += ffi->size * offset;
JSObjectRef owner(internal->GetOwner() ?: object);
return CYFromFFI(context, typical->type_, ffi, base, false, owner);
} CYCatch }
static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
CYPool pool;
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
if (typical->type_ == NULL)
return NULL;
ssize_t offset;
if (JSStringIsEqualToUTF8CString(property, "$cyi"))
offset = 0;
else if (!CYGetOffset(pool, context, property, offset))
return NULL;
ffi_type *ffi(typical->GetFFI());
uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
base += ffi->size * offset;
CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
return true;
} CYCatch }
static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
Type_privateData *typical(internal->type_);
return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
}
static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
CYPool pool;
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ssize_t index;
uint8_t *base;
if (!Index_(pool, context, internal, property, index, base))
return NULL;
JSObjectRef owner(internal->GetOwner() ?: object);
return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
} CYCatch }
static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
CYPool pool;
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
ssize_t index;
uint8_t *base;
if (!Index_(pool, context, internal, property, index, base))
return false;
CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
return true;
} CYCatch }
static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
Type_privateData *typical(internal->type_);
sig::Type *type(typical->type_);
if (type == NULL)
return;
size_t count(type->data.signature.count);
sig::Element *elements(type->data.signature.elements);
char number[32];
for (size_t index(0); index != count; ++index) {
const char *name;
name = elements[index].name;
if (name == NULL) {
sprintf(number, "%zu", index);
name = number;
}
JSPropertyNameAccumulatorAddName(names, CYJSString(name));
}
}
JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { CYTry {
if (setups + count != signature->count - 1)
throw CYJSError(context, "incorrect number of arguments to ffi function");
size_t size(setups + count);
void *values[size];
memcpy(values, setup, sizeof(void *) * setups);
for (size_t index(setups); index != size; ++index) {
sig::Element *element(&signature->elements[index + 1]);
ffi_type *ffi(cif->arg_types[index]);
// XXX: alignment?
values[index] = new(pool) uint8_t[ffi->size];
CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
}
uint8_t value[cif->rtype->size];
if (hooks_ != NULL && hooks_->CallFunction != NULL)
(*hooks_->CallFunction)(context, cif, function, value, values);
else
ffi_call(cif, function, value, values);
return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
} CYCatch }
static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
CYPool pool;
cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
}
static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
Type_privateData *internal(new Type_privateData(type));
return JSObjectMake(context, Type_privateData::Class_, internal);
}
static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
Type_privateData *internal(new Type_privateData(type));
return JSObjectMake(context, Type_privateData::Class_, internal);
}
static void *CYCastSymbol(const char *name) {
return dlsym(RTLD_DEFAULT, name);
}
static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
CYPool pool;
CYUTF8String name(CYPoolUTF8String(pool, context, property));
if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
return value;
sqlite3_stmt *statement;
_sqlcall(sqlite3_prepare(Bridge_,
"select "
"\"bridge\".\"mode\", "
"\"bridge\".\"value\" "
"from \"bridge\" "
"where"
" \"bridge\".\"name\" = ?"
" limit 1"
, -1, &statement, NULL));
_sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
int mode;
const char *value;
if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
mode = -1;
value = NULL;
} else {
mode = sqlite3_column_int(statement, 0);
value = sqlite3_column_pooled(pool, statement, 1);
}
_sqlcall(sqlite3_finalize(statement));
switch (mode) {
default:
_assert(false);
case -1:
return NULL;
case 0:
return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
case 1:
if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
return CYMakeFunctor(context, symbol, value);
else return NULL;
case 2:
if (void *symbol = CYCastSymbol(name.data)) {
// XXX: this is horrendously inefficient
sig::Signature signature;
sig::Parse(pool, &signature, value, &Structor_);
ffi_cif cif;
sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
} else return NULL;
// XXX: implement case 3
case 4:
return CYMakeType(context, value);
}
} CYCatch }
static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 2)
throw CYJSError(context, "incorrect number of arguments to Functor constructor");
CYPool pool;
void *value(CYCastPointer<void *>(context, arguments[0]));
const char *type(CYPoolCString(pool, context, arguments[1]));
sig::Signature signature;
sig::Parse(pool, &signature, type, &Structor_);
return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
} CYCatch }
static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 1)
throw CYJSError(context, "incorrect number of arguments to Type constructor");
CYPool pool;
const char *type(CYPoolCString(pool, context, arguments[0]));
return CYMakeType(context, type);
} CYCatch }
static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
sig::Type type;
if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
type.primitive = sig::pointer_P;
type.data.data.size = 0;
} else {
CYPool pool;
size_t index(CYGetIndex(pool, context, property));
if (index == _not(size_t))
return NULL;
type.primitive = sig::array_P;
type.data.data.size = index;
}
type.name = NULL;
type.flags = 0;
type.data.data.type = internal->type_;
return CYMakeType(context, &type);
} CYCatch }
static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
if (count != 1)
throw CYJSError(context, "incorrect number of arguments to type cast function");
sig::Type *type(internal->type_);
ffi_type *ffi(internal->GetFFI());
// XXX: alignment?
uint8_t value[ffi->size];
CYPool pool;
CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
return CYFromFFI(context, type, ffi, value);
} CYCatch }
static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 0)
throw CYJSError(context, "incorrect number of arguments to type cast function");
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
sig::Type *type(internal->type_);
size_t size;
if (type->primitive != sig::array_P)
size = 0;
else {
size = type->data.data.size;
type = type->data.data.type;
}
void *value(malloc(internal->GetFFI()->size));
return CYMakePointer(context, value, _not(size_t), type, NULL, NULL);
} CYCatch }
static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
if (count != 2)
throw CYJSError(context, "incorrect number of arguments to Functor constructor");
CYPool pool;
const char *type(CYPoolCString(pool, context, arguments[1]));
return CYMakeFunctor(context, arguments[0], type);
} CYCatch }
static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
} CYCatch }
static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
}
static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
char string[32];
sprintf(string, "%p", internal->value_);
return CYCastJSValue(context, string);
} CYCatch }
static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
if (internal->length_ != _not(size_t))
// XXX: maybe dynamically look up Array.toCYON?
return Array_callAsFunction_toCYON(context, object, _this, count, arguments, exception);
else {
char string[32];
sprintf(string, "%p", internal->value_);
return CYCastJSValue(context, string);
}
} CYCatch }
static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
CYPool pool;
const char *type(sig::Unparse(pool, internal->type_));
return CYCastJSValue(context, CYJSString(type));
} CYCatch }
static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
CYPool pool;
const char *type(sig::Unparse(pool, internal->type_));
size_t size(strlen(type));
char *cyon(new(pool) char[12 + size + 1]);
memcpy(cyon, "new Type(\"", 10);
cyon[12 + size] = '\0';
cyon[12 + size - 2] = '"';
cyon[12 + size - 1] = ')';
memcpy(cyon + 10, type, size);
return CYCastJSValue(context, CYJSString(cyon));
} CYCatch }
static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
}
static JSStaticFunction Pointer_staticFunctions[4] = {
{"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSStaticFunction Struct_staticFunctions[2] = {
{"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSStaticFunction Functor_staticFunctions[4] = {
{"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
namespace cy {
JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
}
static JSStaticFunction Type_staticFunctions[4] = {
{"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
{NULL, NULL, 0}
};
static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
void CYSetArgs(int argc, const char *argv[]) {
JSContextRef context(CYGetJSContext());
JSValueRef args[argc];
for (int i(0); i != argc; ++i)
args[i] = CYCastJSValue(context, argv[i]);
JSObjectRef array;
if (JSObjectMakeArray$ != NULL) {
JSValueRef exception(NULL);
array = (*JSObjectMakeArray$)(context, argc, args, &exception);
CYThrow(context, exception);
} else {
JSValueRef value(CYCallAsFunction(context, Array_, NULL, argc, args));
array = CYCastJSObject(context, value);
}
CYSetProperty(context, System_, CYJSString("args"), array);
}
JSObjectRef CYGetGlobalObject(JSContextRef context) {
return JSContextGetGlobalObject(context);
}
const char *CYExecute(apr_pool_t *pool, const char *code) {
JSContextRef context(CYGetJSContext());
JSValueRef exception(NULL), result;
void *handle;
if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
handle = (*hooks_->ExecuteStart)(context);
else
handle = NULL;
const char *json;
try {
result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
} catch (const char *error) {
return error;
}
if (exception != NULL) { error:
result = exception;
exception = NULL;
}
if (JSValueIsUndefined(context, result))
return NULL;
try {
json = CYPoolCCYON(pool, context, result, &exception);
} catch (const char *error) {
return error;
}
if (exception != NULL)
goto error;
CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
(*hooks_->ExecuteEnd)(context, handle);
return json;
}
static apr_pool_t *Pool_;
static bool initialized_;
void CYInitialize() {
if (!initialized_)
initialized_ = true;
else return;
_aprcall(apr_initialize());
_aprcall(apr_pool_create(&Pool_, NULL));
_sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
}
apr_pool_t *CYGetGlobalPool() {
CYInitialize();
return Pool_;
}
void CYThrow(JSContextRef context, JSValueRef value) {
if (value != NULL)
throw CYJSError(context, value);
}
const char *CYJSError::PoolCString(apr_pool_t *pool) const {
return CYPoolCString(pool, context_, value_);
}
JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
// XXX: what if the context is different?
return value_;
}
void CYThrow(const char *format, ...) {
va_list args;
va_start (args, format);
throw CYPoolError(format, args);
// XXX: does this matter? :(
va_end (args);
}
const char *CYPoolError::PoolCString(apr_pool_t *pool) const {
return apr_pstrdup(pool, message_);
}
CYPoolError::CYPoolError(const char *format, ...) {
va_list args;
va_start (args, format);
message_ = apr_pvsprintf(pool_, format, args);
va_end (args);
}
CYPoolError::CYPoolError(const char *format, va_list args) {
message_ = apr_pvsprintf(pool_, format, args);
}
JSValueRef CYCastJSError(JSContextRef context, const char *message) {
JSValueRef arguments[1] = {CYCastJSValue(context, message)};
JSValueRef exception(NULL);
JSValueRef value(JSObjectCallAsConstructor(context, Error_, 1, arguments, &exception));
CYThrow(context, exception);
return value;
}
JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
return CYCastJSError(context, message_);
}
CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
if (context == NULL)
context = CYGetJSContext();
CYPool pool;
va_list args;
va_start (args, format);
const char *message(apr_pvsprintf(pool, format, args));
va_end (args);
value_ = CYCastJSError(context, message);
}
JSGlobalContextRef CYGetJSContext() {
CYInitialize();
if (Context_ == NULL) {
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = "Functor";
definition.staticFunctions = cy::Functor::StaticFunctions;
definition.callAsFunction = &Functor_callAsFunction;
definition.finalize = &CYFinalize;
Functor_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Pointer";
definition.staticFunctions = Pointer_staticFunctions;
definition.getProperty = &Pointer_getProperty;
definition.setProperty = &Pointer_setProperty;
definition.finalize = &CYFinalize;
Pointer_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Struct";
definition.staticFunctions = Struct_staticFunctions;
definition.getProperty = &Struct_getProperty;
definition.setProperty = &Struct_setProperty;
definition.getPropertyNames = &Struct_getPropertyNames;
definition.finalize = &CYFinalize;
Struct_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Type";
definition.staticFunctions = Type_staticFunctions;
definition.getProperty = &Type_getProperty;
definition.callAsFunction = &Type_callAsFunction;
definition.callAsConstructor = &Type_callAsConstructor;
definition.finalize = &CYFinalize;
Type_privateData::Class_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
definition.className = "Runtime";
definition.getProperty = &Runtime_getProperty;
Runtime_ = JSClassCreate(&definition);
definition = kJSClassDefinitionEmpty;
//definition.getProperty = &Global_getProperty;
JSClassRef Global(JSClassCreate(&definition));
JSGlobalContextRef context(JSGlobalContextCreate(Global));
Context_ = context;
JSObjectRef global(CYGetGlobalObject(context));
JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
JSValueProtect(context, Array_);
Error_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error")));
JSValueProtect(context, Error_);
Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
JSValueProtect(context, Function_);
String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
JSValueProtect(context, String_);
length_ = JSStringCreateWithUTF8CString("length");
message_ = JSStringCreateWithUTF8CString("message");
name_ = JSStringCreateWithUTF8CString("name");
prototype_ = JSStringCreateWithUTF8CString("prototype");
toCYON_ = JSStringCreateWithUTF8CString("toCYON");
toJSON_ = JSStringCreateWithUTF8CString("toJSON");
JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
JSValueProtect(context, Object_prototype_);
Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
JSValueProtect(context, Array_prototype_);
JSValueProtect(context, Array_pop_);
JSValueProtect(context, Array_push_);
JSValueProtect(context, Array_splice_);
JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
Function_prototype_ = (JSObjectRef) CYGetProperty(context, Function_, prototype_);
JSValueProtect(context, Function_prototype_);
JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), Function_prototype_);
CYSetProperty(context, global, CYJSString("Functor"), Functor);
CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
CYSetProperty(context, global, CYJSString("Cycript"), cycript);
CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
System_ = JSObjectMake(context, NULL, NULL);
JSValueProtect(context, System_);
CYSetProperty(context, global, CYJSString("system"), System_);
CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
//CYSetProperty(context, System_, CYJSString("global"), global);
CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
Result_ = JSStringCreateWithUTF8CString("_");
if (hooks_ != NULL && hooks_->SetupContext != NULL)
(*hooks_->SetupContext)(context);
}
return Context_;
}
|
/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
// A vector-like container that uses discontiguous storage. Provides fast random access,
// the ability to append at the end, and limited contiguous allocations.
//
// std::deque would be a good fit, except the backing array can grow quite large.
#include "utils/logalloc.hh"
#include "utils/managed_vector.hh"
#include <boost/range/algorithm/equal.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/version.hpp>
#include <memory>
#include <type_traits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <stdexcept>
namespace lsa {
template <typename T>
class chunked_managed_vector {
static const size_t max_contiguous_allocation = logalloc::segment_size * 0.1;
static_assert(std::is_nothrow_move_constructible<T>::value, "T must be nothrow move constructible");
using chunk_ptr = managed_vector<T>;
// Each chunk holds max_chunk_capacity() items, except possibly the last
managed_vector<chunk_ptr, 1> _chunks;
size_t _size = 0;
size_t _capacity = 0;
private:
static size_t max_chunk_capacity() {
return std::max(max_contiguous_allocation / sizeof(T), size_t(1));
}
void reserve_for_push_back() {
if (_size == _capacity) {
do_reserve_for_push_back();
}
}
void do_reserve_for_push_back();
size_t make_room(size_t n, bool stop_after_one);
chunk_ptr new_chunk(size_t n);
const T* addr(size_t i) const {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
T* addr(size_t i) {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
void check_bounds(size_t i) const {
if (i >= _size) {
throw std::out_of_range("chunked_managed_vector out of range access");
}
}
chunk_ptr& back_chunk() {
return _chunks[_size / max_chunk_capacity()];
}
static void migrate(T* begin, T* end, managed_vector<T>& result);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ssize_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
public:
chunked_managed_vector() = default;
chunked_managed_vector(const chunked_managed_vector& x);
chunked_managed_vector(chunked_managed_vector&& x) noexcept;
template <typename Iterator>
chunked_managed_vector(Iterator begin, Iterator end);
explicit chunked_managed_vector(size_t n, const T& value = T());
~chunked_managed_vector();
chunked_managed_vector& operator=(const chunked_managed_vector& x);
chunked_managed_vector& operator=(chunked_managed_vector&& x) noexcept;
bool empty() const {
return !_size;
}
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
T& operator[](size_t i) {
return *addr(i);
}
const T& operator[](size_t i) const {
return *addr(i);
}
T& at(size_t i) {
check_bounds(i);
return *addr(i);
}
const T& at(size_t i) const {
check_bounds(i);
return *addr(i);
}
void push_back(const T& x) {
reserve_for_push_back();
back_chunk().emplace_back(x);
++_size;
}
void push_back(T&& x) {
reserve_for_push_back();
back_chunk().emplace_back(std::move(x));
++_size;
}
template <typename... Args>
T& emplace_back(Args&&... args) {
reserve_for_push_back();
auto& ret = back_chunk().emplace_back(std::forward<Args>(args)...);
++_size;
return ret;
}
void pop_back() {
--_size;
back_chunk().pop_back();
}
const T& back() const {
return *addr(_size - 1);
}
T& back() {
return *addr(_size - 1);
}
void clear();
void shrink_to_fit();
void resize(size_t n);
void reserve(size_t n) {
if (n > _capacity) {
make_room(n, false);
}
}
/// Reserve some of the memory.
///
/// Allows reserving the memory chunk-by-chunk, avoiding stalls when a lot of
/// chunks are needed. To drive the reservation to completion, call this
/// repeatedly with the value returned from the previous call until it
/// returns 0, yielding between calls when necessary. Example usage:
///
/// return do_until([&size] { return !size; }, [&my_vector, &size] () mutable {
/// size = my_vector.reserve_partial(size);
/// });
///
/// Here, `do_until()` takes care of yielding between iterations when
/// necessary.
///
/// \returns the memory that remains to be reserved
size_t reserve_partial(size_t n) {
if (n > _capacity) {
return make_room(n, true);
}
return 0;
}
size_t memory_size() const {
return _capacity * sizeof(T);
}
public:
template <class ValueType>
class iterator_type {
const chunk_ptr* _chunks;
size_t _i;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = ValueType;
using difference_type = ssize_t;
using pointer = ValueType*;
using reference = ValueType&;
private:
pointer addr() const {
return &const_cast<chunk_ptr*>(_chunks)[_i / max_chunk_capacity()][_i % max_chunk_capacity()];
}
iterator_type(const chunk_ptr* chunks, size_t i) : _chunks(chunks), _i(i) {}
public:
iterator_type() = default;
iterator_type(const iterator_type<std::remove_const_t<ValueType>>& x) : _chunks(x._chunks), _i(x._i) {} // needed for iterator->const_iterator conversion
reference operator*() const {
return *addr();
}
pointer operator->() const {
return addr();
}
reference operator[](ssize_t n) const {
return *(*this + n);
}
iterator_type& operator++() {
++_i;
return *this;
}
iterator_type operator++(int) {
auto x = *this;
++_i;
return x;
}
iterator_type& operator--() {
--_i;
return *this;
}
iterator_type operator--(int) {
auto x = *this;
--_i;
return x;
}
iterator_type& operator+=(ssize_t n) {
_i += n;
return *this;
}
iterator_type& operator-=(ssize_t n) {
_i -= n;
return *this;
}
iterator_type operator+(ssize_t n) const {
auto x = *this;
return x += n;
}
iterator_type operator-(ssize_t n) const {
auto x = *this;
return x -= n;
}
friend iterator_type operator+(ssize_t n, iterator_type a) {
return a + n;
}
friend ssize_t operator-(iterator_type a, iterator_type b) {
return a._i - b._i;
}
bool operator==(iterator_type x) const {
return _i == x._i;
}
bool operator!=(iterator_type x) const {
return _i != x._i;
}
bool operator<(iterator_type x) const {
return _i < x._i;
}
bool operator<=(iterator_type x) const {
return _i <= x._i;
}
bool operator>(iterator_type x) const {
return _i > x._i;
}
bool operator>=(iterator_type x) const {
return _i >= x._i;
}
friend class chunked_managed_vector;
};
using iterator = iterator_type<T>;
using const_iterator = iterator_type<const T>;
public:
const T& front() const { return *cbegin(); }
T& front() { return *begin(); }
iterator begin() { return iterator(_chunks.data(), 0); }
iterator end() { return iterator(_chunks.data(), _size); }
const_iterator begin() const { return const_iterator(_chunks.data(), 0); }
const_iterator end() const { return const_iterator(_chunks.data(), _size); }
const_iterator cbegin() const { return const_iterator(_chunks.data(), 0); }
const_iterator cend() const { return const_iterator(_chunks.data(), _size); }
std::reverse_iterator<iterator> rbegin() { return std::reverse_iterator(end()); }
std::reverse_iterator<iterator> rend() { return std::reverse_iterator(begin()); }
std::reverse_iterator<const_iterator> rbegin() const { return std::reverse_iterator(end()); }
std::reverse_iterator<const_iterator> rend() const { return std::reverse_iterator(begin()); }
std::reverse_iterator<const_iterator> crbegin() const { return std::reverse_iterator(cend()); }
std::reverse_iterator<const_iterator> crend() const { return std::reverse_iterator(cbegin()); }
public:
bool operator==(const chunked_managed_vector& x) const {
return boost::equal(*this, x);
}
bool operator!=(const chunked_managed_vector& x) const {
return !operator==(x);
}
// Returns the amount of external memory used to hold inserted items.
// Takes into account reserved space.
size_t external_memory_usage() const {
// This ignores per-chunk sizeof(managed_vector::external) but should
// be close-enough.
return _chunks.external_memory_usage() + _capacity * sizeof(T);
}
// Clears the vector and ensures that the destructor will not have to free any memory so
// that the object can be destroyed under any allocator.
void clear_and_release() noexcept {
clear();
_chunks.clear_and_release();
}
};
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(const chunked_managed_vector& x)
: chunked_managed_vector() {
reserve(x.size());
std::copy(x.begin(), x.end(), std::back_inserter(*this));
}
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(chunked_managed_vector&& x) noexcept
: _chunks(std::exchange(x._chunks, {}))
, _size(std::exchange(x._size, 0))
, _capacity(std::exchange(x._capacity, 0)) {
}
template <typename T>
template <typename Iterator>
chunked_managed_vector<T>::chunked_managed_vector(Iterator begin, Iterator end)
: chunked_managed_vector() {
auto is_random_access = std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category>::value;
if (is_random_access) {
reserve(std::distance(begin, end));
}
std::copy(begin, end, std::back_inserter(*this));
if (!is_random_access) {
shrink_to_fit();
}
}
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(size_t n, const T& value) {
reserve(n);
std::fill_n(std::back_inserter(*this), n, value);
}
template <typename T>
chunked_managed_vector<T>&
chunked_managed_vector<T>::operator=(const chunked_managed_vector& x) {
auto tmp = chunked_managed_vector(x);
return *this = std::move(tmp);
}
template <typename T>
inline
chunked_managed_vector<T>&
chunked_managed_vector<T>::operator=(chunked_managed_vector&& x) noexcept {
if (this != &x) {
this->~chunked_managed_vector();
new (this) chunked_managed_vector(std::move(x));
}
return *this;
}
template <typename T>
chunked_managed_vector<T>::~chunked_managed_vector() {
}
template <typename T>
typename chunked_managed_vector<T>::chunk_ptr
chunked_managed_vector<T>::new_chunk(size_t n) {
managed_vector<T> p;
p.reserve(n);
return p;
}
template <typename T>
void
chunked_managed_vector<T>::migrate(T* begin, T* end, managed_vector<T>& result) {
while (begin != end) {
result.emplace_back(std::move(*begin));
++begin;
}
}
template <typename T>
size_t
chunked_managed_vector<T>::make_room(size_t n, bool stop_after_one) {
// First, if the last chunk is below max_chunk_capacity(), enlarge it
auto last_chunk_capacity_deficit = _chunks.size() * max_chunk_capacity() - _capacity;
if (last_chunk_capacity_deficit) {
auto last_chunk_capacity = max_chunk_capacity() - last_chunk_capacity_deficit;
auto capacity_increase = std::min(last_chunk_capacity_deficit, n - _capacity);
auto new_last_chunk_capacity = last_chunk_capacity + capacity_increase;
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr(_capacity - last_chunk_capacity), addr(_size), new_last_chunk);
_chunks.back() = std::move(new_last_chunk);
_capacity += capacity_increase;
}
// Reduce reallocations in the _chunks vector
auto nr_chunks = (n + max_chunk_capacity() - 1) / max_chunk_capacity();
_chunks.reserve(nr_chunks);
// Add more chunks as needed
bool stop = false;
while (_capacity < n && !stop) {
auto now = std::min(n - _capacity, max_chunk_capacity());
_chunks.push_back(new_chunk(now));
_capacity += now;
stop = stop_after_one;
}
return (n - _capacity);
}
template <typename T>
void
chunked_managed_vector<T>::do_reserve_for_push_back() {
if (_capacity == 0) {
// allocate a bit of room in case utilization will be low
reserve(boost::algorithm::clamp(512 / sizeof(T), 1, max_chunk_capacity()));
} else if (_capacity < max_chunk_capacity() / 2) {
// exponential increase when only one chunk to reduce copying
reserve(_capacity * 2);
} else {
// add a chunk at a time later, since no copying will take place
reserve((_capacity / max_chunk_capacity() + 1) * max_chunk_capacity());
}
}
template <typename T>
void
chunked_managed_vector<T>::resize(size_t n) {
reserve(n);
// FIXME: construct whole chunks at once
while (_size > n) {
pop_back();
}
while (_size < n) {
push_back(T{});
}
shrink_to_fit();
}
template <typename T>
void
chunked_managed_vector<T>::shrink_to_fit() {
if (_chunks.empty()) {
return;
}
while (!_chunks.empty() && _size <= (_chunks.size() - 1) * max_chunk_capacity()) {
_chunks.pop_back();
_capacity = _chunks.size() * max_chunk_capacity();
}
auto overcapacity = _size - _capacity;
if (overcapacity) {
auto new_last_chunk_capacity = _size - (_chunks.size() - 1) * max_chunk_capacity();
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr((_chunks.size() - 1) * max_chunk_capacity()), addr(_size), new_last_chunk);
_chunks.back() = std::move(new_last_chunk);
_capacity = _size;
}
}
template <typename T>
void
chunked_managed_vector<T>::clear() {
while (_size > 0) {
pop_back();
}
shrink_to_fit();
}
}
utils/chunked_managed_vector: expose max_chunk_capacity()
That's useful for tests which want to verify correctness when the
vector is performing operations across the chunk boundary.
Signed-off-by: Raphael S. Carvalho <1e2942cea40e3b4d2162dfcd9e53e41c05a84d22@scylladb.com>
Message-Id: <20220408133555.12397-1-1e2942cea40e3b4d2162dfcd9e53e41c05a84d22@scylladb.com>
/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
// A vector-like container that uses discontiguous storage. Provides fast random access,
// the ability to append at the end, and limited contiguous allocations.
//
// std::deque would be a good fit, except the backing array can grow quite large.
#include "utils/logalloc.hh"
#include "utils/managed_vector.hh"
#include <boost/range/algorithm/equal.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/version.hpp>
#include <memory>
#include <type_traits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <stdexcept>
namespace lsa {
template <typename T>
class chunked_managed_vector {
static const size_t max_contiguous_allocation = logalloc::segment_size * 0.1;
static_assert(std::is_nothrow_move_constructible<T>::value, "T must be nothrow move constructible");
using chunk_ptr = managed_vector<T>;
// Each chunk holds max_chunk_capacity() items, except possibly the last
managed_vector<chunk_ptr, 1> _chunks;
size_t _size = 0;
size_t _capacity = 0;
public:
static size_t max_chunk_capacity() {
return std::max(max_contiguous_allocation / sizeof(T), size_t(1));
}
private:
void reserve_for_push_back() {
if (_size == _capacity) {
do_reserve_for_push_back();
}
}
void do_reserve_for_push_back();
size_t make_room(size_t n, bool stop_after_one);
chunk_ptr new_chunk(size_t n);
const T* addr(size_t i) const {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
T* addr(size_t i) {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
void check_bounds(size_t i) const {
if (i >= _size) {
throw std::out_of_range("chunked_managed_vector out of range access");
}
}
chunk_ptr& back_chunk() {
return _chunks[_size / max_chunk_capacity()];
}
static void migrate(T* begin, T* end, managed_vector<T>& result);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ssize_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
public:
chunked_managed_vector() = default;
chunked_managed_vector(const chunked_managed_vector& x);
chunked_managed_vector(chunked_managed_vector&& x) noexcept;
template <typename Iterator>
chunked_managed_vector(Iterator begin, Iterator end);
explicit chunked_managed_vector(size_t n, const T& value = T());
~chunked_managed_vector();
chunked_managed_vector& operator=(const chunked_managed_vector& x);
chunked_managed_vector& operator=(chunked_managed_vector&& x) noexcept;
bool empty() const {
return !_size;
}
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
T& operator[](size_t i) {
return *addr(i);
}
const T& operator[](size_t i) const {
return *addr(i);
}
T& at(size_t i) {
check_bounds(i);
return *addr(i);
}
const T& at(size_t i) const {
check_bounds(i);
return *addr(i);
}
void push_back(const T& x) {
reserve_for_push_back();
back_chunk().emplace_back(x);
++_size;
}
void push_back(T&& x) {
reserve_for_push_back();
back_chunk().emplace_back(std::move(x));
++_size;
}
template <typename... Args>
T& emplace_back(Args&&... args) {
reserve_for_push_back();
auto& ret = back_chunk().emplace_back(std::forward<Args>(args)...);
++_size;
return ret;
}
void pop_back() {
--_size;
back_chunk().pop_back();
}
const T& back() const {
return *addr(_size - 1);
}
T& back() {
return *addr(_size - 1);
}
void clear();
void shrink_to_fit();
void resize(size_t n);
void reserve(size_t n) {
if (n > _capacity) {
make_room(n, false);
}
}
/// Reserve some of the memory.
///
/// Allows reserving the memory chunk-by-chunk, avoiding stalls when a lot of
/// chunks are needed. To drive the reservation to completion, call this
/// repeatedly with the value returned from the previous call until it
/// returns 0, yielding between calls when necessary. Example usage:
///
/// return do_until([&size] { return !size; }, [&my_vector, &size] () mutable {
/// size = my_vector.reserve_partial(size);
/// });
///
/// Here, `do_until()` takes care of yielding between iterations when
/// necessary.
///
/// \returns the memory that remains to be reserved
size_t reserve_partial(size_t n) {
if (n > _capacity) {
return make_room(n, true);
}
return 0;
}
size_t memory_size() const {
return _capacity * sizeof(T);
}
public:
template <class ValueType>
class iterator_type {
const chunk_ptr* _chunks;
size_t _i;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = ValueType;
using difference_type = ssize_t;
using pointer = ValueType*;
using reference = ValueType&;
private:
pointer addr() const {
return &const_cast<chunk_ptr*>(_chunks)[_i / max_chunk_capacity()][_i % max_chunk_capacity()];
}
iterator_type(const chunk_ptr* chunks, size_t i) : _chunks(chunks), _i(i) {}
public:
iterator_type() = default;
iterator_type(const iterator_type<std::remove_const_t<ValueType>>& x) : _chunks(x._chunks), _i(x._i) {} // needed for iterator->const_iterator conversion
reference operator*() const {
return *addr();
}
pointer operator->() const {
return addr();
}
reference operator[](ssize_t n) const {
return *(*this + n);
}
iterator_type& operator++() {
++_i;
return *this;
}
iterator_type operator++(int) {
auto x = *this;
++_i;
return x;
}
iterator_type& operator--() {
--_i;
return *this;
}
iterator_type operator--(int) {
auto x = *this;
--_i;
return x;
}
iterator_type& operator+=(ssize_t n) {
_i += n;
return *this;
}
iterator_type& operator-=(ssize_t n) {
_i -= n;
return *this;
}
iterator_type operator+(ssize_t n) const {
auto x = *this;
return x += n;
}
iterator_type operator-(ssize_t n) const {
auto x = *this;
return x -= n;
}
friend iterator_type operator+(ssize_t n, iterator_type a) {
return a + n;
}
friend ssize_t operator-(iterator_type a, iterator_type b) {
return a._i - b._i;
}
bool operator==(iterator_type x) const {
return _i == x._i;
}
bool operator!=(iterator_type x) const {
return _i != x._i;
}
bool operator<(iterator_type x) const {
return _i < x._i;
}
bool operator<=(iterator_type x) const {
return _i <= x._i;
}
bool operator>(iterator_type x) const {
return _i > x._i;
}
bool operator>=(iterator_type x) const {
return _i >= x._i;
}
friend class chunked_managed_vector;
};
using iterator = iterator_type<T>;
using const_iterator = iterator_type<const T>;
public:
const T& front() const { return *cbegin(); }
T& front() { return *begin(); }
iterator begin() { return iterator(_chunks.data(), 0); }
iterator end() { return iterator(_chunks.data(), _size); }
const_iterator begin() const { return const_iterator(_chunks.data(), 0); }
const_iterator end() const { return const_iterator(_chunks.data(), _size); }
const_iterator cbegin() const { return const_iterator(_chunks.data(), 0); }
const_iterator cend() const { return const_iterator(_chunks.data(), _size); }
std::reverse_iterator<iterator> rbegin() { return std::reverse_iterator(end()); }
std::reverse_iterator<iterator> rend() { return std::reverse_iterator(begin()); }
std::reverse_iterator<const_iterator> rbegin() const { return std::reverse_iterator(end()); }
std::reverse_iterator<const_iterator> rend() const { return std::reverse_iterator(begin()); }
std::reverse_iterator<const_iterator> crbegin() const { return std::reverse_iterator(cend()); }
std::reverse_iterator<const_iterator> crend() const { return std::reverse_iterator(cbegin()); }
public:
bool operator==(const chunked_managed_vector& x) const {
return boost::equal(*this, x);
}
bool operator!=(const chunked_managed_vector& x) const {
return !operator==(x);
}
// Returns the amount of external memory used to hold inserted items.
// Takes into account reserved space.
size_t external_memory_usage() const {
// This ignores per-chunk sizeof(managed_vector::external) but should
// be close-enough.
return _chunks.external_memory_usage() + _capacity * sizeof(T);
}
// Clears the vector and ensures that the destructor will not have to free any memory so
// that the object can be destroyed under any allocator.
void clear_and_release() noexcept {
clear();
_chunks.clear_and_release();
}
};
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(const chunked_managed_vector& x)
: chunked_managed_vector() {
reserve(x.size());
std::copy(x.begin(), x.end(), std::back_inserter(*this));
}
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(chunked_managed_vector&& x) noexcept
: _chunks(std::exchange(x._chunks, {}))
, _size(std::exchange(x._size, 0))
, _capacity(std::exchange(x._capacity, 0)) {
}
template <typename T>
template <typename Iterator>
chunked_managed_vector<T>::chunked_managed_vector(Iterator begin, Iterator end)
: chunked_managed_vector() {
auto is_random_access = std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category>::value;
if (is_random_access) {
reserve(std::distance(begin, end));
}
std::copy(begin, end, std::back_inserter(*this));
if (!is_random_access) {
shrink_to_fit();
}
}
template <typename T>
chunked_managed_vector<T>::chunked_managed_vector(size_t n, const T& value) {
reserve(n);
std::fill_n(std::back_inserter(*this), n, value);
}
template <typename T>
chunked_managed_vector<T>&
chunked_managed_vector<T>::operator=(const chunked_managed_vector& x) {
auto tmp = chunked_managed_vector(x);
return *this = std::move(tmp);
}
template <typename T>
inline
chunked_managed_vector<T>&
chunked_managed_vector<T>::operator=(chunked_managed_vector&& x) noexcept {
if (this != &x) {
this->~chunked_managed_vector();
new (this) chunked_managed_vector(std::move(x));
}
return *this;
}
template <typename T>
chunked_managed_vector<T>::~chunked_managed_vector() {
}
template <typename T>
typename chunked_managed_vector<T>::chunk_ptr
chunked_managed_vector<T>::new_chunk(size_t n) {
managed_vector<T> p;
p.reserve(n);
return p;
}
template <typename T>
void
chunked_managed_vector<T>::migrate(T* begin, T* end, managed_vector<T>& result) {
while (begin != end) {
result.emplace_back(std::move(*begin));
++begin;
}
}
template <typename T>
size_t
chunked_managed_vector<T>::make_room(size_t n, bool stop_after_one) {
// First, if the last chunk is below max_chunk_capacity(), enlarge it
auto last_chunk_capacity_deficit = _chunks.size() * max_chunk_capacity() - _capacity;
if (last_chunk_capacity_deficit) {
auto last_chunk_capacity = max_chunk_capacity() - last_chunk_capacity_deficit;
auto capacity_increase = std::min(last_chunk_capacity_deficit, n - _capacity);
auto new_last_chunk_capacity = last_chunk_capacity + capacity_increase;
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr(_capacity - last_chunk_capacity), addr(_size), new_last_chunk);
_chunks.back() = std::move(new_last_chunk);
_capacity += capacity_increase;
}
// Reduce reallocations in the _chunks vector
auto nr_chunks = (n + max_chunk_capacity() - 1) / max_chunk_capacity();
_chunks.reserve(nr_chunks);
// Add more chunks as needed
bool stop = false;
while (_capacity < n && !stop) {
auto now = std::min(n - _capacity, max_chunk_capacity());
_chunks.push_back(new_chunk(now));
_capacity += now;
stop = stop_after_one;
}
return (n - _capacity);
}
template <typename T>
void
chunked_managed_vector<T>::do_reserve_for_push_back() {
if (_capacity == 0) {
// allocate a bit of room in case utilization will be low
reserve(boost::algorithm::clamp(512 / sizeof(T), 1, max_chunk_capacity()));
} else if (_capacity < max_chunk_capacity() / 2) {
// exponential increase when only one chunk to reduce copying
reserve(_capacity * 2);
} else {
// add a chunk at a time later, since no copying will take place
reserve((_capacity / max_chunk_capacity() + 1) * max_chunk_capacity());
}
}
template <typename T>
void
chunked_managed_vector<T>::resize(size_t n) {
reserve(n);
// FIXME: construct whole chunks at once
while (_size > n) {
pop_back();
}
while (_size < n) {
push_back(T{});
}
shrink_to_fit();
}
template <typename T>
void
chunked_managed_vector<T>::shrink_to_fit() {
if (_chunks.empty()) {
return;
}
while (!_chunks.empty() && _size <= (_chunks.size() - 1) * max_chunk_capacity()) {
_chunks.pop_back();
_capacity = _chunks.size() * max_chunk_capacity();
}
auto overcapacity = _size - _capacity;
if (overcapacity) {
auto new_last_chunk_capacity = _size - (_chunks.size() - 1) * max_chunk_capacity();
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr((_chunks.size() - 1) * max_chunk_capacity()), addr(_size), new_last_chunk);
_chunks.back() = std::move(new_last_chunk);
_capacity = _size;
}
}
template <typename T>
void
chunked_managed_vector<T>::clear() {
while (_size > 0) {
pop_back();
}
shrink_to_fit();
}
}
|
// 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 "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#if defined(OS_WIN)
#undef IN // On Windows, windef.h defines this, which screws up "India" cases.
#elif defined(OS_MACOSX)
#include "base/scoped_cftyperef.h"
#endif
using base::Time;
namespace {
// NOTE: See comments in GetDataVersion() below! You should probably not change
// the data in this file without changing the result of that function!
// Engine definitions //////////////////////////////////////////////////////////
struct PrepopulatedEngine {
const wchar_t* const name;
// If NULL, we'll autogenerate a keyword based on the search_url every time
// someone asks. Only entries which need keywords to auto-track a dynamically
// generated search URL should use this.
// If the empty string, the engine has no keyword.
const wchar_t* const keyword;
const char* const favicon_url; // If NULL, there is no favicon.
const wchar_t* const search_url;
const char* const encoding;
const wchar_t* const suggest_url; // If NULL, this engine does not support
// suggestions.
// Unique id for this prepopulate engine (corresponds to
// TemplateURL::prepopulate_id). This ID must be greater than zero and must
// remain the same for a particular site regardless of how the url changes;
// the ID is used when modifying engine data in subsequent versions, so that
// we can find the "old" entry to update even when the name or URL changes.
//
// This ID must be "unique" within one country's prepopulated data, but two
// entries can share an ID if they represent the "same" engine (e.g. Yahoo! US
// vs. Yahoo! UK) and will not appear in the same user-visible data set. This
// facilitates changes like adding more specific per-country data in the
// future; in such a case the localized engines will transparently replace the
// previous, non-localized versions. For engines where we need two instances
// to appear for one country (e.g. Live Search U.S. English and Spanish), we
// must use two different unique IDs (and different keywords).
//
// The following unique IDs are available: 66, 93, 103+
// NOTE: CHANGE THE ABOVE NUMBERS IF YOU ADD A NEW ENGINE; ID conflicts = bad!
const int id;
};
const PrepopulatedEngine abcsok = {
L"ABC S\x00f8k",
L"abcsok.no",
"http://abcsok.no/favicon.ico",
L"http://abcsok.no/index.html?q={searchTerms}",
"UTF-8",
NULL,
72,
};
const PrepopulatedEngine adonde = {
L"Adonde.com",
L"adonde.com",
"http://www.adonde.com/favicon.ico",
L"http://www.adonde.com/peru/peru.html?sitesearch=adonde.com&"
L"client=pub-6263803831447773&ie={inputEncoding}&cof=GALT%3A%23CC0000"
L"%3BGL%3A1%3BDIV%3A%23E6E6E6%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF"
L"%3BLBGC%3AFFFFFF%3BALC%3A000000%3BLC%3A000000%3BT%3A0066CC%3BGFNT"
L"%3ACCCCCC%3BGIMP%3ACCCCCC%3BFORID%3A11&q={searchTerms}",
"ISO-8859-1",
NULL,
95,
};
const PrepopulatedEngine aeiou = {
L"AEIOU",
L"aeiou.pt",
"http://aeiou.pt/favicon.ico",
L"http://aeiou.pt/pesquisa/index.php?p={searchTerms}",
"ISO-8859-1",
NULL,
79,
};
const PrepopulatedEngine aladin = {
L"Aladin",
L"aladin.info",
"http://www.aladin.info/favicon.ico",
L"http://www.aladin.info/search/index.php?term={searchTerms}&req=search&"
L"source=2",
"UTF-8",
NULL,
18,
};
const PrepopulatedEngine altavista = {
L"AltaVista",
L"altavista.com",
"http://www.altavista.com/favicon.ico",
L"http://www.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_ar = {
L"AltaVista",
L"ar.altavista.com",
"http://ar.altavista.com/favicon.ico",
L"http://ar.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_es = {
L"AltaVista",
L"es.altavista.com",
"http://es.altavista.com/favicon.ico",
L"http://es.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_mx = {
L"AltaVista",
L"mx.altavista.com",
"http://mx.altavista.com/favicon.ico",
L"http://mx.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_se = {
L"AltaVista",
L"se.altavista.com",
"http://se.altavista.com/favicon.ico",
L"http://se.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine aol = {
L"AOL",
L"aol.com",
"http://search.aol.com/favicon.ico",
L"http://search.aol.com/aol/search?query={searchTerms}",
"UTF-8",
NULL,
35,
};
const PrepopulatedEngine aol_fr = {
L"AOL",
L"aol.fr",
"http://www.aol.fr/favicon.ico",
L"http://www.recherche.aol.fr/aol/search?q={searchTerms}",
"UTF-8",
NULL,
35,
};
const PrepopulatedEngine aonde = {
L"AONDE.com",
L"aonde.com",
"http://busca.aonde.com/favicon.ico",
L"http://busca.aonde.com/?keys={searchTerms}",
"ISO-8859-1",
NULL,
80,
};
const PrepopulatedEngine araby = {
L"\x0639\x0631\x0628\x064a",
L"araby.com",
"http://araby.com/favicon.ico",
L"http://araby.com/?q={searchTerms}",
"UTF-8",
NULL,
12,
};
const PrepopulatedEngine ask = {
L"Ask",
L"ask.com",
"http://www.ask.com/favicon.ico",
L"http://www.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_de = {
L"Ask.com Deutschland",
L"de.ask.com",
"http://de.ask.com/favicon.ico",
L"http://de.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.de.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_es = {
L"Ask.com Espa" L"\x00f1" L"a",
L"es.ask.com",
"http://es.ask.com/favicon.ico",
L"http://es.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.es.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_it = {
L"Ask.com Italia",
L"it.ask.com",
"http://it.ask.com/favicon.ico",
L"http://it.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.it.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_uk = {
L"Ask.com UK",
L"uk.ask.com",
"http://uk.ask.com/favicon.ico",
L"http://uk.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.uk.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine atlas_cz = {
L"Atlas",
L"atlas.cz",
"http://img.atlas.cz/favicon.ico",
L"http://search.atlas.cz/?q={searchTerms}",
"windows-1250",
NULL,
27,
};
const PrepopulatedEngine atlas_sk = {
L"ATLAS.SK",
L"atlas.sk",
"http://www.atlas.sk/images/favicon.ico",
L"http://hladaj.atlas.sk/fulltext/?phrase={searchTerms}",
"UTF-8",
NULL,
27,
};
const PrepopulatedEngine baidu = {
L"\x767e\x5ea6",
L"baidu.com",
"http://www.baidu.com/favicon.ico",
L"http://www.baidu.com/s?wd={searchTerms}",
"GB2312",
NULL,
21,
};
const PrepopulatedEngine biglobe = {
L"BIGLOBE",
L"biglobe.ne.jp",
"http://cgi.search.biglobe.ne.jp/favicon.ico",
L"http://cgi.search.biglobe.ne.jp/cgi-bin/search2-b?q={searchTerms}",
"Shift_JIS",
NULL,
64,
};
const PrepopulatedEngine bigmir = {
L"bigmir)net",
L"bigmir.net",
"http://i.bigmir.net/favicon.ico",
L"http://search.bigmir.net/index.php?q={searchTerms}",
"windows-1251",
NULL,
33,
};
const PrepopulatedEngine bluewin = {
L"Bluewin",
L"search.bluewin.ch",
"http://search.bluewin.ch/favicon.ico",
L"http://search.bluewin.ch/bw/search/web/de/result.jsp?query={searchTerms}",
"ISO-8859-1",
NULL,
52,
};
const PrepopulatedEngine centrum_cz = {
L"Centrum.cz",
L"centrum.cz",
"http://img.centrum.cz/6/vy2/o/favicon.ico",
L"http://search.centrum.cz/index.php?charset={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
26,
};
const PrepopulatedEngine centrum_sk = {
L"Centrum.sk",
L"centrum.sk",
"http://img.centrum.sk/4/favicon.ico",
L"http://search.centrum.sk/index.php?charset={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
26,
};
const PrepopulatedEngine conexcol = {
L"Conexcol.com",
L"conexcol.com",
"http://www.conexcol.com/favicon.ico",
L"http://buscar.conexcol.com/cgi-ps/busqueda.cgi?query={searchTerms}",
"ISO-8859-1",
NULL,
91,
};
const PrepopulatedEngine daum = {
L"Daum",
L"daum.net",
"http://search.daum.net/favicon.ico",
L"http://search.daum.net/search?q={searchTerms}",
"EUC-KR",
L"http://sug.search.daum.net/search_nsuggest?mod=fxjson&q={searchTerms}",
68,
};
const PrepopulatedEngine delfi_ee = {
L"DELFI",
L"delfi.ee",
"http://g.delfi.ee/s/search.png",
L"http://otsing.delfi.ee/i.php?q={searchTerms}",
"ISO-8859-1",
NULL,
45,
};
const PrepopulatedEngine delfi_lt = {
L"DELFI",
L"delfi.lt",
"http://search.delfi.lt/img/favicon.png",
L"http://search.delfi.lt/search.php?q={searchTerms}",
"UTF-8",
NULL,
45,
};
const PrepopulatedEngine delfi_lv = {
L"DELFI",
L"delfi.lv",
"http://smart.delfi.lv/img/smart_search.png",
L"http://smart.delfi.lv/i.php?enc={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
45,
};
const PrepopulatedEngine embla = {
L"Embla",
L"embla.is",
"http://embla.is/favicon.ico",
L"http://embla.is/mm/embla/?s={searchTerms}",
"ISO-8859-1",
NULL,
60,
};
const PrepopulatedEngine empas = {
L"\xc5e0\xd30c\xc2a4",
L"empas.com",
"http://search.empas.com/favicon.ico",
L"http://search.empas.com/search/all.html?q={searchTerms}",
"EUC-KR",
// http://www.empas.com/ac/do.tsp?q={searchTerms}
// returns non-Firefox JSON. searchTerms needs to be in Java notation
// (\uAC00\uAC01).
NULL,
70,
};
const PrepopulatedEngine eniro_dk = {
L"Eniro",
L"eniro.dk",
"http://eniro.dk/favicon.ico",
L"http://eniro.dk/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine eniro_fi = {
L"Eniro",
L"eniro.fi",
"http://eniro.fi/favicon.ico",
L"http://eniro.fi/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine eniro_se = {
L"Eniro",
L"eniro.se",
"http://eniro.se/favicon.ico",
L"http://eniro.se/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine finna = {
L"FINNA",
L"finna.is",
"http://finna.is/favicon.ico",
L"http://finna.is/WWW_Search/?query={searchTerms}",
"UTF-8",
NULL,
61,
};
const PrepopulatedEngine fonecta_02_fi = {
L"Fonecta 02.fi",
L"www.fi",
"http://www.02.fi/img/favicon.ico",
L"http://www.02.fi/haku/{searchTerms}",
"UTF-8",
NULL,
46,
};
const PrepopulatedEngine forthnet = {
L"Forthnet",
L"forthnet.gr",
"http://search.forthnet.gr/favicon.ico",
L"http://search.forthnet.gr/cgi-bin/query?mss=search&q={searchTerms}",
"windows-1253",
NULL,
53,
};
const PrepopulatedEngine gigabusca = {
L"GiGaBusca",
L"gigabusca.com.br",
"http://www.gigabusca.com.br/favicon.ico",
L"http://www.gigabusca.com.br/buscar.php?query={searchTerms}",
"ISO-8859-1",
NULL,
81,
};
const PrepopulatedEngine go = {
L"GO.com",
L"go.com",
"http://search.yahoo.com/favicon.ico",
L"http://search.yahoo.com/search?ei={inputEncoding}&p={searchTerms}&"
L"fr=hsusgo1",
"ISO-8859-1",
NULL,
40,
};
const PrepopulatedEngine goo = {
L"goo",
L"goo.ne.jp",
"http://goo.ne.jp/gooicon.ico",
L"http://search.goo.ne.jp/web.jsp?MT={searchTerms}&IE={inputEncoding}",
"UTF-8",
NULL,
92,
};
const PrepopulatedEngine google = {
L"Google",
NULL,
"http://www.google.com/favicon.ico",
L"{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}"
L"{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&"
L"q={searchTerms}",
"UTF-8",
L"{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}",
1,
};
const PrepopulatedEngine guruji = {
L"guruji",
L"guruji.com",
"http://guruji.com/favicon.ico",
L"http://guruji.com/search?q={searchTerms}",
"UTF-8",
NULL,
38,
};
const PrepopulatedEngine iafrica = {
L"iafrica.com",
L"iafrica.com",
NULL,
L"http://search.iafrica.com/search?q={searchTerms}",
"ISO-8859-1",
NULL,
43,
};
const PrepopulatedEngine ilse = {
L"Ilse",
L"ilse.nl",
"http://search.ilse.nl/images/favicon.ico",
L"http://search.ilse.nl/web?search_for={searchTerms}",
"ISO-8859-1",
NULL,
30,
};
const PrepopulatedEngine in = {
L"in.gr",
L"in.gr",
"http://www.in.gr/favicon.ico",
L"http://find.in.gr/result.asp?q={searchTerms}",
"ISO-8859-7",
NULL,
54,
};
const PrepopulatedEngine jabse = {
L"Jabse",
L"jabse.com",
"http://www.jabse.com/favicon.ico",
L"http://www.jabse.com/searchmachine.php?query={searchTerms}",
"UTF-8",
NULL,
19,
};
const PrepopulatedEngine jamaicalive = {
L"JamaicaLive",
L"jalive.com.jm",
"http://jalive.com.jm/favicon.ico",
L"http://jalive.com.jm/search/?mode=allwords&search={searchTerms}",
"ISO-8859-1",
NULL,
39,
};
const PrepopulatedEngine jubii = {
L"Jubii",
L"jubii.dk",
"http://search.jubii.dk/favicon_jubii.ico",
L"http://search.jubii.dk/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
28,
};
const PrepopulatedEngine krstarica = {
L"Krstarica",
L"krstarica.rs",
"http://pretraga.krstarica.com/favicon.ico",
L"http://pretraga.krstarica.com/index.php?q={searchTerms}",
"windows-1250",
NULL,
84,
};
const PrepopulatedEngine kvasir = {
L"Kvasir",
L"kvasir.no",
"http://www.kvasir.no/img/favicon.ico",
L"http://www.kvasir.no/nettsok/searchResult.html?searchExpr={searchTerms}",
"ISO-8859-1",
NULL,
73,
};
const PrepopulatedEngine latne = {
L"LATNE",
L"latne.lv",
"http://latne.lv/favicon.ico",
L"http://latne.lv/siets.php?q={searchTerms}",
"UTF-8",
NULL,
71,
};
const PrepopulatedEngine leit = {
L"leit.is",
L"leit.is",
"http://leit.is/leit.ico",
L"http://leit.is/query.aspx?qt={searchTerms}",
"ISO-8859-1",
NULL,
59,
};
const PrepopulatedEngine libero = {
L"Libero",
L"libero.it",
"http://arianna.libero.it/favicon.ico",
L"http://arianna.libero.it/search/abin/integrata.cgi?query={searchTerms}",
"ISO-8859-1",
NULL,
63,
};
const PrepopulatedEngine live = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ar_XA = {
L"Live Search (\x0627\x0644\x0639\x0631\x0628\x064a\x0629)",
L"", // "live.com" is already taken by live_en_XA (see comment on ID below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=ar-XA&mkt=ar-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
7, // Can't be 3 as this has to appear in the Arabian countries' lists
// alongside live_en_XA.
};
const PrepopulatedEngine live_bg_BG = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=bg-BG&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_cs_CZ = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=cs-CZ&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_el_GR = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=el-GR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_ID = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en_ID&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_NZ = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-NZ&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_US = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-US&mkt=en-US&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_XA = {
L"Live Search (English)",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-XA&mkt=en-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_et_EE = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=et-EE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_hr_HR = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=hr-HR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_hu_HU = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=hu-HU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_it_IT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=it-IT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_lt_LT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=lt-LT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_pl_PL = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pl-PL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_pt_PT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pt-PT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ro_RO = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=ro-RO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ru_RU = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=ru-RU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_sk_SK = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=sk-SK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_sl_SI = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=sl-SI&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_th_TH = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=th-TH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine lycos_es = {
L"Lycos Espa" L"\x00f1" L"a",
L"lycos.es",
"http://buscador.lycos.es/favicon.ico",
L"http://buscador.lycos.es/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
34,
};
const PrepopulatedEngine lycos_nl = {
L"Lycos",
L"lycos.nl",
"http://zoek.lycos.nl/favicon.ico",
L"http://zoek.lycos.nl/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
34,
};
const PrepopulatedEngine mail_ru = {
L"@MAIL.RU",
L"mail.ru",
"http://img.go.mail.ru/favicon.ico",
L"http://go.mail.ru/search?q={searchTerms}",
"windows-1251",
NULL,
83,
};
const PrepopulatedEngine maktoob = {
L"\x0645\x0643\x062a\x0648\x0628",
L"maktoob.com",
"http://www.maktoob.com/favicon.ico",
L"http://www.maktoob.com/searchResult.php?q={searchTerms}",
"UTF-8",
NULL,
13,
};
const PrepopulatedEngine masrawy = {
L"\x0645\x0635\x0631\x0627\x0648\x064a",
L"masrawy.com",
"http://www.masrawy.com/new/images/masrawy.ico",
L"http://masrawy.com/new/search.aspx?sr={searchTerms}",
"windows-1256",
NULL,
14,
};
const PrepopulatedEngine matkurja = {
L"Mat'Kurja",
L"matkurja.com",
"http://matkurja.com/favicon.ico",
L"http://matkurja.com/si/iskalnik/?q={searchTerms}&search_source=directory",
"ISO-8859-2",
NULL,
88,
};
const PrepopulatedEngine meta = {
L"<META>",
L"meta.ua",
"http://meta.ua/favicon.ico",
L"http://meta.ua/search.asp?q={searchTerms}",
"windows-1251",
L"http://meta.ua/suggestions/?output=fxjson&oe=utf-8&q={searchTerms}",
102,
};
const PrepopulatedEngine msn = {
L"MSN",
L"msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_ar_XA = {
L"MSN (\x0627\x0644\x0639\x0631\x0628\x064a\x0629)",
L"", // "arabia.msn.com" is already taken by msn_en_XA (see comment on ID
// below).
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?setlang=ar-XA&mkt=ar-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
7, // Can't be 3 as this has to appear in the Arabian countries' lists
// alongside msn_en_XA.
};
const PrepopulatedEngine msn_da_DK = {
L"MSN Danmark",
L"dk.msn.com",
"http://search.msn.dk/s/wlflag.ico",
L"http://search.msn.dk/results.aspx?mkt=da-DK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_AT = {
L"MSN \x00d6sterreich",
L"at.msn.com",
"http://search.msn.at/s/wlflag.ico",
L"http://search.msn.at/results.aspx?mkt=de-AT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_CH = {
L"MSN Schweiz (Deutsch)",
L"ch.msn.com",
"http://search.msn.ch/s/wlflag.ico",
L"http://search.msn.ch/results.aspx?setlang=de-CH&mkt=de-CH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_DE = {
L"MSN",
L"de.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=de-DE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_AU = {
L"ninemsn.com.au",
L"ninemsn.com.au",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-AU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_CA = {
L"Sympatico / MSN (English)",
L"sympatico.msn.ca",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-CA&mkt=en-CA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_GB = {
L"MSN UK",
L"uk.msn.com",
"http://search.msn.co.uk/s/wlflag.ico",
L"http://search.msn.co.uk/results.aspx?mkt=en-GB&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_IE = {
L"MSN IE",
L"ie.msn.com",
"http://search.msn.ie/s/wlflag.ico",
L"http://search.msn.ie/results.aspx?mkt=en-IE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_IN = {
L"MSN India",
L"in.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-IN&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_MY = {
L"MSN Malaysia",
L"malaysia.msn.com",
"http://search.msn.com.my/s/wlflag.ico",
L"http://search.msn.com.my/results.aspx?mkt=en-MY&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_PH = {
L"MSN Philippines",
L"ph.msn.com",
"http://search.msn.com.ph/s/wlflag.ico",
L"http://search.msn.com.ph/results.aspx?mkt=en-PH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_SG = {
L"MSN Singapore",
L"sg.msn.com",
"http://search.msn.com.sg/s/wlflag.ico",
L"http://search.msn.com.sg/results.aspx?mkt=en-SG&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_XA = {
L"MSN (English)",
L"arabia.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?setlang=en-XA&mkt=en-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_ZA = {
L"MSN ZA",
L"za.msn.com",
"http://search.msn.co.za/s/wlflag.ico",
L"http://search.msn.co.za/results.aspx?mkt=en-ZA&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_AR = {
L"MSN Argentina",
L"ar.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-AR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_CL = {
L"MSN Chile",
L"cl.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-CL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_CO = {
L"MSN Colombia",
L"co.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-CO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_ES = {
L"MSN Espa" L"\x00f1" L"a",
L"es.msn.com",
"http://search.msn.es/s/wlflag.ico",
L"http://search.msn.es/results.aspx?mkt=es-ES&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_MX = {
L"Prodigy / MSN",
L"prodigy.msn.com",
"http://search.prodigy.msn.com/s/wlflag.ico",
L"http://search.prodigy.msn.com/results.aspx?mkt=es-MX&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_XL = {
L"MSN Latinoam\x00e9rica",
L"latam.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-XL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_fi_FI = {
L"MSN",
L"fi.msn.com",
"http://search.msn.fi/s/wlflag.ico",
L"http://search.msn.fi/results.aspx?mkt=fi-FI&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_fr_BE = {
L"MSN Belgique (Fran" L"\x00e7" L"ais)",
L"", // "be.msn.com" is already taken by msn_nl_BE (see comment on ID below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=fr-BE&mkt=fr-BE&"
L"q={searchTerms}",
"UTF-8",
NULL,
8, // Can't be 3 as this has to appear in the Belgium list alongside
// msn_nl_BE.
};
const PrepopulatedEngine msn_fr_CA = {
L"Sympatico / MSN (Fran" L"\x00e7" L"ais)",
L"", // "sympatico.msn.ca" is already taken by msn_en_CA (see comment on ID
// below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=fr-CA&mkt=fr-CA&"
L"q={searchTerms}",
"UTF-8",
NULL,
9, // Can't be 3 as this has to appear in the Canada list alongside
// msn_en_CA.
};
const PrepopulatedEngine msn_fr_CH = {
L"MSN Suisse (Fran" L"\x00e7" L"ais)",
L"", // "ch.msn.com" is already taken by msn_de_CH (see comment on ID below).
"http://search.msn.ch/s/wlflag.ico",
L"http://search.msn.ch/results.aspx?setlang=fr-CH&mkt=fr-CH&q={searchTerms}",
"UTF-8",
NULL,
10, // Can't be 3 as this has to appear in the Switzerland list alongside
// msn_de_CH.
};
const PrepopulatedEngine msn_fr_FR = {
L"MSN France",
L"fr.msn.com",
"http://search.msn.fr/s/wlflag.ico",
L"http://search.msn.fr/results.aspx?mkt=fr-FR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_he_IL = {
L"msn.co.il",
L"msn.co.il",
"http://msn.co.il/favicon.ico",
L"http://search.msn.co.il/Search.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_ja_JP = {
L"MSN Japan",
L"jp.msn.com",
"http://search.msn.co.jp/s/wlflag.ico",
L"http://search.msn.co.jp/results.aspx?mkt=ja-JP&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nb_NO = {
L"MSN Norge",
L"no.msn.com",
"http://search.msn.no/s/wlflag.ico",
L"http://search.msn.no/results.aspx?mkt=nb-NO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nl_BE = {
L"MSN (Nederlandstalige)",
L"be.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=nl-BE&mkt=nl-BE&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nl_NL = {
L"MSN.nl",
L"nl.msn.com",
"http://search.msn.nl/s/wlflag.ico",
L"http://search.msn.nl/results.aspx?mkt=nl-NL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_pt_BR = {
L"MSN Brasil",
L"br.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pt-BR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_sv_SE = {
L"MSN",
L"se.msn.com",
"http://search.msn.se/s/wlflag.ico",
L"http://search.msn.se/results.aspx?mkt=pv-SE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_tr_TR = {
L"MSN T\x00fckiye'ye",
L"tr.msn.com",
"http://search.msn.com.tr/s/wlflag.ico",
L"http://search.msn.com.tr/results.aspx?mkt=tr-TR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_zh_HK = {
L"MSN Hong Kong",
L"hk.msn.com",
"http://search.msn.com.hk/s/wlflag.ico",
L"http://search.msn.com.hk/results.aspx?mkt=zh-HK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine mweb = {
L"MWEB",
L"mweb.co.za",
"http://mweb.co.za/favicon.ico",
L"http://search.mweb.co.za/search?&q={searchTerms}",
"UTF-8",
NULL,
42,
};
const PrepopulatedEngine mynet = {
L"MYNET",
L"mynet.com",
"http://img.mynet.com/mynetfavori.ico",
L"http://arama.mynet.com/search.aspx?q={searchTerms}&pg=q",
"windows-1254",
NULL,
101,
};
const PrepopulatedEngine mywebsearch = {
L"mywebsearch",
L"mywebsearch.com",
NULL,
L"http://search.mywebsearch.com/mywebsearch/AJmain.jhtml?"
L"searchfor={searchTerms}",
"UTF-8",
NULL,
97,
};
const PrepopulatedEngine najdi = {
L"Najdi.si",
L"najdi.si",
"http://www.najdi.si/master/favicon.ico",
L"http://www.najdi.si/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
87,
};
const PrepopulatedEngine nana10 = {
L"\x05e0\x05e2\x05e0\x05e2 10",
L"nana10.co.il",
"http://f.nau.co.il/Common/Includes/favicon.ico",
L"http://index.nana10.co.il/search.asp?q={searchTerms}",
"windows-1255",
NULL,
56,
};
const PrepopulatedEngine nate = {
L"\xb124\xc774\xd2b8\xb2f7\xcef4",
L"nate.com",
"http://nate.search.empas.com/favicon.ico",
L"http://nate.search.empas.com/search/all.html?q={searchTerms}",
"EUC-KR",
NULL,
69,
};
const PrepopulatedEngine naver = {
L"\xb124\xc774\xbc84",
L"naver.com",
"http://search.naver.com/favicon.ico",
L"http://search.naver.com/search.naver?ie={inputEncoding}"
L"&query={searchTerms}",
"UTF-8",
L"http://ac.search.naver.com/autocompl?m=s&ie={inputEncoding}&oe=utf-8&"
L"q={searchTerms}",
67,
};
const PrepopulatedEngine neti = {
L"NETI",
L"neti.ee",
"http://www.neti.ee/favicon.ico",
L"http://www.neti.ee/cgi-bin/otsing?query={searchTerms}",
"ISO-8859-1",
NULL,
44,
};
const PrepopulatedEngine netindex = {
L"NetINDEX",
L"netindex.pt",
"http://www.netindex.pt/favicon.ico",
L"http://www.netindex.pt/cgi-bin/index.cgi?question={searchTerms}",
"ISO-8859-1",
NULL,
78,
};
const PrepopulatedEngine nifty = {
L"@nifty",
L"nifty.com",
"http://www.nifty.com/favicon.ico",
L"http://search.nifty.com/cgi-bin/search.cgi?Text={searchTerms}",
"Shift_JIS",
NULL,
65,
};
const PrepopulatedEngine ohperu = {
L"Oh Per\x00fa",
L"ohperu.com",
NULL,
L"http://www.google.com.pe/custom?q={searchTerms}&"
L"client=pub-1950414869696311&ie={inputEncoding}&cof=GALT%3A%23000000"
L"%3BGL%3A1%3BDIV%3A%23FFFFFF%3BVLC%3A000000%3BAH%3Acenter%3BBGC%3AFFFFFF"
L"%3BLBGC%3AFFFFFF%3BALC%3A000000%3BLC%3A000000%3BT%3A000000%3BGFNT"
L"%3A000000%3BGIMP%3A000000%3BLH%3A50%3BLW%3A142%3BL%3Ahttp%3A%2F%2F"
L"www.ohperu.com%2Fohperu-logo-inv2.gif%3BS%3Ahttp%3A%2F%2Fwww.ohperu.com"
L"%3BFORID%3A1",
"ISO-8859-1",
NULL,
96,
};
const PrepopulatedEngine ok = {
L"OK.hu",
L"ok.hu",
"http://ok.hu/gfx/favicon.ico",
L"http://ok.hu/katalogus?q={searchTerms}",
"ISO-8859-2",
NULL,
6,
};
const PrepopulatedEngine onet = {
L"Onet.pl",
L"onet.pl",
"http://szukaj.onet.pl/favicon.ico",
L"http://szukaj.onet.pl/query.html?qt={searchTerms}",
"ISO-8859-2",
NULL,
75,
};
const PrepopulatedEngine orange = {
L"Orange",
L"orange.fr",
"http://www.orange.fr/favicon.ico",
L"http://rws.search.ke.voila.fr/RW/S/opensearch_orange?rdata={searchTerms}",
"ISO-8859-1",
L"http://search.ke.voila.fr/fr/cmplopensearch/xml/fullxml?"
L"rdata={searchTerms}",
48,
};
const PrepopulatedEngine ozu = {
L"OZ\x00da",
L"ozu.es",
"http://www.ozu.es/favicon.ico",
L"http://buscar.ozu.es/index.php?q={searchTerms}",
"ISO-8859-1",
NULL,
98,
};
const PrepopulatedEngine pogodak_ba = {
L"Pogodak!",
L"pogodak.ba",
"http://www.pogodak.ba/favicon.ico",
L"http://www.pogodak.ba/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodak_hr = {
L"Pogodak!",
L"pogodak.hr",
"http://www.pogodak.hr/favicon.ico",
L"http://www.pogodak.hr/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodak_rs = {
L"Pogodak!",
L"pogodak.rs",
"http://www.pogodak.rs/favicon.ico",
L"http://www.pogodak.rs/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodok = {
L"\x041f\x043e\x0433\x043e\x0434\x043e\x043a!",
L"pogodok.com.mk",
"http://www.pogodok.com.mk/favicon.ico",
L"http://www.pogodok.com.mk/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24, // Really the same engine as Pogodak, just has a small name change.
};
const PrepopulatedEngine rambler = {
L"Rambler",
L"rambler.ru",
"http://www.rambler.ru/favicon.ico",
L"http://www.rambler.ru/srch?words={searchTerms}",
"windows-1251",
NULL,
16,
};
const PrepopulatedEngine rediff = {
L"Rediff",
L"rediff.com",
"http://search1.rediff.com/favicon.ico",
L"http://search1.rediff.com/dirsrch/default.asp?MT={searchTerms}",
"UTF-8",
NULL,
37,
};
const PrepopulatedEngine rednano = {
L"Rednano",
L"rednano.sg",
"http://rednano.sg/favicon.ico",
L"http://rednano.sg/sfe/lwi.action?querystring={searchTerms}",
"UTF-8",
NULL,
41,
};
const PrepopulatedEngine sanook = {
L"\x0e2a\x0e19\x0e38\x0e01!",
L"sanook.com",
"http://search.sanook.com/favicon.ico",
L"http://search.sanook.com/search.php?q={searchTerms}",
"UTF-8",
NULL,
100,
};
const PrepopulatedEngine sapo = {
L"SAPO",
L"sapo.pt",
"http://imgs.sapo.pt/images/sapo.ico",
L"http://pesquisa.sapo.pt/?q={searchTerms}",
"UTF-8",
L"http://pesquisa.sapo.pt/livesapo?q={searchTerms}",
77,
};
const PrepopulatedEngine search_ch = {
L"search.ch",
L"search.ch",
"http://www.search.ch/favicon.ico",
L"http://www.search.ch/?q={searchTerms}",
"ISO-8859-1",
NULL,
51,
};
const PrepopulatedEngine sensis = {
L"sensis.com.au",
L"sensis.com.au",
"http://www.sensis.com.au/favicon.ico",
L"http://www.sensis.com.au/search.do?find={searchTerms}",
"UTF-8",
NULL,
32,
};
const PrepopulatedEngine sesam = {
L"Sesam",
L"sesam.no",
"http://sesam.no/images/favicon.gif",
L"http://sesam.no/search/?q={searchTerms}",
"UTF-8",
NULL,
74,
};
const PrepopulatedEngine seznam = {
L"Seznam",
L"seznam.cz",
"http://1.im.cz/szn/img/favicon.ico",
L"http://search.seznam.cz/?q={searchTerms}",
"UTF-8",
L"http:///suggest.fulltext.seznam.cz/?dict=fulltext_ff&phrase={searchTerms}&"
L"encoding={inputEncoding}&response_encoding=utf-8",
25,
};
const PrepopulatedEngine sogou = {
L"\x641c\x72d7",
L"sogou.com",
"http://www.sogou.com/favicon.ico",
L"http://www.sogou.com/web?query={searchTerms}",
"GB2312",
NULL,
20,
};
const PrepopulatedEngine soso = {
L"\x641c\x641c",
L"soso.com",
"http://www.soso.com/favicon.ico",
L"http://www.soso.com/q?w={searchTerms}",
"GB2312",
NULL,
22,
};
const PrepopulatedEngine spray = {
L"Spray",
L"spray.se",
"http://www.eniro.se/favicon.ico",
L"http://www.eniro.se/query?ax=spray&search_word={searchTerms}&what=web",
"ISO-8859-1",
NULL,
99,
};
const PrepopulatedEngine szm = {
L"SZM.sk",
L"szm.sk",
"http://szm.sk/favicon.ico",
L"http://szm.sk/search/?co=1&q={searchTerms}",
"windows-1250",
NULL,
86,
};
const PrepopulatedEngine t_online = {
L"T-Online",
L"suche.t-online.de",
"http://suche.t-online.de/favicon.ico",
L"http://suche.t-online.de/fast-cgi/tsc?sr=chrome&q={searchTerms}",
"UTF-8",
NULL,
49,
};
const PrepopulatedEngine tango = {
L"Tango",
L"tango.hu",
"http://tango.hu/favicon.ico",
L"http://tango.hu/search.php?q={searchTerms}",
"windows-1250",
NULL,
58,
};
const PrepopulatedEngine tapuz = {
L"\x05ea\x05e4\x05d5\x05d6 \x05d0\x05e0\x05e9\x05d9\x05dd",
L"tapuz.co.il",
"http://www.tapuz.co.il/favicon.ico",
L"http://www.tapuz.co.il/search/search.asp?q={searchTerms}",
"UTF-8",
NULL,
57,
};
const PrepopulatedEngine terra_ar = {
L"Terra Argentina",
L"terra.com.ar",
"http://buscar.terra.com.ar/favicon.ico",
L"http://buscar.terra.com.ar/Default.aspx?query={searchTerms}&source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_ec = {
L"Terra Ecuador",
L"terra.com.ec",
"http://buscador.terra.com.ec/favicon.ico",
L"http://buscador.terra.com.ec/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_es = {
L"Terra",
L"terra.es",
"http://buscador.terra.es/favicon.ico",
L"http://buscador.terra.es/Default.aspx?query={searchTerms}&source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_mx = {
L"Terra",
L"terra.com.mx",
"http://buscador.terra.com.mx/favicon.ico",
L"http://buscador.terra.com.mx/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_pe = {
L"Terra",
L"terra.com.pe",
"http://buscador.terra.com.pe/favicon.ico",
L"http://buscador.terra.com.pe/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine toile = {
L"La Toile du Qu" L"\x00e9" L"bec",
L"toile.com",
"http://static.search.canoe.ca/s-toile/img/favicon_toile.ico",
L"http://www.toile.com/search?q={searchTerms}",
"UTF-8",
NULL,
36,
};
const PrepopulatedEngine tut = {
L"TUT.BY",
L"tut.by",
"http://www.tut.by/favicon.ico",
L"http://search.tut.by/?query={searchTerms}",
"windows-1251",
NULL,
17,
};
const PrepopulatedEngine uol = {
L"UOL Busca",
L"busca.uol.com.br",
"http://busca.uol.com.br/favicon.ico",
L"http://busca.uol.com.br/www/index.html?q={searchTerms}",
"ISO-8859-1",
NULL,
82,
};
const PrepopulatedEngine vinden = {
L"Vinden.nl",
L"vinden.nl",
"http://www.vinden.nl/favicon.ico",
L"http://www.vinden.nl/?q={searchTerms}",
"UTF-8",
NULL,
31,
};
const PrepopulatedEngine virgilio = {
L"Virgilio",
L"virgilio.alice.it",
"http://ricerca.alice.it/favicon.ico",
L"http://ricerca.alice.it/ricerca?qs={searchTerms}",
"ISO-8859-1",
NULL,
62,
};
const PrepopulatedEngine voila = {
L"Voila",
L"voila.fr",
"http://search.ke.voila.fr/favicon.ico",
L"http://rws.search.ke.voila.fr/RW/S/opensearch_voila?rdata={searchTerms}",
"ISO-8859-1",
L"http://search.ke.voila.fr/fr/cmplopensearch/xml/fullxml?"
L"rdata={searchTerms}",
47,
};
const PrepopulatedEngine walla = {
L"\x05d5\x05d5\x05d0\x05dc\x05d4!",
L"walla.co.il",
"http://www.walla.co.il/favicon.ico",
L"http://search.walla.co.il/?e=hew&q={searchTerms}",
"windows-1255",
NULL,
55,
};
const PrepopulatedEngine web_de = {
L"WEB.DE",
L"web.de",
"http://img.ui-portal.de/search/img/webde/favicon.ico",
L"http://suche.web.de/search/web/?su={searchTerms}",
"ISO-8859-1",
NULL,
50,
};
const PrepopulatedEngine wp = {
L"Wirtualna Polska",
L"wp.pl",
"http://szukaj.wp.pl/favicon.ico",
L"http://szukaj.wp.pl/szukaj.html?szukaj={searchTerms}",
"ISO-8859-2",
NULL,
76,
};
const PrepopulatedEngine yagua = {
L"Yagua.com",
L"yagua.com",
"http://yagua.paraguay.com/favicon.ico",
L"http://yagua.paraguay.com/buscador.php?q={searchTerms}&cs={inputEncoding}",
"ISO-8859-1",
NULL,
94,
};
const PrepopulatedEngine yahoo = {
L"Yahoo!",
L"yahoo.com",
"http://search.yahoo.com/favicon.ico",
L"http://search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}",
"UTF-8",
L"http://ff.search.yahoo.com/gossip?output=fxjson&command={searchTerms}",
2,
};
// For regional Yahoo variants without region-specific suggestion service,
// suggestion is disabled. For some of them, we might consider
// using a fallback (e.g. de for at/ch, ca or fr for qc, en for nl, no, hk).
const PrepopulatedEngine yahoo_ar = {
L"Yahoo! Argentina",
L"ar.yahoo.com",
"http://ar.search.yahoo.com/favicon.ico",
L"http://ar.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://ar-sayt.ff.search.yahoo.com/gossip-ar-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_at = {
L"Yahoo! Suche",
L"at.yahoo.com",
"http://at.search.yahoo.com/favicon.ico",
L"http://at.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_au = {
L"Yahoo!7",
L"au.yahoo.com",
"http://au.search.yahoo.com/favicon.ico",
L"http://au.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://aue-sayt.ff.search.yahoo.com/gossip-au-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_br = {
L"Yahoo! Brasil",
L"br.yahoo.com",
"http://br.search.yahoo.com/favicon.ico",
L"http://br.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://br-sayt.ff.search.yahoo.com/gossip-br-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ca = {
L"Yahoo! Canada",
L"ca.yahoo.com",
"http://ca.search.yahoo.com/favicon.ico",
L"http://ca.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.ca.yahoo.com/gossip-ca-sayt?output=fxjsonp&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ch = {
L"Yahoo! Suche",
L"ch.yahoo.com",
"http://ch.search.yahoo.com/favicon.ico",
L"http://ch.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_cl = {
L"Yahoo! Chile",
L"cl.yahoo.com",
"http://cl.search.yahoo.com/favicon.ico",
L"http://cl.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_cn = {
L"\x4e2d\x56fd\x96c5\x864e",
L"cn.yahoo.com",
"http://search.cn.yahoo.com/favicon.ico",
L"http://search.cn.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"GB2312",
// http://cn.yahoo.com/cnsuggestion/suggestion.inc.php?of=fxjson&query=
// returns in a proprietary format ('|' delimeted word list).
NULL,
2,
};
const PrepopulatedEngine yahoo_co = {
L"Yahoo! Colombia",
L"co.yahoo.com",
"http://co.search.yahoo.com/favicon.ico",
L"http://co.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_de = {
L"Yahoo! Deutschland",
L"de.yahoo.com",
"http://de.search.yahoo.com/favicon.ico",
L"http://de.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://de-sayt.ff.search.yahoo.com/gossip-de-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_dk = {
L"Yahoo! Danmark",
L"dk.yahoo.com",
"http://dk.search.yahoo.com/favicon.ico",
L"http://dk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_es = {
L"Yahoo! Espa" L"\x00f1" L"a",
L"es.yahoo.com",
"http://es.search.yahoo.com/favicon.ico",
L"http://es.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://es-sayt.ff.search.yahoo.com/gossip-es-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_fi = {
L"Yahoo!-haku",
L"fi.yahoo.com",
"http://fi.search.yahoo.com/favicon.ico",
L"http://fi.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_fr = {
L"Yahoo! France",
L"fr.yahoo.com",
"http://fr.search.yahoo.com/favicon.ico",
L"http://fr.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://fr-sayt.ff.search.yahoo.com/gossip-fr-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_hk = {
L"Yahoo! Hong Kong",
L"hk.yahoo.com",
"http://hk.search.yahoo.com/favicon.ico",
L"http://hk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
// http://history.hk.search.yahoo.com/ac/ac_msearch.php?query={searchTerms}
// returns a JSON with key-value pairs. Setting parameters (ot, of, output)
// to fxjson, json, or js doesn't help.
NULL,
2,
};
const PrepopulatedEngine yahoo_id = {
L"Yahoo! Indonesia",
L"id.yahoo.com",
"http://id.search.yahoo.com/favicon.ico",
L"http://id.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://id-sayt.ff.search.yahoo.com/gossip-id-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_in = {
L"Yahoo! India",
L"in.yahoo.com",
"http://in.search.yahoo.com/favicon.ico",
L"http://in.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://in-sayt.ff.search.yahoo.com/gossip-in-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_it = {
L"Yahoo! Italia",
L"it.yahoo.com",
"http://it.search.yahoo.com/favicon.ico",
L"http://it.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://it-sayt.ff.search.yahoo.com/gossip-it-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_jp = {
L"Yahoo! JAPAN",
L"yahoo.co.jp",
"http://search.yahoo.co.jp/favicon.ico",
L"http://search.yahoo.co.jp/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_kr = {
L"\xc57c\xd6c4! \xcf54\xb9ac\xc544",
L"kr.yahoo.com",
"http://kr.search.yahoo.com/favicon.ico",
L"http://kr.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://kr.atc.search.yahoo.com/atcx.php?property=main&ot=fxjson&"
L"ei=utf8&eo=utf8&command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_malaysia = {
L"Yahoo! Malaysia",
L"malaysia.yahoo.com",
"http://malaysia.search.yahoo.com/favicon.ico",
L"http://malaysia.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://my-sayt.ff.search.yahoo.com/gossip-my-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_mx = {
L"Yahoo! M\x00e9xico",
L"mx.yahoo.com",
"http://mx.search.yahoo.com/favicon.ico",
L"http://mx.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.mx.yahoo.com/gossip-mx-sayt?output=fxjsonp&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_nl = {
L"Yahoo! Nederland",
L"nl.yahoo.com",
"http://nl.search.yahoo.com/favicon.ico",
L"http://nl.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_no = {
L"Yahoo! Norge",
L"no.yahoo.com",
"http://no.search.yahoo.com/favicon.ico",
L"http://no.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_nz = {
L"Yahoo!Xtra",
L"nz.yahoo.com",
"http://nz.search.yahoo.com/favicon.ico",
L"http://nz.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://aue-sayt.ff.search.yahoo.com/gossip-nz-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_pe = {
L"Yahoo! Per\x00fa",
L"pe.yahoo.com",
"http://pe.search.yahoo.com/favicon.ico",
L"http://pe.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ph = {
L"Yahoo! Philippines",
L"ph.yahoo.com",
"http://ph.search.yahoo.com/favicon.ico",
L"http://ph.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://ph-sayt.ff.search.yahoo.com/gossip-ph-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_qc = {
L"Yahoo! Qu" L"\x00e9" L"bec",
L"qc.yahoo.com",
"http://qc.search.yahoo.com/favicon.ico",
L"http://qc.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
5, // Can't be 2 as this has to appear in the Canada list alongside yahoo_ca.
};
const PrepopulatedEngine yahoo_ru = {
L"Yahoo! \x043f\x043e-\x0440\x0443\x0441\x0441\x043a\x0438",
L"ru.yahoo.com",
"http://ru.search.yahoo.com/favicon.ico",
L"http://ru.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_sg = {
L"Yahoo! Singapore",
L"sg.yahoo.com",
"http://sg.search.yahoo.com/favicon.ico",
L"http://sg.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://sg-sayt.ff.search.yahoo.com/gossip-sg-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_th = {
L"Yahoo! \x0e1b\x0e23\x0e30\x0e40\x0e17\x0e28\x0e44\x0e17\x0e22",
L"th.yahoo.com",
"http://th.search.yahoo.com/favicon.ico",
L"http://th.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://th-sayt.ff.search.yahoo.com/gossip-th-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_tw = {
L"Yahoo!\x5947\x6469",
L"tw.yahoo.com",
"http://tw.search.yahoo.com/favicon.ico",
L"http://tw.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
// "http://tw.yahoo.com/ac/ac_search.php?eo=utf8&of=js&prop=web&query="
// returns a JSON file prepended with 'fxjson={'.
NULL,
2,
};
const PrepopulatedEngine yahoo_uk = {
L"Yahoo! UK & Ireland",
L"uk.yahoo.com",
"http://uk.search.yahoo.com/favicon.ico",
L"http://uk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://uk-sayt.ff.search.yahoo.com/gossip-uk-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ve = {
L"Yahoo! Venezuela",
L"ve.yahoo.com",
"http://ve.search.yahoo.com/favicon.ico",
L"http://ve.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_vn = {
L"Yahoo! Vi\x1ec7t Nam",
L"vn.yahoo.com",
"http://vn.search.yahoo.com/favicon.ico",
L"http://vn.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://vn-sayt.ff.search.yahoo.com/gossip-vn-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yam = {
L"\u5929\u7a7a",
L"yam.com",
"http://www.yam.com/i/8/sky.ico",
L"http://search.yam.com/wps?k={searchTerms}",
"Big5",
NULL,
23,
};
const PrepopulatedEngine yamli = {
L"Yamli",
L"yamli.com",
"http://www.yamli.com/favicon.ico",
L"http://www.yamli.com/#q={searchTerms}",
"UTF-8",
NULL,
11,
};
const PrepopulatedEngine yandex_ru = {
L"\x042f\x043d\x0434\x0435\x043a\x0441",
L"yandex.ru",
"http://yandex.ru/favicon.ico",
L"http://yandex.ru/yandsearch?text={searchTerms}",
"UTF-8",
L"http://suggest.yandex.net/suggest-ff.cgi?part={searchTerms}",
15,
};
const PrepopulatedEngine yandex_ua = {
L"\x042f\x043d\x0434\x0435\x043a\x0441",
L"yandex.ua",
"http://yandex.ua/favicon.ico",
L"http://yandex.ua/yandsearch?text={searchTerms}",
"UTF-8",
L"http://suggest.yandex.net/suggest-ff.cgi?part={searchTerms}",
15,
};
const PrepopulatedEngine zoznam = {
L"Zoznam",
L"zoznam.sk",
"http://zoznam.sk/favicon.ico",
L"http://zoznam.sk/hladaj.fcgi?s={searchTerms}",
"windows-1250",
NULL,
85,
};
// Lists of engines per country ////////////////////////////////////////////////
// Put these in order with most interesting/important first. The default will
// be the first engine.
// Default (for countries with no better engine set)
const PrepopulatedEngine* engines_default[] = { &google, &yahoo, &live, };
// United Arab Emirates
const PrepopulatedEngine* engines_AE[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Albania
const PrepopulatedEngine* engines_AL[] =
{ &google, &yahoo, &live_en_XA, &live_ar_XA, };
// Argentina
const PrepopulatedEngine* engines_AR[] =
{ &google, &msn_es_AR, &altavista_ar, &terra_ar, &yahoo_ar, };
// Austria
const PrepopulatedEngine* engines_AT[] = { &google, &yahoo_at, &msn_de_AT, };
// Australia
const PrepopulatedEngine* engines_AU[] =
{ &google, &yahoo_au, &msn_en_AU, &sensis, };
// Bosnia and Herzegovina
const PrepopulatedEngine* engines_BA[] =
{ &google, &pogodak_ba, &yahoo, &live, };
// Belgium
const PrepopulatedEngine* engines_BE[] =
{ &google, &yahoo, &msn_nl_BE, &msn_fr_BE, };
// Bulgaria
// The commented-out entry for "dir" below is for dir.bg, &which we don't
// currently support because it uses POST instead of GET for its searches.
// See http://b/1196285
const PrepopulatedEngine* engines_BG[] =
{ &google, &/*dir,*/ yahoo, &jabse, &live_bg_BG, };
// Bahrain
const PrepopulatedEngine* engines_BH[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Brunei
const PrepopulatedEngine* engines_BN[] =
{ &google, &yahoo_malaysia, &msn_en_MY, };
// Bolivia
const PrepopulatedEngine* engines_BO[] =
{ &google, &altavista, &msn_es_XL, &yahoo, &ask_es, };
// Brazil
const PrepopulatedEngine* engines_BR[] =
{ &google, &msn_pt_BR, &yahoo_br, &aonde, &gigabusca, &uol, };
// Belarus
const PrepopulatedEngine* engines_BY[] =
{ &google, &yandex_ru, &rambler, &yahoo, &tut, };
// Belize
const PrepopulatedEngine* engines_BZ[] = { &google, &yahoo, &live, &aol, };
// Canada
const PrepopulatedEngine* engines_CA[] =
{ &google, &msn_en_CA, &msn_fr_CA, &yahoo_ca, &yahoo_qc, &toile, };
// Switzerland
const PrepopulatedEngine* engines_CH[] =
{ &google, &search_ch, &yahoo_ch, &msn_de_CH, &msn_fr_CH, &bluewin, };
// Chile
const PrepopulatedEngine* engines_CL[] =
{ &google, &yahoo_cl, &altavista, &msn_es_CL, };
// China
const PrepopulatedEngine* engines_CN[] =
{ &google, &baidu, &yahoo_cn, &sogou, &soso, };
// Colombia
const PrepopulatedEngine* engines_CO[] =
{ &google, &msn_es_CO, &ask_es, &altavista, &conexcol, &yahoo_co, };
// Costa Rica
const PrepopulatedEngine* engines_CR[] =
{ &google, &msn_es_XL, &yahoo, &altavista, &aol, &lycos_es, };
// Czech Republic
const PrepopulatedEngine* engines_CZ[] =
{ &google, &seznam, ¢rum_cz, &atlas_cz, &live_cs_CZ, };
// Germany
const PrepopulatedEngine* engines_DE[] =
{ &google, &msn_de_DE, &yahoo_de, &t_online, &ask_de, &web_de, };
// Denmark
const PrepopulatedEngine* engines_DK[] =
{ &google, &jubii, &msn_da_DK, &yahoo_dk, &eniro_dk, };
// Dominican Republic
const PrepopulatedEngine* engines_DO[] =
{ &google, &msn_es_XL, &yahoo, &altavista, &go, &aol, };
// Algeria
const PrepopulatedEngine* engines_DZ[] =
{ &google, &yahoo, &yamli, &msn_en_XA, &msn_ar_XA, &araby, };
// Ecuador
const PrepopulatedEngine* engines_EC[] =
{ &google, &msn_es_XL, &yahoo, &terra_ec, };
// Estonia
const PrepopulatedEngine* engines_EE[] =
{ &google, &neti, &delfi_ee, &yahoo, &live_et_EE, };
// Egypt
const PrepopulatedEngine* engines_EG[] =
{ &google, &masrawy, &yahoo, &maktoob, &araby, &msn_en_XA, &msn_ar_XA, };
// Spain
const PrepopulatedEngine* engines_ES[] =
{ &google, &msn_es_ES, &yahoo_es, &terra_es, &ozu, &altavista_es, };
// Faroe Islands
const PrepopulatedEngine* engines_FO[] =
{ &google, &jubii, &msn_da_DK, &yahoo_dk, &eniro_dk, };
// Finland
const PrepopulatedEngine* engines_FI[] =
{ &google, &msn_fi_FI, &yahoo_fi, &eniro_fi, &fonecta_02_fi, };
// France
const PrepopulatedEngine* engines_FR[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// United Kingdom
const PrepopulatedEngine* engines_GB[] =
{ &google, &yahoo_uk, &msn_en_GB, &ask_uk, };
// Greece
const PrepopulatedEngine* engines_GR[] =
{ &google, &yahoo, &forthnet, &in, &live_el_GR };
// Guatemala
const PrepopulatedEngine* engines_GT[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &go, };
// Hong Kong
const PrepopulatedEngine* engines_HK[] =
{ &google, &yahoo_hk, &msn_zh_HK, &sogou, &baidu, };
// Honduras
const PrepopulatedEngine* engines_HN[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, };
// Croatia
const PrepopulatedEngine* engines_HR[] =
{ &google, &yahoo, &pogodak_hr, &live_hr_HR, };
// Hungary
const PrepopulatedEngine* engines_HU[] = { &google, &tango, &ok, &live_hu_HU, };
// Indonesia
const PrepopulatedEngine* engines_ID[] = { &google, &yahoo_id, &live_en_ID, };
// Ireland
const PrepopulatedEngine* engines_IE[] = { &google, &yahoo_uk, &msn_en_IE, };
// Israel
const PrepopulatedEngine* engines_IL[] =
{ &google, &walla, &nana10, &tapuz, &msn_he_IL, };
// India
const PrepopulatedEngine* engines_IN[] =
{ &google, &yahoo_in, &msn_en_IN, &rediff, &guruji, };
// Iraq
const PrepopulatedEngine* engines_IQ[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Iran
const PrepopulatedEngine* engines_IR[] = { &google, };
// Iceland
const PrepopulatedEngine* engines_IS[] = { &google, &leit, &embla, &finna, };
// Italy
const PrepopulatedEngine* engines_IT[] =
{ &google, &virgilio, &yahoo_it, &libero, &ask_it, &live_it_IT, };
// Jamaica
const PrepopulatedEngine* engines_JM[] =
{ &google, &jamaicalive, &yahoo, &live, &go, &aol, };
// Jordan
const PrepopulatedEngine* engines_JO[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Japan
const PrepopulatedEngine* engines_JP[] =
{ &google, &yahoo_jp, &msn_ja_JP, &biglobe, &goo, &nifty, };
// Kenya
const PrepopulatedEngine* engines_KE[] = { &google, &yahoo, &msn, };
// Kuwait
const PrepopulatedEngine* engines_KW[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// South Korea
const PrepopulatedEngine* engines_KR[] =
{ &google, &naver, &daum, &yahoo_kr, &nate, &empas, };
// Lebanon
const PrepopulatedEngine* engines_LB[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Liechtenstein
const PrepopulatedEngine* engines_LI[] =
{ &google, &msn_de_DE, &yahoo_de, &t_online, &ask_de, &web_de, };
// Lithuania
const PrepopulatedEngine* engines_LT[] =
{ &google, &delfi_lt, &yahoo, &yandex_ru, &live_lt_LT, };
// Luxembourg
const PrepopulatedEngine* engines_LU[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// Latvia
const PrepopulatedEngine* engines_LV[] =
{ &google, &delfi_lv, &yahoo, &yandex_ru, &latne, };
// Libya
const PrepopulatedEngine* engines_LY[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Morocco
const PrepopulatedEngine* engines_MA[] =
{ &google, &yamli, &araby, &yahoo, &msn_en_XA, &msn_ar_XA, };
// Monaco
const PrepopulatedEngine* engines_MC[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// Montenegro
const PrepopulatedEngine* engines_ME[] =
{ &google, &yahoo, &krstarica, &pogodak_rs, &aladin, &live, };
// Macedonia
const PrepopulatedEngine* engines_MK[] = { &google, &pogodok, &yahoo, &live, };
// Mexico
const PrepopulatedEngine* engines_MX[] =
{ &google, &msn_es_MX, &yahoo_mx, &ask_es, &altavista_mx, &terra_mx, };
// Malaysia
const PrepopulatedEngine* engines_MY[] =
{ &google, &yahoo_malaysia, &msn_en_MY, };
// Nicaragua
const PrepopulatedEngine* engines_NI[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, };
// Netherlands
const PrepopulatedEngine* engines_NL[] =
{ &google, &ilse, &msn_nl_NL, &yahoo_nl, &lycos_nl, &vinden, };
// Norway
const PrepopulatedEngine* engines_NO[] =
{ &google, &msn_nb_NO, &abcsok, &yahoo_no, &kvasir, &sesam, };
// New Zealand
const PrepopulatedEngine* engines_NZ[] = { &google, &yahoo_nz, &live_en_NZ, };
// Oman
const PrepopulatedEngine* engines_OM[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Panama
const PrepopulatedEngine* engines_PA[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &lycos_es, };
// Peru
const PrepopulatedEngine* engines_PE[] =
{ &google, &msn_es_XL, &yahoo_pe, &terra_pe, &adonde, &ohperu, };
// Philippines
const PrepopulatedEngine* engines_PH[] = { &google, &yahoo_ph, &msn_en_PH, };
// Pakistan
const PrepopulatedEngine* engines_PK[] = { &google, &yahoo, &msn, };
// Puerto Rico
const PrepopulatedEngine* engines_PR[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &mywebsearch, };
// Poland
const PrepopulatedEngine* engines_PL[] = { &google, &onet, &wp, &live_pl_PL, };
// Portugal
const PrepopulatedEngine* engines_PT[] =
{ &google, &sapo, &yahoo, &live_pt_PT, &netindex, &aeiou, };
// Paraguay
const PrepopulatedEngine* engines_PY[] =
{ &google, &msn_es_XL, &yahoo, &lycos_es, &yagua, &go, };
// Qatar
const PrepopulatedEngine* engines_QA[] =
{ &google, &maktoob, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Romania
const PrepopulatedEngine* engines_RO[] = { &google, &yahoo, &live_ro_RO, };
// Serbia
const PrepopulatedEngine* engines_RS[] =
{ &google, &yahoo, &krstarica, &pogodak_rs, &aladin, &live, };
// Russia
const PrepopulatedEngine* engines_RU[] =
{ &google, &yandex_ru, &rambler, &mail_ru, &yahoo_ru, &live_ru_RU, };
// Saudi Arabia
const PrepopulatedEngine* engines_SA[] =
{ &google, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, &maktoob, };
// Sweden
const PrepopulatedEngine* engines_SE[] =
{ &google, &eniro_se, &msn_sv_SE, &altavista_se, &spray, };
// Singapore
const PrepopulatedEngine* engines_SG[] =
{ &google, &yahoo_sg, &msn_en_SG, &rednano, };
// Slovenia
const PrepopulatedEngine* engines_SI[] =
{ &google, &najdi, &yahoo, &matkurja, &live_sl_SI, };
// Slovakia
const PrepopulatedEngine* engines_SK[] =
{ &google, &zoznam, ¢rum_sk, &atlas_sk, &szm, &live_sk_SK, };
// El Salvador
const PrepopulatedEngine* engines_SV[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &go, };
// Syria
const PrepopulatedEngine* engines_SY[] =
{ &google, &yahoo, &maktoob, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Thailand
const PrepopulatedEngine* engines_TH[] =
{ &google, &sanook, &yahoo_th, &live_th_TH, };
// Tunisia
const PrepopulatedEngine* engines_TN[] =
{ &google, &maktoob, &yamli, &yahoo, &msn_en_XA, &msn_ar_XA, };
// Turkey
const PrepopulatedEngine* engines_TR[] =
{ &google, &msn_tr_TR, &yahoo, &mynet, };
// Trinidad and Tobago
const PrepopulatedEngine* engines_TT[] = { &google, &live, &yahoo, &go, &aol, };
// Taiwan
const PrepopulatedEngine* engines_TW[] = { &google, &yahoo_tw, &yam, };
// Ukraine
const PrepopulatedEngine* engines_UA[] =
{ &google, &meta, &yandex_ua, &bigmir, &rambler, };
// United States
const PrepopulatedEngine* engines_US[] =
{ &google, &yahoo, &live_en_US, &aol, &ask, };
// Uruguay
const PrepopulatedEngine* engines_UY[] =
{ &google, &msn_es_XL, &yahoo, &go, &lycos_es, };
// Venezuela
const PrepopulatedEngine* engines_VE[] =
{ &google, &msn_es_XL, &yahoo_ve, &altavista, };
// Vietnam
const PrepopulatedEngine* engines_VN[] = { &google, &yahoo_vn, };
// Yemen
const PrepopulatedEngine* engines_YE[] =
{ &google, &yahoo, &maktoob, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// South Africa
const PrepopulatedEngine* engines_ZA[] =
{ &google, &yahoo, &msn_en_ZA, &mweb, &iafrica, };
// Zimbabwe
const PrepopulatedEngine* engines_ZW[] = { &google, &yahoo, &msn, };
// Geographic mappings /////////////////////////////////////////////////////////
// Please refer to ISO 3166-1 for information about the two-character country
// codes; http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 is useful. In the
// following (C++) code, we pack the two letters of the country code into an int
// value we call the CountryID.
const int kCountryIDUnknown = -1;
inline int CountryCharsToCountryID(char c1, char c2) {
return c1 << 8 | c2;
}
int CountryCharsToCountryIDWithUpdate(char c1, char c2) {
// SPECIAL CASE: In 2003, Yugoslavia renamed itself to Serbia and Montenegro.
// Serbia and Montenegro dissolved their union in June 2006. Yugoslavia was
// ISO 'YU' and Serbia and Montenegro were ISO 'CS'. Serbia was subsequently
// issued 'RS' and Montenegro 'ME'. Windows XP and Mac OS X Leopard still use
// the value 'YU'. If we get a value of 'YU' or 'CS' we will map it to 'RS'.
if ((c1 == 'Y' && c2 == 'U') ||
(c1 == 'C' && c2 == 'S')) {
c1 = 'R';
c2 = 'S';
}
// SPECIAL CASE: Timor-Leste changed from 'TP' to 'TL' in 2002. Windows XP
// predates this; we therefore map this value.
if (c1 == 'T' && c2 == 'P')
c2 = 'L';
return CountryCharsToCountryID(c1, c2);
}
#if defined(OS_WIN)
// For reference, a list of GeoIDs can be found at
// http://msdn.microsoft.com/en-us/library/ms776390.aspx .
int GeoIDToCountryID(GEOID geo_id) {
const int kISOBufferSize = 3; // Two plus one for the terminator.
wchar_t isobuf[kISOBufferSize] = { 0 };
int retval = GetGeoInfo(geo_id, GEO_ISO2, isobuf, kISOBufferSize, 0);
if (retval == kISOBufferSize &&
!(isobuf[0] == L'X' && isobuf[1] == L'X'))
return CountryCharsToCountryIDWithUpdate(static_cast<char>(isobuf[0]),
static_cast<char>(isobuf[1]));
// Various locations have ISO codes that Windows does not return.
switch(geo_id) {
case 0x144: // Guernsey
return CountryCharsToCountryID('G', 'G');
case 0x148: // Jersey
return CountryCharsToCountryID('J', 'E');
case 0x3B16: // Isle of Man
return CountryCharsToCountryID('I', 'M');
// 'UM' (U.S. Minor Outlying Islands)
case 0x7F: // Johnston Atoll
case 0x102: // Wake Island
case 0x131: // Baker Island
case 0x146: // Howland Island
case 0x147: // Jarvis Island
case 0x149: // Kingman Reef
case 0x152: // Palmyra Atoll
case 0x52FA: // Midway Islands
return CountryCharsToCountryID('U', 'M');
// 'SH' (Saint Helena)
case 0x12F: // Ascension Island
case 0x15C: // Tristan da Cunha
return CountryCharsToCountryID('S', 'H');
// 'IO' (British Indian Ocean Territory)
case 0x13A: // Diego Garcia
return CountryCharsToCountryID('I', 'O');
// Other cases where there is no ISO country code; we assign countries that
// can serve as reasonable defaults.
case 0x154: // Rota Island
case 0x155: // Saipan
case 0x15A: // Tinian Island
return CountryCharsToCountryID('U', 'S');
case 0x134: // Channel Islands
return CountryCharsToCountryID('G', 'B');
case 0x143: // Guantanamo Bay
default:
return kCountryIDUnknown;
}
}
int GetCurrentCountryID() {
GEOID geo_id = GetUserGeoID(GEOCLASS_NATION);
return GeoIDToCountryID(geo_id);
}
#elif defined(OS_MACOSX)
int GetCurrentCountryID() {
scoped_cftyperef<CFLocaleRef> locale(CFLocaleCopyCurrent());
CFStringRef country = (CFStringRef)CFLocaleGetValue(locale.get(),
kCFLocaleCountryCode);
if (!country)
return kCountryIDUnknown;
UniChar isobuf[2];
CFRange char_range = CFRangeMake(0, 2);
CFStringGetCharacters(country, char_range, isobuf);
return CountryCharsToCountryIDWithUpdate(static_cast<char>(isobuf[0]),
static_cast<char>(isobuf[1]));
}
#elif defined(OS_LINUX)
int GetCurrentCountryID() {
NOTIMPLEMENTED();
return kCountryIDUnknown;
}
#endif // OS_*
int GetCountryIDFromPrefs(PrefService* prefs) {
// See if the user overrode the country on the command line.
const std::wstring country(
CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kCountry));
if (country.length() == 2)
return CountryCharsToCountryIDWithUpdate(static_cast<char>(country[0]),
static_cast<char>(country[1]));
// Cache first run Country ID value in prefs, and use it afterwards. This
// ensures that just because the user moves around, we won't automatically
// make major changes to their available search providers, which would feel
// surprising.
if (!prefs)
return GetCurrentCountryID();
if (!prefs->HasPrefPath(prefs::kCountryIDAtInstall)) {
int new_country_id;
#if defined(OS_WIN)
// Upgrade the old platform-specific value if it's present.
if (prefs->HasPrefPath(prefs::kGeoIDAtInstall)) {
int geo_id = prefs->GetInteger(prefs::kGeoIDAtInstall);
new_country_id = GeoIDToCountryID(geo_id);
} else {
new_country_id = GetCurrentCountryID();
}
#else
new_country_id = GetCurrentCountryID();
#endif
prefs->SetInteger(prefs::kCountryIDAtInstall, new_country_id);
}
return prefs->GetInteger(prefs::kCountryIDAtInstall);
}
void GetPrepopulationSetFromCountryID(PrefService* prefs,
const PrepopulatedEngine*** engines,
size_t* num_engines) {
// NOTE: This function should ALWAYS set its outparams.
// If you add a new country make sure to update the unit test for coverage.
switch (GetCountryIDFromPrefs(prefs)) {
#define CHAR_A 'A'
#define CHAR_B 'B'
#define CHAR_C 'C'
#define CHAR_D 'D'
#define CHAR_E 'E'
#define CHAR_F 'F'
#define CHAR_G 'G'
#define CHAR_H 'H'
#define CHAR_I 'I'
#define CHAR_J 'J'
#define CHAR_K 'K'
#define CHAR_L 'L'
#define CHAR_M 'M'
#define CHAR_N 'N'
#define CHAR_O 'O'
#define CHAR_P 'P'
#define CHAR_Q 'Q'
#define CHAR_R 'R'
#define CHAR_S 'S'
#define CHAR_T 'T'
#define CHAR_U 'U'
#define CHAR_V 'V'
#define CHAR_W 'W'
#define CHAR_X 'X'
#define CHAR_Y 'Y'
#define CHAR_Z 'Z'
#define CHAR(ch) CHAR_##ch
#define CODE_TO_ID(code1, code2)\
(CHAR(code1) << 8 | CHAR(code2))
#define UNHANDLED_COUNTRY(code1, code2)\
case CODE_TO_ID(code1, code2):
#define END_UNHANDLED_COUNTRIES(code1, code2)\
*engines = engines_##code1##code2;\
*num_engines = arraysize(engines_##code1##code2);\
return;
#define DECLARE_COUNTRY(code1, code2)\
UNHANDLED_COUNTRY(code1, code2)\
END_UNHANDLED_COUNTRIES(code1, code2)
// Countries with their own, dedicated engine set.
DECLARE_COUNTRY(A, E) // United Arab Emirates
DECLARE_COUNTRY(A, L) // Albania
DECLARE_COUNTRY(A, R) // Argentina
DECLARE_COUNTRY(A, T) // Austria
DECLARE_COUNTRY(A, U) // Australia
DECLARE_COUNTRY(B, A) // Bosnia and Herzegovina
DECLARE_COUNTRY(B, E) // Belgium
DECLARE_COUNTRY(B, G) // Bulgaria
DECLARE_COUNTRY(B, H) // Bahrain
DECLARE_COUNTRY(B, N) // Brunei
DECLARE_COUNTRY(B, O) // Bolivia
DECLARE_COUNTRY(B, R) // Brazil
DECLARE_COUNTRY(B, Y) // Belarus
DECLARE_COUNTRY(B, Z) // Belize
DECLARE_COUNTRY(C, A) // Canada
DECLARE_COUNTRY(C, H) // Switzerland
DECLARE_COUNTRY(C, L) // Chile
DECLARE_COUNTRY(C, N) // China
DECLARE_COUNTRY(C, O) // Colombia
DECLARE_COUNTRY(C, R) // Costa Rica
DECLARE_COUNTRY(C, Z) // Czech Republic
DECLARE_COUNTRY(D, E) // Germany
DECLARE_COUNTRY(D, K) // Denmark
DECLARE_COUNTRY(D, O) // Dominican Republic
DECLARE_COUNTRY(D, Z) // Algeria
DECLARE_COUNTRY(E, C) // Ecuador
DECLARE_COUNTRY(E, E) // Estonia
DECLARE_COUNTRY(E, G) // Egypt
DECLARE_COUNTRY(E, S) // Spain
DECLARE_COUNTRY(F, I) // Finland
DECLARE_COUNTRY(F, O) // Faroe Islands
DECLARE_COUNTRY(F, R) // France
DECLARE_COUNTRY(G, B) // United Kingdom
DECLARE_COUNTRY(G, R) // Greece
DECLARE_COUNTRY(G, T) // Guatemala
DECLARE_COUNTRY(H, K) // Hong Kong
DECLARE_COUNTRY(H, N) // Honduras
DECLARE_COUNTRY(H, R) // Croatia
DECLARE_COUNTRY(H, U) // Hungary
DECLARE_COUNTRY(I, D) // Indonesia
DECLARE_COUNTRY(I, E) // Ireland
DECLARE_COUNTRY(I, L) // Israel
DECLARE_COUNTRY(I, N) // India
DECLARE_COUNTRY(I, Q) // Iraq
DECLARE_COUNTRY(I, R) // Iran
DECLARE_COUNTRY(I, S) // Iceland
DECLARE_COUNTRY(I, T) // Italy
DECLARE_COUNTRY(J, M) // Jamaica
DECLARE_COUNTRY(J, O) // Jordan
DECLARE_COUNTRY(J, P) // Japan
DECLARE_COUNTRY(K, E) // Kenya
DECLARE_COUNTRY(K, R) // South Korea
DECLARE_COUNTRY(K, W) // Kuwait
DECLARE_COUNTRY(L, B) // Lebanon
DECLARE_COUNTRY(L, I) // Liechtenstein
DECLARE_COUNTRY(L, T) // Lithuania
DECLARE_COUNTRY(L, U) // Luxembourg
DECLARE_COUNTRY(L, V) // Latvia
DECLARE_COUNTRY(L, Y) // Libya
DECLARE_COUNTRY(M, A) // Morocco
DECLARE_COUNTRY(M, C) // Monaco
DECLARE_COUNTRY(M, E) // Montenegro
DECLARE_COUNTRY(M, K) // Macedonia
DECLARE_COUNTRY(M, X) // Mexico
DECLARE_COUNTRY(M, Y) // Malaysia
DECLARE_COUNTRY(N, I) // Nicaragua
DECLARE_COUNTRY(N, L) // Netherlands
DECLARE_COUNTRY(N, O) // Norway
DECLARE_COUNTRY(N, Z) // New Zealand
DECLARE_COUNTRY(O, M) // Oman
DECLARE_COUNTRY(P, A) // Panama
DECLARE_COUNTRY(P, E) // Peru
DECLARE_COUNTRY(P, H) // Philippines
DECLARE_COUNTRY(P, K) // Pakistan
DECLARE_COUNTRY(P, L) // Poland
DECLARE_COUNTRY(P, R) // Puerto Rico
DECLARE_COUNTRY(P, T) // Portugal
DECLARE_COUNTRY(P, Y) // Paraguay
DECLARE_COUNTRY(Q, A) // Qatar
DECLARE_COUNTRY(R, O) // Romania
DECLARE_COUNTRY(R, S) // Serbia
DECLARE_COUNTRY(R, U) // Russia
DECLARE_COUNTRY(S, A) // Saudi Arabia
DECLARE_COUNTRY(S, E) // Sweden
DECLARE_COUNTRY(S, G) // Singapore
DECLARE_COUNTRY(S, I) // Slovenia
DECLARE_COUNTRY(S, K) // Slovakia
DECLARE_COUNTRY(S, V) // El Salvador
DECLARE_COUNTRY(S, Y) // Syria
DECLARE_COUNTRY(T, H) // Thailand
DECLARE_COUNTRY(T, N) // Tunisia
DECLARE_COUNTRY(T, R) // Turkey
DECLARE_COUNTRY(T, T) // Trinidad and Tobago
DECLARE_COUNTRY(T, W) // Taiwan
DECLARE_COUNTRY(U, A) // Ukraine
DECLARE_COUNTRY(U, S) // United States
DECLARE_COUNTRY(U, Y) // Uruguay
DECLARE_COUNTRY(V, E) // Venezuela
DECLARE_COUNTRY(V, N) // Vietnam
DECLARE_COUNTRY(Y, E) // Yemen
DECLARE_COUNTRY(Z, A) // South Africa
DECLARE_COUNTRY(Z, W) // Zimbabwe
// Countries using the "Australia" engine set.
UNHANDLED_COUNTRY(C, C) // Cocos Islands
UNHANDLED_COUNTRY(C, X) // Christmas Island
UNHANDLED_COUNTRY(H, M) // Heard Island and McDonald Islands
UNHANDLED_COUNTRY(N, F) // Norfolk Island
END_UNHANDLED_COUNTRIES(A, U)
// Countries using the "China" engine set.
UNHANDLED_COUNTRY(M, O) // Macao
END_UNHANDLED_COUNTRIES(C, N)
// Countries using the "Denmark" engine set.
UNHANDLED_COUNTRY(G, L) // Greenland
END_UNHANDLED_COUNTRIES(D, K)
// Countries using the "Spain" engine set.
UNHANDLED_COUNTRY(A, D) // Andorra
END_UNHANDLED_COUNTRIES(E, S)
// Countries using the "France" engine set.
UNHANDLED_COUNTRY(B, F) // Burkina Faso
UNHANDLED_COUNTRY(B, I) // Burundi
UNHANDLED_COUNTRY(B, J) // Benin
UNHANDLED_COUNTRY(C, D) // Congo - Kinshasa
UNHANDLED_COUNTRY(C, F) // Central African Republic
UNHANDLED_COUNTRY(C, G) // Congo - Brazzaville
UNHANDLED_COUNTRY(C, I) // Ivory Coast
UNHANDLED_COUNTRY(C, M) // Cameroon
UNHANDLED_COUNTRY(D, J) // Djibouti
UNHANDLED_COUNTRY(G, A) // Gabon
UNHANDLED_COUNTRY(G, F) // French Guiana
UNHANDLED_COUNTRY(G, N) // Guinea
UNHANDLED_COUNTRY(G, P) // Guadeloupe
UNHANDLED_COUNTRY(H, T) // Haiti
#if defined(OS_WIN)
UNHANDLED_COUNTRY(I, P) // Clipperton Island ('IP' is an WinXP-ism; ISO
// includes it with France)
#endif
UNHANDLED_COUNTRY(M, L) // Mali
UNHANDLED_COUNTRY(M, Q) // Martinique
UNHANDLED_COUNTRY(N, C) // New Caledonia
UNHANDLED_COUNTRY(N, E) // Niger
UNHANDLED_COUNTRY(P, F) // French Polynesia
UNHANDLED_COUNTRY(P, M) // Saint Pierre and Miquelon
UNHANDLED_COUNTRY(R, E) // Reunion
UNHANDLED_COUNTRY(S, N) // Senegal
UNHANDLED_COUNTRY(T, D) // Chad
UNHANDLED_COUNTRY(T, F) // French Southern Territories
UNHANDLED_COUNTRY(T, G) // Togo
UNHANDLED_COUNTRY(W, F) // Wallis and Futuna
UNHANDLED_COUNTRY(Y, T) // Mayotte
END_UNHANDLED_COUNTRIES(F, R)
// Countries using the "Greece" engine set.
UNHANDLED_COUNTRY(C, Y) // Cyprus
END_UNHANDLED_COUNTRIES(G, R)
// Countries using the "Italy" engine set.
UNHANDLED_COUNTRY(S, M) // San Marino
UNHANDLED_COUNTRY(V, A) // Vatican
END_UNHANDLED_COUNTRIES(I, T)
// Countries using the "Netherlands" engine set.
UNHANDLED_COUNTRY(A, N) // Netherlands Antilles
UNHANDLED_COUNTRY(A, W) // Aruba
END_UNHANDLED_COUNTRIES(N, L)
// Countries using the "Norway" engine set.
UNHANDLED_COUNTRY(B, V) // Bouvet Island
UNHANDLED_COUNTRY(S, J) // Svalbard and Jan Mayen
END_UNHANDLED_COUNTRIES(N, O)
// Countries using the "New Zealand" engine set.
UNHANDLED_COUNTRY(C, K) // Cook Islands
UNHANDLED_COUNTRY(N, U) // Niue
UNHANDLED_COUNTRY(T, K) // Tokelau
END_UNHANDLED_COUNTRIES(N, Z)
// Countries using the "Portugal" engine set.
UNHANDLED_COUNTRY(C, V) // Cape Verde
UNHANDLED_COUNTRY(G, W) // Guinea-Bissau
UNHANDLED_COUNTRY(M, Z) // Mozambique
UNHANDLED_COUNTRY(S, T) // Sao Tome and Principe
UNHANDLED_COUNTRY(T, L) // Timor-Leste
END_UNHANDLED_COUNTRIES(P, T)
// Countries using the "Russia" engine set.
UNHANDLED_COUNTRY(A, M) // Armenia
UNHANDLED_COUNTRY(A, Z) // Azerbaijan
UNHANDLED_COUNTRY(K, G) // Kyrgyzstan
UNHANDLED_COUNTRY(K, Z) // Kazakhstan
UNHANDLED_COUNTRY(T, J) // Tajikistan
UNHANDLED_COUNTRY(T, M) // Turkmenistan
UNHANDLED_COUNTRY(U, Z) // Uzbekistan
END_UNHANDLED_COUNTRIES(R, U)
// Countries using the "Saudi Arabia" engine set.
UNHANDLED_COUNTRY(M, R) // Mauritania
UNHANDLED_COUNTRY(P, S) // Palestinian Territory
UNHANDLED_COUNTRY(S, D) // Sudan
END_UNHANDLED_COUNTRIES(S, A)
// Countries using the "United Kingdom" engine set.
UNHANDLED_COUNTRY(B, M) // Bermuda
UNHANDLED_COUNTRY(F, K) // Falkland Islands
UNHANDLED_COUNTRY(G, G) // Guernsey
UNHANDLED_COUNTRY(G, I) // Gibraltar
UNHANDLED_COUNTRY(G, S) // South Georgia and the South Sandwich
// Islands
UNHANDLED_COUNTRY(I, M) // Isle of Man
UNHANDLED_COUNTRY(I, O) // British Indian Ocean Territory
UNHANDLED_COUNTRY(J, E) // Jersey
UNHANDLED_COUNTRY(K, Y) // Cayman Islands
UNHANDLED_COUNTRY(M, S) // Montserrat
UNHANDLED_COUNTRY(M, T) // Malta
UNHANDLED_COUNTRY(P, N) // Pitcairn Islands
UNHANDLED_COUNTRY(S, H) // Saint Helena, Ascension Island, and Tristan da
// Cunha
UNHANDLED_COUNTRY(T, C) // Turks and Caicos Islands
UNHANDLED_COUNTRY(V, G) // British Virgin Islands
END_UNHANDLED_COUNTRIES(G, B)
// Countries using the "United States" engine set.
UNHANDLED_COUNTRY(A, S) // American Samoa
UNHANDLED_COUNTRY(G, U) // Guam
UNHANDLED_COUNTRY(M, P) // Northern Mariana Islands
UNHANDLED_COUNTRY(U, M) // U.S. Minor Outlying Islands
UNHANDLED_COUNTRY(V, I) // U.S. Virgin Islands
END_UNHANDLED_COUNTRIES(U, S)
// Countries using the "default" engine set.
UNHANDLED_COUNTRY(A, F) // Afghanistan
UNHANDLED_COUNTRY(A, G) // Antigua and Barbuda
UNHANDLED_COUNTRY(A, I) // Anguilla
UNHANDLED_COUNTRY(A, O) // Angola
UNHANDLED_COUNTRY(A, Q) // Antarctica
UNHANDLED_COUNTRY(B, B) // Barbados
UNHANDLED_COUNTRY(B, D) // Bangladesh
UNHANDLED_COUNTRY(B, S) // Bahamas
UNHANDLED_COUNTRY(B, T) // Bhutan
UNHANDLED_COUNTRY(B, W) // Botswana
UNHANDLED_COUNTRY(C, U) // Cuba
UNHANDLED_COUNTRY(D, M) // Dominica
UNHANDLED_COUNTRY(E, R) // Eritrea
UNHANDLED_COUNTRY(E, T) // Ethiopia
UNHANDLED_COUNTRY(F, J) // Fiji
UNHANDLED_COUNTRY(F, M) // Micronesia
UNHANDLED_COUNTRY(G, D) // Grenada
UNHANDLED_COUNTRY(G, E) // Georgia
UNHANDLED_COUNTRY(G, H) // Ghana
UNHANDLED_COUNTRY(G, M) // Gambia
UNHANDLED_COUNTRY(G, Q) // Equatorial Guinea
UNHANDLED_COUNTRY(G, Y) // Guyana
UNHANDLED_COUNTRY(K, H) // Cambodia
UNHANDLED_COUNTRY(K, I) // Kiribati
UNHANDLED_COUNTRY(K, M) // Comoros
UNHANDLED_COUNTRY(K, N) // Saint Kitts and Nevis
UNHANDLED_COUNTRY(K, P) // North Korea
UNHANDLED_COUNTRY(L, A) // Laos
UNHANDLED_COUNTRY(L, C) // Saint Lucia
UNHANDLED_COUNTRY(L, K) // Sri Lanka
UNHANDLED_COUNTRY(L, R) // Liberia
UNHANDLED_COUNTRY(L, S) // Lesotho
UNHANDLED_COUNTRY(M, D) // Moldova
UNHANDLED_COUNTRY(M, G) // Madagascar
UNHANDLED_COUNTRY(M, H) // Marshall Islands
UNHANDLED_COUNTRY(M, M) // Myanmar
UNHANDLED_COUNTRY(M, N) // Mongolia
UNHANDLED_COUNTRY(M, U) // Mauritius
UNHANDLED_COUNTRY(M, V) // Maldives
UNHANDLED_COUNTRY(M, W) // Malawi
UNHANDLED_COUNTRY(N, A) // Namibia
UNHANDLED_COUNTRY(N, G) // Nigeria
UNHANDLED_COUNTRY(N, P) // Nepal
UNHANDLED_COUNTRY(N, R) // Nauru
UNHANDLED_COUNTRY(P, G) // Papua New Guinea
UNHANDLED_COUNTRY(P, W) // Palau
UNHANDLED_COUNTRY(R, W) // Rwanda
UNHANDLED_COUNTRY(S, B) // Solomon Islands
UNHANDLED_COUNTRY(S, C) // Seychelles
UNHANDLED_COUNTRY(S, L) // Sierra Leone
UNHANDLED_COUNTRY(S, O) // Somalia
UNHANDLED_COUNTRY(S, R) // Suriname
UNHANDLED_COUNTRY(S, Z) // Swaziland
UNHANDLED_COUNTRY(T, O) // Tonga
UNHANDLED_COUNTRY(T, V) // Tuvalu
UNHANDLED_COUNTRY(T, Z) // Tanzania
UNHANDLED_COUNTRY(U, G) // Uganda
UNHANDLED_COUNTRY(V, C) // Saint Vincent and the Grenadines
UNHANDLED_COUNTRY(V, U) // Vanuatu
UNHANDLED_COUNTRY(W, S) // Samoa
UNHANDLED_COUNTRY(Z, M) // Zambia
case kCountryIDUnknown:
default: // Unhandled location
END_UNHANDLED_COUNTRIES(def, ault)
}
}
} // namespace
namespace TemplateURLPrepopulateData {
void RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kGeoIDAtInstall, -1);
prefs->RegisterIntegerPref(prefs::kCountryIDAtInstall, kCountryIDUnknown);
}
int GetDataVersion() {
return 22; // Increment this if you change the above data in ways that mean
// users with existing data should get a new version.
}
void GetPrepopulatedEngines(PrefService* prefs,
std::vector<TemplateURL*>* t_urls,
size_t* default_search_provider_index) {
const PrepopulatedEngine** engines;
size_t num_engines;
GetPrepopulationSetFromCountryID(prefs, &engines, &num_engines);
*default_search_provider_index = 0;
for (size_t i = 0; i < num_engines; ++i) {
TemplateURL* new_turl = new TemplateURL();
new_turl->SetURL(engines[i]->search_url, 0, 0);
if (engines[i]->favicon_url)
new_turl->SetFavIconURL(GURL(engines[i]->favicon_url));
if (engines[i]->suggest_url)
new_turl->SetSuggestionsURL(engines[i]->suggest_url, 0, 0);
new_turl->set_short_name(engines[i]->name);
if (engines[i]->keyword == NULL)
new_turl->set_autogenerate_keyword(true);
else
new_turl->set_keyword(engines[i]->keyword);
new_turl->set_show_in_default_list(true);
new_turl->set_safe_for_autoreplace(true);
new_turl->set_date_created(Time());
std::vector<std::string> turl_encodings;
turl_encodings.push_back(engines[i]->encoding);
new_turl->set_input_encodings(turl_encodings);
new_turl->set_prepopulate_id(engines[i]->id);
t_urls->push_back(new_turl);
}
}
} // namespace TemplateURLPrepopulateData
Fix some character literals to use the right escape string.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/159714
git-svn-id: http://src.chromium.org/svn/trunk/src@22222 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 11bece164e94643ab83f8adb3a6f2064599c286d
// 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 "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#if defined(OS_WIN)
#undef IN // On Windows, windef.h defines this, which screws up "India" cases.
#elif defined(OS_MACOSX)
#include "base/scoped_cftyperef.h"
#endif
using base::Time;
namespace {
// NOTE: See comments in GetDataVersion() below! You should probably not change
// the data in this file without changing the result of that function!
// Engine definitions //////////////////////////////////////////////////////////
struct PrepopulatedEngine {
const wchar_t* const name;
// If NULL, we'll autogenerate a keyword based on the search_url every time
// someone asks. Only entries which need keywords to auto-track a dynamically
// generated search URL should use this.
// If the empty string, the engine has no keyword.
const wchar_t* const keyword;
const char* const favicon_url; // If NULL, there is no favicon.
const wchar_t* const search_url;
const char* const encoding;
const wchar_t* const suggest_url; // If NULL, this engine does not support
// suggestions.
// Unique id for this prepopulate engine (corresponds to
// TemplateURL::prepopulate_id). This ID must be greater than zero and must
// remain the same for a particular site regardless of how the url changes;
// the ID is used when modifying engine data in subsequent versions, so that
// we can find the "old" entry to update even when the name or URL changes.
//
// This ID must be "unique" within one country's prepopulated data, but two
// entries can share an ID if they represent the "same" engine (e.g. Yahoo! US
// vs. Yahoo! UK) and will not appear in the same user-visible data set. This
// facilitates changes like adding more specific per-country data in the
// future; in such a case the localized engines will transparently replace the
// previous, non-localized versions. For engines where we need two instances
// to appear for one country (e.g. Live Search U.S. English and Spanish), we
// must use two different unique IDs (and different keywords).
//
// The following unique IDs are available: 66, 93, 103+
// NOTE: CHANGE THE ABOVE NUMBERS IF YOU ADD A NEW ENGINE; ID conflicts = bad!
const int id;
};
const PrepopulatedEngine abcsok = {
L"ABC S\x00f8k",
L"abcsok.no",
"http://abcsok.no/favicon.ico",
L"http://abcsok.no/index.html?q={searchTerms}",
"UTF-8",
NULL,
72,
};
const PrepopulatedEngine adonde = {
L"Adonde.com",
L"adonde.com",
"http://www.adonde.com/favicon.ico",
L"http://www.adonde.com/peru/peru.html?sitesearch=adonde.com&"
L"client=pub-6263803831447773&ie={inputEncoding}&cof=GALT%3A%23CC0000"
L"%3BGL%3A1%3BDIV%3A%23E6E6E6%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF"
L"%3BLBGC%3AFFFFFF%3BALC%3A000000%3BLC%3A000000%3BT%3A0066CC%3BGFNT"
L"%3ACCCCCC%3BGIMP%3ACCCCCC%3BFORID%3A11&q={searchTerms}",
"ISO-8859-1",
NULL,
95,
};
const PrepopulatedEngine aeiou = {
L"AEIOU",
L"aeiou.pt",
"http://aeiou.pt/favicon.ico",
L"http://aeiou.pt/pesquisa/index.php?p={searchTerms}",
"ISO-8859-1",
NULL,
79,
};
const PrepopulatedEngine aladin = {
L"Aladin",
L"aladin.info",
"http://www.aladin.info/favicon.ico",
L"http://www.aladin.info/search/index.php?term={searchTerms}&req=search&"
L"source=2",
"UTF-8",
NULL,
18,
};
const PrepopulatedEngine altavista = {
L"AltaVista",
L"altavista.com",
"http://www.altavista.com/favicon.ico",
L"http://www.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_ar = {
L"AltaVista",
L"ar.altavista.com",
"http://ar.altavista.com/favicon.ico",
L"http://ar.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_es = {
L"AltaVista",
L"es.altavista.com",
"http://es.altavista.com/favicon.ico",
L"http://es.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_mx = {
L"AltaVista",
L"mx.altavista.com",
"http://mx.altavista.com/favicon.ico",
L"http://mx.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine altavista_se = {
L"AltaVista",
L"se.altavista.com",
"http://se.altavista.com/favicon.ico",
L"http://se.altavista.com/web/results?q={searchTerms}",
"UTF-8",
NULL,
89,
};
const PrepopulatedEngine aol = {
L"AOL",
L"aol.com",
"http://search.aol.com/favicon.ico",
L"http://search.aol.com/aol/search?query={searchTerms}",
"UTF-8",
NULL,
35,
};
const PrepopulatedEngine aol_fr = {
L"AOL",
L"aol.fr",
"http://www.aol.fr/favicon.ico",
L"http://www.recherche.aol.fr/aol/search?q={searchTerms}",
"UTF-8",
NULL,
35,
};
const PrepopulatedEngine aonde = {
L"AONDE.com",
L"aonde.com",
"http://busca.aonde.com/favicon.ico",
L"http://busca.aonde.com/?keys={searchTerms}",
"ISO-8859-1",
NULL,
80,
};
const PrepopulatedEngine araby = {
L"\x0639\x0631\x0628\x064a",
L"araby.com",
"http://araby.com/favicon.ico",
L"http://araby.com/?q={searchTerms}",
"UTF-8",
NULL,
12,
};
const PrepopulatedEngine ask = {
L"Ask",
L"ask.com",
"http://www.ask.com/favicon.ico",
L"http://www.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_de = {
L"Ask.com Deutschland",
L"de.ask.com",
"http://de.ask.com/favicon.ico",
L"http://de.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.de.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_es = {
L"Ask.com Espa" L"\x00f1" L"a",
L"es.ask.com",
"http://es.ask.com/favicon.ico",
L"http://es.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.es.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_it = {
L"Ask.com Italia",
L"it.ask.com",
"http://it.ask.com/favicon.ico",
L"http://it.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.it.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine ask_uk = {
L"Ask.com UK",
L"uk.ask.com",
"http://uk.ask.com/favicon.ico",
L"http://uk.ask.com/web?q={searchTerms}",
"UTF-8",
L"http://ss.uk.ask.com/query?q={searchTerms}&li=ff",
4,
};
const PrepopulatedEngine atlas_cz = {
L"Atlas",
L"atlas.cz",
"http://img.atlas.cz/favicon.ico",
L"http://search.atlas.cz/?q={searchTerms}",
"windows-1250",
NULL,
27,
};
const PrepopulatedEngine atlas_sk = {
L"ATLAS.SK",
L"atlas.sk",
"http://www.atlas.sk/images/favicon.ico",
L"http://hladaj.atlas.sk/fulltext/?phrase={searchTerms}",
"UTF-8",
NULL,
27,
};
const PrepopulatedEngine baidu = {
L"\x767e\x5ea6",
L"baidu.com",
"http://www.baidu.com/favicon.ico",
L"http://www.baidu.com/s?wd={searchTerms}",
"GB2312",
NULL,
21,
};
const PrepopulatedEngine biglobe = {
L"BIGLOBE",
L"biglobe.ne.jp",
"http://cgi.search.biglobe.ne.jp/favicon.ico",
L"http://cgi.search.biglobe.ne.jp/cgi-bin/search2-b?q={searchTerms}",
"Shift_JIS",
NULL,
64,
};
const PrepopulatedEngine bigmir = {
L"bigmir)net",
L"bigmir.net",
"http://i.bigmir.net/favicon.ico",
L"http://search.bigmir.net/index.php?q={searchTerms}",
"windows-1251",
NULL,
33,
};
const PrepopulatedEngine bluewin = {
L"Bluewin",
L"search.bluewin.ch",
"http://search.bluewin.ch/favicon.ico",
L"http://search.bluewin.ch/bw/search/web/de/result.jsp?query={searchTerms}",
"ISO-8859-1",
NULL,
52,
};
const PrepopulatedEngine centrum_cz = {
L"Centrum.cz",
L"centrum.cz",
"http://img.centrum.cz/6/vy2/o/favicon.ico",
L"http://search.centrum.cz/index.php?charset={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
26,
};
const PrepopulatedEngine centrum_sk = {
L"Centrum.sk",
L"centrum.sk",
"http://img.centrum.sk/4/favicon.ico",
L"http://search.centrum.sk/index.php?charset={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
26,
};
const PrepopulatedEngine conexcol = {
L"Conexcol.com",
L"conexcol.com",
"http://www.conexcol.com/favicon.ico",
L"http://buscar.conexcol.com/cgi-ps/busqueda.cgi?query={searchTerms}",
"ISO-8859-1",
NULL,
91,
};
const PrepopulatedEngine daum = {
L"Daum",
L"daum.net",
"http://search.daum.net/favicon.ico",
L"http://search.daum.net/search?q={searchTerms}",
"EUC-KR",
L"http://sug.search.daum.net/search_nsuggest?mod=fxjson&q={searchTerms}",
68,
};
const PrepopulatedEngine delfi_ee = {
L"DELFI",
L"delfi.ee",
"http://g.delfi.ee/s/search.png",
L"http://otsing.delfi.ee/i.php?q={searchTerms}",
"ISO-8859-1",
NULL,
45,
};
const PrepopulatedEngine delfi_lt = {
L"DELFI",
L"delfi.lt",
"http://search.delfi.lt/img/favicon.png",
L"http://search.delfi.lt/search.php?q={searchTerms}",
"UTF-8",
NULL,
45,
};
const PrepopulatedEngine delfi_lv = {
L"DELFI",
L"delfi.lv",
"http://smart.delfi.lv/img/smart_search.png",
L"http://smart.delfi.lv/i.php?enc={inputEncoding}&q={searchTerms}",
"UTF-8",
NULL,
45,
};
const PrepopulatedEngine embla = {
L"Embla",
L"embla.is",
"http://embla.is/favicon.ico",
L"http://embla.is/mm/embla/?s={searchTerms}",
"ISO-8859-1",
NULL,
60,
};
const PrepopulatedEngine empas = {
L"\xc5e0\xd30c\xc2a4",
L"empas.com",
"http://search.empas.com/favicon.ico",
L"http://search.empas.com/search/all.html?q={searchTerms}",
"EUC-KR",
// http://www.empas.com/ac/do.tsp?q={searchTerms}
// returns non-Firefox JSON. searchTerms needs to be in Java notation
// (\uAC00\uAC01).
NULL,
70,
};
const PrepopulatedEngine eniro_dk = {
L"Eniro",
L"eniro.dk",
"http://eniro.dk/favicon.ico",
L"http://eniro.dk/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine eniro_fi = {
L"Eniro",
L"eniro.fi",
"http://eniro.fi/favicon.ico",
L"http://eniro.fi/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine eniro_se = {
L"Eniro",
L"eniro.se",
"http://eniro.se/favicon.ico",
L"http://eniro.se/query?search_word={searchTerms}&what=web_local",
"ISO-8859-1",
NULL,
29,
};
const PrepopulatedEngine finna = {
L"FINNA",
L"finna.is",
"http://finna.is/favicon.ico",
L"http://finna.is/WWW_Search/?query={searchTerms}",
"UTF-8",
NULL,
61,
};
const PrepopulatedEngine fonecta_02_fi = {
L"Fonecta 02.fi",
L"www.fi",
"http://www.02.fi/img/favicon.ico",
L"http://www.02.fi/haku/{searchTerms}",
"UTF-8",
NULL,
46,
};
const PrepopulatedEngine forthnet = {
L"Forthnet",
L"forthnet.gr",
"http://search.forthnet.gr/favicon.ico",
L"http://search.forthnet.gr/cgi-bin/query?mss=search&q={searchTerms}",
"windows-1253",
NULL,
53,
};
const PrepopulatedEngine gigabusca = {
L"GiGaBusca",
L"gigabusca.com.br",
"http://www.gigabusca.com.br/favicon.ico",
L"http://www.gigabusca.com.br/buscar.php?query={searchTerms}",
"ISO-8859-1",
NULL,
81,
};
const PrepopulatedEngine go = {
L"GO.com",
L"go.com",
"http://search.yahoo.com/favicon.ico",
L"http://search.yahoo.com/search?ei={inputEncoding}&p={searchTerms}&"
L"fr=hsusgo1",
"ISO-8859-1",
NULL,
40,
};
const PrepopulatedEngine goo = {
L"goo",
L"goo.ne.jp",
"http://goo.ne.jp/gooicon.ico",
L"http://search.goo.ne.jp/web.jsp?MT={searchTerms}&IE={inputEncoding}",
"UTF-8",
NULL,
92,
};
const PrepopulatedEngine google = {
L"Google",
NULL,
"http://www.google.com/favicon.ico",
L"{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}"
L"{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&"
L"q={searchTerms}",
"UTF-8",
L"{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}",
1,
};
const PrepopulatedEngine guruji = {
L"guruji",
L"guruji.com",
"http://guruji.com/favicon.ico",
L"http://guruji.com/search?q={searchTerms}",
"UTF-8",
NULL,
38,
};
const PrepopulatedEngine iafrica = {
L"iafrica.com",
L"iafrica.com",
NULL,
L"http://search.iafrica.com/search?q={searchTerms}",
"ISO-8859-1",
NULL,
43,
};
const PrepopulatedEngine ilse = {
L"Ilse",
L"ilse.nl",
"http://search.ilse.nl/images/favicon.ico",
L"http://search.ilse.nl/web?search_for={searchTerms}",
"ISO-8859-1",
NULL,
30,
};
const PrepopulatedEngine in = {
L"in.gr",
L"in.gr",
"http://www.in.gr/favicon.ico",
L"http://find.in.gr/result.asp?q={searchTerms}",
"ISO-8859-7",
NULL,
54,
};
const PrepopulatedEngine jabse = {
L"Jabse",
L"jabse.com",
"http://www.jabse.com/favicon.ico",
L"http://www.jabse.com/searchmachine.php?query={searchTerms}",
"UTF-8",
NULL,
19,
};
const PrepopulatedEngine jamaicalive = {
L"JamaicaLive",
L"jalive.com.jm",
"http://jalive.com.jm/favicon.ico",
L"http://jalive.com.jm/search/?mode=allwords&search={searchTerms}",
"ISO-8859-1",
NULL,
39,
};
const PrepopulatedEngine jubii = {
L"Jubii",
L"jubii.dk",
"http://search.jubii.dk/favicon_jubii.ico",
L"http://search.jubii.dk/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
28,
};
const PrepopulatedEngine krstarica = {
L"Krstarica",
L"krstarica.rs",
"http://pretraga.krstarica.com/favicon.ico",
L"http://pretraga.krstarica.com/index.php?q={searchTerms}",
"windows-1250",
NULL,
84,
};
const PrepopulatedEngine kvasir = {
L"Kvasir",
L"kvasir.no",
"http://www.kvasir.no/img/favicon.ico",
L"http://www.kvasir.no/nettsok/searchResult.html?searchExpr={searchTerms}",
"ISO-8859-1",
NULL,
73,
};
const PrepopulatedEngine latne = {
L"LATNE",
L"latne.lv",
"http://latne.lv/favicon.ico",
L"http://latne.lv/siets.php?q={searchTerms}",
"UTF-8",
NULL,
71,
};
const PrepopulatedEngine leit = {
L"leit.is",
L"leit.is",
"http://leit.is/leit.ico",
L"http://leit.is/query.aspx?qt={searchTerms}",
"ISO-8859-1",
NULL,
59,
};
const PrepopulatedEngine libero = {
L"Libero",
L"libero.it",
"http://arianna.libero.it/favicon.ico",
L"http://arianna.libero.it/search/abin/integrata.cgi?query={searchTerms}",
"ISO-8859-1",
NULL,
63,
};
const PrepopulatedEngine live = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ar_XA = {
L"Live Search (\x0627\x0644\x0639\x0631\x0628\x064a\x0629)",
L"", // "live.com" is already taken by live_en_XA (see comment on ID below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=ar-XA&mkt=ar-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
7, // Can't be 3 as this has to appear in the Arabian countries' lists
// alongside live_en_XA.
};
const PrepopulatedEngine live_bg_BG = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=bg-BG&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_cs_CZ = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=cs-CZ&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_el_GR = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=el-GR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_ID = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en_ID&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_NZ = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-NZ&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_US = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-US&mkt=en-US&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_en_XA = {
L"Live Search (English)",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-XA&mkt=en-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_et_EE = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=et-EE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_hr_HR = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=hr-HR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_hu_HU = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=hu-HU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_it_IT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=it-IT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_lt_LT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=lt-LT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_pl_PL = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pl-PL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_pt_PT = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pt-PT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ro_RO = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=ro-RO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_ru_RU = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=ru-RU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_sk_SK = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=sk-SK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_sl_SI = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=sl-SI&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine live_th_TH = {
L"Live Search",
L"live.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=th-TH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine lycos_es = {
L"Lycos Espa" L"\x00f1" L"a",
L"lycos.es",
"http://buscador.lycos.es/favicon.ico",
L"http://buscador.lycos.es/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
34,
};
const PrepopulatedEngine lycos_nl = {
L"Lycos",
L"lycos.nl",
"http://zoek.lycos.nl/favicon.ico",
L"http://zoek.lycos.nl/cgi-bin/pursuit?query={searchTerms}",
"ISO-8859-1",
NULL,
34,
};
const PrepopulatedEngine mail_ru = {
L"@MAIL.RU",
L"mail.ru",
"http://img.go.mail.ru/favicon.ico",
L"http://go.mail.ru/search?q={searchTerms}",
"windows-1251",
NULL,
83,
};
const PrepopulatedEngine maktoob = {
L"\x0645\x0643\x062a\x0648\x0628",
L"maktoob.com",
"http://www.maktoob.com/favicon.ico",
L"http://www.maktoob.com/searchResult.php?q={searchTerms}",
"UTF-8",
NULL,
13,
};
const PrepopulatedEngine masrawy = {
L"\x0645\x0635\x0631\x0627\x0648\x064a",
L"masrawy.com",
"http://www.masrawy.com/new/images/masrawy.ico",
L"http://masrawy.com/new/search.aspx?sr={searchTerms}",
"windows-1256",
NULL,
14,
};
const PrepopulatedEngine matkurja = {
L"Mat'Kurja",
L"matkurja.com",
"http://matkurja.com/favicon.ico",
L"http://matkurja.com/si/iskalnik/?q={searchTerms}&search_source=directory",
"ISO-8859-2",
NULL,
88,
};
const PrepopulatedEngine meta = {
L"<META>",
L"meta.ua",
"http://meta.ua/favicon.ico",
L"http://meta.ua/search.asp?q={searchTerms}",
"windows-1251",
L"http://meta.ua/suggestions/?output=fxjson&oe=utf-8&q={searchTerms}",
102,
};
const PrepopulatedEngine msn = {
L"MSN",
L"msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_ar_XA = {
L"MSN (\x0627\x0644\x0639\x0631\x0628\x064a\x0629)",
L"", // "arabia.msn.com" is already taken by msn_en_XA (see comment on ID
// below).
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?setlang=ar-XA&mkt=ar-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
7, // Can't be 3 as this has to appear in the Arabian countries' lists
// alongside msn_en_XA.
};
const PrepopulatedEngine msn_da_DK = {
L"MSN Danmark",
L"dk.msn.com",
"http://search.msn.dk/s/wlflag.ico",
L"http://search.msn.dk/results.aspx?mkt=da-DK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_AT = {
L"MSN \x00d6sterreich",
L"at.msn.com",
"http://search.msn.at/s/wlflag.ico",
L"http://search.msn.at/results.aspx?mkt=de-AT&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_CH = {
L"MSN Schweiz (Deutsch)",
L"ch.msn.com",
"http://search.msn.ch/s/wlflag.ico",
L"http://search.msn.ch/results.aspx?setlang=de-CH&mkt=de-CH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_de_DE = {
L"MSN",
L"de.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=de-DE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_AU = {
L"ninemsn.com.au",
L"ninemsn.com.au",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-AU&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_CA = {
L"Sympatico / MSN (English)",
L"sympatico.msn.ca",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=en-CA&mkt=en-CA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_GB = {
L"MSN UK",
L"uk.msn.com",
"http://search.msn.co.uk/s/wlflag.ico",
L"http://search.msn.co.uk/results.aspx?mkt=en-GB&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_IE = {
L"MSN IE",
L"ie.msn.com",
"http://search.msn.ie/s/wlflag.ico",
L"http://search.msn.ie/results.aspx?mkt=en-IE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_IN = {
L"MSN India",
L"in.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=en-IN&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_MY = {
L"MSN Malaysia",
L"malaysia.msn.com",
"http://search.msn.com.my/s/wlflag.ico",
L"http://search.msn.com.my/results.aspx?mkt=en-MY&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_PH = {
L"MSN Philippines",
L"ph.msn.com",
"http://search.msn.com.ph/s/wlflag.ico",
L"http://search.msn.com.ph/results.aspx?mkt=en-PH&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_SG = {
L"MSN Singapore",
L"sg.msn.com",
"http://search.msn.com.sg/s/wlflag.ico",
L"http://search.msn.com.sg/results.aspx?mkt=en-SG&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_XA = {
L"MSN (English)",
L"arabia.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?setlang=en-XA&mkt=en-XA&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_en_ZA = {
L"MSN ZA",
L"za.msn.com",
"http://search.msn.co.za/s/wlflag.ico",
L"http://search.msn.co.za/results.aspx?mkt=en-ZA&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_AR = {
L"MSN Argentina",
L"ar.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-AR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_CL = {
L"MSN Chile",
L"cl.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-CL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_CO = {
L"MSN Colombia",
L"co.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-CO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_ES = {
L"MSN Espa" L"\x00f1" L"a",
L"es.msn.com",
"http://search.msn.es/s/wlflag.ico",
L"http://search.msn.es/results.aspx?mkt=es-ES&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_MX = {
L"Prodigy / MSN",
L"prodigy.msn.com",
"http://search.prodigy.msn.com/s/wlflag.ico",
L"http://search.prodigy.msn.com/results.aspx?mkt=es-MX&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_es_XL = {
L"MSN Latinoam\x00e9rica",
L"latam.msn.com",
"http://search.msn.com/s/wlflag.ico",
L"http://search.msn.com/results.aspx?mkt=es-XL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_fi_FI = {
L"MSN",
L"fi.msn.com",
"http://search.msn.fi/s/wlflag.ico",
L"http://search.msn.fi/results.aspx?mkt=fi-FI&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_fr_BE = {
L"MSN Belgique (Fran" L"\x00e7" L"ais)",
L"", // "be.msn.com" is already taken by msn_nl_BE (see comment on ID below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=fr-BE&mkt=fr-BE&"
L"q={searchTerms}",
"UTF-8",
NULL,
8, // Can't be 3 as this has to appear in the Belgium list alongside
// msn_nl_BE.
};
const PrepopulatedEngine msn_fr_CA = {
L"Sympatico / MSN (Fran" L"\x00e7" L"ais)",
L"", // "sympatico.msn.ca" is already taken by msn_en_CA (see comment on ID
// below).
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=fr-CA&mkt=fr-CA&"
L"q={searchTerms}",
"UTF-8",
NULL,
9, // Can't be 3 as this has to appear in the Canada list alongside
// msn_en_CA.
};
const PrepopulatedEngine msn_fr_CH = {
L"MSN Suisse (Fran" L"\x00e7" L"ais)",
L"", // "ch.msn.com" is already taken by msn_de_CH (see comment on ID below).
"http://search.msn.ch/s/wlflag.ico",
L"http://search.msn.ch/results.aspx?setlang=fr-CH&mkt=fr-CH&q={searchTerms}",
"UTF-8",
NULL,
10, // Can't be 3 as this has to appear in the Switzerland list alongside
// msn_de_CH.
};
const PrepopulatedEngine msn_fr_FR = {
L"MSN France",
L"fr.msn.com",
"http://search.msn.fr/s/wlflag.ico",
L"http://search.msn.fr/results.aspx?mkt=fr-FR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_he_IL = {
L"msn.co.il",
L"msn.co.il",
"http://msn.co.il/favicon.ico",
L"http://search.msn.co.il/Search.aspx?q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_ja_JP = {
L"MSN Japan",
L"jp.msn.com",
"http://search.msn.co.jp/s/wlflag.ico",
L"http://search.msn.co.jp/results.aspx?mkt=ja-JP&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nb_NO = {
L"MSN Norge",
L"no.msn.com",
"http://search.msn.no/s/wlflag.ico",
L"http://search.msn.no/results.aspx?mkt=nb-NO&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nl_BE = {
L"MSN (Nederlandstalige)",
L"be.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?setlang=nl-BE&mkt=nl-BE&"
L"q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_nl_NL = {
L"MSN.nl",
L"nl.msn.com",
"http://search.msn.nl/s/wlflag.ico",
L"http://search.msn.nl/results.aspx?mkt=nl-NL&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_pt_BR = {
L"MSN Brasil",
L"br.msn.com",
"http://search.live.com/s/wlflag.ico",
L"http://search.live.com/results.aspx?mkt=pt-BR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_sv_SE = {
L"MSN",
L"se.msn.com",
"http://search.msn.se/s/wlflag.ico",
L"http://search.msn.se/results.aspx?mkt=pv-SE&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_tr_TR = {
L"MSN T\x00fckiye'ye",
L"tr.msn.com",
"http://search.msn.com.tr/s/wlflag.ico",
L"http://search.msn.com.tr/results.aspx?mkt=tr-TR&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine msn_zh_HK = {
L"MSN Hong Kong",
L"hk.msn.com",
"http://search.msn.com.hk/s/wlflag.ico",
L"http://search.msn.com.hk/results.aspx?mkt=zh-HK&q={searchTerms}",
"UTF-8",
NULL,
3,
};
const PrepopulatedEngine mweb = {
L"MWEB",
L"mweb.co.za",
"http://mweb.co.za/favicon.ico",
L"http://search.mweb.co.za/search?&q={searchTerms}",
"UTF-8",
NULL,
42,
};
const PrepopulatedEngine mynet = {
L"MYNET",
L"mynet.com",
"http://img.mynet.com/mynetfavori.ico",
L"http://arama.mynet.com/search.aspx?q={searchTerms}&pg=q",
"windows-1254",
NULL,
101,
};
const PrepopulatedEngine mywebsearch = {
L"mywebsearch",
L"mywebsearch.com",
NULL,
L"http://search.mywebsearch.com/mywebsearch/AJmain.jhtml?"
L"searchfor={searchTerms}",
"UTF-8",
NULL,
97,
};
const PrepopulatedEngine najdi = {
L"Najdi.si",
L"najdi.si",
"http://www.najdi.si/master/favicon.ico",
L"http://www.najdi.si/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
87,
};
const PrepopulatedEngine nana10 = {
L"\x05e0\x05e2\x05e0\x05e2 10",
L"nana10.co.il",
"http://f.nau.co.il/Common/Includes/favicon.ico",
L"http://index.nana10.co.il/search.asp?q={searchTerms}",
"windows-1255",
NULL,
56,
};
const PrepopulatedEngine nate = {
L"\xb124\xc774\xd2b8\xb2f7\xcef4",
L"nate.com",
"http://nate.search.empas.com/favicon.ico",
L"http://nate.search.empas.com/search/all.html?q={searchTerms}",
"EUC-KR",
NULL,
69,
};
const PrepopulatedEngine naver = {
L"\xb124\xc774\xbc84",
L"naver.com",
"http://search.naver.com/favicon.ico",
L"http://search.naver.com/search.naver?ie={inputEncoding}"
L"&query={searchTerms}",
"UTF-8",
L"http://ac.search.naver.com/autocompl?m=s&ie={inputEncoding}&oe=utf-8&"
L"q={searchTerms}",
67,
};
const PrepopulatedEngine neti = {
L"NETI",
L"neti.ee",
"http://www.neti.ee/favicon.ico",
L"http://www.neti.ee/cgi-bin/otsing?query={searchTerms}",
"ISO-8859-1",
NULL,
44,
};
const PrepopulatedEngine netindex = {
L"NetINDEX",
L"netindex.pt",
"http://www.netindex.pt/favicon.ico",
L"http://www.netindex.pt/cgi-bin/index.cgi?question={searchTerms}",
"ISO-8859-1",
NULL,
78,
};
const PrepopulatedEngine nifty = {
L"@nifty",
L"nifty.com",
"http://www.nifty.com/favicon.ico",
L"http://search.nifty.com/cgi-bin/search.cgi?Text={searchTerms}",
"Shift_JIS",
NULL,
65,
};
const PrepopulatedEngine ohperu = {
L"Oh Per\x00fa",
L"ohperu.com",
NULL,
L"http://www.google.com.pe/custom?q={searchTerms}&"
L"client=pub-1950414869696311&ie={inputEncoding}&cof=GALT%3A%23000000"
L"%3BGL%3A1%3BDIV%3A%23FFFFFF%3BVLC%3A000000%3BAH%3Acenter%3BBGC%3AFFFFFF"
L"%3BLBGC%3AFFFFFF%3BALC%3A000000%3BLC%3A000000%3BT%3A000000%3BGFNT"
L"%3A000000%3BGIMP%3A000000%3BLH%3A50%3BLW%3A142%3BL%3Ahttp%3A%2F%2F"
L"www.ohperu.com%2Fohperu-logo-inv2.gif%3BS%3Ahttp%3A%2F%2Fwww.ohperu.com"
L"%3BFORID%3A1",
"ISO-8859-1",
NULL,
96,
};
const PrepopulatedEngine ok = {
L"OK.hu",
L"ok.hu",
"http://ok.hu/gfx/favicon.ico",
L"http://ok.hu/katalogus?q={searchTerms}",
"ISO-8859-2",
NULL,
6,
};
const PrepopulatedEngine onet = {
L"Onet.pl",
L"onet.pl",
"http://szukaj.onet.pl/favicon.ico",
L"http://szukaj.onet.pl/query.html?qt={searchTerms}",
"ISO-8859-2",
NULL,
75,
};
const PrepopulatedEngine orange = {
L"Orange",
L"orange.fr",
"http://www.orange.fr/favicon.ico",
L"http://rws.search.ke.voila.fr/RW/S/opensearch_orange?rdata={searchTerms}",
"ISO-8859-1",
L"http://search.ke.voila.fr/fr/cmplopensearch/xml/fullxml?"
L"rdata={searchTerms}",
48,
};
const PrepopulatedEngine ozu = {
L"OZ\x00da",
L"ozu.es",
"http://www.ozu.es/favicon.ico",
L"http://buscar.ozu.es/index.php?q={searchTerms}",
"ISO-8859-1",
NULL,
98,
};
const PrepopulatedEngine pogodak_ba = {
L"Pogodak!",
L"pogodak.ba",
"http://www.pogodak.ba/favicon.ico",
L"http://www.pogodak.ba/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodak_hr = {
L"Pogodak!",
L"pogodak.hr",
"http://www.pogodak.hr/favicon.ico",
L"http://www.pogodak.hr/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodak_rs = {
L"Pogodak!",
L"pogodak.rs",
"http://www.pogodak.rs/favicon.ico",
L"http://www.pogodak.rs/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24,
};
const PrepopulatedEngine pogodok = {
L"\x041f\x043e\x0433\x043e\x0434\x043e\x043a!",
L"pogodok.com.mk",
"http://www.pogodok.com.mk/favicon.ico",
L"http://www.pogodok.com.mk/search.jsp?q={searchTerms}",
"UTF-8",
NULL,
24, // Really the same engine as Pogodak, just has a small name change.
};
const PrepopulatedEngine rambler = {
L"Rambler",
L"rambler.ru",
"http://www.rambler.ru/favicon.ico",
L"http://www.rambler.ru/srch?words={searchTerms}",
"windows-1251",
NULL,
16,
};
const PrepopulatedEngine rediff = {
L"Rediff",
L"rediff.com",
"http://search1.rediff.com/favicon.ico",
L"http://search1.rediff.com/dirsrch/default.asp?MT={searchTerms}",
"UTF-8",
NULL,
37,
};
const PrepopulatedEngine rednano = {
L"Rednano",
L"rednano.sg",
"http://rednano.sg/favicon.ico",
L"http://rednano.sg/sfe/lwi.action?querystring={searchTerms}",
"UTF-8",
NULL,
41,
};
const PrepopulatedEngine sanook = {
L"\x0e2a\x0e19\x0e38\x0e01!",
L"sanook.com",
"http://search.sanook.com/favicon.ico",
L"http://search.sanook.com/search.php?q={searchTerms}",
"UTF-8",
NULL,
100,
};
const PrepopulatedEngine sapo = {
L"SAPO",
L"sapo.pt",
"http://imgs.sapo.pt/images/sapo.ico",
L"http://pesquisa.sapo.pt/?q={searchTerms}",
"UTF-8",
L"http://pesquisa.sapo.pt/livesapo?q={searchTerms}",
77,
};
const PrepopulatedEngine search_ch = {
L"search.ch",
L"search.ch",
"http://www.search.ch/favicon.ico",
L"http://www.search.ch/?q={searchTerms}",
"ISO-8859-1",
NULL,
51,
};
const PrepopulatedEngine sensis = {
L"sensis.com.au",
L"sensis.com.au",
"http://www.sensis.com.au/favicon.ico",
L"http://www.sensis.com.au/search.do?find={searchTerms}",
"UTF-8",
NULL,
32,
};
const PrepopulatedEngine sesam = {
L"Sesam",
L"sesam.no",
"http://sesam.no/images/favicon.gif",
L"http://sesam.no/search/?q={searchTerms}",
"UTF-8",
NULL,
74,
};
const PrepopulatedEngine seznam = {
L"Seznam",
L"seznam.cz",
"http://1.im.cz/szn/img/favicon.ico",
L"http://search.seznam.cz/?q={searchTerms}",
"UTF-8",
L"http:///suggest.fulltext.seznam.cz/?dict=fulltext_ff&phrase={searchTerms}&"
L"encoding={inputEncoding}&response_encoding=utf-8",
25,
};
const PrepopulatedEngine sogou = {
L"\x641c\x72d7",
L"sogou.com",
"http://www.sogou.com/favicon.ico",
L"http://www.sogou.com/web?query={searchTerms}",
"GB2312",
NULL,
20,
};
const PrepopulatedEngine soso = {
L"\x641c\x641c",
L"soso.com",
"http://www.soso.com/favicon.ico",
L"http://www.soso.com/q?w={searchTerms}",
"GB2312",
NULL,
22,
};
const PrepopulatedEngine spray = {
L"Spray",
L"spray.se",
"http://www.eniro.se/favicon.ico",
L"http://www.eniro.se/query?ax=spray&search_word={searchTerms}&what=web",
"ISO-8859-1",
NULL,
99,
};
const PrepopulatedEngine szm = {
L"SZM.sk",
L"szm.sk",
"http://szm.sk/favicon.ico",
L"http://szm.sk/search/?co=1&q={searchTerms}",
"windows-1250",
NULL,
86,
};
const PrepopulatedEngine t_online = {
L"T-Online",
L"suche.t-online.de",
"http://suche.t-online.de/favicon.ico",
L"http://suche.t-online.de/fast-cgi/tsc?sr=chrome&q={searchTerms}",
"UTF-8",
NULL,
49,
};
const PrepopulatedEngine tango = {
L"Tango",
L"tango.hu",
"http://tango.hu/favicon.ico",
L"http://tango.hu/search.php?q={searchTerms}",
"windows-1250",
NULL,
58,
};
const PrepopulatedEngine tapuz = {
L"\x05ea\x05e4\x05d5\x05d6 \x05d0\x05e0\x05e9\x05d9\x05dd",
L"tapuz.co.il",
"http://www.tapuz.co.il/favicon.ico",
L"http://www.tapuz.co.il/search/search.asp?q={searchTerms}",
"UTF-8",
NULL,
57,
};
const PrepopulatedEngine terra_ar = {
L"Terra Argentina",
L"terra.com.ar",
"http://buscar.terra.com.ar/favicon.ico",
L"http://buscar.terra.com.ar/Default.aspx?query={searchTerms}&source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_ec = {
L"Terra Ecuador",
L"terra.com.ec",
"http://buscador.terra.com.ec/favicon.ico",
L"http://buscador.terra.com.ec/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_es = {
L"Terra",
L"terra.es",
"http://buscador.terra.es/favicon.ico",
L"http://buscador.terra.es/Default.aspx?query={searchTerms}&source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_mx = {
L"Terra",
L"terra.com.mx",
"http://buscador.terra.com.mx/favicon.ico",
L"http://buscador.terra.com.mx/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine terra_pe = {
L"Terra",
L"terra.com.pe",
"http://buscador.terra.com.pe/favicon.ico",
L"http://buscador.terra.com.pe/Default.aspx?query={searchTerms}&"
L"source=Search",
"ISO-8859-1",
NULL,
90,
};
const PrepopulatedEngine toile = {
L"La Toile du Qu" L"\x00e9" L"bec",
L"toile.com",
"http://static.search.canoe.ca/s-toile/img/favicon_toile.ico",
L"http://www.toile.com/search?q={searchTerms}",
"UTF-8",
NULL,
36,
};
const PrepopulatedEngine tut = {
L"TUT.BY",
L"tut.by",
"http://www.tut.by/favicon.ico",
L"http://search.tut.by/?query={searchTerms}",
"windows-1251",
NULL,
17,
};
const PrepopulatedEngine uol = {
L"UOL Busca",
L"busca.uol.com.br",
"http://busca.uol.com.br/favicon.ico",
L"http://busca.uol.com.br/www/index.html?q={searchTerms}",
"ISO-8859-1",
NULL,
82,
};
const PrepopulatedEngine vinden = {
L"Vinden.nl",
L"vinden.nl",
"http://www.vinden.nl/favicon.ico",
L"http://www.vinden.nl/?q={searchTerms}",
"UTF-8",
NULL,
31,
};
const PrepopulatedEngine virgilio = {
L"Virgilio",
L"virgilio.alice.it",
"http://ricerca.alice.it/favicon.ico",
L"http://ricerca.alice.it/ricerca?qs={searchTerms}",
"ISO-8859-1",
NULL,
62,
};
const PrepopulatedEngine voila = {
L"Voila",
L"voila.fr",
"http://search.ke.voila.fr/favicon.ico",
L"http://rws.search.ke.voila.fr/RW/S/opensearch_voila?rdata={searchTerms}",
"ISO-8859-1",
L"http://search.ke.voila.fr/fr/cmplopensearch/xml/fullxml?"
L"rdata={searchTerms}",
47,
};
const PrepopulatedEngine walla = {
L"\x05d5\x05d5\x05d0\x05dc\x05d4!",
L"walla.co.il",
"http://www.walla.co.il/favicon.ico",
L"http://search.walla.co.il/?e=hew&q={searchTerms}",
"windows-1255",
NULL,
55,
};
const PrepopulatedEngine web_de = {
L"WEB.DE",
L"web.de",
"http://img.ui-portal.de/search/img/webde/favicon.ico",
L"http://suche.web.de/search/web/?su={searchTerms}",
"ISO-8859-1",
NULL,
50,
};
const PrepopulatedEngine wp = {
L"Wirtualna Polska",
L"wp.pl",
"http://szukaj.wp.pl/favicon.ico",
L"http://szukaj.wp.pl/szukaj.html?szukaj={searchTerms}",
"ISO-8859-2",
NULL,
76,
};
const PrepopulatedEngine yagua = {
L"Yagua.com",
L"yagua.com",
"http://yagua.paraguay.com/favicon.ico",
L"http://yagua.paraguay.com/buscador.php?q={searchTerms}&cs={inputEncoding}",
"ISO-8859-1",
NULL,
94,
};
const PrepopulatedEngine yahoo = {
L"Yahoo!",
L"yahoo.com",
"http://search.yahoo.com/favicon.ico",
L"http://search.yahoo.com/search?ei={inputEncoding}&fr=crmas&p={searchTerms}",
"UTF-8",
L"http://ff.search.yahoo.com/gossip?output=fxjson&command={searchTerms}",
2,
};
// For regional Yahoo variants without region-specific suggestion service,
// suggestion is disabled. For some of them, we might consider
// using a fallback (e.g. de for at/ch, ca or fr for qc, en for nl, no, hk).
const PrepopulatedEngine yahoo_ar = {
L"Yahoo! Argentina",
L"ar.yahoo.com",
"http://ar.search.yahoo.com/favicon.ico",
L"http://ar.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://ar-sayt.ff.search.yahoo.com/gossip-ar-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_at = {
L"Yahoo! Suche",
L"at.yahoo.com",
"http://at.search.yahoo.com/favicon.ico",
L"http://at.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_au = {
L"Yahoo!7",
L"au.yahoo.com",
"http://au.search.yahoo.com/favicon.ico",
L"http://au.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://aue-sayt.ff.search.yahoo.com/gossip-au-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_br = {
L"Yahoo! Brasil",
L"br.yahoo.com",
"http://br.search.yahoo.com/favicon.ico",
L"http://br.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://br-sayt.ff.search.yahoo.com/gossip-br-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ca = {
L"Yahoo! Canada",
L"ca.yahoo.com",
"http://ca.search.yahoo.com/favicon.ico",
L"http://ca.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.ca.yahoo.com/gossip-ca-sayt?output=fxjsonp&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ch = {
L"Yahoo! Suche",
L"ch.yahoo.com",
"http://ch.search.yahoo.com/favicon.ico",
L"http://ch.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_cl = {
L"Yahoo! Chile",
L"cl.yahoo.com",
"http://cl.search.yahoo.com/favicon.ico",
L"http://cl.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_cn = {
L"\x4e2d\x56fd\x96c5\x864e",
L"cn.yahoo.com",
"http://search.cn.yahoo.com/favicon.ico",
L"http://search.cn.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"GB2312",
// http://cn.yahoo.com/cnsuggestion/suggestion.inc.php?of=fxjson&query=
// returns in a proprietary format ('|' delimeted word list).
NULL,
2,
};
const PrepopulatedEngine yahoo_co = {
L"Yahoo! Colombia",
L"co.yahoo.com",
"http://co.search.yahoo.com/favicon.ico",
L"http://co.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_de = {
L"Yahoo! Deutschland",
L"de.yahoo.com",
"http://de.search.yahoo.com/favicon.ico",
L"http://de.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://de-sayt.ff.search.yahoo.com/gossip-de-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_dk = {
L"Yahoo! Danmark",
L"dk.yahoo.com",
"http://dk.search.yahoo.com/favicon.ico",
L"http://dk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_es = {
L"Yahoo! Espa" L"\x00f1" L"a",
L"es.yahoo.com",
"http://es.search.yahoo.com/favicon.ico",
L"http://es.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://es-sayt.ff.search.yahoo.com/gossip-es-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_fi = {
L"Yahoo!-haku",
L"fi.yahoo.com",
"http://fi.search.yahoo.com/favicon.ico",
L"http://fi.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_fr = {
L"Yahoo! France",
L"fr.yahoo.com",
"http://fr.search.yahoo.com/favicon.ico",
L"http://fr.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://fr-sayt.ff.search.yahoo.com/gossip-fr-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_hk = {
L"Yahoo! Hong Kong",
L"hk.yahoo.com",
"http://hk.search.yahoo.com/favicon.ico",
L"http://hk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
// http://history.hk.search.yahoo.com/ac/ac_msearch.php?query={searchTerms}
// returns a JSON with key-value pairs. Setting parameters (ot, of, output)
// to fxjson, json, or js doesn't help.
NULL,
2,
};
const PrepopulatedEngine yahoo_id = {
L"Yahoo! Indonesia",
L"id.yahoo.com",
"http://id.search.yahoo.com/favicon.ico",
L"http://id.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://id-sayt.ff.search.yahoo.com/gossip-id-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_in = {
L"Yahoo! India",
L"in.yahoo.com",
"http://in.search.yahoo.com/favicon.ico",
L"http://in.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://in-sayt.ff.search.yahoo.com/gossip-in-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_it = {
L"Yahoo! Italia",
L"it.yahoo.com",
"http://it.search.yahoo.com/favicon.ico",
L"http://it.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://it-sayt.ff.search.yahoo.com/gossip-it-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_jp = {
L"Yahoo! JAPAN",
L"yahoo.co.jp",
"http://search.yahoo.co.jp/favicon.ico",
L"http://search.yahoo.co.jp/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_kr = {
L"\xc57c\xd6c4! \xcf54\xb9ac\xc544",
L"kr.yahoo.com",
"http://kr.search.yahoo.com/favicon.ico",
L"http://kr.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://kr.atc.search.yahoo.com/atcx.php?property=main&ot=fxjson&"
L"ei=utf8&eo=utf8&command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_malaysia = {
L"Yahoo! Malaysia",
L"malaysia.yahoo.com",
"http://malaysia.search.yahoo.com/favicon.ico",
L"http://malaysia.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://my-sayt.ff.search.yahoo.com/gossip-my-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_mx = {
L"Yahoo! M\x00e9xico",
L"mx.yahoo.com",
"http://mx.search.yahoo.com/favicon.ico",
L"http://mx.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.mx.yahoo.com/gossip-mx-sayt?output=fxjsonp&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_nl = {
L"Yahoo! Nederland",
L"nl.yahoo.com",
"http://nl.search.yahoo.com/favicon.ico",
L"http://nl.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_no = {
L"Yahoo! Norge",
L"no.yahoo.com",
"http://no.search.yahoo.com/favicon.ico",
L"http://no.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_nz = {
L"Yahoo!Xtra",
L"nz.yahoo.com",
"http://nz.search.yahoo.com/favicon.ico",
L"http://nz.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://aue-sayt.ff.search.yahoo.com/gossip-nz-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_pe = {
L"Yahoo! Per\x00fa",
L"pe.yahoo.com",
"http://pe.search.yahoo.com/favicon.ico",
L"http://pe.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ph = {
L"Yahoo! Philippines",
L"ph.yahoo.com",
"http://ph.search.yahoo.com/favicon.ico",
L"http://ph.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://ph-sayt.ff.search.yahoo.com/gossip-ph-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_qc = {
L"Yahoo! Qu" L"\x00e9" L"bec",
L"qc.yahoo.com",
"http://qc.search.yahoo.com/favicon.ico",
L"http://qc.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
5, // Can't be 2 as this has to appear in the Canada list alongside yahoo_ca.
};
const PrepopulatedEngine yahoo_ru = {
L"Yahoo! \x043f\x043e-\x0440\x0443\x0441\x0441\x043a\x0438",
L"ru.yahoo.com",
"http://ru.search.yahoo.com/favicon.ico",
L"http://ru.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
NULL,
2,
};
const PrepopulatedEngine yahoo_sg = {
L"Yahoo! Singapore",
L"sg.yahoo.com",
"http://sg.search.yahoo.com/favicon.ico",
L"http://sg.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://sg-sayt.ff.search.yahoo.com/gossip-sg-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_th = {
L"Yahoo! \x0e1b\x0e23\x0e30\x0e40\x0e17\x0e28\x0e44\x0e17\x0e22",
L"th.yahoo.com",
"http://th.search.yahoo.com/favicon.ico",
L"http://th.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://th-sayt.ff.search.yahoo.com/gossip-th-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_tw = {
L"Yahoo!\x5947\x6469",
L"tw.yahoo.com",
"http://tw.search.yahoo.com/favicon.ico",
L"http://tw.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
// "http://tw.yahoo.com/ac/ac_search.php?eo=utf8&of=js&prop=web&query="
// returns a JSON file prepended with 'fxjson={'.
NULL,
2,
};
const PrepopulatedEngine yahoo_uk = {
L"Yahoo! UK & Ireland",
L"uk.yahoo.com",
"http://uk.search.yahoo.com/favicon.ico",
L"http://uk.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://uk-sayt.ff.search.yahoo.com/gossip-uk-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_ve = {
L"Yahoo! Venezuela",
L"ve.yahoo.com",
"http://ve.search.yahoo.com/favicon.ico",
L"http://ve.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://gossip.telemundo.yahoo.com/gossip-e1-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yahoo_vn = {
L"Yahoo! Vi\x1ec7t Nam",
L"vn.yahoo.com",
"http://vn.search.yahoo.com/favicon.ico",
L"http://vn.search.yahoo.com/search?ei={inputEncoding}&fr=crmas&"
L"p={searchTerms}",
"UTF-8",
L"http://vn-sayt.ff.search.yahoo.com/gossip-vn-sayt?output=fxjson&"
L"command={searchTerms}",
2,
};
const PrepopulatedEngine yam = {
L"\x5929\x7a7a",
L"yam.com",
"http://www.yam.com/i/8/sky.ico",
L"http://search.yam.com/wps?k={searchTerms}",
"Big5",
NULL,
23,
};
const PrepopulatedEngine yamli = {
L"Yamli",
L"yamli.com",
"http://www.yamli.com/favicon.ico",
L"http://www.yamli.com/#q={searchTerms}",
"UTF-8",
NULL,
11,
};
const PrepopulatedEngine yandex_ru = {
L"\x042f\x043d\x0434\x0435\x043a\x0441",
L"yandex.ru",
"http://yandex.ru/favicon.ico",
L"http://yandex.ru/yandsearch?text={searchTerms}",
"UTF-8",
L"http://suggest.yandex.net/suggest-ff.cgi?part={searchTerms}",
15,
};
const PrepopulatedEngine yandex_ua = {
L"\x042f\x043d\x0434\x0435\x043a\x0441",
L"yandex.ua",
"http://yandex.ua/favicon.ico",
L"http://yandex.ua/yandsearch?text={searchTerms}",
"UTF-8",
L"http://suggest.yandex.net/suggest-ff.cgi?part={searchTerms}",
15,
};
const PrepopulatedEngine zoznam = {
L"Zoznam",
L"zoznam.sk",
"http://zoznam.sk/favicon.ico",
L"http://zoznam.sk/hladaj.fcgi?s={searchTerms}",
"windows-1250",
NULL,
85,
};
// Lists of engines per country ////////////////////////////////////////////////
// Put these in order with most interesting/important first. The default will
// be the first engine.
// Default (for countries with no better engine set)
const PrepopulatedEngine* engines_default[] = { &google, &yahoo, &live, };
// United Arab Emirates
const PrepopulatedEngine* engines_AE[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Albania
const PrepopulatedEngine* engines_AL[] =
{ &google, &yahoo, &live_en_XA, &live_ar_XA, };
// Argentina
const PrepopulatedEngine* engines_AR[] =
{ &google, &msn_es_AR, &altavista_ar, &terra_ar, &yahoo_ar, };
// Austria
const PrepopulatedEngine* engines_AT[] = { &google, &yahoo_at, &msn_de_AT, };
// Australia
const PrepopulatedEngine* engines_AU[] =
{ &google, &yahoo_au, &msn_en_AU, &sensis, };
// Bosnia and Herzegovina
const PrepopulatedEngine* engines_BA[] =
{ &google, &pogodak_ba, &yahoo, &live, };
// Belgium
const PrepopulatedEngine* engines_BE[] =
{ &google, &yahoo, &msn_nl_BE, &msn_fr_BE, };
// Bulgaria
// The commented-out entry for "dir" below is for dir.bg, &which we don't
// currently support because it uses POST instead of GET for its searches.
// See http://b/1196285
const PrepopulatedEngine* engines_BG[] =
{ &google, &/*dir,*/ yahoo, &jabse, &live_bg_BG, };
// Bahrain
const PrepopulatedEngine* engines_BH[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Brunei
const PrepopulatedEngine* engines_BN[] =
{ &google, &yahoo_malaysia, &msn_en_MY, };
// Bolivia
const PrepopulatedEngine* engines_BO[] =
{ &google, &altavista, &msn_es_XL, &yahoo, &ask_es, };
// Brazil
const PrepopulatedEngine* engines_BR[] =
{ &google, &msn_pt_BR, &yahoo_br, &aonde, &gigabusca, &uol, };
// Belarus
const PrepopulatedEngine* engines_BY[] =
{ &google, &yandex_ru, &rambler, &yahoo, &tut, };
// Belize
const PrepopulatedEngine* engines_BZ[] = { &google, &yahoo, &live, &aol, };
// Canada
const PrepopulatedEngine* engines_CA[] =
{ &google, &msn_en_CA, &msn_fr_CA, &yahoo_ca, &yahoo_qc, &toile, };
// Switzerland
const PrepopulatedEngine* engines_CH[] =
{ &google, &search_ch, &yahoo_ch, &msn_de_CH, &msn_fr_CH, &bluewin, };
// Chile
const PrepopulatedEngine* engines_CL[] =
{ &google, &yahoo_cl, &altavista, &msn_es_CL, };
// China
const PrepopulatedEngine* engines_CN[] =
{ &google, &baidu, &yahoo_cn, &sogou, &soso, };
// Colombia
const PrepopulatedEngine* engines_CO[] =
{ &google, &msn_es_CO, &ask_es, &altavista, &conexcol, &yahoo_co, };
// Costa Rica
const PrepopulatedEngine* engines_CR[] =
{ &google, &msn_es_XL, &yahoo, &altavista, &aol, &lycos_es, };
// Czech Republic
const PrepopulatedEngine* engines_CZ[] =
{ &google, &seznam, ¢rum_cz, &atlas_cz, &live_cs_CZ, };
// Germany
const PrepopulatedEngine* engines_DE[] =
{ &google, &msn_de_DE, &yahoo_de, &t_online, &ask_de, &web_de, };
// Denmark
const PrepopulatedEngine* engines_DK[] =
{ &google, &jubii, &msn_da_DK, &yahoo_dk, &eniro_dk, };
// Dominican Republic
const PrepopulatedEngine* engines_DO[] =
{ &google, &msn_es_XL, &yahoo, &altavista, &go, &aol, };
// Algeria
const PrepopulatedEngine* engines_DZ[] =
{ &google, &yahoo, &yamli, &msn_en_XA, &msn_ar_XA, &araby, };
// Ecuador
const PrepopulatedEngine* engines_EC[] =
{ &google, &msn_es_XL, &yahoo, &terra_ec, };
// Estonia
const PrepopulatedEngine* engines_EE[] =
{ &google, &neti, &delfi_ee, &yahoo, &live_et_EE, };
// Egypt
const PrepopulatedEngine* engines_EG[] =
{ &google, &masrawy, &yahoo, &maktoob, &araby, &msn_en_XA, &msn_ar_XA, };
// Spain
const PrepopulatedEngine* engines_ES[] =
{ &google, &msn_es_ES, &yahoo_es, &terra_es, &ozu, &altavista_es, };
// Faroe Islands
const PrepopulatedEngine* engines_FO[] =
{ &google, &jubii, &msn_da_DK, &yahoo_dk, &eniro_dk, };
// Finland
const PrepopulatedEngine* engines_FI[] =
{ &google, &msn_fi_FI, &yahoo_fi, &eniro_fi, &fonecta_02_fi, };
// France
const PrepopulatedEngine* engines_FR[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// United Kingdom
const PrepopulatedEngine* engines_GB[] =
{ &google, &yahoo_uk, &msn_en_GB, &ask_uk, };
// Greece
const PrepopulatedEngine* engines_GR[] =
{ &google, &yahoo, &forthnet, &in, &live_el_GR };
// Guatemala
const PrepopulatedEngine* engines_GT[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &go, };
// Hong Kong
const PrepopulatedEngine* engines_HK[] =
{ &google, &yahoo_hk, &msn_zh_HK, &sogou, &baidu, };
// Honduras
const PrepopulatedEngine* engines_HN[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, };
// Croatia
const PrepopulatedEngine* engines_HR[] =
{ &google, &yahoo, &pogodak_hr, &live_hr_HR, };
// Hungary
const PrepopulatedEngine* engines_HU[] = { &google, &tango, &ok, &live_hu_HU, };
// Indonesia
const PrepopulatedEngine* engines_ID[] = { &google, &yahoo_id, &live_en_ID, };
// Ireland
const PrepopulatedEngine* engines_IE[] = { &google, &yahoo_uk, &msn_en_IE, };
// Israel
const PrepopulatedEngine* engines_IL[] =
{ &google, &walla, &nana10, &tapuz, &msn_he_IL, };
// India
const PrepopulatedEngine* engines_IN[] =
{ &google, &yahoo_in, &msn_en_IN, &rediff, &guruji, };
// Iraq
const PrepopulatedEngine* engines_IQ[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Iran
const PrepopulatedEngine* engines_IR[] = { &google, };
// Iceland
const PrepopulatedEngine* engines_IS[] = { &google, &leit, &embla, &finna, };
// Italy
const PrepopulatedEngine* engines_IT[] =
{ &google, &virgilio, &yahoo_it, &libero, &ask_it, &live_it_IT, };
// Jamaica
const PrepopulatedEngine* engines_JM[] =
{ &google, &jamaicalive, &yahoo, &live, &go, &aol, };
// Jordan
const PrepopulatedEngine* engines_JO[] =
{ &google, &maktoob, &yamli, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Japan
const PrepopulatedEngine* engines_JP[] =
{ &google, &yahoo_jp, &msn_ja_JP, &biglobe, &goo, &nifty, };
// Kenya
const PrepopulatedEngine* engines_KE[] = { &google, &yahoo, &msn, };
// Kuwait
const PrepopulatedEngine* engines_KW[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// South Korea
const PrepopulatedEngine* engines_KR[] =
{ &google, &naver, &daum, &yahoo_kr, &nate, &empas, };
// Lebanon
const PrepopulatedEngine* engines_LB[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Liechtenstein
const PrepopulatedEngine* engines_LI[] =
{ &google, &msn_de_DE, &yahoo_de, &t_online, &ask_de, &web_de, };
// Lithuania
const PrepopulatedEngine* engines_LT[] =
{ &google, &delfi_lt, &yahoo, &yandex_ru, &live_lt_LT, };
// Luxembourg
const PrepopulatedEngine* engines_LU[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// Latvia
const PrepopulatedEngine* engines_LV[] =
{ &google, &delfi_lv, &yahoo, &yandex_ru, &latne, };
// Libya
const PrepopulatedEngine* engines_LY[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Morocco
const PrepopulatedEngine* engines_MA[] =
{ &google, &yamli, &araby, &yahoo, &msn_en_XA, &msn_ar_XA, };
// Monaco
const PrepopulatedEngine* engines_MC[] =
{ &google, &voila, &yahoo_fr, &msn_fr_FR, &orange, &aol_fr, };
// Montenegro
const PrepopulatedEngine* engines_ME[] =
{ &google, &yahoo, &krstarica, &pogodak_rs, &aladin, &live, };
// Macedonia
const PrepopulatedEngine* engines_MK[] = { &google, &pogodok, &yahoo, &live, };
// Mexico
const PrepopulatedEngine* engines_MX[] =
{ &google, &msn_es_MX, &yahoo_mx, &ask_es, &altavista_mx, &terra_mx, };
// Malaysia
const PrepopulatedEngine* engines_MY[] =
{ &google, &yahoo_malaysia, &msn_en_MY, };
// Nicaragua
const PrepopulatedEngine* engines_NI[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, };
// Netherlands
const PrepopulatedEngine* engines_NL[] =
{ &google, &ilse, &msn_nl_NL, &yahoo_nl, &lycos_nl, &vinden, };
// Norway
const PrepopulatedEngine* engines_NO[] =
{ &google, &msn_nb_NO, &abcsok, &yahoo_no, &kvasir, &sesam, };
// New Zealand
const PrepopulatedEngine* engines_NZ[] = { &google, &yahoo_nz, &live_en_NZ, };
// Oman
const PrepopulatedEngine* engines_OM[] =
{ &google, &maktoob, &yahoo, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Panama
const PrepopulatedEngine* engines_PA[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &lycos_es, };
// Peru
const PrepopulatedEngine* engines_PE[] =
{ &google, &msn_es_XL, &yahoo_pe, &terra_pe, &adonde, &ohperu, };
// Philippines
const PrepopulatedEngine* engines_PH[] = { &google, &yahoo_ph, &msn_en_PH, };
// Pakistan
const PrepopulatedEngine* engines_PK[] = { &google, &yahoo, &msn, };
// Puerto Rico
const PrepopulatedEngine* engines_PR[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &mywebsearch, };
// Poland
const PrepopulatedEngine* engines_PL[] = { &google, &onet, &wp, &live_pl_PL, };
// Portugal
const PrepopulatedEngine* engines_PT[] =
{ &google, &sapo, &yahoo, &live_pt_PT, &netindex, &aeiou, };
// Paraguay
const PrepopulatedEngine* engines_PY[] =
{ &google, &msn_es_XL, &yahoo, &lycos_es, &yagua, &go, };
// Qatar
const PrepopulatedEngine* engines_QA[] =
{ &google, &maktoob, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, };
// Romania
const PrepopulatedEngine* engines_RO[] = { &google, &yahoo, &live_ro_RO, };
// Serbia
const PrepopulatedEngine* engines_RS[] =
{ &google, &yahoo, &krstarica, &pogodak_rs, &aladin, &live, };
// Russia
const PrepopulatedEngine* engines_RU[] =
{ &google, &yandex_ru, &rambler, &mail_ru, &yahoo_ru, &live_ru_RU, };
// Saudi Arabia
const PrepopulatedEngine* engines_SA[] =
{ &google, &yahoo, &araby, &msn_en_XA, &msn_ar_XA, &maktoob, };
// Sweden
const PrepopulatedEngine* engines_SE[] =
{ &google, &eniro_se, &msn_sv_SE, &altavista_se, &spray, };
// Singapore
const PrepopulatedEngine* engines_SG[] =
{ &google, &yahoo_sg, &msn_en_SG, &rednano, };
// Slovenia
const PrepopulatedEngine* engines_SI[] =
{ &google, &najdi, &yahoo, &matkurja, &live_sl_SI, };
// Slovakia
const PrepopulatedEngine* engines_SK[] =
{ &google, &zoznam, ¢rum_sk, &atlas_sk, &szm, &live_sk_SK, };
// El Salvador
const PrepopulatedEngine* engines_SV[] =
{ &google, &msn_es_XL, &yahoo, &ask_es, &altavista, &go, };
// Syria
const PrepopulatedEngine* engines_SY[] =
{ &google, &yahoo, &maktoob, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// Thailand
const PrepopulatedEngine* engines_TH[] =
{ &google, &sanook, &yahoo_th, &live_th_TH, };
// Tunisia
const PrepopulatedEngine* engines_TN[] =
{ &google, &maktoob, &yamli, &yahoo, &msn_en_XA, &msn_ar_XA, };
// Turkey
const PrepopulatedEngine* engines_TR[] =
{ &google, &msn_tr_TR, &yahoo, &mynet, };
// Trinidad and Tobago
const PrepopulatedEngine* engines_TT[] = { &google, &live, &yahoo, &go, &aol, };
// Taiwan
const PrepopulatedEngine* engines_TW[] = { &google, &yahoo_tw, &yam, };
// Ukraine
const PrepopulatedEngine* engines_UA[] =
{ &google, &meta, &yandex_ua, &bigmir, &rambler, };
// United States
const PrepopulatedEngine* engines_US[] =
{ &google, &yahoo, &live_en_US, &aol, &ask, };
// Uruguay
const PrepopulatedEngine* engines_UY[] =
{ &google, &msn_es_XL, &yahoo, &go, &lycos_es, };
// Venezuela
const PrepopulatedEngine* engines_VE[] =
{ &google, &msn_es_XL, &yahoo_ve, &altavista, };
// Vietnam
const PrepopulatedEngine* engines_VN[] = { &google, &yahoo_vn, };
// Yemen
const PrepopulatedEngine* engines_YE[] =
{ &google, &yahoo, &maktoob, &yamli, &araby, &msn_en_XA, &msn_ar_XA, };
// South Africa
const PrepopulatedEngine* engines_ZA[] =
{ &google, &yahoo, &msn_en_ZA, &mweb, &iafrica, };
// Zimbabwe
const PrepopulatedEngine* engines_ZW[] = { &google, &yahoo, &msn, };
// Geographic mappings /////////////////////////////////////////////////////////
// Please refer to ISO 3166-1 for information about the two-character country
// codes; http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 is useful. In the
// following (C++) code, we pack the two letters of the country code into an int
// value we call the CountryID.
const int kCountryIDUnknown = -1;
inline int CountryCharsToCountryID(char c1, char c2) {
return c1 << 8 | c2;
}
int CountryCharsToCountryIDWithUpdate(char c1, char c2) {
// SPECIAL CASE: In 2003, Yugoslavia renamed itself to Serbia and Montenegro.
// Serbia and Montenegro dissolved their union in June 2006. Yugoslavia was
// ISO 'YU' and Serbia and Montenegro were ISO 'CS'. Serbia was subsequently
// issued 'RS' and Montenegro 'ME'. Windows XP and Mac OS X Leopard still use
// the value 'YU'. If we get a value of 'YU' or 'CS' we will map it to 'RS'.
if ((c1 == 'Y' && c2 == 'U') ||
(c1 == 'C' && c2 == 'S')) {
c1 = 'R';
c2 = 'S';
}
// SPECIAL CASE: Timor-Leste changed from 'TP' to 'TL' in 2002. Windows XP
// predates this; we therefore map this value.
if (c1 == 'T' && c2 == 'P')
c2 = 'L';
return CountryCharsToCountryID(c1, c2);
}
#if defined(OS_WIN)
// For reference, a list of GeoIDs can be found at
// http://msdn.microsoft.com/en-us/library/ms776390.aspx .
int GeoIDToCountryID(GEOID geo_id) {
const int kISOBufferSize = 3; // Two plus one for the terminator.
wchar_t isobuf[kISOBufferSize] = { 0 };
int retval = GetGeoInfo(geo_id, GEO_ISO2, isobuf, kISOBufferSize, 0);
if (retval == kISOBufferSize &&
!(isobuf[0] == L'X' && isobuf[1] == L'X'))
return CountryCharsToCountryIDWithUpdate(static_cast<char>(isobuf[0]),
static_cast<char>(isobuf[1]));
// Various locations have ISO codes that Windows does not return.
switch(geo_id) {
case 0x144: // Guernsey
return CountryCharsToCountryID('G', 'G');
case 0x148: // Jersey
return CountryCharsToCountryID('J', 'E');
case 0x3B16: // Isle of Man
return CountryCharsToCountryID('I', 'M');
// 'UM' (U.S. Minor Outlying Islands)
case 0x7F: // Johnston Atoll
case 0x102: // Wake Island
case 0x131: // Baker Island
case 0x146: // Howland Island
case 0x147: // Jarvis Island
case 0x149: // Kingman Reef
case 0x152: // Palmyra Atoll
case 0x52FA: // Midway Islands
return CountryCharsToCountryID('U', 'M');
// 'SH' (Saint Helena)
case 0x12F: // Ascension Island
case 0x15C: // Tristan da Cunha
return CountryCharsToCountryID('S', 'H');
// 'IO' (British Indian Ocean Territory)
case 0x13A: // Diego Garcia
return CountryCharsToCountryID('I', 'O');
// Other cases where there is no ISO country code; we assign countries that
// can serve as reasonable defaults.
case 0x154: // Rota Island
case 0x155: // Saipan
case 0x15A: // Tinian Island
return CountryCharsToCountryID('U', 'S');
case 0x134: // Channel Islands
return CountryCharsToCountryID('G', 'B');
case 0x143: // Guantanamo Bay
default:
return kCountryIDUnknown;
}
}
int GetCurrentCountryID() {
GEOID geo_id = GetUserGeoID(GEOCLASS_NATION);
return GeoIDToCountryID(geo_id);
}
#elif defined(OS_MACOSX)
int GetCurrentCountryID() {
scoped_cftyperef<CFLocaleRef> locale(CFLocaleCopyCurrent());
CFStringRef country = (CFStringRef)CFLocaleGetValue(locale.get(),
kCFLocaleCountryCode);
if (!country)
return kCountryIDUnknown;
UniChar isobuf[2];
CFRange char_range = CFRangeMake(0, 2);
CFStringGetCharacters(country, char_range, isobuf);
return CountryCharsToCountryIDWithUpdate(static_cast<char>(isobuf[0]),
static_cast<char>(isobuf[1]));
}
#elif defined(OS_LINUX)
int GetCurrentCountryID() {
NOTIMPLEMENTED();
return kCountryIDUnknown;
}
#endif // OS_*
int GetCountryIDFromPrefs(PrefService* prefs) {
// See if the user overrode the country on the command line.
const std::wstring country(
CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kCountry));
if (country.length() == 2)
return CountryCharsToCountryIDWithUpdate(static_cast<char>(country[0]),
static_cast<char>(country[1]));
// Cache first run Country ID value in prefs, and use it afterwards. This
// ensures that just because the user moves around, we won't automatically
// make major changes to their available search providers, which would feel
// surprising.
if (!prefs)
return GetCurrentCountryID();
if (!prefs->HasPrefPath(prefs::kCountryIDAtInstall)) {
int new_country_id;
#if defined(OS_WIN)
// Upgrade the old platform-specific value if it's present.
if (prefs->HasPrefPath(prefs::kGeoIDAtInstall)) {
int geo_id = prefs->GetInteger(prefs::kGeoIDAtInstall);
new_country_id = GeoIDToCountryID(geo_id);
} else {
new_country_id = GetCurrentCountryID();
}
#else
new_country_id = GetCurrentCountryID();
#endif
prefs->SetInteger(prefs::kCountryIDAtInstall, new_country_id);
}
return prefs->GetInteger(prefs::kCountryIDAtInstall);
}
void GetPrepopulationSetFromCountryID(PrefService* prefs,
const PrepopulatedEngine*** engines,
size_t* num_engines) {
// NOTE: This function should ALWAYS set its outparams.
// If you add a new country make sure to update the unit test for coverage.
switch (GetCountryIDFromPrefs(prefs)) {
#define CHAR_A 'A'
#define CHAR_B 'B'
#define CHAR_C 'C'
#define CHAR_D 'D'
#define CHAR_E 'E'
#define CHAR_F 'F'
#define CHAR_G 'G'
#define CHAR_H 'H'
#define CHAR_I 'I'
#define CHAR_J 'J'
#define CHAR_K 'K'
#define CHAR_L 'L'
#define CHAR_M 'M'
#define CHAR_N 'N'
#define CHAR_O 'O'
#define CHAR_P 'P'
#define CHAR_Q 'Q'
#define CHAR_R 'R'
#define CHAR_S 'S'
#define CHAR_T 'T'
#define CHAR_U 'U'
#define CHAR_V 'V'
#define CHAR_W 'W'
#define CHAR_X 'X'
#define CHAR_Y 'Y'
#define CHAR_Z 'Z'
#define CHAR(ch) CHAR_##ch
#define CODE_TO_ID(code1, code2)\
(CHAR(code1) << 8 | CHAR(code2))
#define UNHANDLED_COUNTRY(code1, code2)\
case CODE_TO_ID(code1, code2):
#define END_UNHANDLED_COUNTRIES(code1, code2)\
*engines = engines_##code1##code2;\
*num_engines = arraysize(engines_##code1##code2);\
return;
#define DECLARE_COUNTRY(code1, code2)\
UNHANDLED_COUNTRY(code1, code2)\
END_UNHANDLED_COUNTRIES(code1, code2)
// Countries with their own, dedicated engine set.
DECLARE_COUNTRY(A, E) // United Arab Emirates
DECLARE_COUNTRY(A, L) // Albania
DECLARE_COUNTRY(A, R) // Argentina
DECLARE_COUNTRY(A, T) // Austria
DECLARE_COUNTRY(A, U) // Australia
DECLARE_COUNTRY(B, A) // Bosnia and Herzegovina
DECLARE_COUNTRY(B, E) // Belgium
DECLARE_COUNTRY(B, G) // Bulgaria
DECLARE_COUNTRY(B, H) // Bahrain
DECLARE_COUNTRY(B, N) // Brunei
DECLARE_COUNTRY(B, O) // Bolivia
DECLARE_COUNTRY(B, R) // Brazil
DECLARE_COUNTRY(B, Y) // Belarus
DECLARE_COUNTRY(B, Z) // Belize
DECLARE_COUNTRY(C, A) // Canada
DECLARE_COUNTRY(C, H) // Switzerland
DECLARE_COUNTRY(C, L) // Chile
DECLARE_COUNTRY(C, N) // China
DECLARE_COUNTRY(C, O) // Colombia
DECLARE_COUNTRY(C, R) // Costa Rica
DECLARE_COUNTRY(C, Z) // Czech Republic
DECLARE_COUNTRY(D, E) // Germany
DECLARE_COUNTRY(D, K) // Denmark
DECLARE_COUNTRY(D, O) // Dominican Republic
DECLARE_COUNTRY(D, Z) // Algeria
DECLARE_COUNTRY(E, C) // Ecuador
DECLARE_COUNTRY(E, E) // Estonia
DECLARE_COUNTRY(E, G) // Egypt
DECLARE_COUNTRY(E, S) // Spain
DECLARE_COUNTRY(F, I) // Finland
DECLARE_COUNTRY(F, O) // Faroe Islands
DECLARE_COUNTRY(F, R) // France
DECLARE_COUNTRY(G, B) // United Kingdom
DECLARE_COUNTRY(G, R) // Greece
DECLARE_COUNTRY(G, T) // Guatemala
DECLARE_COUNTRY(H, K) // Hong Kong
DECLARE_COUNTRY(H, N) // Honduras
DECLARE_COUNTRY(H, R) // Croatia
DECLARE_COUNTRY(H, U) // Hungary
DECLARE_COUNTRY(I, D) // Indonesia
DECLARE_COUNTRY(I, E) // Ireland
DECLARE_COUNTRY(I, L) // Israel
DECLARE_COUNTRY(I, N) // India
DECLARE_COUNTRY(I, Q) // Iraq
DECLARE_COUNTRY(I, R) // Iran
DECLARE_COUNTRY(I, S) // Iceland
DECLARE_COUNTRY(I, T) // Italy
DECLARE_COUNTRY(J, M) // Jamaica
DECLARE_COUNTRY(J, O) // Jordan
DECLARE_COUNTRY(J, P) // Japan
DECLARE_COUNTRY(K, E) // Kenya
DECLARE_COUNTRY(K, R) // South Korea
DECLARE_COUNTRY(K, W) // Kuwait
DECLARE_COUNTRY(L, B) // Lebanon
DECLARE_COUNTRY(L, I) // Liechtenstein
DECLARE_COUNTRY(L, T) // Lithuania
DECLARE_COUNTRY(L, U) // Luxembourg
DECLARE_COUNTRY(L, V) // Latvia
DECLARE_COUNTRY(L, Y) // Libya
DECLARE_COUNTRY(M, A) // Morocco
DECLARE_COUNTRY(M, C) // Monaco
DECLARE_COUNTRY(M, E) // Montenegro
DECLARE_COUNTRY(M, K) // Macedonia
DECLARE_COUNTRY(M, X) // Mexico
DECLARE_COUNTRY(M, Y) // Malaysia
DECLARE_COUNTRY(N, I) // Nicaragua
DECLARE_COUNTRY(N, L) // Netherlands
DECLARE_COUNTRY(N, O) // Norway
DECLARE_COUNTRY(N, Z) // New Zealand
DECLARE_COUNTRY(O, M) // Oman
DECLARE_COUNTRY(P, A) // Panama
DECLARE_COUNTRY(P, E) // Peru
DECLARE_COUNTRY(P, H) // Philippines
DECLARE_COUNTRY(P, K) // Pakistan
DECLARE_COUNTRY(P, L) // Poland
DECLARE_COUNTRY(P, R) // Puerto Rico
DECLARE_COUNTRY(P, T) // Portugal
DECLARE_COUNTRY(P, Y) // Paraguay
DECLARE_COUNTRY(Q, A) // Qatar
DECLARE_COUNTRY(R, O) // Romania
DECLARE_COUNTRY(R, S) // Serbia
DECLARE_COUNTRY(R, U) // Russia
DECLARE_COUNTRY(S, A) // Saudi Arabia
DECLARE_COUNTRY(S, E) // Sweden
DECLARE_COUNTRY(S, G) // Singapore
DECLARE_COUNTRY(S, I) // Slovenia
DECLARE_COUNTRY(S, K) // Slovakia
DECLARE_COUNTRY(S, V) // El Salvador
DECLARE_COUNTRY(S, Y) // Syria
DECLARE_COUNTRY(T, H) // Thailand
DECLARE_COUNTRY(T, N) // Tunisia
DECLARE_COUNTRY(T, R) // Turkey
DECLARE_COUNTRY(T, T) // Trinidad and Tobago
DECLARE_COUNTRY(T, W) // Taiwan
DECLARE_COUNTRY(U, A) // Ukraine
DECLARE_COUNTRY(U, S) // United States
DECLARE_COUNTRY(U, Y) // Uruguay
DECLARE_COUNTRY(V, E) // Venezuela
DECLARE_COUNTRY(V, N) // Vietnam
DECLARE_COUNTRY(Y, E) // Yemen
DECLARE_COUNTRY(Z, A) // South Africa
DECLARE_COUNTRY(Z, W) // Zimbabwe
// Countries using the "Australia" engine set.
UNHANDLED_COUNTRY(C, C) // Cocos Islands
UNHANDLED_COUNTRY(C, X) // Christmas Island
UNHANDLED_COUNTRY(H, M) // Heard Island and McDonald Islands
UNHANDLED_COUNTRY(N, F) // Norfolk Island
END_UNHANDLED_COUNTRIES(A, U)
// Countries using the "China" engine set.
UNHANDLED_COUNTRY(M, O) // Macao
END_UNHANDLED_COUNTRIES(C, N)
// Countries using the "Denmark" engine set.
UNHANDLED_COUNTRY(G, L) // Greenland
END_UNHANDLED_COUNTRIES(D, K)
// Countries using the "Spain" engine set.
UNHANDLED_COUNTRY(A, D) // Andorra
END_UNHANDLED_COUNTRIES(E, S)
// Countries using the "France" engine set.
UNHANDLED_COUNTRY(B, F) // Burkina Faso
UNHANDLED_COUNTRY(B, I) // Burundi
UNHANDLED_COUNTRY(B, J) // Benin
UNHANDLED_COUNTRY(C, D) // Congo - Kinshasa
UNHANDLED_COUNTRY(C, F) // Central African Republic
UNHANDLED_COUNTRY(C, G) // Congo - Brazzaville
UNHANDLED_COUNTRY(C, I) // Ivory Coast
UNHANDLED_COUNTRY(C, M) // Cameroon
UNHANDLED_COUNTRY(D, J) // Djibouti
UNHANDLED_COUNTRY(G, A) // Gabon
UNHANDLED_COUNTRY(G, F) // French Guiana
UNHANDLED_COUNTRY(G, N) // Guinea
UNHANDLED_COUNTRY(G, P) // Guadeloupe
UNHANDLED_COUNTRY(H, T) // Haiti
#if defined(OS_WIN)
UNHANDLED_COUNTRY(I, P) // Clipperton Island ('IP' is an WinXP-ism; ISO
// includes it with France)
#endif
UNHANDLED_COUNTRY(M, L) // Mali
UNHANDLED_COUNTRY(M, Q) // Martinique
UNHANDLED_COUNTRY(N, C) // New Caledonia
UNHANDLED_COUNTRY(N, E) // Niger
UNHANDLED_COUNTRY(P, F) // French Polynesia
UNHANDLED_COUNTRY(P, M) // Saint Pierre and Miquelon
UNHANDLED_COUNTRY(R, E) // Reunion
UNHANDLED_COUNTRY(S, N) // Senegal
UNHANDLED_COUNTRY(T, D) // Chad
UNHANDLED_COUNTRY(T, F) // French Southern Territories
UNHANDLED_COUNTRY(T, G) // Togo
UNHANDLED_COUNTRY(W, F) // Wallis and Futuna
UNHANDLED_COUNTRY(Y, T) // Mayotte
END_UNHANDLED_COUNTRIES(F, R)
// Countries using the "Greece" engine set.
UNHANDLED_COUNTRY(C, Y) // Cyprus
END_UNHANDLED_COUNTRIES(G, R)
// Countries using the "Italy" engine set.
UNHANDLED_COUNTRY(S, M) // San Marino
UNHANDLED_COUNTRY(V, A) // Vatican
END_UNHANDLED_COUNTRIES(I, T)
// Countries using the "Netherlands" engine set.
UNHANDLED_COUNTRY(A, N) // Netherlands Antilles
UNHANDLED_COUNTRY(A, W) // Aruba
END_UNHANDLED_COUNTRIES(N, L)
// Countries using the "Norway" engine set.
UNHANDLED_COUNTRY(B, V) // Bouvet Island
UNHANDLED_COUNTRY(S, J) // Svalbard and Jan Mayen
END_UNHANDLED_COUNTRIES(N, O)
// Countries using the "New Zealand" engine set.
UNHANDLED_COUNTRY(C, K) // Cook Islands
UNHANDLED_COUNTRY(N, U) // Niue
UNHANDLED_COUNTRY(T, K) // Tokelau
END_UNHANDLED_COUNTRIES(N, Z)
// Countries using the "Portugal" engine set.
UNHANDLED_COUNTRY(C, V) // Cape Verde
UNHANDLED_COUNTRY(G, W) // Guinea-Bissau
UNHANDLED_COUNTRY(M, Z) // Mozambique
UNHANDLED_COUNTRY(S, T) // Sao Tome and Principe
UNHANDLED_COUNTRY(T, L) // Timor-Leste
END_UNHANDLED_COUNTRIES(P, T)
// Countries using the "Russia" engine set.
UNHANDLED_COUNTRY(A, M) // Armenia
UNHANDLED_COUNTRY(A, Z) // Azerbaijan
UNHANDLED_COUNTRY(K, G) // Kyrgyzstan
UNHANDLED_COUNTRY(K, Z) // Kazakhstan
UNHANDLED_COUNTRY(T, J) // Tajikistan
UNHANDLED_COUNTRY(T, M) // Turkmenistan
UNHANDLED_COUNTRY(U, Z) // Uzbekistan
END_UNHANDLED_COUNTRIES(R, U)
// Countries using the "Saudi Arabia" engine set.
UNHANDLED_COUNTRY(M, R) // Mauritania
UNHANDLED_COUNTRY(P, S) // Palestinian Territory
UNHANDLED_COUNTRY(S, D) // Sudan
END_UNHANDLED_COUNTRIES(S, A)
// Countries using the "United Kingdom" engine set.
UNHANDLED_COUNTRY(B, M) // Bermuda
UNHANDLED_COUNTRY(F, K) // Falkland Islands
UNHANDLED_COUNTRY(G, G) // Guernsey
UNHANDLED_COUNTRY(G, I) // Gibraltar
UNHANDLED_COUNTRY(G, S) // South Georgia and the South Sandwich
// Islands
UNHANDLED_COUNTRY(I, M) // Isle of Man
UNHANDLED_COUNTRY(I, O) // British Indian Ocean Territory
UNHANDLED_COUNTRY(J, E) // Jersey
UNHANDLED_COUNTRY(K, Y) // Cayman Islands
UNHANDLED_COUNTRY(M, S) // Montserrat
UNHANDLED_COUNTRY(M, T) // Malta
UNHANDLED_COUNTRY(P, N) // Pitcairn Islands
UNHANDLED_COUNTRY(S, H) // Saint Helena, Ascension Island, and Tristan da
// Cunha
UNHANDLED_COUNTRY(T, C) // Turks and Caicos Islands
UNHANDLED_COUNTRY(V, G) // British Virgin Islands
END_UNHANDLED_COUNTRIES(G, B)
// Countries using the "United States" engine set.
UNHANDLED_COUNTRY(A, S) // American Samoa
UNHANDLED_COUNTRY(G, U) // Guam
UNHANDLED_COUNTRY(M, P) // Northern Mariana Islands
UNHANDLED_COUNTRY(U, M) // U.S. Minor Outlying Islands
UNHANDLED_COUNTRY(V, I) // U.S. Virgin Islands
END_UNHANDLED_COUNTRIES(U, S)
// Countries using the "default" engine set.
UNHANDLED_COUNTRY(A, F) // Afghanistan
UNHANDLED_COUNTRY(A, G) // Antigua and Barbuda
UNHANDLED_COUNTRY(A, I) // Anguilla
UNHANDLED_COUNTRY(A, O) // Angola
UNHANDLED_COUNTRY(A, Q) // Antarctica
UNHANDLED_COUNTRY(B, B) // Barbados
UNHANDLED_COUNTRY(B, D) // Bangladesh
UNHANDLED_COUNTRY(B, S) // Bahamas
UNHANDLED_COUNTRY(B, T) // Bhutan
UNHANDLED_COUNTRY(B, W) // Botswana
UNHANDLED_COUNTRY(C, U) // Cuba
UNHANDLED_COUNTRY(D, M) // Dominica
UNHANDLED_COUNTRY(E, R) // Eritrea
UNHANDLED_COUNTRY(E, T) // Ethiopia
UNHANDLED_COUNTRY(F, J) // Fiji
UNHANDLED_COUNTRY(F, M) // Micronesia
UNHANDLED_COUNTRY(G, D) // Grenada
UNHANDLED_COUNTRY(G, E) // Georgia
UNHANDLED_COUNTRY(G, H) // Ghana
UNHANDLED_COUNTRY(G, M) // Gambia
UNHANDLED_COUNTRY(G, Q) // Equatorial Guinea
UNHANDLED_COUNTRY(G, Y) // Guyana
UNHANDLED_COUNTRY(K, H) // Cambodia
UNHANDLED_COUNTRY(K, I) // Kiribati
UNHANDLED_COUNTRY(K, M) // Comoros
UNHANDLED_COUNTRY(K, N) // Saint Kitts and Nevis
UNHANDLED_COUNTRY(K, P) // North Korea
UNHANDLED_COUNTRY(L, A) // Laos
UNHANDLED_COUNTRY(L, C) // Saint Lucia
UNHANDLED_COUNTRY(L, K) // Sri Lanka
UNHANDLED_COUNTRY(L, R) // Liberia
UNHANDLED_COUNTRY(L, S) // Lesotho
UNHANDLED_COUNTRY(M, D) // Moldova
UNHANDLED_COUNTRY(M, G) // Madagascar
UNHANDLED_COUNTRY(M, H) // Marshall Islands
UNHANDLED_COUNTRY(M, M) // Myanmar
UNHANDLED_COUNTRY(M, N) // Mongolia
UNHANDLED_COUNTRY(M, U) // Mauritius
UNHANDLED_COUNTRY(M, V) // Maldives
UNHANDLED_COUNTRY(M, W) // Malawi
UNHANDLED_COUNTRY(N, A) // Namibia
UNHANDLED_COUNTRY(N, G) // Nigeria
UNHANDLED_COUNTRY(N, P) // Nepal
UNHANDLED_COUNTRY(N, R) // Nauru
UNHANDLED_COUNTRY(P, G) // Papua New Guinea
UNHANDLED_COUNTRY(P, W) // Palau
UNHANDLED_COUNTRY(R, W) // Rwanda
UNHANDLED_COUNTRY(S, B) // Solomon Islands
UNHANDLED_COUNTRY(S, C) // Seychelles
UNHANDLED_COUNTRY(S, L) // Sierra Leone
UNHANDLED_COUNTRY(S, O) // Somalia
UNHANDLED_COUNTRY(S, R) // Suriname
UNHANDLED_COUNTRY(S, Z) // Swaziland
UNHANDLED_COUNTRY(T, O) // Tonga
UNHANDLED_COUNTRY(T, V) // Tuvalu
UNHANDLED_COUNTRY(T, Z) // Tanzania
UNHANDLED_COUNTRY(U, G) // Uganda
UNHANDLED_COUNTRY(V, C) // Saint Vincent and the Grenadines
UNHANDLED_COUNTRY(V, U) // Vanuatu
UNHANDLED_COUNTRY(W, S) // Samoa
UNHANDLED_COUNTRY(Z, M) // Zambia
case kCountryIDUnknown:
default: // Unhandled location
END_UNHANDLED_COUNTRIES(def, ault)
}
}
} // namespace
namespace TemplateURLPrepopulateData {
void RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kGeoIDAtInstall, -1);
prefs->RegisterIntegerPref(prefs::kCountryIDAtInstall, kCountryIDUnknown);
}
int GetDataVersion() {
return 23; // Increment this if you change the above data in ways that mean
// users with existing data should get a new version.
}
void GetPrepopulatedEngines(PrefService* prefs,
std::vector<TemplateURL*>* t_urls,
size_t* default_search_provider_index) {
const PrepopulatedEngine** engines;
size_t num_engines;
GetPrepopulationSetFromCountryID(prefs, &engines, &num_engines);
*default_search_provider_index = 0;
for (size_t i = 0; i < num_engines; ++i) {
TemplateURL* new_turl = new TemplateURL();
new_turl->SetURL(engines[i]->search_url, 0, 0);
if (engines[i]->favicon_url)
new_turl->SetFavIconURL(GURL(engines[i]->favicon_url));
if (engines[i]->suggest_url)
new_turl->SetSuggestionsURL(engines[i]->suggest_url, 0, 0);
new_turl->set_short_name(engines[i]->name);
if (engines[i]->keyword == NULL)
new_turl->set_autogenerate_keyword(true);
else
new_turl->set_keyword(engines[i]->keyword);
new_turl->set_show_in_default_list(true);
new_turl->set_safe_for_autoreplace(true);
new_turl->set_date_created(Time());
std::vector<std::string> turl_encodings;
turl_encodings.push_back(engines[i]->encoding);
new_turl->set_input_encodings(turl_encodings);
new_turl->set_prepopulate_id(engines[i]->id);
t_urls->push_back(new_turl);
}
}
} // namespace TemplateURLPrepopulateData
|
// 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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
class TwoClientLivePreferencesSyncTest : public LiveSyncTest {
protected:
TwoClientLivePreferencesSyncTest() {
// This makes sure browser is visible and active while running test.
InProcessBrowserTest::set_show_window(true);
// Set the initial timeout value to 5 min.
InProcessBrowserTest::SetInitialTimeoutInMS(300000);
}
~TwoClientLivePreferencesSyncTest() {}
void SetupSync() {
client1_.reset(new ProfileSyncServiceTestHarness(
browser()->profile(), username_, password_));
profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
client2_.reset(new ProfileSyncServiceTestHarness(
profile2_.get(), username_, password_));
EXPECT_TRUE(client1_->SetupSync());
EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
EXPECT_TRUE(client2_->SetupSync());
EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
}
void Cleanup() {
client2_.reset();
profile2_.reset();
}
ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
ProfileSyncServiceTestHarness* client2() { return client2_.get(); }
PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
PrefService* prefs2() { return profile2_->GetPrefs(); }
private:
scoped_ptr<ProfileSyncServiceTestHarness> client1_;
scoped_ptr<ProfileSyncServiceTestHarness> client2_;
scoped_ptr<Profile> profile2_;
DISALLOW_COPY_AND_ASSIGN(TwoClientLivePreferencesSyncTest);
};
IN_PROC_BROWSER_TEST_F(TwoClientLivePreferencesSyncTest, Sanity) {
SetupSync();
EXPECT_EQ(false, prefs1()->GetBoolean(prefs::kHomePageIsNewTabPage));
EXPECT_EQ(false, prefs2()->GetBoolean(prefs::kHomePageIsNewTabPage));
PrefService* expected = LiveSyncTest::MakeProfile(
FILE_PATH_LITERAL("verifier"))->GetPrefs();
expected->SetBoolean(prefs::kHomePageIsNewTabPage, true);
prefs1()->SetBoolean(prefs::kHomePageIsNewTabPage, true);
EXPECT_TRUE(client2()->AwaitMutualSyncCycleCompletion(client1()));
EXPECT_EQ(expected->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs1()->GetBoolean(prefs::kHomePageIsNewTabPage));
EXPECT_EQ(expected->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs2()->GetBoolean(prefs::kHomePageIsNewTabPage));
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePreferencesSyncTest, Race) {
SetupSync();
prefs1()->SetString(prefs::kHomePage, L"http://www.google.com/1");
prefs2()->SetString(prefs::kHomePage, L"http://www.google.com/2");
EXPECT_TRUE(client2()->AwaitMutualSyncCycleCompletion(client1()));
EXPECT_EQ(prefs1()->GetString(prefs::kHomePage),
prefs2()->GetString(prefs::kHomePage));
Cleanup();
}
In the sync integration tests for preferences, don't assume a specific
initial value for kHomePageIsNewTabPage.
BUG=42669
TEST=TwoClientLivePreferencesSyncTest.Sanity
Review URL: http://codereview.chromium.org/1801006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@45979 0039d316-1c4b-4281-b951-d872f2087c98
// 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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
class TwoClientLivePreferencesSyncTest : public LiveSyncTest {
protected:
TwoClientLivePreferencesSyncTest() {
// This makes sure browser is visible and active while running test.
InProcessBrowserTest::set_show_window(true);
// Set the initial timeout value to 5 min.
InProcessBrowserTest::SetInitialTimeoutInMS(300000);
}
~TwoClientLivePreferencesSyncTest() {}
void SetupSync() {
client1_.reset(new ProfileSyncServiceTestHarness(
browser()->profile(), username_, password_));
profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
client2_.reset(new ProfileSyncServiceTestHarness(
profile2_.get(), username_, password_));
EXPECT_TRUE(client1_->SetupSync());
EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
EXPECT_TRUE(client2_->SetupSync());
EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
}
void Cleanup() {
client2_.reset();
profile2_.reset();
}
ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
ProfileSyncServiceTestHarness* client2() { return client2_.get(); }
PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
PrefService* prefs2() { return profile2_->GetPrefs(); }
private:
scoped_ptr<ProfileSyncServiceTestHarness> client1_;
scoped_ptr<ProfileSyncServiceTestHarness> client2_;
scoped_ptr<Profile> profile2_;
DISALLOW_COPY_AND_ASSIGN(TwoClientLivePreferencesSyncTest);
};
IN_PROC_BROWSER_TEST_F(TwoClientLivePreferencesSyncTest, Sanity) {
SetupSync();
EXPECT_EQ(prefs1()->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs2()->GetBoolean(prefs::kHomePageIsNewTabPage));
PrefService* expected = LiveSyncTest::MakeProfile(
FILE_PATH_LITERAL("verifier"))->GetPrefs();
bool value = !expected->GetBoolean(prefs::kHomePageIsNewTabPage);
expected->SetBoolean(prefs::kHomePageIsNewTabPage, value);
prefs1()->SetBoolean(prefs::kHomePageIsNewTabPage, value);
EXPECT_TRUE(client2()->AwaitMutualSyncCycleCompletion(client1()));
EXPECT_EQ(expected->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs1()->GetBoolean(prefs::kHomePageIsNewTabPage));
EXPECT_EQ(expected->GetBoolean(prefs::kHomePageIsNewTabPage),
prefs2()->GetBoolean(prefs::kHomePageIsNewTabPage));
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePreferencesSyncTest, Race) {
SetupSync();
prefs1()->SetString(prefs::kHomePage, L"http://www.google.com/1");
prefs2()->SetString(prefs::kHomePage, L"http://www.google.com/2");
EXPECT_TRUE(client2()->AwaitMutualSyncCycleCompletion(client1()));
EXPECT_EQ(prefs1()->GetString(prefs::kHomePage),
prefs2()->GetString(prefs::kHomePage));
Cleanup();
}
|
/*************************************************************************
*
* $RCSfile: rscdbl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2005-01-03 17:24:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCTREE_HXX
#include <rsctree.hxx>
#endif
#ifndef _RSCTOP_HXX
#include <rsctop.hxx>
#endif
#ifndef _RSCLST_HXX
#include "rsclst.hxx"
#endif
/*************************************************************************
|*
|* RscTypCont::FillNameIdList()
|*
|* Beschreibung
|* Ersterstellung MM 07.05.91
|* Letzte Aenderung MM 30.05.91
|*
*************************************************************************/
REResourceList * InsertList( Atom nClassName, const RscId& rId,
REResourceList * pList ){
REResourceList * pSubList;
const char * pStrClass;
ByteString aStrClass;
pStrClass = pHS->getString( nClassName ).getStr();
if( pStrClass )
aStrClass = pStrClass;
else
aStrClass = ByteString::CreateFromInt32( (long)nClassName );
pSubList = new REResourceList( pList, aStrClass, rId );
pList->Insert( pSubList, 0xFFFFFFFF );
return( pSubList );
}
void FillSubList( RSCINST & rInst, REResourceList * pList )
{
sal_uInt32 nCount, i;
SUBINFO_STRUCT aInfo;
REResourceList* pSubList;
RSCINST aTmpI;
nCount = rInst.pClass->GetCount( rInst );
for( i = 0; i < nCount; i++ ){
aInfo = rInst.pClass->GetInfoEle( rInst, i );
aTmpI = rInst.pClass->GetPosEle( rInst, i );
pSubList = InsertList( aInfo.pClass->GetId(),
aInfo.aId, pList );
FillSubList( aTmpI, pSubList );
};
}
void FillListObj( ObjNode * pObjNode, RscTop * pRscTop,
REResourceList * pList, ULONG lFileKey )
{
if( pObjNode ){
if( pObjNode->GetFileKey() == lFileKey ){
RSCINST aTmpI;
REResourceList* pSubList;
FillListObj( (ObjNode*)pObjNode->Left(), pRscTop,
pList, lFileKey );
pSubList = InsertList( pRscTop->GetId(),
pObjNode->GetRscId(), pList );
aTmpI.pClass = pRscTop;
aTmpI.pData = pObjNode->GetRscObj();
FillSubList( aTmpI, pSubList );
FillListObj( (ObjNode*)pObjNode->Right(), pRscTop,
pList, lFileKey );
}
};
}
void FillList( RscTop * pRscTop, REResourceList * pList, ULONG lFileKey ){
if( pRscTop ){
FillList( (RscTop*)pRscTop->Left(), pList, lFileKey );
FillListObj( pRscTop->GetObjNode(), pRscTop, pList, lFileKey );
FillList( (RscTop*)pRscTop->Right(), pList, lFileKey );
};
}
void RscTypCont::FillNameIdList( REResourceList * pList, ULONG lFileKey ){
FillList( pRoot, pList, lFileKey );
}
INTEGRATION: CWS ooo19126 (1.2.18); FILE MERGED
2005/09/05 18:46:54 rt 1.2.18.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rscdbl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 13:35:47 $
*
* 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
*
************************************************************************/
#include <stdio.h>
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCTREE_HXX
#include <rsctree.hxx>
#endif
#ifndef _RSCTOP_HXX
#include <rsctop.hxx>
#endif
#ifndef _RSCLST_HXX
#include "rsclst.hxx"
#endif
/*************************************************************************
|*
|* RscTypCont::FillNameIdList()
|*
|* Beschreibung
|* Ersterstellung MM 07.05.91
|* Letzte Aenderung MM 30.05.91
|*
*************************************************************************/
REResourceList * InsertList( Atom nClassName, const RscId& rId,
REResourceList * pList ){
REResourceList * pSubList;
const char * pStrClass;
ByteString aStrClass;
pStrClass = pHS->getString( nClassName ).getStr();
if( pStrClass )
aStrClass = pStrClass;
else
aStrClass = ByteString::CreateFromInt32( (long)nClassName );
pSubList = new REResourceList( pList, aStrClass, rId );
pList->Insert( pSubList, 0xFFFFFFFF );
return( pSubList );
}
void FillSubList( RSCINST & rInst, REResourceList * pList )
{
sal_uInt32 nCount, i;
SUBINFO_STRUCT aInfo;
REResourceList* pSubList;
RSCINST aTmpI;
nCount = rInst.pClass->GetCount( rInst );
for( i = 0; i < nCount; i++ ){
aInfo = rInst.pClass->GetInfoEle( rInst, i );
aTmpI = rInst.pClass->GetPosEle( rInst, i );
pSubList = InsertList( aInfo.pClass->GetId(),
aInfo.aId, pList );
FillSubList( aTmpI, pSubList );
};
}
void FillListObj( ObjNode * pObjNode, RscTop * pRscTop,
REResourceList * pList, ULONG lFileKey )
{
if( pObjNode ){
if( pObjNode->GetFileKey() == lFileKey ){
RSCINST aTmpI;
REResourceList* pSubList;
FillListObj( (ObjNode*)pObjNode->Left(), pRscTop,
pList, lFileKey );
pSubList = InsertList( pRscTop->GetId(),
pObjNode->GetRscId(), pList );
aTmpI.pClass = pRscTop;
aTmpI.pData = pObjNode->GetRscObj();
FillSubList( aTmpI, pSubList );
FillListObj( (ObjNode*)pObjNode->Right(), pRscTop,
pList, lFileKey );
}
};
}
void FillList( RscTop * pRscTop, REResourceList * pList, ULONG lFileKey ){
if( pRscTop ){
FillList( (RscTop*)pRscTop->Left(), pList, lFileKey );
FillListObj( pRscTop->GetObjNode(), pRscTop, pList, lFileKey );
FillList( (RscTop*)pRscTop->Right(), pList, lFileKey );
};
}
void RscTypCont::FillNameIdList( REResourceList * pList, ULONG lFileKey ){
FillList( pRoot, pList, lFileKey );
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2020-2021 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Tobias Gödderz
////////////////////////////////////////////////////////////////////////////////
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
#include "Replication2/ReplicatedLog/ILogParticipant.h"
#include "Replication2/ReplicatedLog/types.h"
#include "TestHelper.h"
#include <Basics/ScopeGuard.h>
#include <Basics/application-exit.h>
#include <functional>
using namespace arangodb;
using namespace arangodb::replication2;
using namespace arangodb::replication2::replicated_log;
struct ReplicatedLogConcurrentTest : ReplicatedLogTest {
using ThreadIdx = uint16_t;
using IterIdx = uint32_t;
constexpr static auto maxIter = std::numeric_limits<IterIdx>::max();
struct alignas(128) ThreadCoordinationData {
// the testee
std::shared_ptr<ILogParticipant> log;
// only when set to true, all client threads start
std::atomic<bool> go = false;
// when set to true, client threads will stop after the current iteration,
// whatever that means for them.
std::atomic<bool> stopClientThreads = false;
// when set to true, the replication thread stops. should be done only
// after all client threads stopped to avoid them hanging while waiting on
// replication.
std::atomic<bool> stopReplicationThreads = false;
// every thread increases this by one when it's ready to start
std::atomic<std::size_t> threadsReady = 0;
// every thread increases this by one when it's done a certain minimal
// amount of work. This is to guarantee that all threads are running long
// enough side by side.
std::atomic<std::size_t> threadsSatisfied = 0;
};
// Used to generate payloads that are unique across threads.
constexpr static auto genPayload = [](ThreadIdx thread, IterIdx i) {
// This should fit into short string optimization
auto str = std::string(16, ' ');
auto p = str.begin() + 5;
// up to 5 digits for thread
static_assert(std::numeric_limits<ThreadIdx>::max() <= 99'999);
// 1 digit for ':'
*p = ':';
// up to 10 digits for i
static_assert(std::numeric_limits<IterIdx>::max() <= 99'999'999'999);
do {
--p;
*p = static_cast<char>('0' + (thread % 10));
thread /= 10;
} while (thread > 0);
p = str.end();
do {
--p;
*p = static_cast<char>('0' + (i % 10));
i /= 10;
} while (i > 0);
return str;
};
constexpr static auto alternatinglyInsertAndRead = [](ThreadIdx const threadIdx,
ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
data.threadsReady.fetch_add(1);
while (!data.go.load()) {
}
for (auto i = std::uint32_t{0}; i < maxIter && !data.stopClientThreads.load(); ++i) {
auto const payload = LogPayload::createFromString(genPayload(threadIdx, i));
auto const idx = log->insert(payload, false, LogLeader::doNotTriggerAsyncReplication);
std::this_thread::sleep_for(1ns);
auto fut = log->waitFor(idx);
fut.get();
auto snapshot = log->getReplicatedLogSnapshot();
ASSERT_LT(0, idx.value);
ASSERT_LE(idx.value, snapshot.size());
auto const& entry = snapshot[idx.value - 1];
EXPECT_EQ(idx, entry.entry().logIndex());
EXPECT_EQ(payload, entry.entry().logPayload());
if (i == 1000) {
// we should have done at least a few iterations before finishing
data.threadsSatisfied.fetch_add(1, std::memory_order_relaxed);
}
}
};
constexpr static auto insertManyThenRead = [](ThreadIdx const threadIdx,
ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
data.threadsReady.fetch_add(1);
while (!data.go.load()) {
}
constexpr auto batch = 100;
auto idxs = std::vector<LogIndex>{};
idxs.resize(batch);
for (auto i = std::uint32_t{0};
i < maxIter && !data.stopClientThreads.load(); i += batch) {
for (auto k = 0; k < batch && i + k < maxIter; ++k) {
auto const payload = LogPayload::createFromString(genPayload(threadIdx, i + k));
idxs[k] = log->insert(payload, false, LogLeader::doNotTriggerAsyncReplication);
}
std::this_thread::sleep_for(1ns);
auto fut = log->waitFor(idxs.back());
fut.get();
auto snapshot = log->getReplicatedLogSnapshot();
for (auto k = 0; k < batch && i + k < maxIter; ++k) {
using namespace std::string_literals;
auto const payload = std::optional(LogPayload::createFromString(genPayload(threadIdx, i + k)));
auto const idx = idxs[k];
ASSERT_LT(0, idx.value);
ASSERT_LE(idx.value, snapshot.size());
auto const& entry = snapshot[idx.value - 1];
EXPECT_EQ(idx, entry.entry().logIndex());
EXPECT_EQ(payload, entry.entry().logPayload())
<< VPackSlice(payload->dummy.data()).toJson() << " "
<< (entry.entry().logPayload()
? VPackSlice(entry.entry().logPayload()->dummy.data()).toJson()
: "std::nullopt"s);
}
if (i == 10 * batch) {
// we should have done at least a few iterations before finishing
data.threadsSatisfied.fetch_add(1, std::memory_order_relaxed);
}
}
};
constexpr static auto runReplicationWithIntermittentPauses =
[](ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
for (auto i = 0;; ++i) {
log->triggerAsyncReplication();
if (i % 16) {
std::this_thread::sleep_for(100ns);
if (data.stopReplicationThreads.load()) {
return;
}
}
}
};
constexpr static auto runFollowerReplicationWithIntermittentPauses =
// NOLINTNEXTLINE(performance-unnecessary-value-param)
[](std::vector<DelayedFollowerLog*> followers, ThreadCoordinationData& data) {
using namespace std::chrono_literals;
for (auto i = 0;;) {
for (auto* follower : followers) {
follower->runAsyncAppendEntries();
if (i % 17) {
std::this_thread::sleep_for(100ns);
if (data.stopReplicationThreads.load()) {
return;
}
}
++i;
}
}
};
};
TEST_F(ReplicatedLogConcurrentTest, genPayloadTest) {
EXPECT_EQ(" 0: 0", genPayload(0, 0));
EXPECT_EQ(" 11: 42", genPayload(11, 42));
EXPECT_EQ("65535:4294967295", genPayload(65535, 4294967295));
}
TEST_F(ReplicatedLogConcurrentTest, lonelyLeader) {
using namespace std::chrono_literals;
auto replicatedLog = makeReplicatedLogWithAsyncMockLog(LogId{1});
// TODO this test hangs because there is not local follower currently
auto leaderLog = replicatedLog->becomeLeader("leader", LogTerm{1}, {}, 1);
auto data = ThreadCoordinationData{leaderLog};
// start replication
auto replicationThread =
std::thread{runReplicationWithIntermittentPauses, std::ref(data)};
std::vector<std::thread> clientThreads;
auto threadCounter = uint16_t{0};
clientThreads.emplace_back(alternatinglyInsertAndRead, threadCounter++, std::ref(data));
clientThreads.emplace_back(insertManyThenRead, threadCounter++, std::ref(data));
ASSERT_EQ(clientThreads.size(), threadCounter);
while (data.threadsReady.load() < clientThreads.size()) {
}
data.go.store(true);
while (data.threadsSatisfied.load() < clientThreads.size()) {
std::this_thread::sleep_for(100us);
}
data.stopClientThreads.store(true);
for (auto& thread : clientThreads) {
thread.join();
}
// stop replication only after all client threads joined, so we don't block
// them in some intermediate state
data.stopReplicationThreads.store(true);
replicationThread.join();
auto stats = std::get<LeaderStatus>(data.log->getStatus().getVariant()).local;
EXPECT_LE(LogIndex{8000}, stats.commitIndex);
EXPECT_LE(stats.commitIndex, stats.spearHead.index);
stopAsyncMockLogs();
}
TEST_F(ReplicatedLogConcurrentTest, leaderWithFollowers) {
using namespace std::chrono_literals;
auto guard = scopeGuard([] {
LOG_TOPIC("27bc7", FATAL, Logger::REPLICATION2)
<< "Test terminating early, aborting for debugging";
FATAL_ERROR_ABORT();
});
auto leaderLog = makeReplicatedLog(LogId{1});
auto follower1Log = makeReplicatedLog(LogId{2});
auto follower2Log = makeReplicatedLog(LogId{3});
auto follower1 = follower1Log->becomeFollower("follower1", LogTerm{1}, "leader");
auto follower2 = follower2Log->becomeFollower("follower2", LogTerm{1}, "leader");
auto leader =
leaderLog->becomeLeader("leader", LogTerm{1},
{std::static_pointer_cast<AbstractFollower>(follower1),
std::static_pointer_cast<AbstractFollower>(follower2)},
2);
auto data = ThreadCoordinationData{leader};
// start replication
auto replicationThread =
std::thread{runReplicationWithIntermittentPauses, std::ref(data)};
auto followerReplicationThread =
std::thread{runFollowerReplicationWithIntermittentPauses,
std::vector{follower1.get(), follower2.get()}, std::ref(data)};
std::vector<std::thread> clientThreads;
auto threadCounter = uint16_t{0};
clientThreads.emplace_back(alternatinglyInsertAndRead, threadCounter++, std::ref(data));
clientThreads.emplace_back(insertManyThenRead, threadCounter++, std::ref(data));
ASSERT_EQ(clientThreads.size(), threadCounter);
while (data.threadsReady.load() < clientThreads.size()) {
}
data.go.store(true);
while (data.threadsSatisfied.load() < clientThreads.size()) {
std::this_thread::sleep_for(100us);
}
data.stopClientThreads.store(true);
for (auto& thread : clientThreads) {
thread.join();
}
// stop replication only after all client threads joined, so we don't block
// them in some intermediate state
data.stopReplicationThreads.store(true);
replicationThread.join();
followerReplicationThread.join();
guard.cancel();
auto stats = std::get<LeaderStatus>(data.log->getStatus().getVariant()).local;
EXPECT_LE(LogIndex{8000}, stats.commitIndex);
EXPECT_LE(stats.commitIndex, stats.spearHead.index);
}
Suppress a useless warning (#14624)
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2020-2021 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Tobias Gödderz
////////////////////////////////////////////////////////////////////////////////
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
#include "Replication2/ReplicatedLog/ILogParticipant.h"
#include "Replication2/ReplicatedLog/types.h"
#include "TestHelper.h"
#include <Basics/ScopeGuard.h>
#include <Basics/application-exit.h>
#include <functional>
using namespace arangodb;
using namespace arangodb::replication2;
using namespace arangodb::replication2::replicated_log;
struct ReplicatedLogConcurrentTest : ReplicatedLogTest {
using ThreadIdx = uint16_t;
using IterIdx = uint32_t;
constexpr static auto maxIter = std::numeric_limits<IterIdx>::max();
struct alignas(128) ThreadCoordinationData {
// the testee
std::shared_ptr<ILogParticipant> log;
// only when set to true, all client threads start
std::atomic<bool> go = false;
// when set to true, client threads will stop after the current iteration,
// whatever that means for them.
std::atomic<bool> stopClientThreads = false;
// when set to true, the replication thread stops. should be done only
// after all client threads stopped to avoid them hanging while waiting on
// replication.
std::atomic<bool> stopReplicationThreads = false;
// every thread increases this by one when it's ready to start
std::atomic<std::size_t> threadsReady = 0;
// every thread increases this by one when it's done a certain minimal
// amount of work. This is to guarantee that all threads are running long
// enough side by side.
std::atomic<std::size_t> threadsSatisfied = 0;
};
// Used to generate payloads that are unique across threads.
constexpr static auto genPayload = [](ThreadIdx thread, IterIdx i) {
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
// up to 5 digits for thread
static_assert(std::numeric_limits<ThreadIdx>::max() <= 99'999);
// up to 10 digits for i
static_assert(std::numeric_limits<IterIdx>::max() <= 99'999'999'999);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
// This should fit into short string optimization
auto str = std::string(16, ' ');
auto p = str.begin() + 5;
// 1 digit for ':'
*p = ':';
do {
--p;
*p = static_cast<char>('0' + (thread % 10));
thread /= 10;
} while (thread > 0);
p = str.end();
do {
--p;
*p = static_cast<char>('0' + (i % 10));
i /= 10;
} while (i > 0);
return str;
};
constexpr static auto alternatinglyInsertAndRead = [](ThreadIdx const threadIdx,
ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
data.threadsReady.fetch_add(1);
while (!data.go.load()) {
}
for (auto i = std::uint32_t{0}; i < maxIter && !data.stopClientThreads.load(); ++i) {
auto const payload = LogPayload::createFromString(genPayload(threadIdx, i));
auto const idx = log->insert(payload, false, LogLeader::doNotTriggerAsyncReplication);
std::this_thread::sleep_for(1ns);
auto fut = log->waitFor(idx);
fut.get();
auto snapshot = log->getReplicatedLogSnapshot();
ASSERT_LT(0, idx.value);
ASSERT_LE(idx.value, snapshot.size());
auto const& entry = snapshot[idx.value - 1];
EXPECT_EQ(idx, entry.entry().logIndex());
EXPECT_EQ(payload, entry.entry().logPayload());
if (i == 1000) {
// we should have done at least a few iterations before finishing
data.threadsSatisfied.fetch_add(1, std::memory_order_relaxed);
}
}
};
constexpr static auto insertManyThenRead = [](ThreadIdx const threadIdx,
ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
data.threadsReady.fetch_add(1);
while (!data.go.load()) {
}
constexpr auto batch = 100;
auto idxs = std::vector<LogIndex>{};
idxs.resize(batch);
for (auto i = std::uint32_t{0};
i < maxIter && !data.stopClientThreads.load(); i += batch) {
for (auto k = 0; k < batch && i + k < maxIter; ++k) {
auto const payload = LogPayload::createFromString(genPayload(threadIdx, i + k));
idxs[k] = log->insert(payload, false, LogLeader::doNotTriggerAsyncReplication);
}
std::this_thread::sleep_for(1ns);
auto fut = log->waitFor(idxs.back());
fut.get();
auto snapshot = log->getReplicatedLogSnapshot();
for (auto k = 0; k < batch && i + k < maxIter; ++k) {
using namespace std::string_literals;
auto const payload = std::optional(LogPayload::createFromString(genPayload(threadIdx, i + k)));
auto const idx = idxs[k];
ASSERT_LT(0, idx.value);
ASSERT_LE(idx.value, snapshot.size());
auto const& entry = snapshot[idx.value - 1];
EXPECT_EQ(idx, entry.entry().logIndex());
EXPECT_EQ(payload, entry.entry().logPayload())
<< VPackSlice(payload->dummy.data()).toJson() << " "
<< (entry.entry().logPayload()
? VPackSlice(entry.entry().logPayload()->dummy.data()).toJson()
: "std::nullopt"s);
}
if (i == 10 * batch) {
// we should have done at least a few iterations before finishing
data.threadsSatisfied.fetch_add(1, std::memory_order_relaxed);
}
}
};
constexpr static auto runReplicationWithIntermittentPauses =
[](ThreadCoordinationData& data) {
using namespace std::chrono_literals;
auto log = std::dynamic_pointer_cast<LogLeader>(data.log);
ASSERT_NE(log, nullptr);
for (auto i = 0;; ++i) {
log->triggerAsyncReplication();
if (i % 16) {
std::this_thread::sleep_for(100ns);
if (data.stopReplicationThreads.load()) {
return;
}
}
}
};
constexpr static auto runFollowerReplicationWithIntermittentPauses =
// NOLINTNEXTLINE(performance-unnecessary-value-param)
[](std::vector<DelayedFollowerLog*> followers, ThreadCoordinationData& data) {
using namespace std::chrono_literals;
for (auto i = 0;;) {
for (auto* follower : followers) {
follower->runAsyncAppendEntries();
if (i % 17) {
std::this_thread::sleep_for(100ns);
if (data.stopReplicationThreads.load()) {
return;
}
}
++i;
}
}
};
};
TEST_F(ReplicatedLogConcurrentTest, genPayloadTest) {
EXPECT_EQ(" 0: 0", genPayload(0, 0));
EXPECT_EQ(" 11: 42", genPayload(11, 42));
EXPECT_EQ("65535:4294967295", genPayload(65535, 4294967295));
}
TEST_F(ReplicatedLogConcurrentTest, lonelyLeader) {
using namespace std::chrono_literals;
auto replicatedLog = makeReplicatedLogWithAsyncMockLog(LogId{1});
// TODO this test hangs because there is not local follower currently
auto leaderLog = replicatedLog->becomeLeader("leader", LogTerm{1}, {}, 1);
auto data = ThreadCoordinationData{leaderLog};
// start replication
auto replicationThread =
std::thread{runReplicationWithIntermittentPauses, std::ref(data)};
std::vector<std::thread> clientThreads;
auto threadCounter = uint16_t{0};
clientThreads.emplace_back(alternatinglyInsertAndRead, threadCounter++, std::ref(data));
clientThreads.emplace_back(insertManyThenRead, threadCounter++, std::ref(data));
ASSERT_EQ(clientThreads.size(), threadCounter);
while (data.threadsReady.load() < clientThreads.size()) {
}
data.go.store(true);
while (data.threadsSatisfied.load() < clientThreads.size()) {
std::this_thread::sleep_for(100us);
}
data.stopClientThreads.store(true);
for (auto& thread : clientThreads) {
thread.join();
}
// stop replication only after all client threads joined, so we don't block
// them in some intermediate state
data.stopReplicationThreads.store(true);
replicationThread.join();
auto stats = std::get<LeaderStatus>(data.log->getStatus().getVariant()).local;
EXPECT_LE(LogIndex{8000}, stats.commitIndex);
EXPECT_LE(stats.commitIndex, stats.spearHead.index);
stopAsyncMockLogs();
}
TEST_F(ReplicatedLogConcurrentTest, leaderWithFollowers) {
using namespace std::chrono_literals;
auto guard = scopeGuard([] {
LOG_TOPIC("27bc7", FATAL, Logger::REPLICATION2)
<< "Test terminating early, aborting for debugging";
FATAL_ERROR_ABORT();
});
auto leaderLog = makeReplicatedLog(LogId{1});
auto follower1Log = makeReplicatedLog(LogId{2});
auto follower2Log = makeReplicatedLog(LogId{3});
auto follower1 = follower1Log->becomeFollower("follower1", LogTerm{1}, "leader");
auto follower2 = follower2Log->becomeFollower("follower2", LogTerm{1}, "leader");
auto leader =
leaderLog->becomeLeader("leader", LogTerm{1},
{std::static_pointer_cast<AbstractFollower>(follower1),
std::static_pointer_cast<AbstractFollower>(follower2)},
2);
auto data = ThreadCoordinationData{leader};
// start replication
auto replicationThread =
std::thread{runReplicationWithIntermittentPauses, std::ref(data)};
auto followerReplicationThread =
std::thread{runFollowerReplicationWithIntermittentPauses,
std::vector{follower1.get(), follower2.get()}, std::ref(data)};
std::vector<std::thread> clientThreads;
auto threadCounter = uint16_t{0};
clientThreads.emplace_back(alternatinglyInsertAndRead, threadCounter++, std::ref(data));
clientThreads.emplace_back(insertManyThenRead, threadCounter++, std::ref(data));
ASSERT_EQ(clientThreads.size(), threadCounter);
while (data.threadsReady.load() < clientThreads.size()) {
}
data.go.store(true);
while (data.threadsSatisfied.load() < clientThreads.size()) {
std::this_thread::sleep_for(100us);
}
data.stopClientThreads.store(true);
for (auto& thread : clientThreads) {
thread.join();
}
// stop replication only after all client threads joined, so we don't block
// them in some intermediate state
data.stopReplicationThreads.store(true);
replicationThread.join();
followerReplicationThread.join();
guard.cancel();
auto stats = std::get<LeaderStatus>(data.log->getStatus().getVariant()).local;
EXPECT_LE(LogIndex{8000}, stats.commitIndex);
EXPECT_LE(stats.commitIndex, stats.spearHead.index);
}
|
/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ganaya $ $Date: 2000-11-13 21:12:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = 0;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = NULL;
maFrameData.mnInputLang = 0;
maFrameData.mnInputCodePage = 0;
maFrameData.mbGraphics = FALSE;
maFrameData.mbCaption = FALSE;
maFrameData.mbBorder = FALSE;
maFrameData.mbSizeBorder = FALSE;
maFrameData.mbFullScreen = FALSE;
maFrameData.mbPresentation = FALSE;
maFrameData.mbInShow = FALSE;
maFrameData.mbRestoreMaximize = FALSE;
maFrameData.mbInMoveMsg = FALSE;
maFrameData.mbInSizeMsg = FALSE;
maFrameData.mbFullScreenToolWin = FALSE;
maFrameData.mbDefPos = TRUE;
maFrameData.mbOverwriteState = TRUE;
maFrameData.mbIME = FALSE;
maFrameData.mbHandleIME = FALSE;
maFrameData.mbSpezIME = FALSE;
maFrameData.mbAtCursorIME = FALSE;
maFrameData.mbCompositionMode = FALSE;
maFrameData.mbCandidateMode = FALSE;
memset( &maFrameData.maState, 0, sizeof( SalFrameState ) );
maFrameData.maSysData.nSize = sizeof( SystemEnvData );
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
if ( hView )
{
SalData* pSalData = GetSalData();
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mhWnd = maFrameData.mhWnd;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
maFrameData.mbGraphics = TRUE;
}
}
else
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics* )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void* pData )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char*)aByteTitle.GetBuffer();
VCLWindow_SetTitle(maFrameData.mhWnd, pTitle);
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
VCLWindow_makeKeyAndOrderFront( maFrameData.mhWnd );
else
VCLWindow_close( maFrameData.mhWnd );
// This is temporary code for testing only and should be removed when
// development of the SalObject class is complete. This code allows
// us to test our SalGraphics drawing methods.
// Get this window's cached handle to its native content view
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
// Draw a line on the native content view
VCLGraphics_drawLine( hView, 0L, 0L, 1000L, 1000L );
}
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
void SalFrame::UpdateExtTextInputArea()
{
}
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
}
Changed VCLWindow_SetTitle function to VCLWindow_setTitle to be consistent with other C function naming format.
/*************************************************************************
*
* $RCSfile: salframe.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: pluby $ $Date: 2000-11-14 00:18:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <string.h>
#define _SV_SALFRAME_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_VCLWINDOW_H
#include <VCLWindow.h>
#endif
#ifndef _SV_VCLGRAPHICS_H
#include <VCLGraphics.h>
#endif
// =======================================================================
SalFrame::SalFrame()
{
SalData* pSalData = GetSalData();
maFrameData.mhWnd = 0;
maFrameData.mpGraphics = NULL;
maFrameData.mpInst = NULL;
maFrameData.mpProc = NULL;
maFrameData.mnInputLang = 0;
maFrameData.mnInputCodePage = 0;
maFrameData.mbGraphics = FALSE;
maFrameData.mbCaption = FALSE;
maFrameData.mbBorder = FALSE;
maFrameData.mbSizeBorder = FALSE;
maFrameData.mbFullScreen = FALSE;
maFrameData.mbPresentation = FALSE;
maFrameData.mbInShow = FALSE;
maFrameData.mbRestoreMaximize = FALSE;
maFrameData.mbInMoveMsg = FALSE;
maFrameData.mbInSizeMsg = FALSE;
maFrameData.mbFullScreenToolWin = FALSE;
maFrameData.mbDefPos = TRUE;
maFrameData.mbOverwriteState = TRUE;
maFrameData.mbIME = FALSE;
maFrameData.mbHandleIME = FALSE;
maFrameData.mbSpezIME = FALSE;
maFrameData.mbAtCursorIME = FALSE;
maFrameData.mbCompositionMode = FALSE;
maFrameData.mbCandidateMode = FALSE;
memset( &maFrameData.maState, 0, sizeof( SalFrameState ) );
maFrameData.maSysData.nSize = sizeof( SystemEnvData );
}
// -----------------------------------------------------------------------
SalFrame::~SalFrame()
{
}
// -----------------------------------------------------------------------
SalGraphics* SalFrame::GetGraphics()
{
if ( maFrameData.mbGraphics )
return NULL;
if ( !maFrameData.mpGraphics )
{
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
if ( hView )
{
SalData* pSalData = GetSalData();
maFrameData.mpGraphics = new SalGraphics;
maFrameData.mpGraphics->maGraphicsData.mhDC = hView;
maFrameData.mpGraphics->maGraphicsData.mhWnd = maFrameData.mhWnd;
maFrameData.mpGraphics->maGraphicsData.mbPrinter = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbVirDev = FALSE;
maFrameData.mpGraphics->maGraphicsData.mbWindow = TRUE;
maFrameData.mpGraphics->maGraphicsData.mbScreen = TRUE;
maFrameData.mbGraphics = TRUE;
}
}
else
maFrameData.mbGraphics = TRUE;
return maFrameData.mpGraphics;
}
// -----------------------------------------------------------------------
void SalFrame::ReleaseGraphics( SalGraphics* )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::PostEvent( void* pData )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::SetTitle( const XubString& rTitle )
{
ByteString aByteTitle( rTitle, gsl_getSystemTextEncoding() );
char *pTitle = (char *)aByteTitle.GetBuffer();
VCLWindow_setTitle(maFrameData.mhWnd, pTitle);
}
// -----------------------------------------------------------------------
void SalFrame::SetIcon( USHORT nIcon )
{
}
// -----------------------------------------------------------------------
void SalFrame::Show( BOOL bVisible )
{
if ( bVisible )
VCLWindow_makeKeyAndOrderFront( maFrameData.mhWnd );
else
VCLWindow_close( maFrameData.mhWnd );
// This is temporary code for testing only and should be removed when
// development of the SalObject class is complete. This code allows
// us to test our SalGraphics drawing methods.
// Get this window's cached handle to its native content view
VCLVIEW hView = VCLWindow_contentView( maFrameData.mhWnd );
// Draw a line on the native content view
VCLGraphics_drawLine( hView, 0L, 0L, 1000L, 1000L );
}
// -----------------------------------------------------------------------
void SalFrame::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetMinClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetClientSize( long nWidth, long nHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::GetClientSize( long& rWidth, long& rHeight )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetWindowState( const SalFrameState* pState )
{
}
// -----------------------------------------------------------------------
BOOL SalFrame::GetWindowState( SalFrameState* pState )
{
return FALSE;
}
// -----------------------------------------------------------------------
void SalFrame::ShowFullScreen( BOOL bFullScreen )
{
}
// -----------------------------------------------------------------------
void SalFrame::StartPresentation( BOOL bStart )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetAlwaysOnTop( BOOL bOnTop )
{
}
// -----------------------------------------------------------------------
void SalFrame::ToTop( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointer( PointerStyle ePointerStyle )
{
}
// -----------------------------------------------------------------------
void SalFrame::CaptureMouse( BOOL bCapture )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetPointerPos( long nX, long nY )
{
}
// -----------------------------------------------------------------------
void SalFrame::Flush()
{
}
// -----------------------------------------------------------------------
void SalFrame::Sync()
{
}
// -----------------------------------------------------------------------
void SalFrame::SetInputContext( SalInputContext* pContext )
{
}
// -----------------------------------------------------------------------
void SalFrame::UpdateExtTextInputArea()
{
}
// -----------------------------------------------------------------------
void SalFrame::EndExtTextInput( USHORT nFlags )
{
}
// -----------------------------------------------------------------------
XubString SalFrame::GetKeyName( USHORT nKeyCode )
{
return XubString();
}
// -----------------------------------------------------------------------
XubString SalFrame::GetSymbolKeyName( const XubString&, USHORT nKeyCode )
{
return GetKeyName( nKeyCode );
}
// -----------------------------------------------------------------------
void SalFrame::UpdateSettings( AllSettings& rSettings )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* SalFrame::GetSystemData() const
{
return NULL;
}
// -----------------------------------------------------------------------
void SalFrame::Beep( SoundType eSoundType )
{
}
// -----------------------------------------------------------------------
void SalFrame::SetCallback( void* pInst, SALFRAMEPROC pProc )
{
}
|
/*******************************************************************************
* Copyright (c) 2009-2016, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
******************************************************************************/
/*******************************************************************************
* \file imu.c
*
* \author MAV'RIC Team
* \author Felix Schill
* \author Gregoire Heitz
* \author Julien Lecoeur
*
* \brief Inertial measurement unit (IMU)
*
******************************************************************************/
#include "sensing/imu.hpp"
extern "C"
{
#include "hal/common/time_keeper.hpp"
#include "util/print_util.h"
#include "util/constants.h"
}
Imu::Imu(Accelerometer& accelerometer, Gyroscope& gyroscope, Magnetometer& magnetometer, imu_conf_t config):
accelerometer_(accelerometer),
gyroscope_(gyroscope),
magnetometer_(magnetometer),
config_(config),
oriented_acc_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
oriented_gyro_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
oriented_mag_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_acc_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_gyro_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_mag_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
do_accelerometer_bias_calibration_(false),
do_gyroscope_bias_calibration_(false),
do_magnetometer_bias_calibration_(false),
is_ready_(false),
dt_s_(0.004f),
last_update_us_(time_keeper_get_us()),
timestamp_gyro_stable(time_keeper_get_s())
{}
bool Imu::update(void)
{
bool success = false;
// Update timing
uint32_t t = time_keeper_get_us();
dt_s_ = (float)(t - last_update_us_) / 1000000.0f;
last_update_us_ = t;
// Read new values from sensors
success &= accelerometer_.update();
success &= gyroscope_.update();
success &= magnetometer_.update();
// Retrieve data
std::array<float, 3> raw_acc = accelerometer_.acc();
std::array<float, 3> raw_gyro = gyroscope_.gyro();
std::array<float, 3> raw_mag = magnetometer_.mag();
// Rotate sensor values
for (uint8_t i = 0; i < 3; i++)
{
oriented_acc_[i] = raw_acc[ config_.accelerometer.axis[i] ] * config_.accelerometer.sign[i];
oriented_gyro_[i] = raw_gyro[ config_.gyroscope.axis[i] ] * config_.gyroscope.sign[i];
oriented_mag_[i] = raw_mag[ config_.magnetometer.axis[i] ] * config_.magnetometer.sign[i];
}
// Scale sensor values
float new_scaled_acc[3];
float new_scaled_gyro[3];
float new_scaled_mag[3];
for (int8_t i = 0; i < 3; i++)
{
// Scale, then remove bias
new_scaled_acc[i] = oriented_acc_[i] / config_.accelerometer.scale_factor[i] - config_.accelerometer.bias[i];
new_scaled_gyro[i] = oriented_gyro_[i] / config_.gyroscope.scale_factor[i] - config_.gyroscope.bias[i];
new_scaled_mag[i] = oriented_mag_[i] / config_.magnetometer.scale_factor[i] - config_.magnetometer.bias[i];
// Low pass filter
scaled_acc_[i] = config_.lpf_acc * new_scaled_acc[i] + (1.0f - config_.lpf_acc) * scaled_acc_[i];
scaled_gyro_[i] = config_.lpf_gyro * new_scaled_gyro[i] + (1.0f - config_.lpf_gyro) * scaled_gyro_[i];
scaled_mag_[i] = config_.lpf_mag * new_scaled_mag[i] + (1.0f - config_.lpf_mag) * scaled_mag_[i];
}
// Do automatic gyroscope calibration at startup
do_startup_calibration();
// Perform calibration of sensors
do_calibration();
return success;
}
const float& Imu::last_update_us(void) const
{
return last_update_us_;
}
const float& Imu::dt_s(void) const
{
return dt_s_;
}
const std::array<float, 3>& Imu::acc(void) const
{
return scaled_acc_;
}
const std::array<float, 3>& Imu::gyro(void) const
{
return scaled_gyro_;
}
const std::array<float, 3>& Imu::mag(void) const
{
return scaled_mag_;
}
imu_conf_t* Imu::get_config(void)
{
return &config_;
}
bool Imu::start_accelerometer_bias_calibration(void)
{
// Success if not already doing magnetometer calibration
bool success = !do_magnetometer_bias_calibration_;
if (success)
{
do_accelerometer_bias_calibration_ = true;
config_.accelerometer.mean_values[X] = scaled_acc_[X];
config_.accelerometer.mean_values[Y] = scaled_acc_[Y];
config_.accelerometer.mean_values[Z] = scaled_acc_[Z];
}
return success;
}
bool Imu::start_gyroscope_bias_calibration(void)
{
// Success if not already doing magnetometer calibration
bool success = !do_magnetometer_bias_calibration_;
if (success)
{
do_gyroscope_bias_calibration_ = true;
config_.gyroscope.mean_values[X] = scaled_gyro_[X];
config_.gyroscope.mean_values[Y] = scaled_gyro_[Y];
config_.gyroscope.mean_values[Z] = scaled_gyro_[Z];
}
return success;
}
bool Imu::start_magnetometer_bias_calibration(void)
{
// Success if not already doing accelerometer or gyroscope calibration
bool success = true;
success &= !do_accelerometer_bias_calibration_;
success &= !do_gyroscope_bias_calibration_;
if (success)
{
do_magnetometer_bias_calibration_ = true;
config_.magnetometer.max_values[X] = -10000.0f;
config_.magnetometer.max_values[Y] = -10000.0f;
config_.magnetometer.max_values[Z] = -10000.0f;
config_.magnetometer.min_values[X] = 10000.0f;
config_.magnetometer.min_values[Y] = 10000.0f;
config_.magnetometer.min_values[Z] = 10000.0f;
}
return success;
}
bool Imu::stop_accelerometer_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_accelerometer_bias_calibration_;
// Stop calibrating
do_accelerometer_bias_calibration_ = false;
// Update biases
if (success)
{
config_.accelerometer.bias[X] += config_.accelerometer.mean_values[X];
config_.accelerometer.bias[Y] += config_.accelerometer.mean_values[Y];
config_.accelerometer.bias[Z] += config_.accelerometer.mean_values[Z] - (-1.0f);
}
return success;
}
bool Imu::stop_gyroscope_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_gyroscope_bias_calibration_;
// Stop calibrating
do_gyroscope_bias_calibration_ = false;
// Update biases
if (success)
{
config_.gyroscope.bias[X] += config_.gyroscope.mean_values[X];
config_.gyroscope.bias[Y] += config_.gyroscope.mean_values[Y];
config_.gyroscope.bias[Z] += config_.gyroscope.mean_values[Z];
}
return success;
}
bool Imu::stop_magnetometer_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_magnetometer_bias_calibration_;
// Stop calibrating
do_magnetometer_bias_calibration_ = false;
// Update biases
config_.magnetometer.bias[X] += 0.5f * (config_.magnetometer.max_values[X] + config_.magnetometer.min_values[X]);
config_.magnetometer.bias[Y] += 0.5f * (config_.magnetometer.max_values[Y] + config_.magnetometer.min_values[Y]);
config_.magnetometer.bias[Z] += 0.5f * (config_.magnetometer.max_values[Z] + config_.magnetometer.min_values[Z]);
return success;
}
const bool Imu::is_ready(void) const
{
return is_ready_;
}
void Imu::do_startup_calibration(void)
{
if (is_ready_ == false)
{
// Make sure calibration is ongoing
if (do_gyroscope_bias_calibration_ == false)
{
start_gyroscope_bias_calibration();
timestamp_gyro_stable = time_keeper_get_s();
}
// Check if the gyroscope values are stable
bool gyro_is_stable = (maths_f_abs(config_.gyroscope.mean_values[X] - scaled_gyro_[X]) < config_.startup_calib_gyro_threshold)
&& (maths_f_abs(config_.gyroscope.mean_values[Y] - scaled_gyro_[Y]) < config_.startup_calib_gyro_threshold)
&& (maths_f_abs(config_.gyroscope.mean_values[Z] - scaled_gyro_[Z]) < config_.startup_calib_gyro_threshold);
if (gyro_is_stable == false)
{
is_ready_ = false;
// Reset timestamp
timestamp_gyro_stable = time_keeper_get_s();
}
// If gyros have been stable for long enough
if ((gyro_is_stable == true) && ((time_keeper_get_s() - timestamp_gyro_stable) > config_.startup_calib_duration_s))
{
// Sartup calibration is done
is_ready_ = true;
stop_gyroscope_bias_calibration();
}
}
}
void Imu::do_calibration(void)
{
// Do accelero bias calibration
if (do_accelerometer_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.accelerometer.mean_values[i] = (1.0f - config_.lpf_mean) * config_.accelerometer.mean_values[i] + config_.lpf_mean * scaled_acc_[i];
}
}
// Do gyroscope bias calibration
if (do_gyroscope_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.gyroscope.mean_values[i] = (1.0f - config_.lpf_mean) * config_.gyroscope.mean_values[i] + config_.lpf_mean * scaled_gyro_[i];
}
}
// Do magnetometer bias calibration
if (do_magnetometer_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.magnetometer.max_values[i] = maths_f_max(config_.magnetometer.max_values[i], scaled_mag_[i]);
config_.magnetometer.min_values[i] = maths_f_min(config_.magnetometer.min_values[i], scaled_mag_[i]);
}
}
}
reset imu_ready_ flag in case of calibration (#210)
/*******************************************************************************
* Copyright (c) 2009-2016, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
******************************************************************************/
/*******************************************************************************
* \file imu.c
*
* \author MAV'RIC Team
* \author Felix Schill
* \author Gregoire Heitz
* \author Julien Lecoeur
*
* \brief Inertial measurement unit (IMU)
*
******************************************************************************/
#include "sensing/imu.hpp"
extern "C"
{
#include "hal/common/time_keeper.hpp"
#include "util/print_util.h"
#include "util/constants.h"
}
Imu::Imu(Accelerometer& accelerometer, Gyroscope& gyroscope, Magnetometer& magnetometer, imu_conf_t config):
accelerometer_(accelerometer),
gyroscope_(gyroscope),
magnetometer_(magnetometer),
config_(config),
oriented_acc_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
oriented_gyro_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
oriented_mag_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_acc_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_gyro_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
scaled_mag_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}),
do_accelerometer_bias_calibration_(false),
do_gyroscope_bias_calibration_(false),
do_magnetometer_bias_calibration_(false),
is_ready_(false),
dt_s_(0.004f),
last_update_us_(time_keeper_get_us()),
timestamp_gyro_stable(time_keeper_get_s())
{}
bool Imu::update(void)
{
bool success = false;
// Update timing
uint32_t t = time_keeper_get_us();
dt_s_ = (float)(t - last_update_us_) / 1000000.0f;
last_update_us_ = t;
// Read new values from sensors
success &= accelerometer_.update();
success &= gyroscope_.update();
success &= magnetometer_.update();
// Retrieve data
std::array<float, 3> raw_acc = accelerometer_.acc();
std::array<float, 3> raw_gyro = gyroscope_.gyro();
std::array<float, 3> raw_mag = magnetometer_.mag();
// Rotate sensor values
for (uint8_t i = 0; i < 3; i++)
{
oriented_acc_[i] = raw_acc[ config_.accelerometer.axis[i] ] * config_.accelerometer.sign[i];
oriented_gyro_[i] = raw_gyro[ config_.gyroscope.axis[i] ] * config_.gyroscope.sign[i];
oriented_mag_[i] = raw_mag[ config_.magnetometer.axis[i] ] * config_.magnetometer.sign[i];
}
// Scale sensor values
float new_scaled_acc[3];
float new_scaled_gyro[3];
float new_scaled_mag[3];
for (int8_t i = 0; i < 3; i++)
{
// Scale, then remove bias
new_scaled_acc[i] = oriented_acc_[i] / config_.accelerometer.scale_factor[i] - config_.accelerometer.bias[i];
new_scaled_gyro[i] = oriented_gyro_[i] / config_.gyroscope.scale_factor[i] - config_.gyroscope.bias[i];
new_scaled_mag[i] = oriented_mag_[i] / config_.magnetometer.scale_factor[i] - config_.magnetometer.bias[i];
// Low pass filter
scaled_acc_[i] = config_.lpf_acc * new_scaled_acc[i] + (1.0f - config_.lpf_acc) * scaled_acc_[i];
scaled_gyro_[i] = config_.lpf_gyro * new_scaled_gyro[i] + (1.0f - config_.lpf_gyro) * scaled_gyro_[i];
scaled_mag_[i] = config_.lpf_mag * new_scaled_mag[i] + (1.0f - config_.lpf_mag) * scaled_mag_[i];
}
// Do automatic gyroscope calibration at startup
do_startup_calibration();
// Perform calibration of sensors
do_calibration();
return success;
}
const float& Imu::last_update_us(void) const
{
return last_update_us_;
}
const float& Imu::dt_s(void) const
{
return dt_s_;
}
const std::array<float, 3>& Imu::acc(void) const
{
return scaled_acc_;
}
const std::array<float, 3>& Imu::gyro(void) const
{
return scaled_gyro_;
}
const std::array<float, 3>& Imu::mag(void) const
{
return scaled_mag_;
}
imu_conf_t* Imu::get_config(void)
{
return &config_;
}
bool Imu::start_accelerometer_bias_calibration(void)
{
// Success if not already doing magnetometer calibration
// Since this calib needs the robot to remain still,
// whereas for the magneto calib we need to move the robot
bool success = !do_magnetometer_bias_calibration_;
if (success)
{
// Start calibration
is_ready_ = false;
do_accelerometer_bias_calibration_ = true;
config_.accelerometer.mean_values[X] = scaled_acc_[X];
config_.accelerometer.mean_values[Y] = scaled_acc_[Y];
config_.accelerometer.mean_values[Z] = scaled_acc_[Z];
}
return success;
}
bool Imu::start_gyroscope_bias_calibration(void)
{
// Success if not already doing magnetometer calibration
// Since this calib needs the robot to remain still,
// whereas for the magneto calib we need to move the robot
bool success = !do_magnetometer_bias_calibration_;
if (success)
{
// Start calibration
is_ready_ = false;
do_gyroscope_bias_calibration_ = true;
config_.gyroscope.mean_values[X] = scaled_gyro_[X];
config_.gyroscope.mean_values[Y] = scaled_gyro_[Y];
config_.gyroscope.mean_values[Z] = scaled_gyro_[Z];
}
return success;
}
bool Imu::start_magnetometer_bias_calibration(void)
{
// Success if not already doing accelerometer or gyroscope calibration
// Since this calib needs the robot to be moved,
// whereas for the 2 other calibs we need to have the robot still
bool success = true;
success &= !do_accelerometer_bias_calibration_;
success &= !do_gyroscope_bias_calibration_;
if (success)
{
// Start calibration
is_ready_ = false;
do_magnetometer_bias_calibration_ = true;
config_.magnetometer.max_values[X] = -10000.0f;
config_.magnetometer.max_values[Y] = -10000.0f;
config_.magnetometer.max_values[Z] = -10000.0f;
config_.magnetometer.min_values[X] = 10000.0f;
config_.magnetometer.min_values[Y] = 10000.0f;
config_.magnetometer.min_values[Z] = 10000.0f;
}
return success;
}
bool Imu::stop_accelerometer_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_accelerometer_bias_calibration_;
// Stop calibrating
do_accelerometer_bias_calibration_ = false;
// Update biases
if (success)
{
// Stop calibration
is_ready_ = true;
config_.accelerometer.bias[X] += config_.accelerometer.mean_values[X];
config_.accelerometer.bias[Y] += config_.accelerometer.mean_values[Y];
config_.accelerometer.bias[Z] += config_.accelerometer.mean_values[Z] - (-1.0f);
}
return success;
}
bool Imu::stop_gyroscope_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_gyroscope_bias_calibration_;
// Stop calibrating
do_gyroscope_bias_calibration_ = false;
// Update biases
if (success)
{
// Stop calibration
is_ready_ = true;
config_.gyroscope.bias[X] += config_.gyroscope.mean_values[X];
config_.gyroscope.bias[Y] += config_.gyroscope.mean_values[Y];
config_.gyroscope.bias[Z] += config_.gyroscope.mean_values[Z];
}
return success;
}
bool Imu::stop_magnetometer_bias_calibration(void)
{
// Success if calibration is ongoing
bool success = do_magnetometer_bias_calibration_;
// Stop calibrating
do_magnetometer_bias_calibration_ = false;
// Update biases
if (success)
{
// Stop calibration
is_ready_ = true;
config_.magnetometer.bias[X] += 0.5f * (config_.magnetometer.max_values[X] + config_.magnetometer.min_values[X]);
config_.magnetometer.bias[Y] += 0.5f * (config_.magnetometer.max_values[Y] + config_.magnetometer.min_values[Y]);
config_.magnetometer.bias[Z] += 0.5f * (config_.magnetometer.max_values[Z] + config_.magnetometer.min_values[Z]);
}
return success;
}
const bool Imu::is_ready(void) const
{
return is_ready_;
}
void Imu::do_startup_calibration(void)
{
if (is_ready_ == false)
{
// Make sure calibration is ongoing
if (do_gyroscope_bias_calibration_ == false)
{
start_gyroscope_bias_calibration();
timestamp_gyro_stable = time_keeper_get_s();
}
// Check if the gyroscope values are stable
bool gyro_is_stable = (maths_f_abs(config_.gyroscope.mean_values[X] - scaled_gyro_[X]) < config_.startup_calib_gyro_threshold)
&& (maths_f_abs(config_.gyroscope.mean_values[Y] - scaled_gyro_[Y]) < config_.startup_calib_gyro_threshold)
&& (maths_f_abs(config_.gyroscope.mean_values[Z] - scaled_gyro_[Z]) < config_.startup_calib_gyro_threshold);
if (gyro_is_stable == false)
{
is_ready_ = false;
// Reset timestamp
timestamp_gyro_stable = time_keeper_get_s();
}
// If gyros have been stable for long enough
if ((gyro_is_stable == true) && ((time_keeper_get_s() - timestamp_gyro_stable) > config_.startup_calib_duration_s))
{
// Sartup calibration is done
is_ready_ = true;
stop_gyroscope_bias_calibration();
}
}
}
void Imu::do_calibration(void)
{
// Do accelero bias calibration
if (do_accelerometer_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.accelerometer.mean_values[i] = (1.0f - config_.lpf_mean) * config_.accelerometer.mean_values[i] + config_.lpf_mean * scaled_acc_[i];
}
}
// Do gyroscope bias calibration
if (do_gyroscope_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.gyroscope.mean_values[i] = (1.0f - config_.lpf_mean) * config_.gyroscope.mean_values[i] + config_.lpf_mean * scaled_gyro_[i];
}
}
// Do magnetometer bias calibration
if (do_magnetometer_bias_calibration_)
{
for (uint8_t i = 0; i < 3; i++)
{
config_.magnetometer.max_values[i] = maths_f_max(config_.magnetometer.max_values[i], scaled_mag_[i]);
config_.magnetometer.min_values[i] = maths_f_min(config_.magnetometer.min_values[i], scaled_mag_[i]);
}
}
} |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <config_folders.h>
#include <osl/mutex.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <ucbhelper/content.hxx>
#include <cppuhelper/implbase1.hxx>
#include <tools/urlobj.hxx>
#include <vcl/dibtools.hxx>
#include <vcl/salctype.hxx>
#include <vcl/pngread.hxx>
#include <vcl/pngwrite.hxx>
#include <vcl/svgdata.hxx>
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <osl/file.hxx>
#include <vcl/graphicfilter.hxx>
#include <vcl/FilterConfigItem.hxx>
#include <vcl/wmf.hxx>
#include "igif/gifread.hxx"
#include "jpeg/jpeg.hxx"
#include "ixbm/xbmread.hxx"
#include "ixpm/xpmread.hxx"
#include "sgffilt.hxx"
#include "osl/module.hxx"
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/XWeak.hpp>
#include <com/sun/star/uno/XAggregation.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/svg/XSVGWriter.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <rtl/bootstrap.hxx>
#include <rtl/instance.hxx>
#include <vcl/metaact.hxx>
#include <vector>
#include "FilterConfigCache.hxx"
#define PMGCHUNG_msOG 0x6d734f47 // Microsoft Office Animated GIF
#ifndef DISABLE_DYNLOADING
#define IMPORT_FUNCTION_NAME "GraphicImport"
#define EXPORT_FUNCTION_NAME "GraphicExport"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using comphelper::string::getTokenCount;
using comphelper::string::getToken;
typedef ::std::vector< GraphicFilter* > FilterList_impl;
static FilterList_impl* pFilterHdlList = NULL;
static ::osl::Mutex& getListMutex()
{
static ::osl::Mutex s_aListProtection;
return s_aListProtection;
}
class ImpFilterOutputStream : public ::cppu::WeakImplHelper1< css::io::XOutputStream >
{
protected:
SvStream& mrStm;
virtual void SAL_CALL writeBytes( const css::uno::Sequence< sal_Int8 >& rData )
throw (css::io::NotConnectedException, css::io::BufferSizeExceededException, css::io::IOException, css::uno::RuntimeException)
{ mrStm.Write( rData.getConstArray(), rData.getLength() ); }
virtual void SAL_CALL flush()
throw (css::io::NotConnectedException, css::io::BufferSizeExceededException, css::io::IOException, css::uno::RuntimeException)
{ mrStm.Flush(); }
virtual void SAL_CALL closeOutput() throw() {}
public:
ImpFilterOutputStream( SvStream& rStm ) : mrStm( rStm ) {}
~ImpFilterOutputStream() {}
};
#ifndef DISABLE_EXPORT
static bool DirEntryExists( const INetURLObject& rObj )
{
bool bExists = false;
try
{
::ucbhelper::Content aCnt( rObj.GetMainURL( INetURLObject::NO_DECODE ),
css::uno::Reference< css::ucb::XCommandEnvironment >(),
comphelper::getProcessComponentContext() );
bExists = aCnt.isDocument();
}
catch(const css::ucb::CommandAbortedException&)
{
SAL_WARN( "vcl.filter", "CommandAbortedException" );
}
catch(const css::ucb::ContentCreationException&)
{
SAL_WARN( "vcl.filter", "ContentCreationException" );
}
catch( ... )
{
SAL_WARN( "vcl.filter", "Any other exception" );
}
return bExists;
}
static void KillDirEntry( const OUString& rMainUrl )
{
try
{
::ucbhelper::Content aCnt( rMainUrl,
css::uno::Reference< css::ucb::XCommandEnvironment >(),
comphelper::getProcessComponentContext() );
aCnt.executeCommand( "delete",
css::uno::makeAny( sal_Bool( sal_True ) ) );
}
catch(const css::ucb::CommandAbortedException&)
{
SAL_WARN( "vcl.filter", "CommandAbortedException" );
}
catch( ... )
{
SAL_WARN( "vcl.filter", "Any other exception" );
}
}
#endif // !DISABLE_EXPORT
// Helper functions
sal_uInt8* ImplSearchEntry( sal_uInt8* pSource, sal_uInt8* pDest, sal_uLong nComp, sal_uLong nSize )
{
while ( nComp-- >= nSize )
{
sal_uLong i;
for ( i = 0; i < nSize; i++ )
{
if ( ( pSource[i]&~0x20 ) != ( pDest[i]&~0x20 ) )
break;
}
if ( i == nSize )
return pSource;
pSource++;
}
return NULL;
}
inline OUString ImpGetExtension( const OUString &rPath )
{
OUString aExt;
INetURLObject aURL( rPath );
aExt = aURL.GetFileExtension().toAsciiUpperCase();
return aExt;
}
bool isPCT(SvStream& rStream, sal_uLong nStreamPos, sal_uLong nStreamLen)
{
sal_uInt8 sBuf[3];
// store number format
sal_uInt16 oldNumberFormat = rStream.GetNumberFormatInt();
sal_uInt32 nOffset; // in MS documents the pict format is used without the first 512 bytes
for ( nOffset = 0; ( nOffset <= 512 ) && ( ( nStreamPos + nOffset + 14 ) <= nStreamLen ); nOffset += 512 )
{
short y1,x1,y2,x2;
bool bdBoxOk = true;
rStream.Seek( nStreamPos + nOffset);
// size of the pict in version 1 pict ( 2bytes) : ignored
rStream.SeekRel(2);
// bounding box (bytes 2 -> 9)
rStream.SetNumberFormatInt(NUMBERFORMAT_INT_BIGENDIAN);
rStream >> y1 >> x1 >> y2 >> x2;
rStream.SetNumberFormatInt(oldNumberFormat); // reset format
if (x1 > x2 || y1 > y2 || // bad bdbox
(x1 == x2 && y1 == y2) || // 1 pixel picture
x2-x1 > 2048 || y2-y1 > 2048 ) // picture anormaly big
bdBoxOk = false;
// read version op
rStream.Read( sBuf,3 );
// see http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Imaging_With_QuickDraw/Appendix_A.pdf
// normal version 2 - page A23 and A24
if ( sBuf[ 0 ] == 0x00 && sBuf[ 1 ] == 0x11 && sBuf[ 2 ] == 0x02)
return true;
// normal version 1 - page A25
else if (sBuf[ 0 ] == 0x11 && sBuf[ 1 ] == 0x01 && bdBoxOk)
return true;
}
return false;
}
/*************************************************************************
*
* ImpPeekGraphicFormat()
*
* Description:
* This function is two-fold:
* 1.) Start reading file, determine the file format:
* Input parameters:
* rPath - file path
* rFormatExtension - content matter
* bTest - set false
* Output parameters:
* Return value - true if success
* rFormatExtension - on success: normal file extension in capitals
* 2.) Start reading file, verify file format
* Input parameters:
* rPath - file path
* rFormatExtension - normal file extension in capitals
* bTest - set true
* Output parameters:
* Return value - false, if cannot verify the file type
* passed to the function
* true, when the format is PROBABLY verified or
* WHEN THE FORMAT IS NOT KNOWN!
*
*************************************************************************/
static bool ImpPeekGraphicFormat( SvStream& rStream, OUString& rFormatExtension, bool bTest )
{
sal_uInt16 i;
sal_uInt8 sFirstBytes[ 256 ];
sal_uLong nFirstLong,nSecondLong;
sal_uLong nStreamPos = rStream.Tell();
rStream.Seek( STREAM_SEEK_TO_END );
sal_uLong nStreamLen = rStream.Tell() - nStreamPos;
rStream.Seek( nStreamPos );
if ( !nStreamLen )
{
SvLockBytes* pLockBytes = rStream.GetLockBytes();
if ( pLockBytes )
pLockBytes->SetSynchronMode( true );
rStream.Seek( STREAM_SEEK_TO_END );
nStreamLen = rStream.Tell() - nStreamPos;
rStream.Seek( nStreamPos );
}
if (!nStreamLen)
{
return false; // this prevents at least a STL assertion
}
else if (nStreamLen >= 256)
{ // load first 256 bytes into a buffer
rStream.Read( sFirstBytes, 256 );
}
else
{
rStream.Read( sFirstBytes, nStreamLen );
for( i = (sal_uInt16) nStreamLen; i < 256; i++ )
sFirstBytes[ i ]=0;
}
if( rStream.GetError() )
return false;
// Accommodate the first 8 bytes in nFirstLong, nSecondLong
// Big-Endian:
for( i = 0, nFirstLong = 0L, nSecondLong = 0L; i < 4; i++ )
{
nFirstLong=(nFirstLong<<8)|(sal_uLong)sFirstBytes[i];
nSecondLong=(nSecondLong<<8)|(sal_uLong)sFirstBytes[i+4];
}
// The following variable is used when bTest == true. It remains sal_False
// if the format (rFormatExtension) has not yet been set.
bool bSomethingTested = false;
// Now the different formats are checked. The order *does* matter. e.g. a MET file
// could also go through the BMP test, howeve a BMP file can hardly go through the MET test.
// So MET should be tested prior to BMP. However, theoretically a BMP file could conceivably
// go through the MET test. These problems are of course not only in MET and BMP.
// Therefore, in the case of a format check (bTest == true) we only test *exactly* this
// format. Everything else could have fatal consequences, for example if the user says it is
// a BMP file (and it is a BMP) file, and the file would go through the MET test ...
//--------------------------- MET ------------------------------------
if( !bTest || rFormatExtension.startsWith( "MET" ) )
{
bSomethingTested=true;
if( sFirstBytes[2] == 0xd3 )
{
rStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
rStream.Seek( nStreamPos );
sal_uInt16 nFieldSize;
sal_uInt8 nMagic;
bool bOK=true;
rStream >> nFieldSize >> nMagic;
for (i=0; i<3; i++) {
if (nFieldSize<6) { bOK=false; break; }
if (nStreamLen < rStream.Tell() + nFieldSize ) { bOK=false; break; }
rStream.SeekRel(nFieldSize-3);
rStream >> nFieldSize >> nMagic;
if (nMagic!=0xd3) { bOK=false; break; }
}
rStream.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
if (bOK && !rStream.GetError()) {
rFormatExtension = "MET";
return true;
}
}
}
//--------------------------- BMP ------------------------------------
if( !bTest || rFormatExtension.startsWith( "BMP" ) )
{
sal_uInt8 nOffs;
bSomethingTested=true;
// We're possibly also able to read an OS/2 bitmap array
// ('BA'), therefore we must adjust the offset to discover the
// first bitmap in the array
if ( sFirstBytes[0] == 0x42 && sFirstBytes[1] == 0x41 )
nOffs = 14;
else
nOffs = 0;
// Now we initially test on 'BM'
if ( sFirstBytes[0+nOffs]==0x42 && sFirstBytes[1+nOffs]==0x4d )
{
// OS/2 can set the Reserved flags to a value other than 0
// (which they really should not do...);
// In this case we test the size of the BmpInfoHeaders
if ( ( sFirstBytes[6+nOffs]==0x00 &&
sFirstBytes[7+nOffs]==0x00 &&
sFirstBytes[8+nOffs]==0x00 &&
sFirstBytes[9+nOffs]==0x00 ) ||
sFirstBytes[14+nOffs] == 0x28 ||
sFirstBytes[14+nOffs] == 0x0c )
{
rFormatExtension = "BMP";
return true;
}
}
}
//--------------------------- WMF/EMF ------------------------------------
if( !bTest ||
rFormatExtension.startsWith( "WMF" ) ||
rFormatExtension.startsWith( "EMF" ) )
{
bSomethingTested = true;
if ( nFirstLong==0xd7cdc69a || nFirstLong==0x01000900 )
{
rFormatExtension = "WMF";
return true;
}
else if( nFirstLong == 0x01000000 && sFirstBytes[ 40 ] == 0x20 && sFirstBytes[ 41 ] == 0x45 &&
sFirstBytes[ 42 ] == 0x4d && sFirstBytes[ 43 ] == 0x46 )
{
rFormatExtension = "EMF";
return true;
}
}
//--------------------------- PCX ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCX" ) )
{
bSomethingTested=true;
if (sFirstBytes[0]==0x0a)
{
sal_uInt8 nVersion=sFirstBytes[1];
sal_uInt8 nEncoding=sFirstBytes[2];
if( ( nVersion==0 || nVersion==2 || nVersion==3 || nVersion==5 ) && nEncoding<=1 )
{
rFormatExtension = "PCX";
return true;
}
}
}
//--------------------------- TIF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "TIF" ) )
{
bSomethingTested=true;
if ( nFirstLong==0x49492a00 || nFirstLong==0x4d4d002a )
{
rFormatExtension = "TIF";
return true;
}
}
//--------------------------- GIF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "GIF" ) )
{
bSomethingTested=true;
if ( nFirstLong==0x47494638 && (sFirstBytes[4]==0x37 || sFirstBytes[4]==0x39) && sFirstBytes[5]==0x61 )
{
rFormatExtension = "GIF";
return true;
}
}
//--------------------------- PNG ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PNG" ) )
{
bSomethingTested=true;
if (nFirstLong==0x89504e47 && nSecondLong==0x0d0a1a0a)
{
rFormatExtension = "PNG";
return true;
}
}
//--------------------------- JPG ------------------------------------
if( !bTest || rFormatExtension.startsWith( "JPG" ) )
{
bSomethingTested=true;
if ( ( nFirstLong==0xffd8ffe0 && sFirstBytes[6]==0x4a && sFirstBytes[7]==0x46 && sFirstBytes[8]==0x49 && sFirstBytes[9]==0x46 ) ||
( nFirstLong==0xffd8fffe ) || ( 0xffd8ff00 == ( nFirstLong & 0xffffff00 ) ) )
{
rFormatExtension = "JPG";
return true;
}
}
//--------------------------- SVM ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SVM" ) )
{
bSomethingTested=true;
if( nFirstLong==0x53564744 && sFirstBytes[4]==0x49 )
{
rFormatExtension = "SVM";
return true;
}
else if( sFirstBytes[0]==0x56 && sFirstBytes[1]==0x43 && sFirstBytes[2]==0x4C &&
sFirstBytes[3]==0x4D && sFirstBytes[4]==0x54 && sFirstBytes[5]==0x46 )
{
rFormatExtension = "SVM";
return true;
}
}
//--------------------------- PCD ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCD" ) )
{
bSomethingTested = true;
if( nStreamLen >= 2055 )
{
char sBuf[8];
rStream.Seek( nStreamPos + 2048 );
rStream.Read( sBuf, 7 );
if( strncmp( sBuf, "PCD_IPI", 7 ) == 0 )
{
rFormatExtension = "PCD";
return true;
}
}
}
//--------------------------- PSD ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PSD" ) )
{
bSomethingTested = true;
if ( ( nFirstLong == 0x38425053 ) && ( (nSecondLong >> 16 ) == 1 ) )
{
rFormatExtension = "PSD";
return true;
}
}
//--------------------------- EPS ------------------------------------
if( !bTest || rFormatExtension.startsWith( "EPS" ) )
{
bSomethingTested = true;
if ( ( nFirstLong == 0xC5D0D3C6 ) || ( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"%!PS-Adobe", 10, 10 ) &&
ImplSearchEntry( &sFirstBytes[15], (sal_uInt8*)"EPS", 3, 3 ) ) )
{
rFormatExtension = "EPS";
return true;
}
}
//--------------------------- DXF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "DXF" ) )
{
// Binary DXF File Format
if( strncmp( (const char*) sFirstBytes, "AutoCAD Binary DXF", 18 ) == 0 )
{
rFormatExtension = "DXF";
return true;
}
// ASCII DXF File Format
i=0;
while (i<256 && sFirstBytes[i]<=32)
++i;
if (i<256 && sFirstBytes[i]=='0')
{
++i;
// only now do we have sufficient data to make a judgement
// based on a '0' + 'SECTION' == DXF argument
bSomethingTested=true;
while( i<256 && sFirstBytes[i]<=32 )
++i;
if (i+7<256 && (strncmp((const char*)(sFirstBytes+i),"SECTION",7)==0))
{
rFormatExtension = "DXF";
return true;
}
}
}
//--------------------------- PCT ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCT" ) )
{
bSomethingTested = true;
if (isPCT(rStream, nStreamPos, nStreamLen))
{
rFormatExtension = "PCT";
return true;
}
}
//------------------------- PBM + PGM + PPM ---------------------------
if( !bTest ||
rFormatExtension.startsWith( "PBM" ) ||
rFormatExtension.startsWith( "PGM" ) ||
rFormatExtension.startsWith( "PPM" ) )
{
bSomethingTested=true;
if ( sFirstBytes[ 0 ] == 'P' )
{
switch( sFirstBytes[ 1 ] )
{
case '1' :
case '4' :
rFormatExtension = "PBM";
return true;
case '2' :
case '5' :
rFormatExtension = "PGM";
return true;
case '3' :
case '6' :
rFormatExtension = "PPM";
return true;
}
}
}
//--------------------------- RAS( SUN RasterFile )------------------
if( !bTest || rFormatExtension.startsWith( "RAS" ) )
{
bSomethingTested=true;
if( nFirstLong == 0x59a66a95 )
{
rFormatExtension = "RAS";
return true;
}
}
//--------------------------- XPM ------------------------------------
if( !bTest )
{
bSomethingTested = true;
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"/* XPM */", 256, 9 ) )
{
rFormatExtension = "XPM";
return true;
}
}
else if( rFormatExtension.startsWith( "XPM" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- XBM ------------------------------------
if( !bTest )
{
sal_uLong nSize = ( nStreamLen > 2048 ) ? 2048 : nStreamLen;
sal_uInt8* pBuf = new sal_uInt8 [ nSize ];
rStream.Seek( nStreamPos );
rStream.Read( pBuf, nSize );
sal_uInt8* pPtr = ImplSearchEntry( pBuf, (sal_uInt8*)"#define", nSize, 7 );
if( pPtr )
{
if( ImplSearchEntry( pPtr, (sal_uInt8*)"_width", pBuf + nSize - pPtr, 6 ) )
{
rFormatExtension = "XBM";
delete[] pBuf;
return true;
}
}
delete[] pBuf;
}
else if( rFormatExtension.startsWith( "XBM" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- SVG ------------------------------------
if( !bTest )
{
// check for Xml
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<?xml", 256, 5 ) // is it xml
&& ImplSearchEntry( sFirstBytes, (sal_uInt8*)"version", 256, 7 )) // does it have a version (required for xml)
{
bool bIsSvg(false);
// check for DOCTYPE svg combination
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"DOCTYPE", 256, 7 ) // 'DOCTYPE' is there
&& ImplSearchEntry( sFirstBytes, (sal_uInt8*)"svg", 256, 3 )) // 'svg' is there
{
bIsSvg = true;
}
// check for svg element in 1st 256 bytes
if(!bIsSvg && ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<svg", 256, 4 )) // '<svg'
{
bIsSvg = true;
}
if(!bIsSvg)
{
// it's a xml, look for '<svg' in full file. Should not happen too
// often since the tests above will handle most cases, but can happen
// with Svg files containing big comment headers or Svg as the host
// language
const sal_uLong nSize((nStreamLen > 2048) ? 2048 : nStreamLen);
sal_uInt8* pBuf = new sal_uInt8[nSize];
rStream.Seek(nStreamPos);
rStream.Read(pBuf, nSize);
if(ImplSearchEntry(pBuf, (sal_uInt8*)"<svg", nSize, 4)) // '<svg'
{
bIsSvg = true;
}
delete[] pBuf;
}
if(bIsSvg)
{
rFormatExtension = "SVG";
return true;
}
}
else
{
// #119176# SVG files which have no xml header at all have shown up,
// detect those, too
bool bIsSvg(false);
// check for svg element in 1st 256 bytes
if(ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<svg", 256, 4 )) // '<svg'
{
bIsSvg = true;
}
if(!bIsSvg)
{
// look for '<svg' in full file. Should not happen too
// often since the tests above will handle most cases, but can happen
// with SVG files containing big comment headers or SVG as the host
// language
const sal_uLong nSize((nStreamLen > 2048) ? 2048 : nStreamLen);
sal_uInt8* pBuf = new sal_uInt8[nSize];
rStream.Seek(nStreamPos);
rStream.Read(pBuf, nSize);
if(ImplSearchEntry(pBuf, (sal_uInt8*)"<svg", nSize, 4)) // '<svg'
{
bIsSvg = true;
}
delete[] pBuf;
}
if(bIsSvg)
{
rFormatExtension = "SVG";
return true;
}
}
}
else if( rFormatExtension.startsWith( "SVG" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- TGA ------------------------------------
if( !bTest || rFormatExtension.startsWith( "TGA" ) )
{
bSomethingTested = true;
// just a simple test for the extension
if( rFormatExtension.startsWith( "TGA" ) )
return true;
}
//--------------------------- SGV ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SGV" ) )
{
bSomethingTested = true;
// just a simple test for the extension
if( rFormatExtension.startsWith( "SGV" ) )
return true;
}
//--------------------------- SGF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SGF" ) )
{
bSomethingTested=true;
if( sFirstBytes[ 0 ] == 'J' && sFirstBytes[ 1 ] == 'J' )
{
rFormatExtension = "SGF";
return true;
}
}
if(!bTest || rFormatExtension.startsWith( "MOV" ))
{
if ((sFirstBytes[ 4 ] == 'f' && sFirstBytes[ 5 ] == 't' && sFirstBytes[ 6 ] == 'y' &&
sFirstBytes[ 7 ] == 'p' && sFirstBytes[ 8 ] == 'q' && sFirstBytes[ 9 ] == 't') ||
(sFirstBytes[ 4 ] == 'm' && sFirstBytes[ 5 ] == 'o' && sFirstBytes[ 6 ] == 'o' &&
sFirstBytes[ 7 ] == 'v' && sFirstBytes[ 11 ] == 'l' && sFirstBytes[ 12 ] == 'm'))
{
bSomethingTested=true;
rFormatExtension = "MOV";
return true;
}
}
return bTest && !bSomethingTested;
}
//--------------------------------------------------------------------------
sal_uInt16 GraphicFilter::ImpTestOrFindFormat( const OUString& rPath, SvStream& rStream, sal_uInt16& rFormat )
{
// determine or check the filter/format by reading into it
if( rFormat == GRFILTER_FORMAT_DONTKNOW )
{
OUString aFormatExt;
if( ImpPeekGraphicFormat( rStream, aFormatExt, false ) )
{
rFormat = pConfig->GetImportFormatNumberForExtension( aFormatExt );
if( rFormat != GRFILTER_FORMAT_DONTKNOW )
return GRFILTER_OK;
}
// determine filter by file extension
if( !rPath.isEmpty() )
{
OUString aExt( ImpGetExtension( rPath ) );
rFormat = pConfig->GetImportFormatNumberForExtension( aExt );
if( rFormat != GRFILTER_FORMAT_DONTKNOW )
return GRFILTER_OK;
}
return GRFILTER_FORMATERROR;
}
else
{
OUString aTmpStr( pConfig->GetImportFormatExtension( rFormat ) );
aTmpStr = aTmpStr.toAsciiUpperCase();
if( !ImpPeekGraphicFormat( rStream, aTmpStr, true ) )
return GRFILTER_FORMATERROR;
if ( pConfig->GetImportFormatExtension( rFormat ).equalsIgnoreAsciiCase( "pcd" ) )
{
sal_Int32 nBase = 2; // default Base0
if ( pConfig->GetImportFilterType( rFormat ).equalsIgnoreAsciiCase( "pcd_Photo_CD_Base4" ) )
nBase = 1;
else if ( pConfig->GetImportFilterType( rFormat ).equalsIgnoreAsciiCase( "pcd_Photo_CD_Base16" ) )
nBase = 0;
OUString aFilterConfigPath( "Office.Common/Filter/Graphic/Import/PCD" );
FilterConfigItem aFilterConfigItem( aFilterConfigPath );
aFilterConfigItem.WriteInt32( "Resolution", nBase );
}
}
return GRFILTER_OK;
}
//--------------------------------------------------------------------------
#ifndef DISABLE_EXPORT
static Graphic ImpGetScaledGraphic( const Graphic& rGraphic, FilterConfigItem& rConfigItem )
{
Graphic aGraphic;
ResMgr* pResMgr = ResMgr::CreateResMgr( "svt", Application::GetSettings().GetUILanguageTag() );
sal_Int32 nLogicalWidth = rConfigItem.ReadInt32( "LogicalWidth", 0 );
sal_Int32 nLogicalHeight = rConfigItem.ReadInt32( "LogicalHeight", 0 );
if ( rGraphic.GetType() != GRAPHIC_NONE )
{
sal_Int32 nMode = rConfigItem.ReadInt32( "ExportMode", -1 );
if ( nMode == -1 ) // the property is not there, this is possible, if the graphic filter
{ // is called via UnoGraphicExporter and not from a graphic export Dialog
nMode = 0; // then we are defaulting this mode to 0
if ( nLogicalWidth || nLogicalHeight )
nMode = 2;
}
Size aOriginalSize;
Size aPrefSize( rGraphic.GetPrefSize() );
MapMode aPrefMapMode( rGraphic.GetPrefMapMode() );
if ( aPrefMapMode == MAP_PIXEL )
aOriginalSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_100TH_MM );
else
aOriginalSize = Application::GetDefaultDevice()->LogicToLogic( aPrefSize, aPrefMapMode, MAP_100TH_MM );
if ( !nLogicalWidth )
nLogicalWidth = aOriginalSize.Width();
if ( !nLogicalHeight )
nLogicalHeight = aOriginalSize.Height();
if( rGraphic.GetType() == GRAPHIC_BITMAP )
{
// Resolution is set
if( nMode == 1 )
{
Bitmap aBitmap( rGraphic.GetBitmap() );
MapMode aMap( MAP_100TH_INCH );
sal_Int32 nDPI = rConfigItem.ReadInt32( "Resolution", 75 );
Fraction aFrac( 1, std::min( std::max( nDPI, sal_Int32( 75 ) ), sal_Int32( 600 ) ) );
aMap.SetScaleX( aFrac );
aMap.SetScaleY( aFrac );
Size aOldSize = aBitmap.GetSizePixel();
aGraphic = rGraphic;
aGraphic.SetPrefMapMode( aMap );
aGraphic.SetPrefSize( Size( aOldSize.Width() * 100,
aOldSize.Height() * 100 ) );
}
// Size is set
else if( nMode == 2 )
{
aGraphic = rGraphic;
aGraphic.SetPrefMapMode( MapMode( MAP_100TH_MM ) );
aGraphic.SetPrefSize( Size( nLogicalWidth, nLogicalHeight ) );
}
else
aGraphic = rGraphic;
sal_Int32 nColors = rConfigItem.ReadInt32( "Color", 0 ); // #92767#
if ( nColors ) // graphic conversion necessary ?
{
BitmapEx aBmpEx( aGraphic.GetBitmapEx() );
aBmpEx.Convert( (BmpConversion)nColors ); // the entries in the xml section have the same meaning as
aGraphic = aBmpEx; // they have in the BmpConversion enum, so it should be
} // allowed to cast them
}
else
{
if( ( nMode == 1 ) || ( nMode == 2 ) )
{
GDIMetaFile aMtf( rGraphic.GetGDIMetaFile() );
css::awt::Size aDefaultSize( 10000, 10000 );
Size aNewSize( OutputDevice::LogicToLogic( Size( nLogicalWidth, nLogicalHeight ), MAP_100TH_MM, aMtf.GetPrefMapMode() ) );
if( aNewSize.Width() && aNewSize.Height() )
{
const Size aPreferredSize( aMtf.GetPrefSize() );
aMtf.Scale( Fraction( aNewSize.Width(), aPreferredSize.Width() ),
Fraction( aNewSize.Height(), aPreferredSize.Height() ) );
}
aGraphic = Graphic( aMtf );
}
else
aGraphic = rGraphic;
}
}
else
aGraphic = rGraphic;
delete pResMgr;
return aGraphic;
}
#endif
static OUString ImpCreateFullFilterPath( const OUString& rPath, const OUString& rFilterName )
{
OUString aPathURL;
::osl::FileBase::getFileURLFromSystemPath( rPath, aPathURL );
aPathURL += "/";
OUString aSystemPath;
::osl::FileBase::getSystemPathFromFileURL( aPathURL, aSystemPath );
aSystemPath += rFilterName;
return OUString( aSystemPath );
}
class ImpFilterLibCache;
struct ImpFilterLibCacheEntry
{
ImpFilterLibCacheEntry* mpNext;
#ifndef DISABLE_DYNLOADING
osl::Module maLibrary;
#endif
OUString maFiltername;
PFilterCall mpfnImport;
PFilterDlgCall mpfnImportDlg;
ImpFilterLibCacheEntry( const OUString& rPathname, const OUString& rFiltername );
bool operator==( const OUString& rFiltername ) const { return maFiltername == rFiltername; }
PFilterCall GetImportFunction();
};
ImpFilterLibCacheEntry::ImpFilterLibCacheEntry( const OUString& rPathname, const OUString& rFiltername ) :
mpNext ( NULL ),
#ifndef DISABLE_DYNLOADING
maLibrary ( rPathname ),
#endif
maFiltername ( rFiltername ),
mpfnImport ( NULL ),
mpfnImportDlg ( NULL )
{
#ifdef DISABLE_DYNLOADING
(void) rPathname;
#endif
}
#ifdef DISABLE_DYNLOADING
extern "C" sal_Bool icdGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool idxGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool imeGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipbGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipdGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipsGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool iptGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipxGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool iraGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool itgGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool itiGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
#endif
PFilterCall ImpFilterLibCacheEntry::GetImportFunction()
{
if( !mpfnImport )
{
#ifndef DISABLE_DYNLOADING
mpfnImport = (PFilterCall) maLibrary.getFunctionSymbol(OUString(IMPORT_FUNCTION_NAME));
#else
if( maFiltername.equalsAscii( "icd" ) )
mpfnImport = icdGraphicImport;
else if( maFiltername.equalsAscii( "idx" ) )
mpfnImport = idxGraphicImport;
else if( maFiltername.equalsAscii( "ime" ) )
mpfnImport = imeGraphicImport;
else if( maFiltername.equalsAscii( "ipb" ) )
mpfnImport = ipbGraphicImport;
else if( maFiltername.equalsAscii( "ipd" ) )
mpfnImport = ipdGraphicImport;
else if( maFiltername.equalsAscii( "ips" ) )
mpfnImport = ipsGraphicImport;
else if( maFiltername.equalsAscii( "ipt" ) )
mpfnImport = iptGraphicImport;
else if( maFiltername.equalsAscii( "ipx" ) )
mpfnImport = ipxGraphicImport;
else if( maFiltername.equalsAscii( "ira" ) )
mpfnImport = iraGraphicImport;
else if( maFiltername.equalsAscii( "itg" ) )
mpfnImport = itgGraphicImport;
else if( maFiltername.equalsAscii( "iti" ) )
mpfnImport = itiGraphicImport;
#endif
}
return mpfnImport;
}
class ImpFilterLibCache
{
ImpFilterLibCacheEntry* mpFirst;
ImpFilterLibCacheEntry* mpLast;
public:
ImpFilterLibCache();
~ImpFilterLibCache();
ImpFilterLibCacheEntry* GetFilter( const OUString& rFilterPath, const OUString& rFiltername );
};
ImpFilterLibCache::ImpFilterLibCache() :
mpFirst ( NULL ),
mpLast ( NULL )
{
}
ImpFilterLibCache::~ImpFilterLibCache()
{
ImpFilterLibCacheEntry* pEntry = mpFirst;
while( pEntry )
{
ImpFilterLibCacheEntry* pNext = pEntry->mpNext;
delete pEntry;
pEntry = pNext;
}
}
ImpFilterLibCacheEntry* ImpFilterLibCache::GetFilter( const OUString& rFilterPath, const OUString& rFilterName )
{
ImpFilterLibCacheEntry* pEntry = mpFirst;
while( pEntry )
{
if( *pEntry == rFilterName )
break;
else
pEntry = pEntry->mpNext;
}
if( !pEntry )
{
OUString aPhysicalName( ImpCreateFullFilterPath( rFilterPath, rFilterName ) );
pEntry = new ImpFilterLibCacheEntry( aPhysicalName, rFilterName );
#ifndef DISABLE_DYNLOADING
if ( pEntry->maLibrary.is() )
#endif
{
if( !mpFirst )
mpFirst = mpLast = pEntry;
else
mpLast = mpLast->mpNext = pEntry;
}
#ifndef DISABLE_DYNLOADING
else
{
delete pEntry;
pEntry = NULL;
}
#endif
}
return pEntry;
};
namespace { struct Cache : public rtl::Static<ImpFilterLibCache, Cache> {}; }
GraphicFilter::GraphicFilter( sal_Bool bConfig ) :
bUseConfig ( bConfig ),
nExpGraphHint ( 0 )
{
ImplInit();
}
GraphicFilter::~GraphicFilter()
{
{
::osl::MutexGuard aGuard( getListMutex() );
for(
FilterList_impl::iterator it = pFilterHdlList->begin();
it != pFilterHdlList->end();
++it
) {
if( *it == this )
{
pFilterHdlList->erase( it );
break;
}
}
if( pFilterHdlList->empty() )
{
delete pFilterHdlList, pFilterHdlList = NULL;
delete pConfig;
}
}
delete pErrorEx;
}
void GraphicFilter::ImplInit()
{
{
::osl::MutexGuard aGuard( getListMutex() );
if ( !pFilterHdlList )
{
pFilterHdlList = new FilterList_impl;
pConfig = new FilterConfigCache( bUseConfig );
}
else
pConfig = pFilterHdlList->front()->pConfig;
pFilterHdlList->push_back( this );
}
if( bUseConfig )
{
OUString url("$BRAND_BASE_DIR/" LIBO_LIB_FOLDER);
rtl::Bootstrap::expandMacros(url); //TODO: detect failure
utl::LocalFileHelper::ConvertURLToPhysicalName(url, aFilterPath);
}
pErrorEx = new FilterErrorEx;
bAbort = sal_False;
}
sal_uLong GraphicFilter::ImplSetError( sal_uLong nError, const SvStream* pStm )
{
pErrorEx->nFilterError = nError;
pErrorEx->nStreamError = pStm ? pStm->GetError() : ERRCODE_NONE;
return nError;
}
sal_uInt16 GraphicFilter::GetImportFormatCount()
{
return pConfig->GetImportFormatCount();
}
sal_uInt16 GraphicFilter::GetImportFormatNumber( const OUString& rFormatName )
{
return pConfig->GetImportFormatNumber( rFormatName );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForMediaType( const OUString& rMediaType )
{
return pConfig->GetImportFormatNumberForMediaType( rMediaType );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForShortName( const OUString& rShortName )
{
return pConfig->GetImportFormatNumberForShortName( rShortName );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForTypeName( const OUString& rType )
{
return pConfig->GetImportFormatNumberForTypeName( rType );
}
OUString GraphicFilter::GetImportFormatName( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatName( nFormat );
}
OUString GraphicFilter::GetImportFormatTypeName( sal_uInt16 nFormat )
{
return pConfig->GetImportFilterTypeName( nFormat );
}
OUString GraphicFilter::GetImportFormatMediaType( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatMediaType( nFormat );
}
OUString GraphicFilter::GetImportFormatShortName( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatShortName( nFormat );
}
OUString GraphicFilter::GetImportOSFileType( sal_uInt16 )
{
OUString aOSFileType;
return aOSFileType;
}
OUString GraphicFilter::GetImportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry )
{
return pConfig->GetImportWildcard( nFormat, nEntry );
}
sal_Bool GraphicFilter::IsImportPixelFormat( sal_uInt16 nFormat )
{
return pConfig->IsImportPixelFormat( nFormat );
}
sal_uInt16 GraphicFilter::GetExportFormatCount()
{
return pConfig->GetExportFormatCount();
}
sal_uInt16 GraphicFilter::GetExportFormatNumber( const OUString& rFormatName )
{
return pConfig->GetExportFormatNumber( rFormatName );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForMediaType( const OUString& rMediaType )
{
return pConfig->GetExportFormatNumberForMediaType( rMediaType );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForShortName( const OUString& rShortName )
{
return pConfig->GetExportFormatNumberForShortName( rShortName );
}
OUString GraphicFilter::GetExportInternalFilterName( sal_uInt16 nFormat )
{
return pConfig->GetExportInternalFilterName( nFormat );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForTypeName( const OUString& rType )
{
return pConfig->GetExportFormatNumberForTypeName( rType );
}
OUString GraphicFilter::GetExportFormatName( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatName( nFormat );
}
OUString GraphicFilter::GetExportFormatTypeName( sal_uInt16 nFormat )
{
return pConfig->GetExportFilterTypeName( nFormat );
}
OUString GraphicFilter::GetExportFormatMediaType( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatMediaType( nFormat );
}
OUString GraphicFilter::GetExportFormatShortName( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatShortName( nFormat );
}
OUString GraphicFilter::GetExportOSFileType( sal_uInt16 )
{
OUString aOSFileType;
return aOSFileType;
}
OUString GraphicFilter::GetExportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry )
{
return pConfig->GetExportWildcard( nFormat, nEntry );
}
sal_Bool GraphicFilter::IsExportPixelFormat( sal_uInt16 nFormat )
{
return pConfig->IsExportPixelFormat( nFormat );
}
sal_uInt16 GraphicFilter::CanImportGraphic( const INetURLObject& rPath,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat )
{
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::CanImportGraphic() : ProtType == INET_PROT_NOT_VALID" );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_READ | STREAM_SHARE_DENYNONE );
if ( pStream )
{
nRetValue = CanImportGraphic( aMainUrl, *pStream, nFormat, pDeterminedFormat );
delete pStream;
}
return nRetValue;
}
sal_uInt16 GraphicFilter::CanImportGraphic( const OUString& rMainUrl, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat )
{
sal_uLong nStreamPos = rIStream.Tell();
sal_uInt16 nRes = ImpTestOrFindFormat( rMainUrl, rIStream, nFormat );
rIStream.Seek(nStreamPos);
if( nRes==GRFILTER_OK && pDeterminedFormat!=NULL )
*pDeterminedFormat = nFormat;
return (sal_uInt16) ImplSetError( nRes, &rIStream );
}
//SJ: TODO, we need to create a GraphicImporter component
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const INetURLObject& rPath,
sal_uInt16 nFormat, sal_uInt16 * pDeterminedFormat, sal_uInt32 nImportFlags )
{
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::ImportGraphic() : ProtType == INET_PROT_NOT_VALID" );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_READ | STREAM_SHARE_DENYNONE );
if ( pStream )
{
nRetValue = ImportGraphic( rGraphic, aMainUrl, *pStream, nFormat, pDeterminedFormat, nImportFlags );
delete pStream;
}
return nRetValue;
}
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const OUString& rPath, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat, sal_uInt32 nImportFlags, WMF_EXTERNALHEADER *pExtHeader )
{
return ImportGraphic( rGraphic, rPath, rIStream, nFormat, pDeterminedFormat, nImportFlags, NULL, pExtHeader );
}
//-------------------------------------------------------------------------
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const OUString& rPath, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat, sal_uInt32 nImportFlags,
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >* pFilterData,
WMF_EXTERNALHEADER *pExtHeader )
{
OUString aFilterName;
sal_uLong nStmBegin;
sal_uInt16 nStatus;
GraphicReader* pContext = rGraphic.GetContext();
GfxLinkType eLinkType = GFX_LINK_TYPE_NONE;
bool bDummyContext = ( pContext == (GraphicReader*) 1 );
const sal_Bool bLinkSet = rGraphic.IsLink();
FilterConfigItem* pFilterConfigItem = NULL;
Size aPreviewSizeHint( 0, 0 );
sal_Bool bAllowPartialStreamRead = sal_False;
sal_Bool bCreateNativeLink = sal_True;
ResetLastError();
if ( pFilterData )
{
sal_Int32 i;
for ( i = 0; i < pFilterData->getLength(); i++ )
{
if ( (*pFilterData)[ i ].Name == "PreviewSizeHint" )
{
awt::Size aSize;
if ( (*pFilterData)[ i ].Value >>= aSize )
{
aPreviewSizeHint = Size( aSize.Width, aSize.Height );
if ( aSize.Width || aSize.Height )
nImportFlags |= GRFILTER_I_FLAGS_FOR_PREVIEW;
else
nImportFlags &=~GRFILTER_I_FLAGS_FOR_PREVIEW;
}
}
else if ( (*pFilterData)[ i ].Name == "AllowPartialStreamRead" )
{
(*pFilterData)[ i ].Value >>= bAllowPartialStreamRead;
if ( bAllowPartialStreamRead )
nImportFlags |= GRFILTER_I_FLAGS_ALLOW_PARTIAL_STREAMREAD;
else
nImportFlags &=~GRFILTER_I_FLAGS_ALLOW_PARTIAL_STREAMREAD;
}
else if ( (*pFilterData)[ i ].Name == "CreateNativeLink" )
{
(*pFilterData)[ i ].Value >>= bCreateNativeLink;
}
}
}
if( !pContext || bDummyContext )
{
if( bDummyContext )
{
rGraphic.SetContext( NULL );
nStmBegin = 0;
}
else
nStmBegin = rIStream.Tell();
bAbort = sal_False;
nStatus = ImpTestOrFindFormat( rPath, rIStream, nFormat );
// if pending, return GRFILTER_OK in order to request more bytes
if( rIStream.GetError() == ERRCODE_IO_PENDING )
{
rGraphic.SetContext( (GraphicReader*) 1 );
rIStream.ResetError();
rIStream.Seek( nStmBegin );
return (sal_uInt16) ImplSetError( GRFILTER_OK );
}
rIStream.Seek( nStmBegin );
if( ( nStatus != GRFILTER_OK ) || rIStream.GetError() )
return (sal_uInt16) ImplSetError( ( nStatus != GRFILTER_OK ) ? nStatus : GRFILTER_OPENERROR, &rIStream );
if( pDeterminedFormat )
*pDeterminedFormat = nFormat;
aFilterName = pConfig->GetImportFilterName( nFormat );
}
else
{
if( pContext && !bDummyContext )
aFilterName = pContext->GetUpperFilterName();
nStmBegin = 0;
nStatus = GRFILTER_OK;
}
// read graphic
if ( pConfig->IsImportInternalFilter( nFormat ) )
{
if( aFilterName.equalsIgnoreAsciiCase( IMP_GIF ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportGIF( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
else
eLinkType = GFX_LINK_TYPE_NATIVE_GIF;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_PNG ) )
{
if ( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
vcl::PNGReader aPNGReader( rIStream );
// ignore animation for previews and set preview size
if( aPreviewSizeHint.Width() || aPreviewSizeHint.Height() )
{
// position the stream at the end of the image if requested
if( !bAllowPartialStreamRead )
aPNGReader.GetChunks();
}
else
{
// check if this PNG contains a GIF chunk!
const std::vector< vcl::PNGReader::ChunkData >& rChunkData = aPNGReader.GetChunks();
std::vector< vcl::PNGReader::ChunkData >::const_iterator aIter( rChunkData.begin() );
std::vector< vcl::PNGReader::ChunkData >::const_iterator aEnd ( rChunkData.end() );
while( aIter != aEnd )
{
// Microsoft Office is storing Animated GIFs in following chunk
if ( aIter->nType == PMGCHUNG_msOG )
{
sal_uInt32 nChunkSize = aIter->aData.size();
if ( nChunkSize > 11 )
{
const std::vector< sal_uInt8 >& rData = aIter->aData;
SvMemoryStream aIStrm( (void*)&rData[ 11 ], nChunkSize - 11, STREAM_READ );
ImportGIF( aIStrm, rGraphic );
eLinkType = GFX_LINK_TYPE_NATIVE_PNG;
break;
}
}
++aIter;
}
}
if ( eLinkType == GFX_LINK_TYPE_NONE )
{
BitmapEx aBmpEx( aPNGReader.Read( aPreviewSizeHint ) );
if ( aBmpEx.IsEmpty() )
nStatus = GRFILTER_FILTERERROR;
else
{
rGraphic = aBmpEx;
eLinkType = GFX_LINK_TYPE_NATIVE_PNG;
}
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_JPEG ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
// set LOGSIZE flag always, if not explicitly disabled
// (see #90508 and #106763)
if( 0 == ( nImportFlags & GRFILTER_I_FLAGS_DONT_SET_LOGSIZE_FOR_JPEG ) )
nImportFlags |= GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
if( !ImportJPEG( rIStream, rGraphic, NULL, nImportFlags ) )
nStatus = GRFILTER_FILTERERROR;
else
eLinkType = GFX_LINK_TYPE_NATIVE_JPG;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_SVG ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
const sal_uInt32 nStmPos(rIStream.Tell());
const sal_uInt32 nStmLen(rIStream.Seek(STREAM_SEEK_TO_END) - nStmPos);
bool bOkay(false);
if(nStmLen)
{
SvgDataArray aNewData(new sal_uInt8[nStmLen]);
rIStream.Seek(nStmPos);
rIStream.Read(aNewData.get(), nStmLen);
if(!rIStream.GetError())
{
SvgDataPtr aSvgDataPtr(
new SvgData(
aNewData,
nStmLen,
rPath));
rGraphic = Graphic(aSvgDataPtr);
bOkay = true;
}
}
if(bOkay)
{
eLinkType = GFX_LINK_TYPE_NATIVE_SVG;
}
else
{
nStatus = GRFILTER_FILTERERROR;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_XBM ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportXBM( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_XPM ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportXPM( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_BMP ) ||
aFilterName.equalsIgnoreAsciiCase( IMP_SVMETAFILE ) )
{
// SV internal filters for import bitmaps and MetaFiles
rIStream >> rGraphic;
if( rIStream.GetError() )
nStatus = GRFILTER_FORMATERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_MOV ) )
{
rIStream >> rGraphic;
if( rIStream.GetError() )
nStatus = GRFILTER_FORMATERROR;
else
{
rGraphic.SetDefaultType();
rIStream.Seek( STREAM_SEEK_TO_END );
eLinkType = GFX_LINK_TYPE_NATIVE_MOV;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_WMF ) ||
aFilterName.equalsIgnoreAsciiCase( IMP_EMF ) )
{
GDIMetaFile aMtf;
if( !ConvertWMFToGDIMetaFile( rIStream, aMtf, NULL, pExtHeader ) )
nStatus = GRFILTER_FORMATERROR;
else
{
rGraphic = aMtf;
eLinkType = GFX_LINK_TYPE_NATIVE_WMF;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_SVSGF )
|| aFilterName.equalsIgnoreAsciiCase( IMP_SVSGV ) )
{
sal_uInt16 nVersion;
unsigned char nTyp = CheckSgfTyp( rIStream, nVersion );
switch( nTyp )
{
case SGF_BITIMAGE:
{
SvMemoryStream aTempStream;
if( aTempStream.GetError() )
return GRFILTER_OPENERROR;
if( !SgfBMapFilter( rIStream, aTempStream ) )
nStatus = GRFILTER_FILTERERROR;
else
{
aTempStream.Seek( 0L );
aTempStream >> rGraphic;
if( aTempStream.GetError() )
nStatus = GRFILTER_FILTERERROR;
}
}
break;
case SGF_SIMPVECT:
{
GDIMetaFile aMtf;
if( !SgfVectFilter( rIStream, aMtf ) )
nStatus = GRFILTER_FILTERERROR;
else
rGraphic = Graphic( aMtf );
}
break;
case SGF_STARDRAW:
{
if( nVersion != SGV_VERSION )
nStatus = GRFILTER_VERSIONERROR;
else
{
GDIMetaFile aMtf;
if( !SgfSDrwFilter( rIStream, aMtf,
INetURLObject(aFilterPath) ) )
{
nStatus = GRFILTER_FILTERERROR;
}
else
rGraphic = Graphic( aMtf );
}
}
break;
default:
{
nStatus = GRFILTER_FORMATERROR;
}
break;
}
}
else
nStatus = GRFILTER_FILTERERROR;
}
else
{
ImpFilterLibCacheEntry* pFilter = NULL;
// find first filter in filter paths
sal_Int32 i, nTokenCount = getTokenCount(aFilterPath, ';');
ImpFilterLibCache &rCache = Cache::get();
for( i = 0; ( i < nTokenCount ) && ( pFilter == NULL ); i++ )
pFilter = rCache.GetFilter( getToken(aFilterPath, i, ';'), aFilterName );
if( !pFilter )
nStatus = GRFILTER_FILTERERROR;
else
{
PFilterCall pFunc = pFilter->GetImportFunction();
if( !pFunc )
nStatus = GRFILTER_FILTERERROR;
else
{
OUString aShortName;
if( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
aShortName = GetImportFormatShortName( nFormat ).toAsciiUpperCase();
if ( ( pFilterConfigItem == NULL ) && aShortName == "PCD" )
{
OUString aFilterConfigPath( "Office.Common/Filter/Graphic/Import/PCD" );
pFilterConfigItem = new FilterConfigItem( aFilterConfigPath );
}
}
if( !(*pFunc)( rIStream, rGraphic, pFilterConfigItem, sal_False ) )
nStatus = GRFILTER_FORMATERROR;
else
{
// try to set link type if format matches
if( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
if( aShortName.startsWith( TIF_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_TIF;
else if( aShortName.startsWith( MET_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_MET;
else if( aShortName.startsWith( PCT_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_PCT;
}
}
}
}
}
if( nStatus == GRFILTER_OK && bCreateNativeLink && ( eLinkType != GFX_LINK_TYPE_NONE ) && !rGraphic.GetContext() && !bLinkSet )
{
const sal_uLong nStmEnd = rIStream.Tell();
const sal_uLong nBufSize = nStmEnd - nStmBegin;
if( nBufSize )
{
sal_uInt8* pBuf=0;
try
{
pBuf = new sal_uInt8[ nBufSize ];
}
catch (const std::bad_alloc&)
{
nStatus = GRFILTER_TOOBIG;
}
if( nStatus == GRFILTER_OK )
{
rIStream.Seek( nStmBegin );
rIStream.Read( pBuf, nBufSize );
rGraphic.SetLink( GfxLink( pBuf, nBufSize, eLinkType, sal_True ) );
}
}
}
// Set error code or try to set native buffer
if( nStatus != GRFILTER_OK )
{
if( bAbort )
nStatus = GRFILTER_ABORT;
ImplSetError( nStatus, &rIStream );
rIStream.Seek( nStmBegin );
rGraphic.Clear();
}
delete pFilterConfigItem;
return nStatus;
}
sal_uInt16 GraphicFilter::ExportGraphic( const Graphic& rGraphic, const INetURLObject& rPath,
sal_uInt16 nFormat, const uno::Sequence< beans::PropertyValue >* pFilterData )
{
#ifdef DISABLE_EXPORT
(void) rGraphic;
(void) rPath;
(void) nFormat;
(void) pFilterData;
return GRFILTER_FORMATERROR;
#else
SAL_INFO( "vcl.filter", "GraphicFilter::ExportGraphic() (thb)" );
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::ExportGraphic() : ProtType == INET_PROT_NOT_VALID" );
bool bAlreadyExists = DirEntryExists( rPath );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_WRITE | STREAM_TRUNC );
if ( pStream )
{
nRetValue = ExportGraphic( rGraphic, aMainUrl, *pStream, nFormat, pFilterData );
delete pStream;
if( ( GRFILTER_OK != nRetValue ) && !bAlreadyExists )
KillDirEntry( aMainUrl );
}
return nRetValue;
#endif
}
#ifdef DISABLE_DYNLOADING
#ifndef DISABLE_EXPORT
extern "C" sal_Bool egiGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool emeGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epbGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epgGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eppGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epsGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eptGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eraGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool etiGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool expGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
#endif
#endif
sal_uInt16 GraphicFilter::ExportGraphic( const Graphic& rGraphic, const OUString& rPath,
SvStream& rOStm, sal_uInt16 nFormat, const uno::Sequence< beans::PropertyValue >* pFilterData )
{
#ifdef DISABLE_EXPORT
(void) rGraphic;
(void) rPath;
(void) rOStm;
(void) nFormat;
(void) pFilterData;
return GRFILTER_FORMATERROR;
#else
SAL_INFO( "vcl.filter", "GraphicFilter::ExportGraphic() (thb)" );
sal_uInt16 nFormatCount = GetExportFormatCount();
ResetLastError();
nExpGraphHint = 0;
if( nFormat == GRFILTER_FORMAT_DONTKNOW )
{
INetURLObject aURL( rPath );
OUString aExt( aURL.GetFileExtension().toAsciiUpperCase() );
for( sal_uInt16 i = 0; i < nFormatCount; i++ )
{
if ( pConfig->GetExportFormatExtension( i ).equalsIgnoreAsciiCase( aExt ) )
{
nFormat=i;
break;
}
}
}
if( nFormat >= nFormatCount )
return (sal_uInt16) ImplSetError( GRFILTER_FORMATERROR );
FilterConfigItem aConfigItem( (uno::Sequence< beans::PropertyValue >*)pFilterData );
OUString aFilterName( pConfig->GetExportFilterName( nFormat ) );
bAbort = sal_False;
sal_uInt16 nStatus = GRFILTER_OK;
GraphicType eType;
Graphic aGraphic( rGraphic );
aGraphic = ImpGetScaledGraphic( rGraphic, aConfigItem );
eType = aGraphic.GetType();
if( pConfig->IsExportPixelFormat( nFormat ) )
{
if( eType != GRAPHIC_BITMAP )
{
Size aSizePixel;
sal_uLong nColorCount,nBitsPerPixel,nNeededMem,nMaxMem;
VirtualDevice aVirDev;
nMaxMem = 1024;
nMaxMem *= 1024; // In Bytes
// Calculate how big the image would normally be:
aSizePixel=aVirDev.LogicToPixel(aGraphic.GetPrefSize(),aGraphic.GetPrefMapMode());
// Calculate how much memory the image will take up
nColorCount=aVirDev.GetColorCount();
if (nColorCount<=2) nBitsPerPixel=1;
else if (nColorCount<=4) nBitsPerPixel=2;
else if (nColorCount<=16) nBitsPerPixel=4;
else if (nColorCount<=256) nBitsPerPixel=8;
else if (nColorCount<=65536) nBitsPerPixel=16;
else nBitsPerPixel=24;
nNeededMem=((sal_uLong)aSizePixel.Width()*(sal_uLong)aSizePixel.Height()*nBitsPerPixel+7)/8;
// is the image larger than available memory?
if (nMaxMem<nNeededMem)
{
double fFak=sqrt(((double)nMaxMem)/((double)nNeededMem));
aSizePixel.Width()=(sal_uLong)(((double)aSizePixel.Width())*fFak);
aSizePixel.Height()=(sal_uLong)(((double)aSizePixel.Height())*fFak);
}
aVirDev.SetMapMode(MapMode(MAP_PIXEL));
aVirDev.SetOutputSizePixel(aSizePixel);
Graphic aGraphic2=aGraphic;
aGraphic2.Draw(&aVirDev,Point(0,0),aSizePixel); // this changes the MapMode
aVirDev.SetMapMode(MapMode(MAP_PIXEL));
aGraphic=Graphic(aVirDev.GetBitmap(Point(0,0),aSizePixel));
}
}
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
if( GRFILTER_OK == nStatus )
{
if ( pConfig->IsExportInternalFilter( nFormat ) )
{
if( aFilterName.equalsIgnoreAsciiCase( EXP_BMP ) )
{
Bitmap aBmp( aGraphic.GetBitmap() );
sal_Int32 nColorRes = aConfigItem.ReadInt32( "Colors", 0 );
if ( nColorRes && ( nColorRes <= (sal_uInt16)BMP_CONVERSION_24BIT) )
{
if( !aBmp.Convert( (BmpConversion) nColorRes ) )
aBmp = aGraphic.GetBitmap();
}
sal_Bool bRleCoding = aConfigItem.ReadBool( "RLE_Coding", sal_True );
// save RLE encoded?
WriteDIB(aBmp, rOStm, bRleCoding, true);
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_SVMETAFILE ) )
{
sal_Int32 nVersion = aConfigItem.ReadInt32( "Version", 0 ) ;
if ( nVersion )
rOStm.SetVersion( nVersion );
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
GDIMetaFile aMTF(aGraphic.GetGDIMetaFile());
aMTF.Write( rOStm );
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_WMF ) )
{
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
if ( !ConvertGDIMetaFileToWMF( aGraphic.GetGDIMetaFile(), rOStm, &aConfigItem ) )
nStatus = GRFILTER_FORMATERROR;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_EMF ) )
{
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
if ( !ConvertGDIMetaFileToEMF( aGraphic.GetGDIMetaFile(), rOStm, &aConfigItem ) )
nStatus = GRFILTER_FORMATERROR;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_JPEG ) )
{
bool bExportedGrayJPEG = false;
if( !ExportJPEG( rOStm, aGraphic, pFilterData, &bExportedGrayJPEG ) )
nStatus = GRFILTER_FORMATERROR;
nExpGraphHint = bExportedGrayJPEG ? GRFILTER_OUTHINT_GREY : 0;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_PNG ) )
{
vcl::PNGWriter aPNGWriter( aGraphic.GetBitmapEx(), pFilterData );
if ( pFilterData )
{
sal_Int32 k, j, i = 0;
for ( i = 0; i < pFilterData->getLength(); i++ )
{
if ( (*pFilterData)[ i ].Name == "AdditionalChunks" )
{
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > aAdditionalChunkSequence;
if ( (*pFilterData)[ i ].Value >>= aAdditionalChunkSequence )
{
for ( j = 0; j < aAdditionalChunkSequence.getLength(); j++ )
{
if ( aAdditionalChunkSequence[ j ].Name.getLength() == 4 )
{
sal_uInt32 nChunkType = 0;
for ( k = 0; k < 4; k++ )
{
nChunkType <<= 8;
nChunkType |= (sal_uInt8)aAdditionalChunkSequence[ j ].Name[ k ];
}
com::sun::star::uno::Sequence< sal_Int8 > aByteSeq;
if ( aAdditionalChunkSequence[ j ].Value >>= aByteSeq )
{
std::vector< vcl::PNGWriter::ChunkData >& rChunkData = aPNGWriter.GetChunks();
if ( !rChunkData.empty() )
{
sal_uInt32 nChunkLen = aByteSeq.getLength();
vcl::PNGWriter::ChunkData aChunkData;
aChunkData.nType = nChunkType;
if ( nChunkLen )
{
aChunkData.aData.resize( nChunkLen );
memcpy( &aChunkData.aData[ 0 ], aByteSeq.getConstArray(), nChunkLen );
}
std::vector< vcl::PNGWriter::ChunkData >::iterator aIter = rChunkData.end() - 1;
rChunkData.insert( aIter, aChunkData );
}
}
}
}
}
}
}
}
aPNGWriter.Write( rOStm );
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_SVG ) )
{
bool bDone(false);
// do we have a native SVG RenderGraphic, whose data can be written directly?
const SvgDataPtr aSvgDataPtr(rGraphic.getSvgData());
if(aSvgDataPtr.get() && aSvgDataPtr->getSvgDataArrayLength())
{
rOStm.Write(aSvgDataPtr->getSvgDataArray().get(), aSvgDataPtr->getSvgDataArrayLength());
if( rOStm.GetError() )
{
nStatus = GRFILTER_IOERROR;
}
else
{
bDone = true;
}
}
if( !bDone )
{
// do the normal GDIMetaFile export instead
try
{
css::uno::Reference< css::uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
css::uno::Reference< css::xml::sax::XDocumentHandler > xSaxWriter(
xml::sax::Writer::create( xContext ), uno::UNO_QUERY_THROW);
css::uno::Sequence< css::uno::Any > aArguments( 1 );
aArguments[ 0 ] <<= aConfigItem.GetFilterData();
css::uno::Reference< css::svg::XSVGWriter > xSVGWriter(
xContext->getServiceManager()->createInstanceWithArgumentsAndContext( "com.sun.star.svg.SVGWriter", aArguments, xContext),
css::uno::UNO_QUERY );
if( xSaxWriter.is() && xSVGWriter.is() )
{
css::uno::Reference< css::io::XActiveDataSource > xActiveDataSource(
xSaxWriter, css::uno::UNO_QUERY );
if( xActiveDataSource.is() )
{
const css::uno::Reference< css::uno::XInterface > xStmIf(
static_cast< ::cppu::OWeakObject* >( new ImpFilterOutputStream( rOStm ) ) );
SvMemoryStream aMemStm( 65535, 65535 );
// #i119735# just use GetGDIMetaFile, it will create a buffered version of contained bitmap now automatically
( (GDIMetaFile&) aGraphic.GetGDIMetaFile() ).Write( aMemStm );
xActiveDataSource->setOutputStream( css::uno::Reference< css::io::XOutputStream >(
xStmIf, css::uno::UNO_QUERY ) );
css::uno::Sequence< sal_Int8 > aMtfSeq( (sal_Int8*) aMemStm.GetData(), aMemStm.Tell() );
xSVGWriter->write( xSaxWriter, aMtfSeq );
}
}
}
catch(const css::uno::Exception&)
{
nStatus = GRFILTER_IOERROR;
}
}
}
else
nStatus = GRFILTER_FILTERERROR;
}
else
{
sal_Int32 i, nTokenCount = getTokenCount(aFilterPath, ';');
for ( i = 0; i < nTokenCount; i++ )
{
#ifndef DISABLE_DYNLOADING
OUString aPhysicalName( ImpCreateFullFilterPath( getToken(aFilterPath, i, ';'), aFilterName ) );
osl::Module aLibrary( aPhysicalName );
PFilterCall pFunc = (PFilterCall) aLibrary.getFunctionSymbol(OUString(EXPORT_FUNCTION_NAME));
// Execute dialog in DLL
#else
PFilterCall pFunc = NULL;
if( aFilterName.equalsAscii( "egi" ) )
pFunc = egiGraphicExport;
else if( aFilterName.equalsAscii( "eme" ) )
pFunc = emeGraphicExport;
else if( aFilterName.equalsAscii( "epb" ) )
pFunc = epbGraphicExport;
else if( aFilterName.equalsAscii( "epg" ) )
pFunc = epgGraphicExport;
else if( aFilterName.equalsAscii( "epp" ) )
pFunc = eppGraphicExport;
else if( aFilterName.equalsAscii( "eps" ) )
pFunc = epsGraphicExport;
else if( aFilterName.equalsAscii( "ept" ) )
pFunc = eptGraphicExport;
else if( aFilterName.equalsAscii( "era" ) )
pFunc = eraGraphicExport;
else if( aFilterName.equalsAscii( "eti" ) )
pFunc = etiGraphicExport;
else if( aFilterName.equalsAscii( "exp" ) )
pFunc = expGraphicExport;
#endif
if( pFunc )
{
if ( !(*pFunc)( rOStm, aGraphic, &aConfigItem, sal_False ) )
nStatus = GRFILTER_FORMATERROR;
break;
}
else
nStatus = GRFILTER_FILTERERROR;
}
}
}
if( nStatus != GRFILTER_OK )
{
if( bAbort )
nStatus = GRFILTER_ABORT;
ImplSetError( nStatus, &rOStm );
}
return nStatus;
#endif
}
const FilterErrorEx& GraphicFilter::GetLastError() const
{
return *pErrorEx;
}
void GraphicFilter::ResetLastError()
{
pErrorEx->nFilterError = pErrorEx->nStreamError = 0UL;
}
const Link GraphicFilter::GetFilterCallback() const
{
const Link aLink( LINK( this, GraphicFilter, FilterCallback ) );
return aLink;
}
IMPL_LINK( GraphicFilter, FilterCallback, ConvertData*, pData )
{
bool nRet = false;
if( pData )
{
sal_uInt16 nFormat = GRFILTER_FORMAT_DONTKNOW;
OString aShortName;
switch( pData->mnFormat )
{
case( CVT_BMP ): aShortName = BMP_SHORTNAME; break;
case( CVT_GIF ): aShortName = GIF_SHORTNAME; break;
case( CVT_JPG ): aShortName = JPG_SHORTNAME; break;
case( CVT_MET ): aShortName = MET_SHORTNAME; break;
case( CVT_PCT ): aShortName = PCT_SHORTNAME; break;
case( CVT_PNG ): aShortName = PNG_SHORTNAME; break;
case( CVT_SVM ): aShortName = SVM_SHORTNAME; break;
case( CVT_TIF ): aShortName = TIF_SHORTNAME; break;
case( CVT_WMF ): aShortName = WMF_SHORTNAME; break;
case( CVT_EMF ): aShortName = EMF_SHORTNAME; break;
case( CVT_SVG ): aShortName = SVG_SHORTNAME; break;
default:
break;
}
if( GRAPHIC_NONE == pData->maGraphic.GetType() || pData->maGraphic.GetContext() ) // Import
{
// Import
nFormat = GetImportFormatNumberForShortName( OStringToOUString( aShortName, RTL_TEXTENCODING_UTF8) );
nRet = ImportGraphic( pData->maGraphic, OUString(), pData->mrStm, nFormat ) == 0;
}
#ifndef DISABLE_EXPORT
else if( !aShortName.isEmpty() )
{
// Export
nFormat = GetExportFormatNumberForShortName( OStringToOUString(aShortName, RTL_TEXTENCODING_UTF8) );
nRet = ExportGraphic( pData->maGraphic, OUString(), pData->mrStm, nFormat ) == 0;
}
#endif
}
return long(nRet);
}
namespace
{
class StandardGraphicFilter
{
public:
StandardGraphicFilter()
{
m_aFilter.GetImportFormatCount();
}
GraphicFilter m_aFilter;
};
class theGraphicFilter : public rtl::Static<StandardGraphicFilter, theGraphicFilter> {};
}
GraphicFilter& GraphicFilter::GetGraphicFilter()
{
return theGraphicFilter::get().m_aFilter;
}
int GraphicFilter::LoadGraphic( const OUString &rPath, const OUString &rFilterName,
Graphic& rGraphic, GraphicFilter* pFilter,
sal_uInt16* pDeterminedFormat )
{
if ( !pFilter )
pFilter = &GetGraphicFilter();
const sal_uInt16 nFilter = !rFilterName.isEmpty() && pFilter->GetImportFormatCount()
? pFilter->GetImportFormatNumber( rFilterName )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURL( rPath );
if ( aURL.HasError() )
{
aURL.SetSmartProtocol( INET_PROT_FILE );
aURL.SetSmartURL( rPath );
}
SvStream* pStream = NULL;
if ( INET_PROT_FILE != aURL.GetProtocol() )
{
pStream = ::utl::UcbStreamHelper::CreateStream( rPath, STREAM_READ );
}
int nRes = GRFILTER_OK;
if ( !pStream )
nRes = pFilter->ImportGraphic( rGraphic, aURL, nFilter, pDeterminedFormat );
else
nRes = pFilter->ImportGraphic( rGraphic, rPath, *pStream, nFilter, pDeterminedFormat );
#ifdef DBG_UTIL
if( nRes )
DBG_WARNING2( "GrafikFehler [%d] - [%s]", nRes, rPath.getStr() );
#endif
return nRes;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
typo: howeve -> however
Change-Id: I12ca3f217eb1f3c77003014dc26ce4318d2b2857
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <config_folders.h>
#include <osl/mutex.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <ucbhelper/content.hxx>
#include <cppuhelper/implbase1.hxx>
#include <tools/urlobj.hxx>
#include <vcl/dibtools.hxx>
#include <vcl/salctype.hxx>
#include <vcl/pngread.hxx>
#include <vcl/pngwrite.hxx>
#include <vcl/svgdata.hxx>
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <osl/file.hxx>
#include <vcl/graphicfilter.hxx>
#include <vcl/FilterConfigItem.hxx>
#include <vcl/wmf.hxx>
#include "igif/gifread.hxx"
#include "jpeg/jpeg.hxx"
#include "ixbm/xbmread.hxx"
#include "ixpm/xpmread.hxx"
#include "sgffilt.hxx"
#include "osl/module.hxx"
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/XWeak.hpp>
#include <com/sun/star/uno/XAggregation.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/svg/XSVGWriter.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <rtl/bootstrap.hxx>
#include <rtl/instance.hxx>
#include <vcl/metaact.hxx>
#include <vector>
#include "FilterConfigCache.hxx"
#define PMGCHUNG_msOG 0x6d734f47 // Microsoft Office Animated GIF
#ifndef DISABLE_DYNLOADING
#define IMPORT_FUNCTION_NAME "GraphicImport"
#define EXPORT_FUNCTION_NAME "GraphicExport"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using comphelper::string::getTokenCount;
using comphelper::string::getToken;
typedef ::std::vector< GraphicFilter* > FilterList_impl;
static FilterList_impl* pFilterHdlList = NULL;
static ::osl::Mutex& getListMutex()
{
static ::osl::Mutex s_aListProtection;
return s_aListProtection;
}
class ImpFilterOutputStream : public ::cppu::WeakImplHelper1< css::io::XOutputStream >
{
protected:
SvStream& mrStm;
virtual void SAL_CALL writeBytes( const css::uno::Sequence< sal_Int8 >& rData )
throw (css::io::NotConnectedException, css::io::BufferSizeExceededException, css::io::IOException, css::uno::RuntimeException)
{ mrStm.Write( rData.getConstArray(), rData.getLength() ); }
virtual void SAL_CALL flush()
throw (css::io::NotConnectedException, css::io::BufferSizeExceededException, css::io::IOException, css::uno::RuntimeException)
{ mrStm.Flush(); }
virtual void SAL_CALL closeOutput() throw() {}
public:
ImpFilterOutputStream( SvStream& rStm ) : mrStm( rStm ) {}
~ImpFilterOutputStream() {}
};
#ifndef DISABLE_EXPORT
static bool DirEntryExists( const INetURLObject& rObj )
{
bool bExists = false;
try
{
::ucbhelper::Content aCnt( rObj.GetMainURL( INetURLObject::NO_DECODE ),
css::uno::Reference< css::ucb::XCommandEnvironment >(),
comphelper::getProcessComponentContext() );
bExists = aCnt.isDocument();
}
catch(const css::ucb::CommandAbortedException&)
{
SAL_WARN( "vcl.filter", "CommandAbortedException" );
}
catch(const css::ucb::ContentCreationException&)
{
SAL_WARN( "vcl.filter", "ContentCreationException" );
}
catch( ... )
{
SAL_WARN( "vcl.filter", "Any other exception" );
}
return bExists;
}
static void KillDirEntry( const OUString& rMainUrl )
{
try
{
::ucbhelper::Content aCnt( rMainUrl,
css::uno::Reference< css::ucb::XCommandEnvironment >(),
comphelper::getProcessComponentContext() );
aCnt.executeCommand( "delete",
css::uno::makeAny( sal_Bool( sal_True ) ) );
}
catch(const css::ucb::CommandAbortedException&)
{
SAL_WARN( "vcl.filter", "CommandAbortedException" );
}
catch( ... )
{
SAL_WARN( "vcl.filter", "Any other exception" );
}
}
#endif // !DISABLE_EXPORT
// Helper functions
sal_uInt8* ImplSearchEntry( sal_uInt8* pSource, sal_uInt8* pDest, sal_uLong nComp, sal_uLong nSize )
{
while ( nComp-- >= nSize )
{
sal_uLong i;
for ( i = 0; i < nSize; i++ )
{
if ( ( pSource[i]&~0x20 ) != ( pDest[i]&~0x20 ) )
break;
}
if ( i == nSize )
return pSource;
pSource++;
}
return NULL;
}
inline OUString ImpGetExtension( const OUString &rPath )
{
OUString aExt;
INetURLObject aURL( rPath );
aExt = aURL.GetFileExtension().toAsciiUpperCase();
return aExt;
}
bool isPCT(SvStream& rStream, sal_uLong nStreamPos, sal_uLong nStreamLen)
{
sal_uInt8 sBuf[3];
// store number format
sal_uInt16 oldNumberFormat = rStream.GetNumberFormatInt();
sal_uInt32 nOffset; // in MS documents the pict format is used without the first 512 bytes
for ( nOffset = 0; ( nOffset <= 512 ) && ( ( nStreamPos + nOffset + 14 ) <= nStreamLen ); nOffset += 512 )
{
short y1,x1,y2,x2;
bool bdBoxOk = true;
rStream.Seek( nStreamPos + nOffset);
// size of the pict in version 1 pict ( 2bytes) : ignored
rStream.SeekRel(2);
// bounding box (bytes 2 -> 9)
rStream.SetNumberFormatInt(NUMBERFORMAT_INT_BIGENDIAN);
rStream >> y1 >> x1 >> y2 >> x2;
rStream.SetNumberFormatInt(oldNumberFormat); // reset format
if (x1 > x2 || y1 > y2 || // bad bdbox
(x1 == x2 && y1 == y2) || // 1 pixel picture
x2-x1 > 2048 || y2-y1 > 2048 ) // picture anormaly big
bdBoxOk = false;
// read version op
rStream.Read( sBuf,3 );
// see http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Imaging_With_QuickDraw/Appendix_A.pdf
// normal version 2 - page A23 and A24
if ( sBuf[ 0 ] == 0x00 && sBuf[ 1 ] == 0x11 && sBuf[ 2 ] == 0x02)
return true;
// normal version 1 - page A25
else if (sBuf[ 0 ] == 0x11 && sBuf[ 1 ] == 0x01 && bdBoxOk)
return true;
}
return false;
}
/*************************************************************************
*
* ImpPeekGraphicFormat()
*
* Description:
* This function is two-fold:
* 1.) Start reading file, determine the file format:
* Input parameters:
* rPath - file path
* rFormatExtension - content matter
* bTest - set false
* Output parameters:
* Return value - true if success
* rFormatExtension - on success: normal file extension in capitals
* 2.) Start reading file, verify file format
* Input parameters:
* rPath - file path
* rFormatExtension - normal file extension in capitals
* bTest - set true
* Output parameters:
* Return value - false, if cannot verify the file type
* passed to the function
* true, when the format is PROBABLY verified or
* WHEN THE FORMAT IS NOT KNOWN!
*
*************************************************************************/
static bool ImpPeekGraphicFormat( SvStream& rStream, OUString& rFormatExtension, bool bTest )
{
sal_uInt16 i;
sal_uInt8 sFirstBytes[ 256 ];
sal_uLong nFirstLong,nSecondLong;
sal_uLong nStreamPos = rStream.Tell();
rStream.Seek( STREAM_SEEK_TO_END );
sal_uLong nStreamLen = rStream.Tell() - nStreamPos;
rStream.Seek( nStreamPos );
if ( !nStreamLen )
{
SvLockBytes* pLockBytes = rStream.GetLockBytes();
if ( pLockBytes )
pLockBytes->SetSynchronMode( true );
rStream.Seek( STREAM_SEEK_TO_END );
nStreamLen = rStream.Tell() - nStreamPos;
rStream.Seek( nStreamPos );
}
if (!nStreamLen)
{
return false; // this prevents at least a STL assertion
}
else if (nStreamLen >= 256)
{ // load first 256 bytes into a buffer
rStream.Read( sFirstBytes, 256 );
}
else
{
rStream.Read( sFirstBytes, nStreamLen );
for( i = (sal_uInt16) nStreamLen; i < 256; i++ )
sFirstBytes[ i ]=0;
}
if( rStream.GetError() )
return false;
// Accommodate the first 8 bytes in nFirstLong, nSecondLong
// Big-Endian:
for( i = 0, nFirstLong = 0L, nSecondLong = 0L; i < 4; i++ )
{
nFirstLong=(nFirstLong<<8)|(sal_uLong)sFirstBytes[i];
nSecondLong=(nSecondLong<<8)|(sal_uLong)sFirstBytes[i+4];
}
// The following variable is used when bTest == true. It remains sal_False
// if the format (rFormatExtension) has not yet been set.
bool bSomethingTested = false;
// Now the different formats are checked. The order *does* matter. e.g. a MET file
// could also go through the BMP test, however, a BMP file can hardly go through the MET test.
// So MET should be tested prior to BMP. However, theoretically a BMP file could conceivably
// go through the MET test. These problems are of course not only in MET and BMP.
// Therefore, in the case of a format check (bTest == true) we only test *exactly* this
// format. Everything else could have fatal consequences, for example if the user says it is
// a BMP file (and it is a BMP) file, and the file would go through the MET test ...
//--------------------------- MET ------------------------------------
if( !bTest || rFormatExtension.startsWith( "MET" ) )
{
bSomethingTested=true;
if( sFirstBytes[2] == 0xd3 )
{
rStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
rStream.Seek( nStreamPos );
sal_uInt16 nFieldSize;
sal_uInt8 nMagic;
bool bOK=true;
rStream >> nFieldSize >> nMagic;
for (i=0; i<3; i++) {
if (nFieldSize<6) { bOK=false; break; }
if (nStreamLen < rStream.Tell() + nFieldSize ) { bOK=false; break; }
rStream.SeekRel(nFieldSize-3);
rStream >> nFieldSize >> nMagic;
if (nMagic!=0xd3) { bOK=false; break; }
}
rStream.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
if (bOK && !rStream.GetError()) {
rFormatExtension = "MET";
return true;
}
}
}
//--------------------------- BMP ------------------------------------
if( !bTest || rFormatExtension.startsWith( "BMP" ) )
{
sal_uInt8 nOffs;
bSomethingTested=true;
// We're possibly also able to read an OS/2 bitmap array
// ('BA'), therefore we must adjust the offset to discover the
// first bitmap in the array
if ( sFirstBytes[0] == 0x42 && sFirstBytes[1] == 0x41 )
nOffs = 14;
else
nOffs = 0;
// Now we initially test on 'BM'
if ( sFirstBytes[0+nOffs]==0x42 && sFirstBytes[1+nOffs]==0x4d )
{
// OS/2 can set the Reserved flags to a value other than 0
// (which they really should not do...);
// In this case we test the size of the BmpInfoHeaders
if ( ( sFirstBytes[6+nOffs]==0x00 &&
sFirstBytes[7+nOffs]==0x00 &&
sFirstBytes[8+nOffs]==0x00 &&
sFirstBytes[9+nOffs]==0x00 ) ||
sFirstBytes[14+nOffs] == 0x28 ||
sFirstBytes[14+nOffs] == 0x0c )
{
rFormatExtension = "BMP";
return true;
}
}
}
//--------------------------- WMF/EMF ------------------------------------
if( !bTest ||
rFormatExtension.startsWith( "WMF" ) ||
rFormatExtension.startsWith( "EMF" ) )
{
bSomethingTested = true;
if ( nFirstLong==0xd7cdc69a || nFirstLong==0x01000900 )
{
rFormatExtension = "WMF";
return true;
}
else if( nFirstLong == 0x01000000 && sFirstBytes[ 40 ] == 0x20 && sFirstBytes[ 41 ] == 0x45 &&
sFirstBytes[ 42 ] == 0x4d && sFirstBytes[ 43 ] == 0x46 )
{
rFormatExtension = "EMF";
return true;
}
}
//--------------------------- PCX ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCX" ) )
{
bSomethingTested=true;
if (sFirstBytes[0]==0x0a)
{
sal_uInt8 nVersion=sFirstBytes[1];
sal_uInt8 nEncoding=sFirstBytes[2];
if( ( nVersion==0 || nVersion==2 || nVersion==3 || nVersion==5 ) && nEncoding<=1 )
{
rFormatExtension = "PCX";
return true;
}
}
}
//--------------------------- TIF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "TIF" ) )
{
bSomethingTested=true;
if ( nFirstLong==0x49492a00 || nFirstLong==0x4d4d002a )
{
rFormatExtension = "TIF";
return true;
}
}
//--------------------------- GIF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "GIF" ) )
{
bSomethingTested=true;
if ( nFirstLong==0x47494638 && (sFirstBytes[4]==0x37 || sFirstBytes[4]==0x39) && sFirstBytes[5]==0x61 )
{
rFormatExtension = "GIF";
return true;
}
}
//--------------------------- PNG ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PNG" ) )
{
bSomethingTested=true;
if (nFirstLong==0x89504e47 && nSecondLong==0x0d0a1a0a)
{
rFormatExtension = "PNG";
return true;
}
}
//--------------------------- JPG ------------------------------------
if( !bTest || rFormatExtension.startsWith( "JPG" ) )
{
bSomethingTested=true;
if ( ( nFirstLong==0xffd8ffe0 && sFirstBytes[6]==0x4a && sFirstBytes[7]==0x46 && sFirstBytes[8]==0x49 && sFirstBytes[9]==0x46 ) ||
( nFirstLong==0xffd8fffe ) || ( 0xffd8ff00 == ( nFirstLong & 0xffffff00 ) ) )
{
rFormatExtension = "JPG";
return true;
}
}
//--------------------------- SVM ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SVM" ) )
{
bSomethingTested=true;
if( nFirstLong==0x53564744 && sFirstBytes[4]==0x49 )
{
rFormatExtension = "SVM";
return true;
}
else if( sFirstBytes[0]==0x56 && sFirstBytes[1]==0x43 && sFirstBytes[2]==0x4C &&
sFirstBytes[3]==0x4D && sFirstBytes[4]==0x54 && sFirstBytes[5]==0x46 )
{
rFormatExtension = "SVM";
return true;
}
}
//--------------------------- PCD ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCD" ) )
{
bSomethingTested = true;
if( nStreamLen >= 2055 )
{
char sBuf[8];
rStream.Seek( nStreamPos + 2048 );
rStream.Read( sBuf, 7 );
if( strncmp( sBuf, "PCD_IPI", 7 ) == 0 )
{
rFormatExtension = "PCD";
return true;
}
}
}
//--------------------------- PSD ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PSD" ) )
{
bSomethingTested = true;
if ( ( nFirstLong == 0x38425053 ) && ( (nSecondLong >> 16 ) == 1 ) )
{
rFormatExtension = "PSD";
return true;
}
}
//--------------------------- EPS ------------------------------------
if( !bTest || rFormatExtension.startsWith( "EPS" ) )
{
bSomethingTested = true;
if ( ( nFirstLong == 0xC5D0D3C6 ) || ( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"%!PS-Adobe", 10, 10 ) &&
ImplSearchEntry( &sFirstBytes[15], (sal_uInt8*)"EPS", 3, 3 ) ) )
{
rFormatExtension = "EPS";
return true;
}
}
//--------------------------- DXF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "DXF" ) )
{
// Binary DXF File Format
if( strncmp( (const char*) sFirstBytes, "AutoCAD Binary DXF", 18 ) == 0 )
{
rFormatExtension = "DXF";
return true;
}
// ASCII DXF File Format
i=0;
while (i<256 && sFirstBytes[i]<=32)
++i;
if (i<256 && sFirstBytes[i]=='0')
{
++i;
// only now do we have sufficient data to make a judgement
// based on a '0' + 'SECTION' == DXF argument
bSomethingTested=true;
while( i<256 && sFirstBytes[i]<=32 )
++i;
if (i+7<256 && (strncmp((const char*)(sFirstBytes+i),"SECTION",7)==0))
{
rFormatExtension = "DXF";
return true;
}
}
}
//--------------------------- PCT ------------------------------------
if( !bTest || rFormatExtension.startsWith( "PCT" ) )
{
bSomethingTested = true;
if (isPCT(rStream, nStreamPos, nStreamLen))
{
rFormatExtension = "PCT";
return true;
}
}
//------------------------- PBM + PGM + PPM ---------------------------
if( !bTest ||
rFormatExtension.startsWith( "PBM" ) ||
rFormatExtension.startsWith( "PGM" ) ||
rFormatExtension.startsWith( "PPM" ) )
{
bSomethingTested=true;
if ( sFirstBytes[ 0 ] == 'P' )
{
switch( sFirstBytes[ 1 ] )
{
case '1' :
case '4' :
rFormatExtension = "PBM";
return true;
case '2' :
case '5' :
rFormatExtension = "PGM";
return true;
case '3' :
case '6' :
rFormatExtension = "PPM";
return true;
}
}
}
//--------------------------- RAS( SUN RasterFile )------------------
if( !bTest || rFormatExtension.startsWith( "RAS" ) )
{
bSomethingTested=true;
if( nFirstLong == 0x59a66a95 )
{
rFormatExtension = "RAS";
return true;
}
}
//--------------------------- XPM ------------------------------------
if( !bTest )
{
bSomethingTested = true;
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"/* XPM */", 256, 9 ) )
{
rFormatExtension = "XPM";
return true;
}
}
else if( rFormatExtension.startsWith( "XPM" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- XBM ------------------------------------
if( !bTest )
{
sal_uLong nSize = ( nStreamLen > 2048 ) ? 2048 : nStreamLen;
sal_uInt8* pBuf = new sal_uInt8 [ nSize ];
rStream.Seek( nStreamPos );
rStream.Read( pBuf, nSize );
sal_uInt8* pPtr = ImplSearchEntry( pBuf, (sal_uInt8*)"#define", nSize, 7 );
if( pPtr )
{
if( ImplSearchEntry( pPtr, (sal_uInt8*)"_width", pBuf + nSize - pPtr, 6 ) )
{
rFormatExtension = "XBM";
delete[] pBuf;
return true;
}
}
delete[] pBuf;
}
else if( rFormatExtension.startsWith( "XBM" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- SVG ------------------------------------
if( !bTest )
{
// check for Xml
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<?xml", 256, 5 ) // is it xml
&& ImplSearchEntry( sFirstBytes, (sal_uInt8*)"version", 256, 7 )) // does it have a version (required for xml)
{
bool bIsSvg(false);
// check for DOCTYPE svg combination
if( ImplSearchEntry( sFirstBytes, (sal_uInt8*)"DOCTYPE", 256, 7 ) // 'DOCTYPE' is there
&& ImplSearchEntry( sFirstBytes, (sal_uInt8*)"svg", 256, 3 )) // 'svg' is there
{
bIsSvg = true;
}
// check for svg element in 1st 256 bytes
if(!bIsSvg && ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<svg", 256, 4 )) // '<svg'
{
bIsSvg = true;
}
if(!bIsSvg)
{
// it's a xml, look for '<svg' in full file. Should not happen too
// often since the tests above will handle most cases, but can happen
// with Svg files containing big comment headers or Svg as the host
// language
const sal_uLong nSize((nStreamLen > 2048) ? 2048 : nStreamLen);
sal_uInt8* pBuf = new sal_uInt8[nSize];
rStream.Seek(nStreamPos);
rStream.Read(pBuf, nSize);
if(ImplSearchEntry(pBuf, (sal_uInt8*)"<svg", nSize, 4)) // '<svg'
{
bIsSvg = true;
}
delete[] pBuf;
}
if(bIsSvg)
{
rFormatExtension = "SVG";
return true;
}
}
else
{
// #119176# SVG files which have no xml header at all have shown up,
// detect those, too
bool bIsSvg(false);
// check for svg element in 1st 256 bytes
if(ImplSearchEntry( sFirstBytes, (sal_uInt8*)"<svg", 256, 4 )) // '<svg'
{
bIsSvg = true;
}
if(!bIsSvg)
{
// look for '<svg' in full file. Should not happen too
// often since the tests above will handle most cases, but can happen
// with SVG files containing big comment headers or SVG as the host
// language
const sal_uLong nSize((nStreamLen > 2048) ? 2048 : nStreamLen);
sal_uInt8* pBuf = new sal_uInt8[nSize];
rStream.Seek(nStreamPos);
rStream.Read(pBuf, nSize);
if(ImplSearchEntry(pBuf, (sal_uInt8*)"<svg", nSize, 4)) // '<svg'
{
bIsSvg = true;
}
delete[] pBuf;
}
if(bIsSvg)
{
rFormatExtension = "SVG";
return true;
}
}
}
else if( rFormatExtension.startsWith( "SVG" ) )
{
bSomethingTested = true;
return true;
}
//--------------------------- TGA ------------------------------------
if( !bTest || rFormatExtension.startsWith( "TGA" ) )
{
bSomethingTested = true;
// just a simple test for the extension
if( rFormatExtension.startsWith( "TGA" ) )
return true;
}
//--------------------------- SGV ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SGV" ) )
{
bSomethingTested = true;
// just a simple test for the extension
if( rFormatExtension.startsWith( "SGV" ) )
return true;
}
//--------------------------- SGF ------------------------------------
if( !bTest || rFormatExtension.startsWith( "SGF" ) )
{
bSomethingTested=true;
if( sFirstBytes[ 0 ] == 'J' && sFirstBytes[ 1 ] == 'J' )
{
rFormatExtension = "SGF";
return true;
}
}
if(!bTest || rFormatExtension.startsWith( "MOV" ))
{
if ((sFirstBytes[ 4 ] == 'f' && sFirstBytes[ 5 ] == 't' && sFirstBytes[ 6 ] == 'y' &&
sFirstBytes[ 7 ] == 'p' && sFirstBytes[ 8 ] == 'q' && sFirstBytes[ 9 ] == 't') ||
(sFirstBytes[ 4 ] == 'm' && sFirstBytes[ 5 ] == 'o' && sFirstBytes[ 6 ] == 'o' &&
sFirstBytes[ 7 ] == 'v' && sFirstBytes[ 11 ] == 'l' && sFirstBytes[ 12 ] == 'm'))
{
bSomethingTested=true;
rFormatExtension = "MOV";
return true;
}
}
return bTest && !bSomethingTested;
}
//--------------------------------------------------------------------------
sal_uInt16 GraphicFilter::ImpTestOrFindFormat( const OUString& rPath, SvStream& rStream, sal_uInt16& rFormat )
{
// determine or check the filter/format by reading into it
if( rFormat == GRFILTER_FORMAT_DONTKNOW )
{
OUString aFormatExt;
if( ImpPeekGraphicFormat( rStream, aFormatExt, false ) )
{
rFormat = pConfig->GetImportFormatNumberForExtension( aFormatExt );
if( rFormat != GRFILTER_FORMAT_DONTKNOW )
return GRFILTER_OK;
}
// determine filter by file extension
if( !rPath.isEmpty() )
{
OUString aExt( ImpGetExtension( rPath ) );
rFormat = pConfig->GetImportFormatNumberForExtension( aExt );
if( rFormat != GRFILTER_FORMAT_DONTKNOW )
return GRFILTER_OK;
}
return GRFILTER_FORMATERROR;
}
else
{
OUString aTmpStr( pConfig->GetImportFormatExtension( rFormat ) );
aTmpStr = aTmpStr.toAsciiUpperCase();
if( !ImpPeekGraphicFormat( rStream, aTmpStr, true ) )
return GRFILTER_FORMATERROR;
if ( pConfig->GetImportFormatExtension( rFormat ).equalsIgnoreAsciiCase( "pcd" ) )
{
sal_Int32 nBase = 2; // default Base0
if ( pConfig->GetImportFilterType( rFormat ).equalsIgnoreAsciiCase( "pcd_Photo_CD_Base4" ) )
nBase = 1;
else if ( pConfig->GetImportFilterType( rFormat ).equalsIgnoreAsciiCase( "pcd_Photo_CD_Base16" ) )
nBase = 0;
OUString aFilterConfigPath( "Office.Common/Filter/Graphic/Import/PCD" );
FilterConfigItem aFilterConfigItem( aFilterConfigPath );
aFilterConfigItem.WriteInt32( "Resolution", nBase );
}
}
return GRFILTER_OK;
}
//--------------------------------------------------------------------------
#ifndef DISABLE_EXPORT
static Graphic ImpGetScaledGraphic( const Graphic& rGraphic, FilterConfigItem& rConfigItem )
{
Graphic aGraphic;
ResMgr* pResMgr = ResMgr::CreateResMgr( "svt", Application::GetSettings().GetUILanguageTag() );
sal_Int32 nLogicalWidth = rConfigItem.ReadInt32( "LogicalWidth", 0 );
sal_Int32 nLogicalHeight = rConfigItem.ReadInt32( "LogicalHeight", 0 );
if ( rGraphic.GetType() != GRAPHIC_NONE )
{
sal_Int32 nMode = rConfigItem.ReadInt32( "ExportMode", -1 );
if ( nMode == -1 ) // the property is not there, this is possible, if the graphic filter
{ // is called via UnoGraphicExporter and not from a graphic export Dialog
nMode = 0; // then we are defaulting this mode to 0
if ( nLogicalWidth || nLogicalHeight )
nMode = 2;
}
Size aOriginalSize;
Size aPrefSize( rGraphic.GetPrefSize() );
MapMode aPrefMapMode( rGraphic.GetPrefMapMode() );
if ( aPrefMapMode == MAP_PIXEL )
aOriginalSize = Application::GetDefaultDevice()->PixelToLogic( aPrefSize, MAP_100TH_MM );
else
aOriginalSize = Application::GetDefaultDevice()->LogicToLogic( aPrefSize, aPrefMapMode, MAP_100TH_MM );
if ( !nLogicalWidth )
nLogicalWidth = aOriginalSize.Width();
if ( !nLogicalHeight )
nLogicalHeight = aOriginalSize.Height();
if( rGraphic.GetType() == GRAPHIC_BITMAP )
{
// Resolution is set
if( nMode == 1 )
{
Bitmap aBitmap( rGraphic.GetBitmap() );
MapMode aMap( MAP_100TH_INCH );
sal_Int32 nDPI = rConfigItem.ReadInt32( "Resolution", 75 );
Fraction aFrac( 1, std::min( std::max( nDPI, sal_Int32( 75 ) ), sal_Int32( 600 ) ) );
aMap.SetScaleX( aFrac );
aMap.SetScaleY( aFrac );
Size aOldSize = aBitmap.GetSizePixel();
aGraphic = rGraphic;
aGraphic.SetPrefMapMode( aMap );
aGraphic.SetPrefSize( Size( aOldSize.Width() * 100,
aOldSize.Height() * 100 ) );
}
// Size is set
else if( nMode == 2 )
{
aGraphic = rGraphic;
aGraphic.SetPrefMapMode( MapMode( MAP_100TH_MM ) );
aGraphic.SetPrefSize( Size( nLogicalWidth, nLogicalHeight ) );
}
else
aGraphic = rGraphic;
sal_Int32 nColors = rConfigItem.ReadInt32( "Color", 0 ); // #92767#
if ( nColors ) // graphic conversion necessary ?
{
BitmapEx aBmpEx( aGraphic.GetBitmapEx() );
aBmpEx.Convert( (BmpConversion)nColors ); // the entries in the xml section have the same meaning as
aGraphic = aBmpEx; // they have in the BmpConversion enum, so it should be
} // allowed to cast them
}
else
{
if( ( nMode == 1 ) || ( nMode == 2 ) )
{
GDIMetaFile aMtf( rGraphic.GetGDIMetaFile() );
css::awt::Size aDefaultSize( 10000, 10000 );
Size aNewSize( OutputDevice::LogicToLogic( Size( nLogicalWidth, nLogicalHeight ), MAP_100TH_MM, aMtf.GetPrefMapMode() ) );
if( aNewSize.Width() && aNewSize.Height() )
{
const Size aPreferredSize( aMtf.GetPrefSize() );
aMtf.Scale( Fraction( aNewSize.Width(), aPreferredSize.Width() ),
Fraction( aNewSize.Height(), aPreferredSize.Height() ) );
}
aGraphic = Graphic( aMtf );
}
else
aGraphic = rGraphic;
}
}
else
aGraphic = rGraphic;
delete pResMgr;
return aGraphic;
}
#endif
static OUString ImpCreateFullFilterPath( const OUString& rPath, const OUString& rFilterName )
{
OUString aPathURL;
::osl::FileBase::getFileURLFromSystemPath( rPath, aPathURL );
aPathURL += "/";
OUString aSystemPath;
::osl::FileBase::getSystemPathFromFileURL( aPathURL, aSystemPath );
aSystemPath += rFilterName;
return OUString( aSystemPath );
}
class ImpFilterLibCache;
struct ImpFilterLibCacheEntry
{
ImpFilterLibCacheEntry* mpNext;
#ifndef DISABLE_DYNLOADING
osl::Module maLibrary;
#endif
OUString maFiltername;
PFilterCall mpfnImport;
PFilterDlgCall mpfnImportDlg;
ImpFilterLibCacheEntry( const OUString& rPathname, const OUString& rFiltername );
bool operator==( const OUString& rFiltername ) const { return maFiltername == rFiltername; }
PFilterCall GetImportFunction();
};
ImpFilterLibCacheEntry::ImpFilterLibCacheEntry( const OUString& rPathname, const OUString& rFiltername ) :
mpNext ( NULL ),
#ifndef DISABLE_DYNLOADING
maLibrary ( rPathname ),
#endif
maFiltername ( rFiltername ),
mpfnImport ( NULL ),
mpfnImportDlg ( NULL )
{
#ifdef DISABLE_DYNLOADING
(void) rPathname;
#endif
}
#ifdef DISABLE_DYNLOADING
extern "C" sal_Bool icdGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool idxGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool imeGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipbGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipdGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipsGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool iptGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool ipxGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool iraGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool itgGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool itiGraphicImport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
#endif
PFilterCall ImpFilterLibCacheEntry::GetImportFunction()
{
if( !mpfnImport )
{
#ifndef DISABLE_DYNLOADING
mpfnImport = (PFilterCall) maLibrary.getFunctionSymbol(OUString(IMPORT_FUNCTION_NAME));
#else
if( maFiltername.equalsAscii( "icd" ) )
mpfnImport = icdGraphicImport;
else if( maFiltername.equalsAscii( "idx" ) )
mpfnImport = idxGraphicImport;
else if( maFiltername.equalsAscii( "ime" ) )
mpfnImport = imeGraphicImport;
else if( maFiltername.equalsAscii( "ipb" ) )
mpfnImport = ipbGraphicImport;
else if( maFiltername.equalsAscii( "ipd" ) )
mpfnImport = ipdGraphicImport;
else if( maFiltername.equalsAscii( "ips" ) )
mpfnImport = ipsGraphicImport;
else if( maFiltername.equalsAscii( "ipt" ) )
mpfnImport = iptGraphicImport;
else if( maFiltername.equalsAscii( "ipx" ) )
mpfnImport = ipxGraphicImport;
else if( maFiltername.equalsAscii( "ira" ) )
mpfnImport = iraGraphicImport;
else if( maFiltername.equalsAscii( "itg" ) )
mpfnImport = itgGraphicImport;
else if( maFiltername.equalsAscii( "iti" ) )
mpfnImport = itiGraphicImport;
#endif
}
return mpfnImport;
}
class ImpFilterLibCache
{
ImpFilterLibCacheEntry* mpFirst;
ImpFilterLibCacheEntry* mpLast;
public:
ImpFilterLibCache();
~ImpFilterLibCache();
ImpFilterLibCacheEntry* GetFilter( const OUString& rFilterPath, const OUString& rFiltername );
};
ImpFilterLibCache::ImpFilterLibCache() :
mpFirst ( NULL ),
mpLast ( NULL )
{
}
ImpFilterLibCache::~ImpFilterLibCache()
{
ImpFilterLibCacheEntry* pEntry = mpFirst;
while( pEntry )
{
ImpFilterLibCacheEntry* pNext = pEntry->mpNext;
delete pEntry;
pEntry = pNext;
}
}
ImpFilterLibCacheEntry* ImpFilterLibCache::GetFilter( const OUString& rFilterPath, const OUString& rFilterName )
{
ImpFilterLibCacheEntry* pEntry = mpFirst;
while( pEntry )
{
if( *pEntry == rFilterName )
break;
else
pEntry = pEntry->mpNext;
}
if( !pEntry )
{
OUString aPhysicalName( ImpCreateFullFilterPath( rFilterPath, rFilterName ) );
pEntry = new ImpFilterLibCacheEntry( aPhysicalName, rFilterName );
#ifndef DISABLE_DYNLOADING
if ( pEntry->maLibrary.is() )
#endif
{
if( !mpFirst )
mpFirst = mpLast = pEntry;
else
mpLast = mpLast->mpNext = pEntry;
}
#ifndef DISABLE_DYNLOADING
else
{
delete pEntry;
pEntry = NULL;
}
#endif
}
return pEntry;
};
namespace { struct Cache : public rtl::Static<ImpFilterLibCache, Cache> {}; }
GraphicFilter::GraphicFilter( sal_Bool bConfig ) :
bUseConfig ( bConfig ),
nExpGraphHint ( 0 )
{
ImplInit();
}
GraphicFilter::~GraphicFilter()
{
{
::osl::MutexGuard aGuard( getListMutex() );
for(
FilterList_impl::iterator it = pFilterHdlList->begin();
it != pFilterHdlList->end();
++it
) {
if( *it == this )
{
pFilterHdlList->erase( it );
break;
}
}
if( pFilterHdlList->empty() )
{
delete pFilterHdlList, pFilterHdlList = NULL;
delete pConfig;
}
}
delete pErrorEx;
}
void GraphicFilter::ImplInit()
{
{
::osl::MutexGuard aGuard( getListMutex() );
if ( !pFilterHdlList )
{
pFilterHdlList = new FilterList_impl;
pConfig = new FilterConfigCache( bUseConfig );
}
else
pConfig = pFilterHdlList->front()->pConfig;
pFilterHdlList->push_back( this );
}
if( bUseConfig )
{
OUString url("$BRAND_BASE_DIR/" LIBO_LIB_FOLDER);
rtl::Bootstrap::expandMacros(url); //TODO: detect failure
utl::LocalFileHelper::ConvertURLToPhysicalName(url, aFilterPath);
}
pErrorEx = new FilterErrorEx;
bAbort = sal_False;
}
sal_uLong GraphicFilter::ImplSetError( sal_uLong nError, const SvStream* pStm )
{
pErrorEx->nFilterError = nError;
pErrorEx->nStreamError = pStm ? pStm->GetError() : ERRCODE_NONE;
return nError;
}
sal_uInt16 GraphicFilter::GetImportFormatCount()
{
return pConfig->GetImportFormatCount();
}
sal_uInt16 GraphicFilter::GetImportFormatNumber( const OUString& rFormatName )
{
return pConfig->GetImportFormatNumber( rFormatName );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForMediaType( const OUString& rMediaType )
{
return pConfig->GetImportFormatNumberForMediaType( rMediaType );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForShortName( const OUString& rShortName )
{
return pConfig->GetImportFormatNumberForShortName( rShortName );
}
sal_uInt16 GraphicFilter::GetImportFormatNumberForTypeName( const OUString& rType )
{
return pConfig->GetImportFormatNumberForTypeName( rType );
}
OUString GraphicFilter::GetImportFormatName( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatName( nFormat );
}
OUString GraphicFilter::GetImportFormatTypeName( sal_uInt16 nFormat )
{
return pConfig->GetImportFilterTypeName( nFormat );
}
OUString GraphicFilter::GetImportFormatMediaType( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatMediaType( nFormat );
}
OUString GraphicFilter::GetImportFormatShortName( sal_uInt16 nFormat )
{
return pConfig->GetImportFormatShortName( nFormat );
}
OUString GraphicFilter::GetImportOSFileType( sal_uInt16 )
{
OUString aOSFileType;
return aOSFileType;
}
OUString GraphicFilter::GetImportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry )
{
return pConfig->GetImportWildcard( nFormat, nEntry );
}
sal_Bool GraphicFilter::IsImportPixelFormat( sal_uInt16 nFormat )
{
return pConfig->IsImportPixelFormat( nFormat );
}
sal_uInt16 GraphicFilter::GetExportFormatCount()
{
return pConfig->GetExportFormatCount();
}
sal_uInt16 GraphicFilter::GetExportFormatNumber( const OUString& rFormatName )
{
return pConfig->GetExportFormatNumber( rFormatName );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForMediaType( const OUString& rMediaType )
{
return pConfig->GetExportFormatNumberForMediaType( rMediaType );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForShortName( const OUString& rShortName )
{
return pConfig->GetExportFormatNumberForShortName( rShortName );
}
OUString GraphicFilter::GetExportInternalFilterName( sal_uInt16 nFormat )
{
return pConfig->GetExportInternalFilterName( nFormat );
}
sal_uInt16 GraphicFilter::GetExportFormatNumberForTypeName( const OUString& rType )
{
return pConfig->GetExportFormatNumberForTypeName( rType );
}
OUString GraphicFilter::GetExportFormatName( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatName( nFormat );
}
OUString GraphicFilter::GetExportFormatTypeName( sal_uInt16 nFormat )
{
return pConfig->GetExportFilterTypeName( nFormat );
}
OUString GraphicFilter::GetExportFormatMediaType( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatMediaType( nFormat );
}
OUString GraphicFilter::GetExportFormatShortName( sal_uInt16 nFormat )
{
return pConfig->GetExportFormatShortName( nFormat );
}
OUString GraphicFilter::GetExportOSFileType( sal_uInt16 )
{
OUString aOSFileType;
return aOSFileType;
}
OUString GraphicFilter::GetExportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry )
{
return pConfig->GetExportWildcard( nFormat, nEntry );
}
sal_Bool GraphicFilter::IsExportPixelFormat( sal_uInt16 nFormat )
{
return pConfig->IsExportPixelFormat( nFormat );
}
sal_uInt16 GraphicFilter::CanImportGraphic( const INetURLObject& rPath,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat )
{
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::CanImportGraphic() : ProtType == INET_PROT_NOT_VALID" );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_READ | STREAM_SHARE_DENYNONE );
if ( pStream )
{
nRetValue = CanImportGraphic( aMainUrl, *pStream, nFormat, pDeterminedFormat );
delete pStream;
}
return nRetValue;
}
sal_uInt16 GraphicFilter::CanImportGraphic( const OUString& rMainUrl, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat )
{
sal_uLong nStreamPos = rIStream.Tell();
sal_uInt16 nRes = ImpTestOrFindFormat( rMainUrl, rIStream, nFormat );
rIStream.Seek(nStreamPos);
if( nRes==GRFILTER_OK && pDeterminedFormat!=NULL )
*pDeterminedFormat = nFormat;
return (sal_uInt16) ImplSetError( nRes, &rIStream );
}
//SJ: TODO, we need to create a GraphicImporter component
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const INetURLObject& rPath,
sal_uInt16 nFormat, sal_uInt16 * pDeterminedFormat, sal_uInt32 nImportFlags )
{
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::ImportGraphic() : ProtType == INET_PROT_NOT_VALID" );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_READ | STREAM_SHARE_DENYNONE );
if ( pStream )
{
nRetValue = ImportGraphic( rGraphic, aMainUrl, *pStream, nFormat, pDeterminedFormat, nImportFlags );
delete pStream;
}
return nRetValue;
}
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const OUString& rPath, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat, sal_uInt32 nImportFlags, WMF_EXTERNALHEADER *pExtHeader )
{
return ImportGraphic( rGraphic, rPath, rIStream, nFormat, pDeterminedFormat, nImportFlags, NULL, pExtHeader );
}
//-------------------------------------------------------------------------
sal_uInt16 GraphicFilter::ImportGraphic( Graphic& rGraphic, const OUString& rPath, SvStream& rIStream,
sal_uInt16 nFormat, sal_uInt16* pDeterminedFormat, sal_uInt32 nImportFlags,
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >* pFilterData,
WMF_EXTERNALHEADER *pExtHeader )
{
OUString aFilterName;
sal_uLong nStmBegin;
sal_uInt16 nStatus;
GraphicReader* pContext = rGraphic.GetContext();
GfxLinkType eLinkType = GFX_LINK_TYPE_NONE;
bool bDummyContext = ( pContext == (GraphicReader*) 1 );
const sal_Bool bLinkSet = rGraphic.IsLink();
FilterConfigItem* pFilterConfigItem = NULL;
Size aPreviewSizeHint( 0, 0 );
sal_Bool bAllowPartialStreamRead = sal_False;
sal_Bool bCreateNativeLink = sal_True;
ResetLastError();
if ( pFilterData )
{
sal_Int32 i;
for ( i = 0; i < pFilterData->getLength(); i++ )
{
if ( (*pFilterData)[ i ].Name == "PreviewSizeHint" )
{
awt::Size aSize;
if ( (*pFilterData)[ i ].Value >>= aSize )
{
aPreviewSizeHint = Size( aSize.Width, aSize.Height );
if ( aSize.Width || aSize.Height )
nImportFlags |= GRFILTER_I_FLAGS_FOR_PREVIEW;
else
nImportFlags &=~GRFILTER_I_FLAGS_FOR_PREVIEW;
}
}
else if ( (*pFilterData)[ i ].Name == "AllowPartialStreamRead" )
{
(*pFilterData)[ i ].Value >>= bAllowPartialStreamRead;
if ( bAllowPartialStreamRead )
nImportFlags |= GRFILTER_I_FLAGS_ALLOW_PARTIAL_STREAMREAD;
else
nImportFlags &=~GRFILTER_I_FLAGS_ALLOW_PARTIAL_STREAMREAD;
}
else if ( (*pFilterData)[ i ].Name == "CreateNativeLink" )
{
(*pFilterData)[ i ].Value >>= bCreateNativeLink;
}
}
}
if( !pContext || bDummyContext )
{
if( bDummyContext )
{
rGraphic.SetContext( NULL );
nStmBegin = 0;
}
else
nStmBegin = rIStream.Tell();
bAbort = sal_False;
nStatus = ImpTestOrFindFormat( rPath, rIStream, nFormat );
// if pending, return GRFILTER_OK in order to request more bytes
if( rIStream.GetError() == ERRCODE_IO_PENDING )
{
rGraphic.SetContext( (GraphicReader*) 1 );
rIStream.ResetError();
rIStream.Seek( nStmBegin );
return (sal_uInt16) ImplSetError( GRFILTER_OK );
}
rIStream.Seek( nStmBegin );
if( ( nStatus != GRFILTER_OK ) || rIStream.GetError() )
return (sal_uInt16) ImplSetError( ( nStatus != GRFILTER_OK ) ? nStatus : GRFILTER_OPENERROR, &rIStream );
if( pDeterminedFormat )
*pDeterminedFormat = nFormat;
aFilterName = pConfig->GetImportFilterName( nFormat );
}
else
{
if( pContext && !bDummyContext )
aFilterName = pContext->GetUpperFilterName();
nStmBegin = 0;
nStatus = GRFILTER_OK;
}
// read graphic
if ( pConfig->IsImportInternalFilter( nFormat ) )
{
if( aFilterName.equalsIgnoreAsciiCase( IMP_GIF ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportGIF( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
else
eLinkType = GFX_LINK_TYPE_NATIVE_GIF;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_PNG ) )
{
if ( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
vcl::PNGReader aPNGReader( rIStream );
// ignore animation for previews and set preview size
if( aPreviewSizeHint.Width() || aPreviewSizeHint.Height() )
{
// position the stream at the end of the image if requested
if( !bAllowPartialStreamRead )
aPNGReader.GetChunks();
}
else
{
// check if this PNG contains a GIF chunk!
const std::vector< vcl::PNGReader::ChunkData >& rChunkData = aPNGReader.GetChunks();
std::vector< vcl::PNGReader::ChunkData >::const_iterator aIter( rChunkData.begin() );
std::vector< vcl::PNGReader::ChunkData >::const_iterator aEnd ( rChunkData.end() );
while( aIter != aEnd )
{
// Microsoft Office is storing Animated GIFs in following chunk
if ( aIter->nType == PMGCHUNG_msOG )
{
sal_uInt32 nChunkSize = aIter->aData.size();
if ( nChunkSize > 11 )
{
const std::vector< sal_uInt8 >& rData = aIter->aData;
SvMemoryStream aIStrm( (void*)&rData[ 11 ], nChunkSize - 11, STREAM_READ );
ImportGIF( aIStrm, rGraphic );
eLinkType = GFX_LINK_TYPE_NATIVE_PNG;
break;
}
}
++aIter;
}
}
if ( eLinkType == GFX_LINK_TYPE_NONE )
{
BitmapEx aBmpEx( aPNGReader.Read( aPreviewSizeHint ) );
if ( aBmpEx.IsEmpty() )
nStatus = GRFILTER_FILTERERROR;
else
{
rGraphic = aBmpEx;
eLinkType = GFX_LINK_TYPE_NATIVE_PNG;
}
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_JPEG ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
// set LOGSIZE flag always, if not explicitly disabled
// (see #90508 and #106763)
if( 0 == ( nImportFlags & GRFILTER_I_FLAGS_DONT_SET_LOGSIZE_FOR_JPEG ) )
nImportFlags |= GRFILTER_I_FLAGS_SET_LOGSIZE_FOR_JPEG;
if( !ImportJPEG( rIStream, rGraphic, NULL, nImportFlags ) )
nStatus = GRFILTER_FILTERERROR;
else
eLinkType = GFX_LINK_TYPE_NATIVE_JPG;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_SVG ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
const sal_uInt32 nStmPos(rIStream.Tell());
const sal_uInt32 nStmLen(rIStream.Seek(STREAM_SEEK_TO_END) - nStmPos);
bool bOkay(false);
if(nStmLen)
{
SvgDataArray aNewData(new sal_uInt8[nStmLen]);
rIStream.Seek(nStmPos);
rIStream.Read(aNewData.get(), nStmLen);
if(!rIStream.GetError())
{
SvgDataPtr aSvgDataPtr(
new SvgData(
aNewData,
nStmLen,
rPath));
rGraphic = Graphic(aSvgDataPtr);
bOkay = true;
}
}
if(bOkay)
{
eLinkType = GFX_LINK_TYPE_NATIVE_SVG;
}
else
{
nStatus = GRFILTER_FILTERERROR;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_XBM ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportXBM( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_XPM ) )
{
if( rGraphic.GetContext() == (GraphicReader*) 1 )
rGraphic.SetContext( NULL );
if( !ImportXPM( rIStream, rGraphic ) )
nStatus = GRFILTER_FILTERERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_BMP ) ||
aFilterName.equalsIgnoreAsciiCase( IMP_SVMETAFILE ) )
{
// SV internal filters for import bitmaps and MetaFiles
rIStream >> rGraphic;
if( rIStream.GetError() )
nStatus = GRFILTER_FORMATERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_MOV ) )
{
rIStream >> rGraphic;
if( rIStream.GetError() )
nStatus = GRFILTER_FORMATERROR;
else
{
rGraphic.SetDefaultType();
rIStream.Seek( STREAM_SEEK_TO_END );
eLinkType = GFX_LINK_TYPE_NATIVE_MOV;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_WMF ) ||
aFilterName.equalsIgnoreAsciiCase( IMP_EMF ) )
{
GDIMetaFile aMtf;
if( !ConvertWMFToGDIMetaFile( rIStream, aMtf, NULL, pExtHeader ) )
nStatus = GRFILTER_FORMATERROR;
else
{
rGraphic = aMtf;
eLinkType = GFX_LINK_TYPE_NATIVE_WMF;
}
}
else if( aFilterName.equalsIgnoreAsciiCase( IMP_SVSGF )
|| aFilterName.equalsIgnoreAsciiCase( IMP_SVSGV ) )
{
sal_uInt16 nVersion;
unsigned char nTyp = CheckSgfTyp( rIStream, nVersion );
switch( nTyp )
{
case SGF_BITIMAGE:
{
SvMemoryStream aTempStream;
if( aTempStream.GetError() )
return GRFILTER_OPENERROR;
if( !SgfBMapFilter( rIStream, aTempStream ) )
nStatus = GRFILTER_FILTERERROR;
else
{
aTempStream.Seek( 0L );
aTempStream >> rGraphic;
if( aTempStream.GetError() )
nStatus = GRFILTER_FILTERERROR;
}
}
break;
case SGF_SIMPVECT:
{
GDIMetaFile aMtf;
if( !SgfVectFilter( rIStream, aMtf ) )
nStatus = GRFILTER_FILTERERROR;
else
rGraphic = Graphic( aMtf );
}
break;
case SGF_STARDRAW:
{
if( nVersion != SGV_VERSION )
nStatus = GRFILTER_VERSIONERROR;
else
{
GDIMetaFile aMtf;
if( !SgfSDrwFilter( rIStream, aMtf,
INetURLObject(aFilterPath) ) )
{
nStatus = GRFILTER_FILTERERROR;
}
else
rGraphic = Graphic( aMtf );
}
}
break;
default:
{
nStatus = GRFILTER_FORMATERROR;
}
break;
}
}
else
nStatus = GRFILTER_FILTERERROR;
}
else
{
ImpFilterLibCacheEntry* pFilter = NULL;
// find first filter in filter paths
sal_Int32 i, nTokenCount = getTokenCount(aFilterPath, ';');
ImpFilterLibCache &rCache = Cache::get();
for( i = 0; ( i < nTokenCount ) && ( pFilter == NULL ); i++ )
pFilter = rCache.GetFilter( getToken(aFilterPath, i, ';'), aFilterName );
if( !pFilter )
nStatus = GRFILTER_FILTERERROR;
else
{
PFilterCall pFunc = pFilter->GetImportFunction();
if( !pFunc )
nStatus = GRFILTER_FILTERERROR;
else
{
OUString aShortName;
if( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
aShortName = GetImportFormatShortName( nFormat ).toAsciiUpperCase();
if ( ( pFilterConfigItem == NULL ) && aShortName == "PCD" )
{
OUString aFilterConfigPath( "Office.Common/Filter/Graphic/Import/PCD" );
pFilterConfigItem = new FilterConfigItem( aFilterConfigPath );
}
}
if( !(*pFunc)( rIStream, rGraphic, pFilterConfigItem, sal_False ) )
nStatus = GRFILTER_FORMATERROR;
else
{
// try to set link type if format matches
if( nFormat != GRFILTER_FORMAT_DONTKNOW )
{
if( aShortName.startsWith( TIF_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_TIF;
else if( aShortName.startsWith( MET_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_MET;
else if( aShortName.startsWith( PCT_SHORTNAME ) )
eLinkType = GFX_LINK_TYPE_NATIVE_PCT;
}
}
}
}
}
if( nStatus == GRFILTER_OK && bCreateNativeLink && ( eLinkType != GFX_LINK_TYPE_NONE ) && !rGraphic.GetContext() && !bLinkSet )
{
const sal_uLong nStmEnd = rIStream.Tell();
const sal_uLong nBufSize = nStmEnd - nStmBegin;
if( nBufSize )
{
sal_uInt8* pBuf=0;
try
{
pBuf = new sal_uInt8[ nBufSize ];
}
catch (const std::bad_alloc&)
{
nStatus = GRFILTER_TOOBIG;
}
if( nStatus == GRFILTER_OK )
{
rIStream.Seek( nStmBegin );
rIStream.Read( pBuf, nBufSize );
rGraphic.SetLink( GfxLink( pBuf, nBufSize, eLinkType, sal_True ) );
}
}
}
// Set error code or try to set native buffer
if( nStatus != GRFILTER_OK )
{
if( bAbort )
nStatus = GRFILTER_ABORT;
ImplSetError( nStatus, &rIStream );
rIStream.Seek( nStmBegin );
rGraphic.Clear();
}
delete pFilterConfigItem;
return nStatus;
}
sal_uInt16 GraphicFilter::ExportGraphic( const Graphic& rGraphic, const INetURLObject& rPath,
sal_uInt16 nFormat, const uno::Sequence< beans::PropertyValue >* pFilterData )
{
#ifdef DISABLE_EXPORT
(void) rGraphic;
(void) rPath;
(void) nFormat;
(void) pFilterData;
return GRFILTER_FORMATERROR;
#else
SAL_INFO( "vcl.filter", "GraphicFilter::ExportGraphic() (thb)" );
sal_uInt16 nRetValue = GRFILTER_FORMATERROR;
DBG_ASSERT( rPath.GetProtocol() != INET_PROT_NOT_VALID, "GraphicFilter::ExportGraphic() : ProtType == INET_PROT_NOT_VALID" );
bool bAlreadyExists = DirEntryExists( rPath );
OUString aMainUrl( rPath.GetMainURL( INetURLObject::NO_DECODE ) );
SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( aMainUrl, STREAM_WRITE | STREAM_TRUNC );
if ( pStream )
{
nRetValue = ExportGraphic( rGraphic, aMainUrl, *pStream, nFormat, pFilterData );
delete pStream;
if( ( GRFILTER_OK != nRetValue ) && !bAlreadyExists )
KillDirEntry( aMainUrl );
}
return nRetValue;
#endif
}
#ifdef DISABLE_DYNLOADING
#ifndef DISABLE_EXPORT
extern "C" sal_Bool egiGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool emeGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epbGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epgGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eppGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool epsGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eptGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool eraGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool etiGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
extern "C" sal_Bool expGraphicExport( SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pConfigItem, sal_Bool );
#endif
#endif
sal_uInt16 GraphicFilter::ExportGraphic( const Graphic& rGraphic, const OUString& rPath,
SvStream& rOStm, sal_uInt16 nFormat, const uno::Sequence< beans::PropertyValue >* pFilterData )
{
#ifdef DISABLE_EXPORT
(void) rGraphic;
(void) rPath;
(void) rOStm;
(void) nFormat;
(void) pFilterData;
return GRFILTER_FORMATERROR;
#else
SAL_INFO( "vcl.filter", "GraphicFilter::ExportGraphic() (thb)" );
sal_uInt16 nFormatCount = GetExportFormatCount();
ResetLastError();
nExpGraphHint = 0;
if( nFormat == GRFILTER_FORMAT_DONTKNOW )
{
INetURLObject aURL( rPath );
OUString aExt( aURL.GetFileExtension().toAsciiUpperCase() );
for( sal_uInt16 i = 0; i < nFormatCount; i++ )
{
if ( pConfig->GetExportFormatExtension( i ).equalsIgnoreAsciiCase( aExt ) )
{
nFormat=i;
break;
}
}
}
if( nFormat >= nFormatCount )
return (sal_uInt16) ImplSetError( GRFILTER_FORMATERROR );
FilterConfigItem aConfigItem( (uno::Sequence< beans::PropertyValue >*)pFilterData );
OUString aFilterName( pConfig->GetExportFilterName( nFormat ) );
bAbort = sal_False;
sal_uInt16 nStatus = GRFILTER_OK;
GraphicType eType;
Graphic aGraphic( rGraphic );
aGraphic = ImpGetScaledGraphic( rGraphic, aConfigItem );
eType = aGraphic.GetType();
if( pConfig->IsExportPixelFormat( nFormat ) )
{
if( eType != GRAPHIC_BITMAP )
{
Size aSizePixel;
sal_uLong nColorCount,nBitsPerPixel,nNeededMem,nMaxMem;
VirtualDevice aVirDev;
nMaxMem = 1024;
nMaxMem *= 1024; // In Bytes
// Calculate how big the image would normally be:
aSizePixel=aVirDev.LogicToPixel(aGraphic.GetPrefSize(),aGraphic.GetPrefMapMode());
// Calculate how much memory the image will take up
nColorCount=aVirDev.GetColorCount();
if (nColorCount<=2) nBitsPerPixel=1;
else if (nColorCount<=4) nBitsPerPixel=2;
else if (nColorCount<=16) nBitsPerPixel=4;
else if (nColorCount<=256) nBitsPerPixel=8;
else if (nColorCount<=65536) nBitsPerPixel=16;
else nBitsPerPixel=24;
nNeededMem=((sal_uLong)aSizePixel.Width()*(sal_uLong)aSizePixel.Height()*nBitsPerPixel+7)/8;
// is the image larger than available memory?
if (nMaxMem<nNeededMem)
{
double fFak=sqrt(((double)nMaxMem)/((double)nNeededMem));
aSizePixel.Width()=(sal_uLong)(((double)aSizePixel.Width())*fFak);
aSizePixel.Height()=(sal_uLong)(((double)aSizePixel.Height())*fFak);
}
aVirDev.SetMapMode(MapMode(MAP_PIXEL));
aVirDev.SetOutputSizePixel(aSizePixel);
Graphic aGraphic2=aGraphic;
aGraphic2.Draw(&aVirDev,Point(0,0),aSizePixel); // this changes the MapMode
aVirDev.SetMapMode(MapMode(MAP_PIXEL));
aGraphic=Graphic(aVirDev.GetBitmap(Point(0,0),aSizePixel));
}
}
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
if( GRFILTER_OK == nStatus )
{
if ( pConfig->IsExportInternalFilter( nFormat ) )
{
if( aFilterName.equalsIgnoreAsciiCase( EXP_BMP ) )
{
Bitmap aBmp( aGraphic.GetBitmap() );
sal_Int32 nColorRes = aConfigItem.ReadInt32( "Colors", 0 );
if ( nColorRes && ( nColorRes <= (sal_uInt16)BMP_CONVERSION_24BIT) )
{
if( !aBmp.Convert( (BmpConversion) nColorRes ) )
aBmp = aGraphic.GetBitmap();
}
sal_Bool bRleCoding = aConfigItem.ReadBool( "RLE_Coding", sal_True );
// save RLE encoded?
WriteDIB(aBmp, rOStm, bRleCoding, true);
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_SVMETAFILE ) )
{
sal_Int32 nVersion = aConfigItem.ReadInt32( "Version", 0 ) ;
if ( nVersion )
rOStm.SetVersion( nVersion );
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
GDIMetaFile aMTF(aGraphic.GetGDIMetaFile());
aMTF.Write( rOStm );
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_WMF ) )
{
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
if ( !ConvertGDIMetaFileToWMF( aGraphic.GetGDIMetaFile(), rOStm, &aConfigItem ) )
nStatus = GRFILTER_FORMATERROR;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_EMF ) )
{
// #i119735# just use GetGDIMetaFile, it will create a bufferd version of contained bitmap now automatically
if ( !ConvertGDIMetaFileToEMF( aGraphic.GetGDIMetaFile(), rOStm, &aConfigItem ) )
nStatus = GRFILTER_FORMATERROR;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_JPEG ) )
{
bool bExportedGrayJPEG = false;
if( !ExportJPEG( rOStm, aGraphic, pFilterData, &bExportedGrayJPEG ) )
nStatus = GRFILTER_FORMATERROR;
nExpGraphHint = bExportedGrayJPEG ? GRFILTER_OUTHINT_GREY : 0;
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if ( aFilterName.equalsIgnoreAsciiCase( EXP_PNG ) )
{
vcl::PNGWriter aPNGWriter( aGraphic.GetBitmapEx(), pFilterData );
if ( pFilterData )
{
sal_Int32 k, j, i = 0;
for ( i = 0; i < pFilterData->getLength(); i++ )
{
if ( (*pFilterData)[ i ].Name == "AdditionalChunks" )
{
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > aAdditionalChunkSequence;
if ( (*pFilterData)[ i ].Value >>= aAdditionalChunkSequence )
{
for ( j = 0; j < aAdditionalChunkSequence.getLength(); j++ )
{
if ( aAdditionalChunkSequence[ j ].Name.getLength() == 4 )
{
sal_uInt32 nChunkType = 0;
for ( k = 0; k < 4; k++ )
{
nChunkType <<= 8;
nChunkType |= (sal_uInt8)aAdditionalChunkSequence[ j ].Name[ k ];
}
com::sun::star::uno::Sequence< sal_Int8 > aByteSeq;
if ( aAdditionalChunkSequence[ j ].Value >>= aByteSeq )
{
std::vector< vcl::PNGWriter::ChunkData >& rChunkData = aPNGWriter.GetChunks();
if ( !rChunkData.empty() )
{
sal_uInt32 nChunkLen = aByteSeq.getLength();
vcl::PNGWriter::ChunkData aChunkData;
aChunkData.nType = nChunkType;
if ( nChunkLen )
{
aChunkData.aData.resize( nChunkLen );
memcpy( &aChunkData.aData[ 0 ], aByteSeq.getConstArray(), nChunkLen );
}
std::vector< vcl::PNGWriter::ChunkData >::iterator aIter = rChunkData.end() - 1;
rChunkData.insert( aIter, aChunkData );
}
}
}
}
}
}
}
}
aPNGWriter.Write( rOStm );
if( rOStm.GetError() )
nStatus = GRFILTER_IOERROR;
}
else if( aFilterName.equalsIgnoreAsciiCase( EXP_SVG ) )
{
bool bDone(false);
// do we have a native SVG RenderGraphic, whose data can be written directly?
const SvgDataPtr aSvgDataPtr(rGraphic.getSvgData());
if(aSvgDataPtr.get() && aSvgDataPtr->getSvgDataArrayLength())
{
rOStm.Write(aSvgDataPtr->getSvgDataArray().get(), aSvgDataPtr->getSvgDataArrayLength());
if( rOStm.GetError() )
{
nStatus = GRFILTER_IOERROR;
}
else
{
bDone = true;
}
}
if( !bDone )
{
// do the normal GDIMetaFile export instead
try
{
css::uno::Reference< css::uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
css::uno::Reference< css::xml::sax::XDocumentHandler > xSaxWriter(
xml::sax::Writer::create( xContext ), uno::UNO_QUERY_THROW);
css::uno::Sequence< css::uno::Any > aArguments( 1 );
aArguments[ 0 ] <<= aConfigItem.GetFilterData();
css::uno::Reference< css::svg::XSVGWriter > xSVGWriter(
xContext->getServiceManager()->createInstanceWithArgumentsAndContext( "com.sun.star.svg.SVGWriter", aArguments, xContext),
css::uno::UNO_QUERY );
if( xSaxWriter.is() && xSVGWriter.is() )
{
css::uno::Reference< css::io::XActiveDataSource > xActiveDataSource(
xSaxWriter, css::uno::UNO_QUERY );
if( xActiveDataSource.is() )
{
const css::uno::Reference< css::uno::XInterface > xStmIf(
static_cast< ::cppu::OWeakObject* >( new ImpFilterOutputStream( rOStm ) ) );
SvMemoryStream aMemStm( 65535, 65535 );
// #i119735# just use GetGDIMetaFile, it will create a buffered version of contained bitmap now automatically
( (GDIMetaFile&) aGraphic.GetGDIMetaFile() ).Write( aMemStm );
xActiveDataSource->setOutputStream( css::uno::Reference< css::io::XOutputStream >(
xStmIf, css::uno::UNO_QUERY ) );
css::uno::Sequence< sal_Int8 > aMtfSeq( (sal_Int8*) aMemStm.GetData(), aMemStm.Tell() );
xSVGWriter->write( xSaxWriter, aMtfSeq );
}
}
}
catch(const css::uno::Exception&)
{
nStatus = GRFILTER_IOERROR;
}
}
}
else
nStatus = GRFILTER_FILTERERROR;
}
else
{
sal_Int32 i, nTokenCount = getTokenCount(aFilterPath, ';');
for ( i = 0; i < nTokenCount; i++ )
{
#ifndef DISABLE_DYNLOADING
OUString aPhysicalName( ImpCreateFullFilterPath( getToken(aFilterPath, i, ';'), aFilterName ) );
osl::Module aLibrary( aPhysicalName );
PFilterCall pFunc = (PFilterCall) aLibrary.getFunctionSymbol(OUString(EXPORT_FUNCTION_NAME));
// Execute dialog in DLL
#else
PFilterCall pFunc = NULL;
if( aFilterName.equalsAscii( "egi" ) )
pFunc = egiGraphicExport;
else if( aFilterName.equalsAscii( "eme" ) )
pFunc = emeGraphicExport;
else if( aFilterName.equalsAscii( "epb" ) )
pFunc = epbGraphicExport;
else if( aFilterName.equalsAscii( "epg" ) )
pFunc = epgGraphicExport;
else if( aFilterName.equalsAscii( "epp" ) )
pFunc = eppGraphicExport;
else if( aFilterName.equalsAscii( "eps" ) )
pFunc = epsGraphicExport;
else if( aFilterName.equalsAscii( "ept" ) )
pFunc = eptGraphicExport;
else if( aFilterName.equalsAscii( "era" ) )
pFunc = eraGraphicExport;
else if( aFilterName.equalsAscii( "eti" ) )
pFunc = etiGraphicExport;
else if( aFilterName.equalsAscii( "exp" ) )
pFunc = expGraphicExport;
#endif
if( pFunc )
{
if ( !(*pFunc)( rOStm, aGraphic, &aConfigItem, sal_False ) )
nStatus = GRFILTER_FORMATERROR;
break;
}
else
nStatus = GRFILTER_FILTERERROR;
}
}
}
if( nStatus != GRFILTER_OK )
{
if( bAbort )
nStatus = GRFILTER_ABORT;
ImplSetError( nStatus, &rOStm );
}
return nStatus;
#endif
}
const FilterErrorEx& GraphicFilter::GetLastError() const
{
return *pErrorEx;
}
void GraphicFilter::ResetLastError()
{
pErrorEx->nFilterError = pErrorEx->nStreamError = 0UL;
}
const Link GraphicFilter::GetFilterCallback() const
{
const Link aLink( LINK( this, GraphicFilter, FilterCallback ) );
return aLink;
}
IMPL_LINK( GraphicFilter, FilterCallback, ConvertData*, pData )
{
bool nRet = false;
if( pData )
{
sal_uInt16 nFormat = GRFILTER_FORMAT_DONTKNOW;
OString aShortName;
switch( pData->mnFormat )
{
case( CVT_BMP ): aShortName = BMP_SHORTNAME; break;
case( CVT_GIF ): aShortName = GIF_SHORTNAME; break;
case( CVT_JPG ): aShortName = JPG_SHORTNAME; break;
case( CVT_MET ): aShortName = MET_SHORTNAME; break;
case( CVT_PCT ): aShortName = PCT_SHORTNAME; break;
case( CVT_PNG ): aShortName = PNG_SHORTNAME; break;
case( CVT_SVM ): aShortName = SVM_SHORTNAME; break;
case( CVT_TIF ): aShortName = TIF_SHORTNAME; break;
case( CVT_WMF ): aShortName = WMF_SHORTNAME; break;
case( CVT_EMF ): aShortName = EMF_SHORTNAME; break;
case( CVT_SVG ): aShortName = SVG_SHORTNAME; break;
default:
break;
}
if( GRAPHIC_NONE == pData->maGraphic.GetType() || pData->maGraphic.GetContext() ) // Import
{
// Import
nFormat = GetImportFormatNumberForShortName( OStringToOUString( aShortName, RTL_TEXTENCODING_UTF8) );
nRet = ImportGraphic( pData->maGraphic, OUString(), pData->mrStm, nFormat ) == 0;
}
#ifndef DISABLE_EXPORT
else if( !aShortName.isEmpty() )
{
// Export
nFormat = GetExportFormatNumberForShortName( OStringToOUString(aShortName, RTL_TEXTENCODING_UTF8) );
nRet = ExportGraphic( pData->maGraphic, OUString(), pData->mrStm, nFormat ) == 0;
}
#endif
}
return long(nRet);
}
namespace
{
class StandardGraphicFilter
{
public:
StandardGraphicFilter()
{
m_aFilter.GetImportFormatCount();
}
GraphicFilter m_aFilter;
};
class theGraphicFilter : public rtl::Static<StandardGraphicFilter, theGraphicFilter> {};
}
GraphicFilter& GraphicFilter::GetGraphicFilter()
{
return theGraphicFilter::get().m_aFilter;
}
int GraphicFilter::LoadGraphic( const OUString &rPath, const OUString &rFilterName,
Graphic& rGraphic, GraphicFilter* pFilter,
sal_uInt16* pDeterminedFormat )
{
if ( !pFilter )
pFilter = &GetGraphicFilter();
const sal_uInt16 nFilter = !rFilterName.isEmpty() && pFilter->GetImportFormatCount()
? pFilter->GetImportFormatNumber( rFilterName )
: GRFILTER_FORMAT_DONTKNOW;
INetURLObject aURL( rPath );
if ( aURL.HasError() )
{
aURL.SetSmartProtocol( INET_PROT_FILE );
aURL.SetSmartURL( rPath );
}
SvStream* pStream = NULL;
if ( INET_PROT_FILE != aURL.GetProtocol() )
{
pStream = ::utl::UcbStreamHelper::CreateStream( rPath, STREAM_READ );
}
int nRes = GRFILTER_OK;
if ( !pStream )
nRes = pFilter->ImportGraphic( rGraphic, aURL, nFilter, pDeterminedFormat );
else
nRes = pFilter->ImportGraphic( rGraphic, rPath, *pStream, nFilter, pDeterminedFormat );
#ifdef DBG_UTIL
if( nRes )
DBG_WARNING2( "GrafikFehler [%d] - [%s]", nRes, rPath.getStr() );
#endif
return nRes;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/*
* 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.
*
* Written (W) 1999-2007 Soeren Sonnenburg
* Written (W) 1999-2007 Gunnar Raetsch
* Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "structure/DynProg.h"
#include "lib/Mathematics.h"
#include "lib/io.h"
#include "lib/config.h"
#include "features/StringFeatures.h"
#include "features/CharFeatures.h"
#include "features/Alphabet.h"
#include "structure/Plif.h"
#include "lib/Array.h"
#include "lib/Array2.h"
#include "lib/Array3.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#ifdef SUNOS
extern "C" int finite(double);
#endif
//#define USE_TMP_ARRAYCLASS
//#define DYNPROG_DEBUG
//CArray2<INT> g_orf_info(1,1) ;
static INT word_degree_default[4]={3,4,5,6} ;
static INT cum_num_words_default[5]={0,64,320,1344,5440} ;
static INT num_words_default[4]= {64,256,1024,4096} ;
static INT mod_words_default[32] = {1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0} ;
static bool sign_words_default[16] = {true,true,true,true,true,true,true,true,
false,false,false,false,false,false,false,false} ; // whether to use counts or signum of counts
static INT string_words_default[16] = {0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1} ; // which string should be used
CDynProg::CDynProg()
: CSGObject(),transition_matrix_a_id(1,1), transition_matrix_a(1,1),
transition_matrix_a_deriv(1,1), initial_state_distribution_p(1),
initial_state_distribution_p_deriv(1), end_state_distribution_q(1),
end_state_distribution_q_deriv(1), dict_weights(1,1),
dict_weights_array(dict_weights.get_array()),
// multi svm
num_degrees(4),
num_svms(8),
num_strings(1),
word_degree(word_degree_default, num_degrees, true, true),
cum_num_words(cum_num_words_default, num_degrees+1, true, true),
cum_num_words_array(cum_num_words.get_array()),
num_words(num_words_default, num_degrees, true, true),
num_words_array(num_words.get_array()),
mod_words(mod_words_default, num_svms, 2, true, true),
mod_words_array(mod_words.get_array()),
sign_words(sign_words_default, num_svms, true, true),
sign_words_array(sign_words.get_array()),
string_words(string_words_default, num_svms, true, true),
string_words_array(string_words.get_array()),
// word_used(num_degrees, num_words[num_degrees-1], num_strings),
// word_used_array(word_used.get_array()),
// svm_values_unnormalized(num_degrees, num_svms),
svm_pos_start(num_degrees),
num_unique_words(num_degrees),
svm_arrays_clean(true),
// single svm
num_svms_single(1),
word_degree_single(1),
num_words_single(4),
word_used_single(num_words_single),
svm_value_unnormalized_single(num_svms_single),
num_unique_words_single(0),
max_a_id(0), m_seq(1,1,1), m_pos(1), m_orf_info(1,2),
m_segment_sum_weights(1,1), m_plif_list(1),
m_PEN(1,1), m_PEN_state_signals(1,1),
m_genestr(1,1), m_dict_weights(1,1), m_segment_loss(1,1,2),
m_segment_ids_mask(1,1),
m_scores(1), m_states(1,1), m_positions(1,1)
{
trans_list_forward = NULL ;
trans_list_forward_cnt = NULL ;
trans_list_forward_val = NULL ;
trans_list_forward_id = NULL ;
trans_list_len = 0 ;
mem_initialized = true ;
this->N=1;
m_step=0 ;
#ifdef ARRAY_STATISTICS
word_degree.set_name("word_degree") ;
#endif
}
CDynProg::~CDynProg()
{
if (trans_list_forward_cnt)
delete[] trans_list_forward_cnt ;
if (trans_list_forward)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward[i])
delete[] trans_list_forward[i] ;
delete[] trans_list_forward ;
}
if (trans_list_forward_val)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward_val[i])
delete[] trans_list_forward_val[i] ;
delete[] trans_list_forward_val ;
}
if (trans_list_forward_id)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward_id[i])
delete[] trans_list_forward_id[i] ;
delete[] trans_list_forward_id ;
}
}
////////////////////////////////////////////////////////////////////////////////
void CDynProg::set_N(INT p_N)
{
N=p_N ;
transition_matrix_a_id.resize_array(N,N) ;
transition_matrix_a.resize_array(N,N) ;
transition_matrix_a_deriv.resize_array(N,N) ;
initial_state_distribution_p.resize_array(N) ;
initial_state_distribution_p_deriv.resize_array(N) ;
end_state_distribution_q.resize_array(N);
end_state_distribution_q_deriv.resize_array(N) ;
m_orf_info.resize_array(N,2) ;
m_PEN.resize_array(N,N) ;
m_PEN_state_signals.resize_array(N,1) ;
}
void CDynProg::set_p_vector(DREAL *p, INT p_N)
{
ASSERT(p_N==N) ;
//m_orf_info.resize_array(p_N,2) ;
//m_PEN.resize_array(p_N,p_N) ;
initial_state_distribution_p.set_array(p, p_N, true, true) ;
}
void CDynProg::set_q_vector(DREAL *q, INT q_N)
{
ASSERT(q_N==N) ;
end_state_distribution_q.set_array(q, q_N, true, true) ;
}
void CDynProg::set_a(DREAL *a, INT p_M, INT p_N)
{
ASSERT(p_N==N) ;
ASSERT(p_M==p_N) ;
transition_matrix_a.set_array(a, p_N, p_N, true, true) ;
transition_matrix_a_deriv.resize_array(p_N, p_N) ;
}
void CDynProg::set_a_id(INT *a, INT p_M, INT p_N)
{
ASSERT(p_N==N) ;
ASSERT(p_M==p_N) ;
transition_matrix_a_id.set_array(a, p_N, p_N, true, true) ;
max_a_id = 0 ;
for (INT i=0; i<p_N; i++)
for (INT j=0; j<p_N; j++)
max_a_id = CMath::max(max_a_id, transition_matrix_a_id.element(i,j)) ;
}
void CDynProg::set_a_trans_matrix(DREAL *a_trans, INT num_trans, INT p_N)
{
ASSERT((p_N==3) || (p_N==4)) ;
delete[] trans_list_forward ;
delete[] trans_list_forward_cnt ;
delete[] trans_list_forward_val ;
delete[] trans_list_forward_id ;
trans_list_forward = NULL ;
trans_list_forward_cnt = NULL ;
trans_list_forward_val = NULL ;
trans_list_len = 0 ;
transition_matrix_a.zero() ;
transition_matrix_a_id.zero() ;
mem_initialized = true ;
trans_list_forward_cnt=NULL ;
trans_list_len = N ;
trans_list_forward = new T_STATES*[N] ;
trans_list_forward_cnt = new T_STATES[N] ;
trans_list_forward_val = new DREAL*[N] ;
trans_list_forward_id = new INT*[N] ;
INT start_idx=0;
for (INT j=0; j<N; j++)
{
INT old_start_idx=start_idx;
while (start_idx<num_trans && a_trans[start_idx+num_trans]==j)
{
start_idx++;
if (start_idx>1 && start_idx<num_trans)
ASSERT(a_trans[start_idx+num_trans-1] <= a_trans[start_idx+num_trans]);
}
if (start_idx>1 && start_idx<num_trans)
ASSERT(a_trans[start_idx+num_trans-1] <= a_trans[start_idx+num_trans]);
INT len=start_idx-old_start_idx;
ASSERT(len>=0);
trans_list_forward_cnt[j] = 0 ;
if (len>0)
{
trans_list_forward[j] = new T_STATES[len] ;
trans_list_forward_val[j] = new DREAL[len] ;
trans_list_forward_id[j] = new INT[len] ;
}
else
{
trans_list_forward[j] = NULL;
trans_list_forward_val[j] = NULL;
trans_list_forward_id[j] = NULL;
}
}
for (INT i=0; i<num_trans; i++)
{
INT from_state = (INT)a_trans[i] ;
INT to_state = (INT)a_trans[i+num_trans] ;
DREAL val = a_trans[i+num_trans*2] ;
INT id = 0 ;
if (p_N==4)
id = (INT)a_trans[i+num_trans*3] ;
//SG_DEBUG( "id=%i\n", id) ;
ASSERT(to_state>=0 && to_state<N) ;
ASSERT(from_state>=0 && from_state<N) ;
trans_list_forward[to_state][trans_list_forward_cnt[to_state]]=from_state ;
trans_list_forward_val[to_state][trans_list_forward_cnt[to_state]]=val ;
trans_list_forward_id[to_state][trans_list_forward_cnt[to_state]]=id ;
trans_list_forward_cnt[to_state]++ ;
transition_matrix_a.element(from_state, to_state) = val ;
transition_matrix_a_id.element(from_state, to_state) = id ;
} ;
max_a_id = 0 ;
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
//if (transition_matrix_a_id.element(i,j))
//SG_DEBUG( "(%i,%i)=%i\n", i,j, transition_matrix_a_id.element(i,j)) ;
max_a_id = CMath::max(max_a_id, transition_matrix_a_id.element(i,j)) ;
}
//SG_DEBUG( "max_a_id=%i\n", max_a_id) ;
}
void CDynProg::init_svm_arrays(INT p_num_degrees, INT p_num_svms)
{
svm_arrays_clean=false ;
word_degree.resize_array(num_degrees) ;
cum_num_words.resize_array(num_degrees+1) ;
cum_num_words_array=cum_num_words.get_array() ;
num_words.resize_array(num_degrees) ;
num_words_array=num_words.get_array() ;
//svm_values_unnormalized.resize_array(num_degrees, num_svms) ;
svm_pos_start.resize_array(num_degrees) ;
num_unique_words.resize_array(num_degrees) ;
}
void CDynProg::init_word_degree_array(INT * p_word_degree_array, INT num_elem)
{
svm_arrays_clean=false ;
word_degree.resize_array(num_degrees) ;
ASSERT(num_degrees==num_elem) ;
for (INT i=0; i<num_degrees; i++)
word_degree[i]=p_word_degree_array[i] ;
}
void CDynProg::init_cum_num_words_array(INT * p_cum_num_words_array, INT num_elem)
{
svm_arrays_clean=false ;
cum_num_words.resize_array(num_degrees+1) ;
cum_num_words_array=cum_num_words.get_array() ;
ASSERT(num_degrees+1==num_elem) ;
for (INT i=0; i<num_degrees+1; i++)
cum_num_words[i]=p_cum_num_words_array[i] ;
}
void CDynProg::init_num_words_array(INT * p_num_words_array, INT num_elem)
{
svm_arrays_clean=false ;
num_words.resize_array(num_degrees) ;
num_words_array=num_words.get_array() ;
ASSERT(num_degrees==num_elem) ;
for (INT i=0; i<num_degrees; i++)
num_words[i]=p_num_words_array[i] ;
//word_used.resize_array(num_degrees, num_words[num_degrees-1], num_strings) ;
//word_used_array=word_used.get_array() ;
}
void CDynProg::init_mod_words_array(INT * p_mod_words_array, INT num_elem, INT num_columns)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
ASSERT(num_columns==2) ;
mod_words.set_array(p_mod_words_array, num_elem, 2, true, true) ;
mod_words_array = mod_words.get_array() ;
/*SG_DEBUG( "mod_words=[") ;
for (INT i=0; i<num_elem; i++)
SG_DEBUG( "%i, ", p_mod_words_array[i]) ;
SG_DEBUG( "]\n") ;*/
}
void CDynProg::init_sign_words_array(bool* p_sign_words_array, INT num_elem)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
sign_words.set_array(p_sign_words_array, num_elem, true, true) ;
sign_words_array = sign_words.get_array() ;
}
void CDynProg::init_string_words_array(INT* p_string_words_array, INT num_elem)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
string_words.set_array(p_string_words_array, num_elem, true, true) ;
string_words_array = string_words.get_array() ;
}
bool CDynProg::check_svm_arrays()
{
//SG_DEBUG( "wd_dim1=%d, cum_num_words=%d, num_words=%d, svm_pos_start=%d, num_uniq_w=%d, mod_words_dims=(%d,%d), sign_w=%d,string_w=%d\n num_degrees=%d, num_svms=%d, num_strings=%d", word_degree.get_dim1(), cum_num_words.get_dim1(), num_words.get_dim1(), svm_pos_start.get_dim1(), num_unique_words.get_dim1(), mod_words.get_dim1(), mod_words.get_dim2(), sign_words.get_dim1(), string_words.get_dim1(), num_degrees, num_svms, num_strings);
if ((word_degree.get_dim1()==num_degrees) &&
(cum_num_words.get_dim1()==num_degrees+1) &&
(num_words.get_dim1()==num_degrees) &&
//(word_used.get_dim1()==num_degrees) &&
//(word_used.get_dim2()==num_words[num_degrees-1]) &&
//(word_used.get_dim3()==num_strings) &&
// (svm_values_unnormalized.get_dim1()==num_degrees) &&
// (svm_values_unnormalized.get_dim2()==num_svms) &&
(svm_pos_start.get_dim1()==num_degrees) &&
(num_unique_words.get_dim1()==num_degrees) &&
(mod_words.get_dim1()==num_svms) &&
(mod_words.get_dim2()==2) &&
(sign_words.get_dim1()==num_svms) &&
(string_words.get_dim1()==num_svms))
{
svm_arrays_clean=true ;
return true ;
}
else
{
if ((num_unique_words.get_dim1()==num_degrees) &&
(mod_words.get_dim1()==num_svms) &&
(mod_words.get_dim2()==2) &&
(sign_words.get_dim1()==num_svms) &&
(string_words.get_dim1()==num_svms))
fprintf(stderr, "OK\n") ;
else
fprintf(stderr, "not OK\n") ;
if (!(word_degree.get_dim1()==num_degrees))
SG_WARNING("SVM array: word_degree.get_dim1()!=num_degrees") ;
if (!(cum_num_words.get_dim1()==num_degrees+1))
SG_WARNING("SVM array: cum_num_words.get_dim1()!=num_degrees+1") ;
if (!(num_words.get_dim1()==num_degrees))
SG_WARNING("SVM array: num_words.get_dim1()==num_degrees") ;
if (!(svm_pos_start.get_dim1()==num_degrees))
SG_WARNING("SVM array: svm_pos_start.get_dim1()!=num_degrees") ;
if (!(num_unique_words.get_dim1()==num_degrees))
SG_WARNING("SVM array: num_unique_words.get_dim1()!=num_degrees") ;
if (!(mod_words.get_dim1()==num_svms))
SG_WARNING("SVM array: mod_words.get_dim1()!=num_svms") ;
if (!(mod_words.get_dim2()==2))
SG_WARNING("SVM array: mod_words.get_dim2()!=2") ;
if (!(sign_words.get_dim1()==num_svms))
SG_WARNING("SVM array: sign_words.get_dim1()!=num_svms") ;
if (!(string_words.get_dim1()==num_svms))
SG_WARNING("SVM array: string_words.get_dim1()!=num_svms") ;
svm_arrays_clean=false ;
return false ;
}
}
void CDynProg::best_path_set_seq(DREAL *seq, INT p_N, INT seq_len)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
ASSERT(p_N==N) ;
ASSERT(initial_state_distribution_p.get_dim1()==N) ;
ASSERT(end_state_distribution_q.get_dim1()==N) ;
m_seq.set_array(seq, N, seq_len, 1, true, true) ;
this->N=N ;
m_call=3 ;
m_step=2 ;
}
void CDynProg::best_path_set_seq3d(DREAL *seq, INT p_N, INT seq_len, INT max_num_signals)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
ASSERT(p_N==N) ;
ASSERT(initial_state_distribution_p.get_dim1()==N) ;
ASSERT(end_state_distribution_q.get_dim1()==N) ;
m_seq.set_array(seq, N, seq_len, max_num_signals, true, true) ;
this->N=N ;
m_call=3 ;
m_step=2 ;
}
void CDynProg::best_path_set_pos(INT *pos, INT seq_len)
{
if (m_step!=2)
SG_ERROR( "please call best_path_set_seq first\n") ;
if (seq_len!=m_seq.get_dim2())
SG_ERROR( "pos size does not match previous info %i!=%i\n", seq_len, m_seq.get_dim2()) ;
m_pos.set_array(pos, seq_len, true, true) ;
m_step=3 ;
}
void CDynProg::best_path_set_orf_info(INT *orf_info, INT m, INT n)
{
if (m_step!=3)
SG_ERROR( "please call best_path_set_pos first\n") ;
if (m!=N)
SG_ERROR( "orf_info size does not match previous info %i!=%i\n", m, N) ;
if (n!=2)
SG_ERROR( "orf_info size incorrect %i!=2\n", n) ;
m_orf_info.set_array(orf_info, m, n, true, true) ;
m_call=1 ;
m_step=4 ;
}
void CDynProg::best_path_set_segment_sum_weights(DREAL *segment_sum_weights, INT num_states, INT seq_len)
{
if (m_step!=3)
SG_ERROR( "please call best_path_set_pos first\n") ;
if (num_states!=N)
SG_ERROR( "segment_sum_weights size does not match previous info %i!=%i\n", num_states, N) ;
if (seq_len!=m_pos.get_dim1())
SG_ERROR( "segment_sum_weights size incorrect %i!=%i\n", seq_len, m_pos.get_dim1()) ;
m_segment_sum_weights.set_array(segment_sum_weights, num_states, seq_len, true, true) ;
m_call=2 ;
m_step=4 ;
}
void CDynProg::best_path_set_plif_list(CDynamicArray<CPlifBase*>* plifs)
{
ASSERT(plifs);
CPlifBase** plif_list=plifs->get_array();
INT num_plif=plifs->get_num_elements();
if (m_step!=4)
SG_ERROR( "please call best_path_set_orf_info or best_path_segment_sum_weights first\n") ;
m_plif_list.set_array(plif_list, num_plif, true, true) ;
m_step=5 ;
}
void CDynProg::best_path_set_plif_id_matrix(INT *plif_id_matrix, INT m, INT n)
{
if (m_step!=5)
SG_ERROR( "please call best_path_set_plif_list first\n") ;
if ((m!=N) || (n!=N))
SG_ERROR( "plif_id_matrix size does not match previous info %i!=%i or %i!=%i\n", m, N, n, N) ;
CArray2<INT> id_matrix(plif_id_matrix, N, N, false, false) ;
#ifdef DYNPROG_DEBUG
id_matrix.set_name("id_matrix");
id_matrix.display_array();
#endif //DYNPROG_DEBUG
m_PEN.resize_array(N, N) ;
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
if (id_matrix.element(i,j)>=0)
m_PEN.element(i,j)=m_plif_list[id_matrix.element(i,j)] ;
else
m_PEN.element(i,j)=NULL ;
m_step=6 ;
}
void CDynProg::best_path_set_plif_state_signal_matrix(INT *plif_id_matrix, INT m, INT max_num_signals)
{
if (m_step!=6)
SG_ERROR( "please call best_path_set_plif_id_matrix first\n") ;
if (m!=N)
SG_ERROR( "plif_state_signal_matrix size does not match previous info %i!=%i\n", m, N) ;
if (m_seq.get_dim3() != max_num_signals)
SG_ERROR( "size(plif_state_signal_matrix,2) does not match with size(m_seq,3): %i!=%i\nSorry, Soeren... interface changed\n", m_seq.get_dim3(), max_num_signals) ;
CArray2<INT> id_matrix(plif_id_matrix, N, max_num_signals, false, false) ;
m_PEN_state_signals.resize_array(N, max_num_signals) ;
for (INT i=0; i<N; i++)
{
for (INT j=0; j<max_num_signals; j++)
{
if (id_matrix.element(i,j)>=0)
m_PEN_state_signals.element(i,j)=m_plif_list[id_matrix.element(i,j)] ;
else
m_PEN_state_signals.element(i,j)=NULL ;
}
}
m_step=6 ;
}
void CDynProg::best_path_set_genestr(CHAR* genestr, INT genestr_len, INT genestr_num)
{
if (m_step!=6)
SG_ERROR( "please call best_path_set_plif_id_matrix first\n") ;
ASSERT(genestr);
ASSERT(genestr_len>0);
ASSERT(genestr_num>0);
m_genestr.set_array(genestr, genestr_len, genestr_num, true, true) ;
m_step=7 ;
}
void CDynProg::best_path_set_my_state_seq(INT* my_state_seq, INT seq_len)
{
ASSERT(my_state_seq && seq_len>0);
m_my_state_seq.resize_array(seq_len);
for (INT i=0; i<seq_len; i++)
m_my_state_seq[i]=my_state_seq[i];
}
void CDynProg::best_path_set_my_pos_seq(INT* my_pos_seq, INT seq_len)
{
ASSERT(my_pos_seq && seq_len>0);
m_my_pos_seq.resize_array(seq_len);
for (INT i=0; i<seq_len; i++)
m_my_pos_seq[i]=my_pos_seq[i];
}
void CDynProg::best_path_set_dict_weights(DREAL* dictionary_weights, INT dict_len, INT n)
{
if (m_step!=7)
SG_ERROR( "please call best_path_set_genestr first\n") ;
if (num_svms!=n)
SG_ERROR( "dict_weights array does not match num_svms=%i!=%i\n", num_svms, n) ;
m_dict_weights.set_array(dictionary_weights, dict_len, num_svms, true, true) ;
// initialize, so it does not bother when not used
m_segment_loss.resize_array(max_a_id+1, max_a_id+1, 2) ;
m_segment_loss.zero() ;
m_segment_ids_mask.resize_array(2, m_seq.get_dim2()) ;
m_segment_ids_mask.zero() ;
m_step=8 ;
}
void CDynProg::best_path_set_segment_loss(DREAL* segment_loss, INT m, INT n)
{
// here we need two matrices. Store it in one: 2N x N
if (2*m!=n)
SG_ERROR( "segment_loss should be 2 x quadratic matrix: %i!=%i\n", m, 2*n) ;
if (m!=max_a_id+1)
SG_ERROR( "segment_loss size should match max_a_id: %i!=%i\n", m, max_a_id+1) ;
m_segment_loss.set_array(segment_loss, m, n/2, 2, true, true) ;
/*for (INT i=0; i<n; i++)
for (INT j=0; j<n; j++)
SG_DEBUG( "loss(%i,%i)=%f\n", i,j, m_segment_loss.element(0,i,j)) ;*/
}
void CDynProg::best_path_set_segment_ids_mask(INT* segment_ids_mask, INT m, INT n)
{
if (m!=2)// || n!=m_seq.get_dim2())
SG_ERROR( "segment_ids_mask should be a 2 x seq_len matrix: %i!=2 and %i!=%i\n", m, m_seq.get_dim2(), n) ;
m_segment_ids_mask.set_array(segment_ids_mask, m, n, true, true) ;
}
void CDynProg::best_path_call(INT nbest, bool use_orf)
{
if (m_step!=8)
SG_ERROR( "please call best_path_set_dict_weights first\n") ;
if (m_call!=1)
SG_ERROR( "please call best_path_set_orf_info first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_positions.resize_array(nbest, m_seq.get_dim2()) ;
m_call=1 ;
assert(nbest==1|nbest==2) ;
assert(m_genestr.get_dim2()==1) ;
if (nbest==1)
best_path_trans<1,false,false>(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_orf_info.get_array(), m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
use_orf) ;
else
best_path_trans<2,false,false>(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_orf_info.get_array(), m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
use_orf) ;
m_step=9 ;
}
void CDynProg::best_path_deriv_call()
{
//if (m_step!=8)
//SG_ERROR( "please call best_path_set_dict_weights first\n") ;
//if (m_call!=1)
//SG_ERROR( "please call best_path_set_orf_info first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_call=5 ; // or so ...
m_my_scores.resize_array(m_my_state_seq.get_array_size()) ;
m_my_losses.resize_array(m_my_state_seq.get_array_size()) ;
best_path_trans_deriv(m_my_state_seq.get_array(), m_my_pos_seq.get_array(),
m_my_scores.get_array(), m_my_losses.get_array(), m_my_state_seq.get_array_size(),
m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2()) ;
m_step=12 ;
}
void CDynProg::best_path_2struct_call(INT nbest)
{
if (m_step!=8)
SG_ERROR( "please call best_path_set_orf_dict_weights first\n") ;
if (m_call!=2)
SG_ERROR( "please call best_path_set_segment_sum_weights first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_positions.resize_array(nbest, m_seq.get_dim2()) ;
m_call=2 ;
best_path_2struct(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_PEN.get_array(),
m_genestr.get_array(), m_genestr.get_dim1(),
nbest,
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
m_segment_sum_weights.get_array()) ;
m_step=9 ;
}
void CDynProg::best_path_simple_call(INT nbest)
{
if (m_step!=2)
SG_ERROR( "please call best_path_set_seq first\n") ;
if (m_call!=3)
SG_ERROR( "please call best_path_set_seq first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_call=3 ;
best_path_trans_simple(m_seq.get_array(), m_seq.get_dim2(),
nbest,
m_scores.get_array(), m_states.get_array()) ;
m_step=9 ;
}
void CDynProg::best_path_deriv_call(INT nbest)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
//FIXME
}
void CDynProg::best_path_get_scores(DREAL **scores, INT *m)
{
if (m_step!=9 && m_step!=12)
SG_ERROR( "please call best_path*_call first\n") ;
if (m_step==9)
{
*scores=m_scores.get_array() ;
*m=m_scores.get_dim1() ;
} else
{
*scores=m_my_scores.get_array() ;
*m=m_my_scores.get_dim1() ;
}
m_step=10 ;
}
void CDynProg::best_path_get_states(INT **states, INT *m, INT *n)
{
if (m_step!=10)
SG_ERROR( "please call best_path_get_score first\n") ;
*states=m_states.get_array() ;
*m=m_states.get_dim1() ;
*n=m_states.get_dim2() ;
m_step=11 ;
}
void CDynProg::best_path_get_positions(INT **positions, INT *m, INT *n)
{
if (m_step!=11)
SG_ERROR( "please call best_path_get_positions first\n") ;
if (m_call==3)
SG_ERROR( "no position information for best_path_simple\n") ;
*positions=m_positions.get_array() ;
*m=m_positions.get_dim1() ;
*n=m_positions.get_dim2() ;
}
void CDynProg::best_path_get_losses(DREAL** losses, INT* seq_len)
{
ASSERT(losses && seq_len);
*losses=m_my_losses.get_array();
*seq_len=m_my_losses.get_dim1();
}
////////////////////////////////////////////////////////////////////////////////
DREAL CDynProg::best_path_no_b(INT max_iter, INT &best_iter, INT *my_path)
{
CArray2<T_STATES> psi(max_iter, N) ;
CArray<DREAL>* delta = new CArray<DREAL>(N) ;
CArray<DREAL>* delta_new = new CArray<DREAL>(N) ;
{ // initialization
for (INT i=0; i<N; i++)
{
delta->element(i) = get_p(i) ;
psi.element(0, i)= 0 ;
}
}
DREAL best_iter_prob = CMath::ALMOST_NEG_INFTY ;
best_iter = 0 ;
// recursion
for (INT t=1; t<max_iter; t++)
{
CArray<DREAL>* dummy;
INT NN=N ;
for (INT j=0; j<NN; j++)
{
DREAL maxj = delta->element(0) + transition_matrix_a.element(0,j);
INT argmax=0;
for (INT i=1; i<NN; i++)
{
DREAL temp = delta->element(i) + transition_matrix_a.element(i,j);
if (temp>maxj)
{
maxj=temp;
argmax=i;
}
}
delta_new->element(j)=maxj ;
psi.element(t, j)=argmax ;
}
dummy=delta;
delta=delta_new;
delta_new=dummy; //switch delta/delta_new
{ //termination
DREAL maxj=delta->element(0)+get_q(0);
INT argmax=0;
for (INT i=1; i<N; i++)
{
DREAL temp=delta->element(i)+get_q(i);
if (temp>maxj)
{
maxj=temp;
argmax=i;
}
}
//pat_prob=maxj;
if (maxj>best_iter_prob)
{
my_path[t]=argmax;
best_iter=t ;
best_iter_prob = maxj ;
} ;
} ;
}
{ //state sequence backtracking
for (INT t = best_iter; t>0; t--)
{
my_path[t-1]=psi.element(t, my_path[t]);
}
}
delete delta ;
delete delta_new ;
return best_iter_prob ;
}
void CDynProg::best_path_no_b_trans(INT max_iter, INT &max_best_iter, short int nbest, DREAL *prob_nbest, INT *my_paths)
{
//T_STATES *psi=new T_STATES[max_iter*N*nbest] ;
CArray3<T_STATES> psi(max_iter, N, nbest) ;
CArray3<short int> ktable(max_iter, N, nbest) ;
CArray2<short int> ktable_ends(max_iter, nbest) ;
CArray<DREAL> tempvv(nbest*N) ;
CArray<INT> tempii(nbest*N) ;
CArray2<T_STATES> path_ends(max_iter, nbest) ;
CArray2<DREAL> *delta=new CArray2<DREAL>(N, nbest) ;
CArray2<DREAL> *delta_new=new CArray2<DREAL>(N, nbest) ;
CArray2<DREAL> delta_end(max_iter, nbest) ;
CArray2<INT> paths(max_iter, nbest) ;
paths.set_array(my_paths, max_iter, nbest, false, false) ;
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta->element(i,0) = get_p(i) ;
for (short int k=1; k<nbest; k++)
{
delta->element(i,k)=-CMath::INFTY ;
ktable.element(0,i,k)=0 ;
}
}
}
// recursion
for (INT t=1; t<max_iter; t++)
{
CArray2<DREAL>* dummy=NULL;
for (T_STATES j=0; j<N; j++)
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT list_len=0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
tempvv.element(list_len) = -(delta->element(ii,diff) + elem_val[i]) ;
tempii.element(list_len) = diff*N + ii ;
list_len++ ;
}
}
CMath::qsort_index(tempvv.get_array(), tempii.get_array(), list_len) ;
for (short int k=0; k<nbest; k++)
{
if (k<list_len)
{
delta_new->element(j,k) = -tempvv[k] ;
psi.element(t,j,k) = (tempii[k]%N) ;
ktable.element(t,j,k) = (tempii[k]-(tempii[k]%N))/N ;
}
else
{
delta_new->element(j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
}
}
}
dummy=delta;
delta=delta_new;
delta_new=dummy; //switch delta/delta_new
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
tempvv.element(list_len) = -(delta->element(i,diff)+get_q(i));
tempii.element(list_len) = diff*N + i ;
list_len++ ;
}
}
CMath::qsort_index(tempvv.get_array(), tempii.get_array(), list_len) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(t-1,k) = -tempvv[k] ;
path_ends.element(t-1,k) = (tempii[k]%N) ;
ktable_ends.element(t-1,k) = (tempii[k]-(tempii[k]%N))/N ;
}
}
}
{ //state sequence backtracking
max_best_iter=0 ;
CArray<DREAL> sort_delta_end(max_iter*nbest) ;
CArray<short int> sort_k(max_iter*nbest) ;
CArray<INT> sort_t(max_iter*nbest) ;
CArray<INT> sort_idx(max_iter*nbest) ;
INT i=0 ;
for (INT iter=0; iter<max_iter-1; iter++)
for (short int k=0; k<nbest; k++)
{
sort_delta_end[i]=-delta_end.element(iter,k) ;
sort_k[i]=k ;
sort_t[i]=iter+1 ;
sort_idx[i]=i ;
i++ ;
}
CMath::qsort_index(sort_delta_end.get_array(), sort_idx.get_array(), (max_iter-1)*nbest) ;
for (short int n=0; n<nbest; n++)
{
short int k=sort_k[sort_idx[n]] ;
INT iter=sort_t[sort_idx[n]] ;
prob_nbest[n]=-sort_delta_end[n] ;
if (iter>max_best_iter)
max_best_iter=iter ;
ASSERT(k<nbest) ;
ASSERT(iter<max_iter) ;
paths.element(iter,n) = path_ends.element(iter-1, k) ;
short int q = ktable_ends.element(iter-1, k) ;
for (INT t = iter; t>0; t--)
{
paths.element(t-1,n)=psi.element(t, paths.element(t,n), q);
q = ktable.element(t, paths.element(t,n), q) ;
}
}
}
delete delta ;
delete delta_new ;
}
void CDynProg::translate_from_single_order(WORD* obs, INT sequence_length,
INT start, INT order,
INT max_val)
{
INT i,j;
WORD value=0;
for (i=sequence_length-1; i>= ((int) order)-1; i--) //convert interval of size T
{
value=0;
for (j=i; j>=i-((int) order)+1; j--)
value= (value >> max_val) | (obs[j] << (max_val * (order-1)));
obs[i]= (WORD) value;
}
for (i=order-2;i>=0;i--)
{
value=0;
for (j=i; j>=i-order+1; j--)
{
value= (value >> max_val);
if (j>=0)
value|=obs[j] << (max_val * (order-1));
}
obs[i]=value;
//ASSERT(value<num_words) ;
}
if (start>0)
for (i=start; i<sequence_length; i++)
obs[i-start]=obs[i];
}
void CDynProg::reset_svm_value(INT pos, INT & last_svm_pos, DREAL * svm_value)
{
for (int i=0; i<num_words_single; i++)
word_used_single[i]=false ;
for (INT s=0; s<num_svms; s++)
svm_value_unnormalized_single[s] = 0 ;
for (INT s=0; s<num_svms; s++)
svm_value[s] = 0 ;
last_svm_pos = pos - 6+1 ;
num_unique_words_single=0 ;
}
void CDynProg::extend_svm_value(WORD* wordstr, INT pos, INT &last_svm_pos, DREAL* svm_value)
{
bool did_something = false ;
for (int i=last_svm_pos-1; (i>=pos) && (i>=0); i--)
{
if (wordstr[i]>=num_words_single)
SG_DEBUG( "wordstr[%i]=%i\n", i, wordstr[i]) ;
if (!word_used_single[wordstr[i]])
{
for (INT s=0; s<num_svms_single; s++)
svm_value_unnormalized_single[s]+=dict_weights.element(wordstr[i],s) ;
word_used_single[wordstr[i]]=true ;
num_unique_words_single++ ;
did_something=true ;
}
} ;
if (num_unique_words_single>0)
{
last_svm_pos=pos ;
if (did_something)
for (INT s=0; s<num_svms; s++)
svm_value[s]= svm_value_unnormalized_single[s]/sqrt((double)num_unique_words_single) ; // full normalization
}
else
{
// what should I do?
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
}
void CDynProg::reset_segment_sum_value(INT num_states, INT pos, INT & last_segment_sum_pos, DREAL * segment_sum_value)
{
for (INT s=0; s<num_states; s++)
segment_sum_value[s] = 0 ;
last_segment_sum_pos = pos ;
//SG_DEBUG( "start: %i\n", pos) ;
}
void CDynProg::extend_segment_sum_value(DREAL *segment_sum_weights, INT seqlen, INT num_states,
INT pos, INT &last_segment_sum_pos, DREAL* segment_sum_value)
{
for (int i=last_segment_sum_pos-1; (i>=pos) && (i>=0); i--)
{
for (INT s=0; s<num_states; s++)
segment_sum_value[s] += segment_sum_weights[i*num_states+s] ;
} ;
//SG_DEBUG( "extend %i: %f\n", pos, segment_sum_value[0]) ;
last_segment_sum_pos = pos ;
}
void CDynProg::best_path_2struct(const DREAL *seq_array, INT seq_len, const INT *pos,
CPlifBase **Plif_matrix,
const char *genestr, INT genestr_len,
short int nbest,
DREAL *prob_nbest, INT *my_state_seq, INT *my_pos_seq,
DREAL *dictionary_weights, INT dict_len, DREAL *segment_sum_weights)
{
const INT default_look_back = 100 ;
INT max_look_back = default_look_back ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*num_words_single) ;
dict_weights.set_array(dictionary_weights, dict_len, num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false) ;
CArray2<DREAL> seq((DREAL *)seq_array, N, seq_len, false) ;
DREAL svm_value[num_svms] ;
DREAL segment_sum_value[N] ;
{ // initialize svm_svalue
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
{ // determine maximal length of look-back
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->get_max_value()>max_look_back)
max_look_back=(INT) CMath::ceil(penij->get_max_value());
if (penij->uses_svm_values())
use_svm=true ;
}
}
max_look_back = CMath::min(genestr_len, max_look_back) ;
//SG_DEBUG("use_svm=%i\n", use_svm) ;
//SG_DEBUG("max_look_back=%i\n", max_look_back) ;
const INT look_back_buflen = (max_look_back+1)*nbest*N ;
//SG_DEBUG("look_back_buflen=%i\n", look_back_buflen) ;
const DREAL mem_use = (DREAL)(seq_len*N*nbest*(sizeof(T_STATES)+sizeof(short int)+sizeof(INT))+
look_back_buflen*(2*sizeof(DREAL)+sizeof(INT))+
seq_len*(sizeof(T_STATES)+sizeof(INT))+
genestr_len*sizeof(bool))/(1024*1024)
;
bool is_big = (mem_use>200) || (seq_len>5000) ;
if (is_big)
{
SG_DEBUG("calling best_path_2struct: seq_len=%i, N=%i, lookback=%i nbest=%i\n",
seq_len, N, max_look_back, nbest) ;
SG_DEBUG("allocating %1.2fMB of memory\n",
mem_use) ;
}
ASSERT(nbest<32000) ;
CArray3<DREAL> delta(max_look_back+1, N, nbest) ;
CArray3<T_STATES> psi(seq_len,N,nbest) ;
CArray3<short int> ktable(seq_len,N,nbest) ;
CArray3<INT> ptable(seq_len,N,nbest) ;
CArray<DREAL> delta_end(nbest) ;
CArray<T_STATES> path_ends(nbest) ;
CArray<short int> ktable_end(nbest) ;
CArray<DREAL> tempvv(look_back_buflen) ;
CArray<INT> tempii(look_back_buflen) ;
CArray<T_STATES> state_seq(seq_len) ;
CArray<INT> pos_seq(seq_len) ;
// translate to words, if svm is used
WORD* wordstr=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[i]=0 ; break ;
case 'C':
case 'c': wordstr[i]=1 ; break ;
case 'G':
case 'g': wordstr[i]=2 ; break ;
case 'T':
case 't': wordstr[i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr, genestr_len, word_degree_single-1, word_degree_single) ;
}
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta.element(0,i,0) = get_p(i) + seq.element(i,0) ;
psi.element(0,i,0) = 0 ;
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
delta.element(0,i,k) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ;
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
// recursion
for (INT t=1; t<seq_len; t++)
{
if (is_big && t%(seq_len/10000)==1)
SG_PROGRESS(t, 0, seq_len);
//fprintf(stderr, "%i\n", t) ;
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(t%max_look_back,j,k) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT list_len=0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
//SG_DEBUG( "i=%i ii=%i num_elem=%i PEN=%ld\n", i, ii, num_elem, PEN(j,ii)) ;
const CPlifBase * penalty = PEN.element(j,ii) ;
INT look_back = default_look_back ;
if (penalty!=NULL)
look_back=(INT) (CMath::ceil(penalty->get_max_value()));
INT last_svm_pos ;
if (use_svm)
reset_svm_value(pos[t], last_svm_pos, svm_value) ;
INT last_segment_sum_pos ;
reset_segment_sum_value(N, pos[t], last_segment_sum_pos, segment_sum_value) ;
for (INT ts=t-1; ts>=0 && pos[t]-pos[ts]<=look_back; ts--)
{
if (use_svm)
extend_svm_value(wordstr, pos[ts], last_svm_pos, svm_value) ;
extend_segment_sum_value(segment_sum_weights, seq_len, N, pos[ts], last_segment_sum_pos, segment_sum_value) ;
DREAL pen_val = 0.0 ;
if (penalty)
pen_val=penalty->lookup_penalty(pos[t]-pos[ts], svm_value) + segment_sum_value[j] ;
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = delta.element(ts%max_look_back,ii,diff) + elem_val[i] ;
val += pen_val ;
tempvv[list_len] = -val ;
tempii[list_len] = ii + diff*N + ts*N*nbest;
//SG_DEBUG( "%i (%i,%i,%i, %i, %i) ", list_len, diff, ts, i, pos[t]-pos[ts], look_back) ;
list_len++ ;
}
}
}
CMath::nmin<INT>(tempvv.get_array(), tempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
if (k<list_len)
{
delta.element(t%max_look_back,j,k) = -tempvv[k] + seq.element(j,t);
psi.element(t,j,k) = (tempii[k]%N) ;
ktable.element(t,j,k) = (tempii[k]%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (tempii[k]-(tempii[k]%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(t%max_look_back,j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
tempvv[list_len] = -(delta.element((seq_len-1)%max_look_back,i,diff)+get_q(i)) ;
tempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(tempvv.get_array(), tempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -tempvv[k] ;
path_ends.element(k) = (tempii[k]%N) ;
ktable_end.element(k) = (tempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*(seq_len+1)] = state_seq[num_states-i-1] ;
my_pos_seq[i+k*(seq_len+1)] = pos_seq[num_states-i-1] ;
}
my_state_seq[num_states+k*(seq_len+1)]=-1 ;
my_pos_seq[num_states+k*(seq_len+1)]=-1 ;
}
}
if (is_big)
SG_PRINT( "DONE. \n") ;
}
/*void CDynProg::reset_svm_values(INT pos, INT * last_svm_pos, DREAL * svm_value)
{
for (INT j=0; j<num_degrees; j++)
{
for (INT i=0; i<num_words_array[j]; i++)
word_used.element(word_used_array, j, i, num_degrees)=false ;
for (INT s=0; s<num_svms; s++)
svm_values_unnormalized.element(j,s) = 0 ;
num_unique_words[j]=0 ;
last_svm_pos[j] = pos - word_degree[j]+1 ;
svm_pos_start[j] = pos - word_degree[j] ;
}
for (INT s=0; s<num_svms; s++)
svm_value[s] = 0 ;
}
void CDynProg::extend_svm_values(WORD** wordstr, INT pos, INT *last_svm_pos, DREAL* svm_value)
{
bool did_something = false ;
for (INT j=0; j<num_degrees; j++)
{
for (int i=last_svm_pos[j]-1; (i>=pos) && (i>=0); i--)
{
if (wordstr[j][i]>=num_words_array[j])
SG_DEBUG( "wordstr[%i]=%i\n", i, wordstr[j][i]) ;
ASSERT(wordstr[j][i]<num_words_array[j]) ;
if (!word_used.element(word_used_array, j, wordstr[j][i], num_degrees))
{
for (INT s=0; s<num_svms; s++)
svm_values_unnormalized.element(j,s)+=dict_weights_array[wordstr[j][i]+cum_num_words_array[j]+s*cum_num_words_array[num_degrees]] ;
//svm_values_unnormalized.element(j,s)+=dict_weights.element(wordstr[j][i]+cum_num_words_array[j],s) ;
//word_used.element(j,wordstr[j][i])=true ;
word_used.element(word_used_array, j, wordstr[j][i], num_degrees)=true ;
num_unique_words[j]++ ;
did_something=true ;
} ;
} ;
if (num_unique_words[j]>0)
last_svm_pos[j]=pos ;
} ;
if (did_something)
for (INT s=0; s<num_svms; s++)
{
svm_value[s]=0.0 ;
for (INT j=0; j<num_degrees; j++)
if (num_unique_words[j]>0)
svm_value[s]+= svm_values_unnormalized.element(j,s)/sqrt((double)num_unique_words[j]) ; // full normalization
}
}
*/
void CDynProg::init_segment_loss(struct segment_loss_struct & loss, INT seqlen, INT howmuchlookback)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (!loss.num_segment_id)
{
loss.segments_changed = new INT[seqlen] ;
loss.num_segment_id = new INT[(max_a_id+1)*seqlen] ;
loss.length_segment_id = new INT[(max_a_id+1)*seqlen] ;
}
for (INT j=0; j<CMath::min(howmuchlookback,seqlen); j++)
{
loss.segments_changed[j]=0 ;
for (INT i=0; i<max_a_id+1; i++)
{
loss.num_segment_id[i*seqlen+j] = 0;
loss.length_segment_id[i*seqlen+j] = 0;
}
}
loss.maxlookback = howmuchlookback ;
loss.seqlen = seqlen;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_init_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::clear_segment_loss(struct segment_loss_struct & loss)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (loss.num_segment_id != NULL)
{
delete[] loss.segments_changed ;
delete[] loss.num_segment_id ;
delete[] loss.length_segment_id ;
loss.segments_changed = NULL ;
loss.num_segment_id = NULL ;
loss.length_segment_id = NULL ;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_clean_time += MyTime.time_diff_sec() ;
#endif
}
DREAL CDynProg::extend_segment_loss(struct segment_loss_struct & loss, const INT * pos_array, INT segment_id, INT pos, INT & last_pos, DREAL &last_value)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (pos==last_pos)
return last_value ;
ASSERT(pos<last_pos) ;
last_pos-- ;
bool changed = false ;
while (last_pos>=pos)
{
if (loss.segments_changed[last_pos])
{
changed=true ;
break ;
}
last_pos-- ;
}
if (last_pos<pos)
last_pos = pos ;
if (!changed)
{
ASSERT(last_pos>=0) ;
ASSERT(last_pos<loss.seqlen) ;
DREAL length_contrib = (pos_array[last_pos]-pos_array[pos])*m_segment_loss.element(m_segment_ids_mask.element(0, pos), segment_id, 1) ;
DREAL ret = last_value + length_contrib ;
last_pos = pos ;
return ret ;
}
CArray2<INT> num_segment_id(loss.num_segment_id, loss.seqlen, max_a_id+1, false, false) ;
CArray2<INT> length_segment_id(loss.length_segment_id, loss.seqlen, max_a_id+1, false, false) ;
DREAL ret = 0.0 ;
for (INT i=0; i<max_a_id+1; i++)
{
//SG_DEBUG( "%i: %i, %i, %f (%f), %f (%f)\n", pos, num_segment_id.element(pos, i), length_segment_id.element(pos, i), num_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id,0), m_segment_loss.element(i, segment_id, 0), length_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 1), m_segment_loss.element(i, segment_id,1)) ;
if (num_segment_id.element(pos, i)!=0)
ret += num_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 0) ;
if (length_segment_id.element(pos, i)!=0)
ret += length_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 1) ;
}
last_pos = pos ;
last_value = ret ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_extend_time += MyTime.time_diff_sec() ;
#endif
return ret ;
}
void CDynProg::find_segment_loss_till_pos(const INT * pos, INT t_end, CArray2<INT>& segment_ids_mask, struct segment_loss_struct & loss)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
CArray2<INT> num_segment_id(loss.num_segment_id, loss.seqlen, max_a_id+1, false, false) ;
CArray2<INT> length_segment_id(loss.length_segment_id, loss.seqlen, max_a_id+1, false, false) ;
for (INT i=0; i<max_a_id+1; i++)
{
num_segment_id.element(t_end, i) = 0 ;
length_segment_id.element(t_end, i) = 0 ;
}
INT wobble_pos_segment_id_switch = 0 ;
INT last_segment_id = -1 ;
INT ts = t_end-1 ;
while ((ts>=0) && (pos[t_end] - pos[ts] <= loss.maxlookback))
{
INT cur_segment_id = segment_ids_mask.element(0, ts) ;
// allow at most one wobble
bool wobble_pos = (segment_ids_mask.element(1, ts)==0) && (wobble_pos_segment_id_switch==0) ;
ASSERT(cur_segment_id<=max_a_id) ;
ASSERT(cur_segment_id>=0) ;
for (INT i=0; i<max_a_id+1; i++)
{
num_segment_id.element(ts, i) = num_segment_id.element(ts+1, i) ;
length_segment_id.element(ts, i) = length_segment_id.element(ts+1, i) ;
}
if (cur_segment_id!=last_segment_id)
{
if (wobble_pos)
{
//SG_DEBUG( "no change at %i: %i, %i\n", ts, last_segment_id, cur_segment_id) ;
wobble_pos_segment_id_switch++ ;
//ASSERT(wobble_pos_segment_id_switch<=1) ;
}
else
{
//SG_DEBUG( "change at %i: %i, %i\n", ts, last_segment_id, cur_segment_id) ;
loss.segments_changed[ts] = true ;
num_segment_id.element(ts, cur_segment_id) += segment_ids_mask.element(1, ts) ;
length_segment_id.element(ts, cur_segment_id) += (pos[ts+1]-pos[ts])*segment_ids_mask.element(1, ts) ;
wobble_pos_segment_id_switch = 0 ;
}
last_segment_id = cur_segment_id ;
}
else
if (!wobble_pos)
length_segment_id.element(ts, cur_segment_id) += pos[ts+1] - pos[ts] ;
ts--;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_pos_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::init_svm_values(struct svm_values_struct & svs, INT start_pos, INT seqlen, INT maxlookback)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
See find_svm_values_till_pos for comments
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
where t_end is the end of all segments we are currently looking at
*/
if (!svs.svm_values)
{
svs.svm_values = new DREAL[seqlen*num_svms] ;
svs.num_unique_words = new INT*[num_degrees] ;
svs.svm_values_unnormalized = new DREAL*[num_degrees] ;
svs.word_used = new bool**[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
svs.word_used[j] = new bool*[num_svms] ;
for (INT s=0; s<num_svms; s++)
svs.word_used[j][s] = new bool[num_words_array[j]] ;
}
for (INT j=0; j<num_degrees; j++)
{
svs.svm_values_unnormalized[j] = new DREAL[num_svms] ;
svs.num_unique_words[j] = new INT[num_svms] ;
}
svs.start_pos = new INT[num_svms] ;
}
//for (INT i=0; i<maxlookback*num_svms; i++) // initializing this for safety, though we should be able to live without it
// svs.svm_values[i] = 0;
memset(svs.svm_values, 0, CMath::min(maxlookback,seqlen)*num_svms*sizeof(DREAL)) ;
for (INT j=0; j<num_degrees; j++)
{
//for (INT s=0; s<num_svms; s++)
// svs.svm_values_unnormalized[j][s] = 0 ;
memset(svs.svm_values_unnormalized[j], 0, num_svms*sizeof(DREAL)) ;
//for (INT s=0; s<num_svms; s++)
// svs.num_unique_words[j][s] = 0 ;
memset(svs.num_unique_words[j], 0, num_svms*sizeof(INT)) ;
}
for (INT j=0; j<num_degrees; j++)
for (INT s=0; s<num_svms; s++)
{
//for (INT i=0; i<num_words_array[j]; i++)
// svs.word_used[j][s][i] = false ;
memset(svs.word_used[j][s], 0, num_words_array[j]*sizeof(bool)) ;
}
for (INT s=0; s<num_svms; s++)
svs.start_pos[s] = start_pos - mod_words.element(s,1) ;
svs.maxlookback = maxlookback ;
svs.seqlen = seqlen ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_init_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::clear_svm_values(struct svm_values_struct & svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (NULL != svs.svm_values)
{
for (INT j=0; j<num_degrees; j++)
{
for (INT s=0; s<num_svms; s++)
delete[] svs.word_used[j][s] ;
delete[] svs.word_used[j];
}
delete[] svs.word_used;
for (INT j=0; j<num_degrees; j++)
delete[] svs.svm_values_unnormalized[j] ;
for (INT j=0; j<num_degrees; j++)
delete[] svs.num_unique_words[j] ;
delete[] svs.svm_values_unnormalized;
delete[] svs.svm_values;
delete[] svs.num_unique_words ;
svs.word_used=NULL ;
svs.svm_values=NULL ;
svs.svm_values_unnormalized=NULL ;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_clean_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::find_svm_values_till_pos(WORD*** wordstr, const INT *pos, INT t_end, struct svm_values_struct &svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
wordstr is a vector of L n-gram indices, with wordstr(i) representing a number betweeen 0 and 4095
corresponding to the 6-mer in genestr(i-5:i)
pos is a vector of candidate transition positions (it is input to best_path_trans)
t_end is some index in pos
svs has been initialized by init_svm_values
At the end of this procedure,
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
The SVM weights are precomputed in dict_weights
*/
for (INT j=0; j<num_degrees; j++)
{
INT plen = 1;
INT ts = t_end-1; // index in pos; pos(ts) and pos(t) are indices of wordstr
INT offset;
INT posprev = pos[t_end]-word_degree[j]+1;
INT poscurrent = pos[ts];
//SG_DEBUG( "j=%i seqlen=%i posprev = %i, poscurrent = %i", j, svs.seqlen, posprev, poscurrent) ;
if (poscurrent<0)
poscurrent = 0;
DREAL * my_svm_values_unnormalized = svs.svm_values_unnormalized[j] ;
INT * my_num_unique_words = svs.num_unique_words[j] ;
bool ** my_word_used = svs.word_used[j] ;
INT len = pos[t_end] - poscurrent;
while ((ts>=0) && (len <= svs.maxlookback))
{
for (int i=posprev-1 ; (i>=poscurrent) && (i>=0) ; i--)
{
//fprintf(stderr, "string_words_array[0]=%i (%ld), j=%i (%ld) i=%i\n", string_words_array[0], wordstr[string_words_array[0]], j, wordstr[string_words_array[0]][j], i) ;
WORD word = wordstr[string_words_array[0]][j][i] ;
INT last_string = string_words_array[0] ;
for (INT s=0; s<num_svms; s++)
{
// try to avoid memory accesses
if (last_string != string_words_array[s])
{
last_string = string_words_array[s] ;
word = wordstr[last_string][j][i] ;
}
// do not consider k-mer, if seen before and in signum mode
if (sign_words_array[s] && my_word_used[s][word])
continue ;
// only count k-mer if in frame (if applicable)
if ((svs.start_pos[s]-i>0) && ((svs.start_pos[s]-i)%mod_words_array[s]==0))
{
my_svm_values_unnormalized[s] += dict_weights_array[(word+cum_num_words_array[j])+s*cum_num_words_array[num_degrees]] ;
//svs.svm_values_unnormalized[j][s]+=dict_weights.element(word+cum_num_words_array[j], s) ;
my_num_unique_words[s]++ ;
if (sign_words_array[s])
my_word_used[s][word]=true ;
}
}
}
offset = plen*num_svms ;
for (INT s=0; s<num_svms; s++)
{
double normalization_factor = 1.0;
if (my_num_unique_words[s] > 0)
if (sign_words_array[s])
normalization_factor = sqrt((double)my_num_unique_words[s]);
else
normalization_factor = (double)my_num_unique_words[s];
if (j==0)
svs.svm_values[offset+s]=0 ;
svs.svm_values[offset+s] += my_svm_values_unnormalized[s] / normalization_factor;
}
if (posprev > poscurrent) // remember posprev initially set to pos[t_end]-word_degree+1... pos[ts] could be e.g. pos[t_end]-2
posprev = poscurrent;
ts--;
plen++;
if (ts>=0)
{
poscurrent=pos[ts];
if (poscurrent<0)
poscurrent = 0;
len = pos[t_end] - poscurrent;
}
}
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_pos_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::find_svm_values_till_pos(WORD** wordstr, const INT *pos, INT t_end, struct svm_values_struct &svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
wordstr is a vector of L n-gram indices, with wordstr(i) representing a number betweeen 0 and 4095
corresponding to the 6-mer in genestr(i-5:i)
pos is a vector of candidate transition positions (it is input to best_path_trans)
t_end is some index in pos
svs has been initialized by init_svm_values
At the end of this procedure,
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
The SVM weights are precomputed in dict_weights
*/
for (INT j=0; j<num_degrees; j++)
{
INT plen = 1;
INT ts = t_end-1; // index in pos; pos(ts) and pos(t) are indices of wordstr
INT offset;
INT posprev = pos[t_end]-word_degree[j]+1;
INT poscurrent = pos[ts];
//SG_DEBUG( "j=%i seqlen=%i posprev = %i, poscurrent = %i", j, svs.seqlen, posprev, poscurrent) ;
if (poscurrent<0)
poscurrent = 0;
DREAL * my_svm_values_unnormalized = svs.svm_values_unnormalized[j] ;
INT * my_num_unique_words = svs.num_unique_words[j] ;
bool ** my_word_used = svs.word_used[j] ;
INT len = pos[t_end] - poscurrent;
while ((ts>=0) && (len <= svs.maxlookback))
{
for (int i=posprev-1 ; (i>=poscurrent) && (i>=0) ; i--)
{
//fprintf(stderr, "string_words_array[0]=%i (%ld), j=%i (%ld) i=%i\n", string_words_array[0], wordstr[string_words_array[0]], j, wordstr[string_words_array[0]][j], i) ;
WORD word = wordstr[j][i] ;
for (INT s=0; s<num_svms; s++)
{
// do not consider k-mer, if seen before and in signum mode
if (sign_words_array[s] && my_word_used[s][word])
continue ;
// only count k-mer if in frame (if applicable)
if ((svs.start_pos[s]-i>0) && ((svs.start_pos[s]-i)%mod_words_array[s]==0))
{
my_svm_values_unnormalized[s] += dict_weights_array[(word+cum_num_words_array[j])+s*cum_num_words_array[num_degrees]] ;
//svs.svm_values_unnormalized[j][s]+=dict_weights.element(word+cum_num_words_array[j], s) ;
my_num_unique_words[s]++ ;
if (sign_words_array[s])
my_word_used[s][word]=true ;
}
}
}
offset = plen*num_svms ;
for (INT s=0; s<num_svms; s++)
{
double normalization_factor = 1.0;
if (my_num_unique_words[s] > 0)
if (sign_words_array[s])
normalization_factor = sqrt((double)my_num_unique_words[s]);
else
normalization_factor = (double)my_num_unique_words[s];
if (j==0)
svs.svm_values[offset+s]=0 ;
svs.svm_values[offset+s] += my_svm_values_unnormalized[s] / normalization_factor;
}
if (posprev > poscurrent) // remember posprev initially set to pos[t_end]-word_degree+1... pos[ts] could be e.g. pos[t_end]-2
posprev = poscurrent;
ts--;
plen++;
if (ts>=0)
{
poscurrent=pos[ts];
if (poscurrent<0)
poscurrent = 0;
len = pos[t_end] - poscurrent;
}
}
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_pos_time += MyTime.time_diff_sec() ;
#endif
}
bool CDynProg::extend_orf(const CArray<bool>& genestr_stop, INT orf_from, INT orf_to, INT start, INT &last_pos, INT to)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (start<0)
start=0 ;
if (to<0)
to=0 ;
INT orf_target = orf_to-orf_from ;
if (orf_target<0) orf_target+=3 ;
INT pos ;
if (last_pos==to)
pos = to-orf_to-3 ;
else
pos=last_pos ;
if (pos<0)
return true ;
for (; pos>=start; pos-=3)
if (genestr_stop[pos])
return false ;
last_pos = CMath::min(pos+3,to-orf_to-3) ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
orf_time += MyTime.time_diff_sec() ;
#endif
return true ;
}
template <short int nbest, bool with_loss, bool with_multiple_sequences>
void CDynProg::best_path_trans(const DREAL *seq_array, INT seq_len, const INT *pos,
const INT *orf_info_array, CPlifBase **Plif_matrix,
CPlifBase **Plif_state_signals, INT max_num_signals,
const char *genestr, INT genestr_len, INT genestr_num,
DREAL *prob_nbest, INT *my_state_seq, INT *my_pos_seq,
DREAL *dictionary_weights, INT dict_len, bool use_orf)
{
#ifdef DYNPROG_TIMING
segment_init_time = 0.0 ;
segment_pos_time = 0.0 ;
segment_extend_time = 0.0 ;
segment_clean_time = 0.0 ;
orf_time = 0.0 ;
svm_init_time = 0.0 ;
svm_pos_time = 0.0 ;
svm_clean_time = 0.0 ;
MyTime2.start() ;
#endif
//SG_PRINT( "best_path_trans:%x\n", seq_array);
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
}
#ifdef DYNPROG_DEBUG
transition_matrix_a.set_name("transition_matrix");
transition_matrix_a.display_array();
mod_words.display_array() ;
sign_words.display_array() ;
string_words.display_array() ;
fprintf(stderr, "use_orf = %i\n", use_orf) ;
#endif
const INT default_look_back = 30000 ;
INT max_look_back = default_look_back ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*cum_num_words_array[num_degrees]) ;
dict_weights.set_array(dictionary_weights, cum_num_words_array[num_degrees], num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false, false) ;
CArray2<CPlifBase*> PEN_state_signals(Plif_state_signals, N, max_num_signals, false, false) ;
CArray3<DREAL> seq_input(seq_array, N, seq_len, max_num_signals) ;
seq_input.set_name("seq_input") ;
//seq_input.display_array() ;
CArray2<DREAL> seq(N, seq_len) ;
seq.set_name("seq") ;
seq.zero() ;
CArray2<INT> orf_info(orf_info_array, N, 2) ;
orf_info.set_name("orf_info") ;
//g_orf_info = orf_info ;
//orf_info.display_array() ;
DREAL svm_value[num_svms] ;
{ // initialize svm_svalue
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
{ // convert seq_input to seq
// this is independent of the svm values
for (INT i=0; i<N; i++)
for (INT j=0; j<seq_len; j++)
seq.element(i,j) = 0 ;
for (INT i=0; i<N; i++)
for (INT j=0; j<seq_len; j++)
for (INT k=0; k<max_num_signals; k++)
{
if ((PEN_state_signals.element(i,k)==NULL) && (k==0))
{
// no plif
seq.element(i,j) = seq_input.element(i,j,k) ;
break ;
}
if (PEN_state_signals.element(i,k)!=NULL)
{
// just one plif
if (finite(seq_input.element(i,j,k)))
seq.element(i,j) += PEN_state_signals.element(i,k)->lookup_penalty(seq_input.element(i,j,k), svm_value) ;
else
// keep infinity values
seq.element(i,j) = seq_input.element(i, j, k) ;
}
else
break ;
}
}
{ // determine maximal length of look-back
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->get_max_value()>max_look_back)
{
SG_DEBUG( "%d %d -> value: %f\n", i,j,penij->get_max_value());
max_look_back=(INT) (CMath::ceil(penij->get_max_value()));
}
if (penij->uses_svm_values())
use_svm=true ;
}
}
max_look_back = CMath::min(genestr_len, max_look_back) ;
SG_DEBUG("use_svm=%i\n", use_svm) ;
SG_DEBUG("maxlook: %d N: %d nbest: %d genestrlen:%d\n", max_look_back, N, nbest, genestr_len);
const INT look_back_buflen = (max_look_back*N+1)*nbest ;
SG_DEBUG("look_back_buflen=%i\n", look_back_buflen) ;
const DREAL mem_use = (DREAL)(seq_len*N*nbest*(sizeof(T_STATES)+sizeof(short int)+sizeof(INT))+
look_back_buflen*(2*sizeof(DREAL)+sizeof(INT))+
seq_len*(sizeof(T_STATES)+sizeof(INT))+
genestr_len*sizeof(bool))/(1024*1024);
bool is_big = (mem_use>200) || (seq_len>5000) ;
if (is_big)
{
SG_DEBUG("calling best_path_trans: seq_len=%i, N=%i, lookback=%i nbest=%i\n",
seq_len, N, max_look_back, nbest) ;
SG_DEBUG("allocating %1.2fMB of memory\n",
mem_use) ;
}
ASSERT(nbest<32000) ;
//char* xx=strndup(genestr, genestr_len) ;
//fprintf(stderr, "genestr='%s'\n", xx) ;
CArray<bool> genestr_stop(genestr_len) ;
//genestr_stop.zero() ;
CArray3<DREAL> delta(seq_len, N, nbest) ;
DREAL* delta_array = delta.get_array() ;
//delta.zero() ;
CArray3<T_STATES> psi(seq_len, N, nbest) ;
//psi.zero() ;
CArray3<short int> ktable(seq_len, N, nbest) ;
//ktable.zero() ;
CArray3<INT> ptable(seq_len, N, nbest) ;
//ptable.zero() ;
CArray<DREAL> delta_end(nbest) ;
//delta_end.zero() ;
CArray<T_STATES> path_ends(nbest) ;
//path_ends.zero() ;
CArray<short int> ktable_end(nbest) ;
//ktable_end.zero() ;
DREAL * fixedtempvv=new DREAL[look_back_buflen] ;
memset(fixedtempvv, 0, look_back_buflen*sizeof(DREAL)) ;
INT * fixedtempii=new INT[look_back_buflen] ;
memset(fixedtempii, 0, look_back_buflen*sizeof(INT)) ;
CArray<DREAL> oldtempvv(look_back_buflen) ;
CArray<DREAL> oldtempvv2(look_back_buflen) ;
//oldtempvv.zero() ;
//oldtempvv.display_size() ;
CArray<INT> oldtempii(look_back_buflen) ;
CArray<INT> oldtempii2(look_back_buflen) ;
//oldtempii.zero() ;
CArray<T_STATES> state_seq(seq_len) ;
//state_seq.zero() ;
CArray<INT> pos_seq(seq_len) ;
//pos_seq.zero() ;
dict_weights.set_name("dict_weights") ;
word_degree.set_name("word_degree") ;
cum_num_words.set_name("cum_num_words") ;
num_words.set_name("num_words") ;
//word_used.set_name("word_used") ;
//svm_values_unnormalized.set_name("svm_values_unnormalized") ;
svm_pos_start.set_name("svm_pos_start") ;
num_unique_words.set_name("num_unique_words") ;
PEN.set_name("PEN") ;
seq.set_name("seq") ;
orf_info.set_name("orf_info") ;
genestr_stop.set_name("genestr_stop") ;
delta.set_name("delta") ;
psi.set_name("psi") ;
ktable.set_name("ktable") ;
ptable.set_name("ptable") ;
delta_end.set_name("delta_end") ;
path_ends.set_name("path_ends") ;
ktable_end.set_name("ktable_end") ;
#ifdef USE_TMP_ARRAYCLASS
fixedtempvv.set_name("fixedtempvv") ;
fixedtempii.set_name("fixedtempvv") ;
#endif
oldtempvv.set_name("oldtempvv") ;
oldtempvv2.set_name("oldtempvv2") ;
oldtempii.set_name("oldtempii") ;
oldtempii2.set_name("oldtempii2") ;
////////////////////////////////////////////////////////////////////////////////
#ifdef DYNPROG_DEBUG
state_seq.display_size() ;
pos_seq.display_size() ;
dict_weights.display_size() ;
word_degree.display_array() ;
cum_num_words.display_array() ;
num_words.display_array() ;
//word_used.display_size() ;
//svm_values_unnormalized.display_size() ;
svm_pos_start.display_array() ;
num_unique_words.display_array() ;
PEN.display_size() ;
PEN_state_signals.display_size() ;
seq.display_size() ;
orf_info.display_size() ;
genestr_stop.display_size() ;
delta.display_size() ;
psi.display_size() ;
ktable.display_size() ;
ptable.display_size() ;
delta_end.display_size() ;
path_ends.display_size() ;
ktable_end.display_size() ;
#ifdef USE_TMP_ARRAYCLASS
fixedtempvv.display_size() ;
fixedtempii.display_size() ;
#endif
//oldtempvv.display_size() ;
//oldtempii.display_size() ;
state_seq.display_size() ;
pos_seq.display_size() ;
CArray<INT>pp = CArray<INT>(pos, seq_len) ;
pp.display_array() ;
//seq.zero() ;
//seq_input.display_array() ;
#endif //DYNPROG_DEBUG
////////////////////////////////////////////////////////////////////////////////
{ // precompute stop codons
for (INT i=0; i<genestr_len-2; i++)
if ((genestr[i]=='t' || genestr[i]=='T') &&
(((genestr[i+1]=='a' || genestr[i+1]=='A') &&
(genestr[i+2]=='a' || genestr[i+2]=='g' || genestr[i+2]=='A' || genestr[i+2]=='G')) ||
((genestr[i+1]=='g'||genestr[i+1]=='G') && (genestr[i+2]=='a' || genestr[i+2]=='A') )))
genestr_stop[i]=true ;
else
genestr_stop[i]=false ;
genestr_stop[genestr_len-1]=false ;
genestr_stop[genestr_len-1]=false ;
}
{
for (INT s=0; s<num_svms; s++)
ASSERT(string_words_array[s]<genestr_num) ;
}
// translate to words, if svm is used
SG_DEBUG("genestr_num = %i, genestr_len = %i, num_degree=%i, use_svm=%i\n", genestr_num, genestr_len, num_degrees, use_svm) ;
WORD** wordstr[genestr_num] ;
for (INT k=0; k<genestr_num; k++)
{
wordstr[k]=new WORD*[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
wordstr[k][j]=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr[k][j]=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[k][j][i]=0 ; break ;
case 'C':
case 'c': wordstr[k][j][i]=1 ; break ;
case 'G':
case 'g': wordstr[k][j][i]=2 ; break ;
case 'T':
case 't': wordstr[k][j][i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr[k][j], genestr_len,
word_degree[j]-1, word_degree[j]) ;
}
}
}
{ // initialization
for (T_STATES i=0; i<N; i++)
{
//delta.element(0, i, 0) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
delta.element(delta_array, 0, i, 0, seq_len, N) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
psi.element(0,i,0) = 0 ;
if (nbest>1)
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
INT dim1, dim2, dim3 ;
delta.get_array_size(dim1, dim2, dim3) ;
//SG_DEBUG("i=%i, k=%i -- %i, %i, %i\n", i, k, dim1, dim2, dim3) ;
//delta.element(0, i, k) = -CMath::INFTY ;
delta.element(delta_array, 0, i, k, seq_len, N) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ; // <--- what's this for?
if (nbest>1)
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
struct svm_values_struct svs;
svs.num_unique_words = NULL;
svs.svm_values = NULL;
svs.svm_values_unnormalized = NULL;
svs.word_used = NULL;
struct segment_loss_struct loss;
loss.segments_changed = NULL;
loss.num_segment_id = NULL;
// recursion
for (INT t=1; t<seq_len; t++)
{
if (is_big && t%(1+(seq_len/1000))==1)
SG_PROGRESS(t, 0, seq_len);
//fprintf(stderr, "%i\n", t) ;
init_svm_values(svs, pos[t], seq_len, max_look_back) ;
if (with_multiple_sequences)
find_svm_values_till_pos(wordstr, pos, t, svs);
else
find_svm_values_till_pos(wordstr[0], pos, t, svs);
if (with_loss)
{
init_segment_loss(loss, seq_len, max_look_back);
find_segment_loss_till_pos(pos, t, m_segment_ids_mask, loss);
}
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<=-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(delta_array, t, j, k, seq_len, N) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
if (nbest>1)
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
const INT *elem_id = trans_list_forward_id[j] ;
INT fixed_list_len = 0 ;
DREAL fixedtempvv_ = CMath::INFTY ;
INT fixedtempii_ = 0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
const CPlifBase * penalty = PEN.element(j,ii) ;
INT look_back = default_look_back ;
{ // find lookback length
CPlifBase *pen = (CPlifBase*) penalty ;
if (pen!=NULL)
look_back=(INT) (CMath::ceil(pen->get_max_value()));
ASSERT(look_back<1e6);
}
INT orf_from = orf_info.element(ii,0) ;
INT orf_to = orf_info.element(j,1) ;
if((orf_from!=-1)!=(orf_to!=-1))
SG_DEBUG("j=%i ii=%i orf_from=%i orf_to=%i p=%1.2f\n", j, ii, orf_from, orf_to, elem_val[i]) ;
ASSERT((orf_from!=-1)==(orf_to!=-1)) ;
INT orf_target = -1 ;
if (orf_from!=-1)
{
orf_target=orf_to-orf_from ;
if (orf_target<0)
orf_target+=3 ;
ASSERT(orf_target>=0 && orf_target<3) ;
}
INT orf_last_pos = pos[t] ;
INT loss_last_pos = t ;
DREAL last_loss = 0.0 ;
for (INT ts=t-1; ts>=0 && pos[t]-pos[ts]<=look_back; ts--)
{
bool ok ;
int plen=t-ts;
/*for (INT s=0; s<num_svms; s++)
if ((fabs(svs.svm_values[s*svs.seqlen+plen]-svs2.svm_values[s*svs.seqlen+plen])>1e-6) ||
(fabs(svs.svm_values[s*svs.seqlen+plen]-svs3.svm_values[s*svs.seqlen+plen])>1e-6))
{
SG_DEBUG( "s=%i, t=%i, ts=%i, %1.5e, %1.5e, %1.5e\n", s, t, ts, svs.svm_values[s*svs.seqlen+plen], svs2.svm_values[s*svs.seqlen+plen], svs3.svm_values[s*svs.seqlen+plen]);
}*/
if (orf_target==-1)
ok=true ;
else if (pos[ts]!=-1 && (pos[t]-pos[ts])%3==orf_target)
ok=(!use_orf) || extend_orf(genestr_stop, orf_from, orf_to, pos[ts], orf_last_pos, pos[t]) ;
else
ok=false ;
if (ok)
{
DREAL segment_loss = 0.0 ;
if (with_loss)
segment_loss = extend_segment_loss(loss, pos, elem_id[i], ts, loss_last_pos, last_loss) ;
INT offset = plen*num_svms ;
for (INT ss=0; ss<num_svms; ss++)
svm_value[ss]=svs.svm_values[offset+ss];
DREAL pen_val = 0.0 ;
if (penalty)
pen_val = penalty->lookup_penalty(pos[t]-pos[ts], svm_value) ;
if (nbest==1)
{
DREAL val = elem_val[i] + pen_val ;
if (with_loss)
val += segment_loss ;
DREAL mval = -(val + delta.element(delta_array, ts, ii, 0, seq_len, N)) ;
if (mval<fixedtempvv_)
{
fixedtempvv_ = mval ;
fixedtempii_ = ii + ts*N;
fixed_list_len = 1 ;
}
}
else
{
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = elem_val[i] ;
val += pen_val ;
if (with_loss)
val += segment_loss ;
DREAL mval = -(val + delta.element(delta_array, ts, ii, diff, seq_len, N)) ;
/* only place -val in fixedtempvv if it is one of the nbest lowest values in there */
/* fixedtempvv[i], i=0:nbest-1, is sorted so that fixedtempvv[0] <= fixedtempvv[1] <= ...*/
/* fixed_list_len has the number of elements in fixedtempvv */
if ((fixed_list_len < nbest) || ((0==fixed_list_len) || (mval < fixedtempvv[fixed_list_len-1])))
{
if ( (fixed_list_len<nbest) && ((0==fixed_list_len) || (mval>fixedtempvv[fixed_list_len-1])) )
{
fixedtempvv[fixed_list_len] = mval ;
fixedtempii[fixed_list_len] = ii + diff*N + ts*N*nbest;
fixed_list_len++ ;
}
else // must have mval < fixedtempvv[fixed_list_len-1]
{
int addhere = fixed_list_len;
while ((addhere > 0) && (mval < fixedtempvv[addhere-1]))
addhere--;
// move everything from addhere+1 one forward
for (int jj=fixed_list_len-1; jj>addhere; jj--)
{
fixedtempvv[jj] = fixedtempvv[jj-1];
fixedtempii[jj] = fixedtempii[jj-1];
}
fixedtempvv[addhere] = mval;
fixedtempii[addhere] = ii + diff*N + ts*N*nbest;
if (fixed_list_len < nbest)
fixed_list_len++;
}
}
}
}
}
}
}
int numEnt = fixed_list_len;
double minusscore;
long int fromtjk;
for (short int k=0; k<nbest; k++)
{
if (k<numEnt)
{
if (nbest==1)
{
minusscore = fixedtempvv_ ;
fromtjk = fixedtempii_ ;
}
else
{
minusscore = fixedtempvv[k];
fromtjk = fixedtempii[k];
}
delta.element(delta_array, t, j, k, seq_len, N) = -minusscore + seq.element(j,t);
psi.element(t,j,k) = (fromtjk%N) ;
if (nbest>1)
ktable.element(t,j,k) = (fromtjk%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (fromtjk-(fromtjk%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(delta_array, t, j, k, seq_len, N) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
if (nbest>1)
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
clear_svm_values(svs);
if (with_loss)
clear_segment_loss(loss);
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
oldtempvv[list_len] = -(delta.element(delta_array, (seq_len-1), i, diff, seq_len, N)+get_q(i)) ;
oldtempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(oldtempvv.get_array(), oldtempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -oldtempvv[k] ;
path_ends.element(k) = (oldtempii[k]%N) ;
if (nbest>1)
ktable_end.element(k) = (oldtempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = 0 ;
if (nbest>1)
q=ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
if (nbest>1)
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*seq_len] = state_seq[num_states-i-1] ;
my_pos_seq[i+k*seq_len] = pos_seq[num_states-i-1] ;
}
my_state_seq[num_states+k*seq_len]=-1 ;
my_pos_seq[num_states+k*seq_len]=-1 ;
}
}
if (is_big)
SG_PRINT( "DONE. \n") ;
for (INT k=0; k<genestr_num; k++)
{
for (INT j=0; j<num_degrees; j++)
delete[] wordstr[k][j] ;
delete[] wordstr[k] ;
}
#ifdef DYNPROG_TIMING
MyTime2.stop() ;
if (is_big)
SG_PRINT("Timing: orf=%1.2f s \n Segment_init=%1.2f s Segment_pos=%1.2f s Segment_extend=%1.2f s Segment_clean=%1.2f s\nsvm_init=%1.2f s svm_pos=%1.2f svm_clean=%1.2f\n total=%1.2f\n", orf_time, segment_init_time, segment_pos_time, segment_extend_time, segment_clean_time, svm_init_time, svm_pos_time, svm_clean_time, MyTime2.time_diff_sec()) ;
#endif
delete[] fixedtempvv ;
delete[] fixedtempii ;
}
void CDynProg::best_path_trans_deriv(INT *my_state_seq, INT *my_pos_seq, DREAL *my_scores, DREAL* my_losses,
INT my_seq_len,
const DREAL *seq_array, INT seq_len, const INT *pos,
CPlifBase **Plif_matrix,
CPlifBase **Plif_state_signals, INT max_num_signals,
const char *genestr, INT genestr_len, INT genestr_num,
DREAL *dictionary_weights, INT dict_len)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
//SG_DEBUG( "genestr_len=%i, genestr_num=%i\n", genestr_len, genestr_num) ;
//mod_words.display() ;
//sign_words.display() ;
//string_words.display() ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*cum_num_words_array[num_degrees]) ;
dict_weights.set_array(dictionary_weights, cum_num_words_array[num_degrees], num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false, false) ;
CArray2<CPlifBase*> PEN_state_signals(Plif_state_signals, N, max_num_signals, false, false) ;
CArray3<DREAL> seq_input(seq_array, N, seq_len, max_num_signals) ;
{ // determine whether to use svm outputs and clear derivatives
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->uses_svm_values())
use_svm=true ;
penij->penalty_clear_derivative() ;
}
for (INT i=0; i<N; i++)
for (INT j=0; j<max_num_signals; j++)
{
CPlifBase *penij=PEN_state_signals.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->uses_svm_values())
use_svm=true ;
penij->penalty_clear_derivative() ;
}
}
// translate to words, if svm is used
WORD** wordstr[genestr_num] ;
for (INT k=0; k<genestr_num; k++)
{
wordstr[k]=new WORD*[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
wordstr[k][j]=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr[k][j]=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[k][j][i]=0 ; break ;
case 'C':
case 'c': wordstr[k][j][i]=1 ; break ;
case 'G':
case 'g': wordstr[k][j][i]=2 ; break ;
case 'T':
case 't': wordstr[k][j][i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr[k][j], genestr_len,
word_degree[j]-1, word_degree[j]) ;
}
}
}
{ // set derivatives of p, q and a to zero
for (INT i=0; i<N; i++)
{
initial_state_distribution_p_deriv.element(i)=0 ;
end_state_distribution_q_deriv.element(i)=0 ;
for (INT j=0; j<N; j++)
transition_matrix_a_deriv.element(i,j)=0 ;
}
}
{ // clear score vector
for (INT i=0; i<my_seq_len; i++)
{
my_scores[i]=0.0 ;
my_losses[i]=0.0 ;
}
}
//INT total_len = 0 ;
//transition_matrix_a.display_array() ;
//transition_matrix_a_id.display_array() ;
{ // compute derivatives for given path
DREAL svm_value[num_svms] ;
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
for (INT i=0; i<my_seq_len; i++)
{
my_scores[i]=0.0 ;
my_losses[i]=0.0 ;
}
#ifdef DYNPROG_DEBUG
DREAL total_score = 0.0 ;
DREAL total_loss = 0.0 ;
#endif
ASSERT(my_state_seq[0]>=0) ;
initial_state_distribution_p_deriv.element(my_state_seq[0])++ ;
my_scores[0] += initial_state_distribution_p.element(my_state_seq[0]) ;
ASSERT(my_state_seq[my_seq_len-1]>=0) ;
end_state_distribution_q_deriv.element(my_state_seq[my_seq_len-1])++ ;
my_scores[my_seq_len-1] += end_state_distribution_q.element(my_state_seq[my_seq_len-1]);
#ifdef DYNPROG_DEBUG
total_score += my_scores[0] + my_scores[my_seq_len-1] ;
#endif
struct svm_values_struct svs;
svs.num_unique_words = NULL;
svs.svm_values = NULL;
svs.svm_values_unnormalized = NULL;
svs.word_used = NULL;
init_svm_values(svs, my_state_seq[0], seq_len, 100);
struct segment_loss_struct loss;
loss.segments_changed = NULL;
loss.num_segment_id = NULL;
//SG_DEBUG( "seq_len=%i\n", my_seq_len) ;
for (INT i=0; i<my_seq_len-1; i++)
{
if (my_state_seq[i+1]==-1)
break ;
INT from_state = my_state_seq[i] ;
INT to_state = my_state_seq[i+1] ;
INT from_pos = my_pos_seq[i] ;
INT to_pos = my_pos_seq[i+1] ;
// compute loss relative to another segmentation using the segment_loss function
init_segment_loss(loss, seq_len, pos[to_pos]-pos[from_pos]+10);
find_segment_loss_till_pos(pos, to_pos, m_segment_ids_mask, loss);
INT loss_last_pos = to_pos ;
DREAL last_loss = 0.0 ;
//INT elem_id = transition_matrix_a_id.element(to_state, from_state) ;
INT elem_id = transition_matrix_a_id.element(from_state, to_state) ;
my_losses[i] = extend_segment_loss(loss, pos, elem_id, from_pos, loss_last_pos, last_loss) ;
#ifdef DYNPROG_DEBUG
io.set_loglevel(M_DEBUG) ;
SG_DEBUG( "%i. segment loss %f (id=%i): from=%i(%i), to=%i(%i)\n", i, my_losses[i], elem_id, from_pos, from_state, to_pos, to_state) ;
#endif
// increase usage of this transition
transition_matrix_a_deriv.element(from_state, to_state)++ ;
my_scores[i] += transition_matrix_a.element(from_state, to_state) ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f\n", i, my_scores[i]) ;
#endif
/*INT last_svm_pos[num_degrees] ;
for (INT qq=0; qq<num_degrees; qq++)
last_svm_pos[qq]=-1 ;*/
if (use_svm)
{
//reset_svm_values(pos[to_pos], last_svm_pos, svm_value) ;
//extend_svm_values(wordstr, pos[from_pos], last_svm_pos, svm_value) ;
init_svm_values(svs, pos[to_pos], seq_len, pos[to_pos]-pos[from_pos]+100);
find_svm_values_till_pos(wordstr, pos, to_pos, svs);
INT plen = to_pos - from_pos ;
INT offset = plen*num_svms ;
for (INT ss=0; ss<num_svms; ss++)
{
svm_value[ss]=svs.svm_values[offset+ss];
#ifdef DYNPROG_DEBUG
SG_DEBUG( "svm[%i]: %f\n", ss, svm_value[ss]) ;
#endif
}
}
if (PEN.element(to_state, from_state)!=NULL)
{
DREAL nscore = PEN.element(to_state, from_state)->lookup_penalty(pos[to_pos]-pos[from_pos], svm_value) ;
my_scores[i] += nscore ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. transition penalty: from_state=%i to_state=%i from_pos=%i [%i] to_pos=%i [%i] value=%i\n", i, from_state, to_state, from_pos, pos[from_pos], to_pos, pos[to_pos], pos[to_pos]-pos[from_pos]) ;
/*
INT orf_from = g_orf_info.element(from_state,0) ;
INT orf_to = g_orf_info.element(to_state,1) ;
ASSERT((orf_from!=-1)==(orf_to!=-1)) ;
if (orf_from != -1)
total_len = total_len + pos[to_pos]-pos[from_pos] ;
SG_DEBUG( "%i. orf_info: from_orf=%i to_orf=%i orf_diff=%i, len=%i, lenmod3=%i, total_len=%i, total_lenmod3=%i\n", i, orf_from, orf_to, (orf_to-orf_from)%3, pos[to_pos]-pos[from_pos], (pos[to_pos]-pos[from_pos])%3, total_len, total_len%3) ;
*/
#endif
PEN.element(to_state, from_state)->penalty_add_derivative(pos[to_pos]-pos[from_pos], svm_value) ;
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f\n", i, my_scores[i]) ;
#endif
//SG_DEBUG( "emmission penalty skipped: to_state=%i to_pos=%i value=%1.2f score=%1.2f\n", to_state, to_pos, seq_input.element(to_state, to_pos), 0.0) ;
for (INT k=0; k<max_num_signals; k++)
{
if ((PEN_state_signals.element(to_state,k)==NULL)&&(k==0))
{
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. emmission penalty: to_state=%i to_pos=%i score=%1.2f (no signal plif)\n", i, to_state, to_pos, seq_input.element(to_state, to_pos, k)) ;
#endif
my_scores[i] += seq_input.element(to_state, to_pos, k) ;
break ;
}
if (PEN_state_signals.element(to_state, k)!=NULL)
{
DREAL nscore = PEN_state_signals.element(to_state,k)->lookup_penalty(seq_input.element(to_state, to_pos, k), svm_value) ;
my_scores[i] += nscore ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. emmission penalty: to_state=%i to_pos=%i value=%1.2f score=%1.2f k=%i\n", i, to_state, to_pos, seq_input.element(to_state, to_pos, k), nscore, k) ;
#endif
PEN_state_signals.element(to_state,k)->penalty_add_derivative(seq_input.element(to_state, to_pos, k), svm_value) ;
} else
break ;
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f (final) \n", i, my_scores[i]) ;
total_score += my_scores[i] ;
total_loss += my_losses[i] ;
#endif
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "total score = %f \n", total_score) ;
SG_DEBUG( "total loss = %f \n", total_loss) ;
#endif
clear_svm_values(svs);
clear_segment_loss(loss);
}
for (INT k=0; k<genestr_num; k++)
{
for (INT j=0; j<num_degrees; j++)
delete[] wordstr[k][j] ;
delete[] wordstr[k] ;
}
}
void CDynProg::best_path_trans_simple(const DREAL *seq_array, INT seq_len, short int nbest,
DREAL *prob_nbest, INT *my_state_seq)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
INT max_look_back = 2 ;
const INT look_back_buflen = max_look_back*nbest*N ;
ASSERT(nbest<32000) ;
CArray2<DREAL> seq((DREAL *)seq_array, N, seq_len, false) ;
CArray3<DREAL> delta(max_look_back, N, nbest) ;
CArray3<T_STATES> psi(seq_len, N, nbest) ;
CArray3<short int> ktable(seq_len,N,nbest) ;
CArray3<INT> ptable(seq_len,N,nbest) ;
CArray<DREAL> delta_end(nbest) ;
CArray<T_STATES> path_ends(nbest) ;
CArray<short int> ktable_end(nbest) ;
CArray<DREAL> oldtempvv(look_back_buflen) ;
CArray<INT> oldtempii(look_back_buflen) ;
CArray<T_STATES> state_seq(seq_len) ;
CArray<INT> pos_seq(seq_len) ;
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta.element(0,i,0) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
psi.element(0,i,0) = 0 ;
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
delta.element(0,i,k) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ; // <--- what's this for?
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
// recursion
for (INT t=1; t<seq_len; t++)
{
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(t%max_look_back,j,k) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT old_list_len = 0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
INT ts=t-1;
if (ts>=0)
{
bool ok=true ;
if (ok)
{
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = delta.element(ts%max_look_back,ii,diff) + elem_val[i] ;
DREAL mval = -val;
oldtempvv[old_list_len] = mval ;
oldtempii[old_list_len] = ii + diff*N + ts*N*nbest;
old_list_len++ ;
}
}
}
}
CMath::nmin<INT>(oldtempvv.get_array(), oldtempii.get_array(), old_list_len, nbest) ;
int numEnt = 0;
numEnt = old_list_len;
double minusscore;
long int fromtjk;
for (short int k=0; k<nbest; k++)
{
if (k<numEnt)
{
minusscore = oldtempvv[k];
fromtjk = oldtempii[k];
delta.element(t%max_look_back,j,k) = -minusscore + seq.element(j,t);
psi.element(t,j,k) = (fromtjk%N) ;
ktable.element(t,j,k) = (fromtjk%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (fromtjk-(fromtjk%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(t%max_look_back,j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
oldtempvv[list_len] = -(delta.element((seq_len-1)%max_look_back,i,diff)+get_q(i)) ;
oldtempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(oldtempvv.get_array(), oldtempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -oldtempvv[k] ;
path_ends.element(k) = (oldtempii[k]%N) ;
ktable_end.element(k) = (oldtempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*seq_len] = state_seq[num_states-i-1] ;
}
//my_state_seq[num_states+k*seq_len]=-1 ;
}
}
}
fix uninitialized memory reads.
/*
* 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.
*
* Written (W) 1999-2007 Soeren Sonnenburg
* Written (W) 1999-2007 Gunnar Raetsch
* Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "structure/DynProg.h"
#include "lib/Mathematics.h"
#include "lib/io.h"
#include "lib/config.h"
#include "features/StringFeatures.h"
#include "features/CharFeatures.h"
#include "features/Alphabet.h"
#include "structure/Plif.h"
#include "lib/Array.h"
#include "lib/Array2.h"
#include "lib/Array3.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#ifdef SUNOS
extern "C" int finite(double);
#endif
//#define USE_TMP_ARRAYCLASS
//#define DYNPROG_DEBUG
//CArray2<INT> g_orf_info(1,1) ;
static INT word_degree_default[4]={3,4,5,6} ;
static INT cum_num_words_default[5]={0,64,320,1344,5440} ;
static INT num_words_default[4]= {64,256,1024,4096} ;
static INT mod_words_default[32] = {1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0} ;
static bool sign_words_default[16] = {true,true,true,true,true,true,true,true,
false,false,false,false,false,false,false,false} ; // whether to use counts or signum of counts
static INT string_words_default[16] = {0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1} ; // which string should be used
CDynProg::CDynProg()
: CSGObject(),transition_matrix_a_id(1,1), transition_matrix_a(1,1),
transition_matrix_a_deriv(1,1), initial_state_distribution_p(1),
initial_state_distribution_p_deriv(1), end_state_distribution_q(1),
end_state_distribution_q_deriv(1), dict_weights(1,1),
dict_weights_array(dict_weights.get_array()),
// multi svm
num_degrees(4),
num_svms(8),
num_strings(1),
word_degree(word_degree_default, num_degrees, true, true),
cum_num_words(cum_num_words_default, num_degrees+1, true, true),
cum_num_words_array(cum_num_words.get_array()),
num_words(num_words_default, num_degrees, true, true),
num_words_array(num_words.get_array()),
mod_words(mod_words_default, num_svms, 2, true, true),
mod_words_array(mod_words.get_array()),
sign_words(sign_words_default, num_svms, true, true),
sign_words_array(sign_words.get_array()),
string_words(string_words_default, num_svms, true, true),
string_words_array(string_words.get_array()),
// word_used(num_degrees, num_words[num_degrees-1], num_strings),
// word_used_array(word_used.get_array()),
// svm_values_unnormalized(num_degrees, num_svms),
svm_pos_start(num_degrees),
num_unique_words(num_degrees),
svm_arrays_clean(true),
// single svm
num_svms_single(1),
word_degree_single(1),
num_words_single(4),
word_used_single(num_words_single),
svm_value_unnormalized_single(num_svms_single),
num_unique_words_single(0),
max_a_id(0), m_seq(1,1,1), m_pos(1), m_orf_info(1,2),
m_segment_sum_weights(1,1), m_plif_list(1),
m_PEN(1,1), m_PEN_state_signals(1,1),
m_genestr(1,1), m_dict_weights(1,1), m_segment_loss(1,1,2),
m_segment_ids_mask(1,1),
m_scores(1), m_states(1,1), m_positions(1,1)
{
trans_list_forward = NULL ;
trans_list_forward_cnt = NULL ;
trans_list_forward_val = NULL ;
trans_list_forward_id = NULL ;
trans_list_len = 0 ;
mem_initialized = true ;
this->N=1;
m_step=0 ;
#ifdef ARRAY_STATISTICS
word_degree.set_name("word_degree") ;
#endif
}
CDynProg::~CDynProg()
{
if (trans_list_forward_cnt)
delete[] trans_list_forward_cnt ;
if (trans_list_forward)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward[i])
delete[] trans_list_forward[i] ;
delete[] trans_list_forward ;
}
if (trans_list_forward_val)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward_val[i])
delete[] trans_list_forward_val[i] ;
delete[] trans_list_forward_val ;
}
if (trans_list_forward_id)
{
for (INT i=0; i<trans_list_len; i++)
if (trans_list_forward_id[i])
delete[] trans_list_forward_id[i] ;
delete[] trans_list_forward_id ;
}
}
////////////////////////////////////////////////////////////////////////////////
void CDynProg::set_N(INT p_N)
{
N=p_N ;
transition_matrix_a_id.resize_array(N,N) ;
transition_matrix_a.resize_array(N,N) ;
transition_matrix_a_deriv.resize_array(N,N) ;
initial_state_distribution_p.resize_array(N) ;
initial_state_distribution_p_deriv.resize_array(N) ;
end_state_distribution_q.resize_array(N);
end_state_distribution_q_deriv.resize_array(N) ;
m_orf_info.resize_array(N,2) ;
m_PEN.resize_array(N,N) ;
m_PEN_state_signals.resize_array(N,1) ;
}
void CDynProg::set_p_vector(DREAL *p, INT p_N)
{
ASSERT(p_N==N) ;
//m_orf_info.resize_array(p_N,2) ;
//m_PEN.resize_array(p_N,p_N) ;
initial_state_distribution_p.set_array(p, p_N, true, true) ;
}
void CDynProg::set_q_vector(DREAL *q, INT q_N)
{
ASSERT(q_N==N) ;
end_state_distribution_q.set_array(q, q_N, true, true) ;
}
void CDynProg::set_a(DREAL *a, INT p_M, INT p_N)
{
ASSERT(p_N==N) ;
ASSERT(p_M==p_N) ;
transition_matrix_a.set_array(a, p_N, p_N, true, true) ;
transition_matrix_a_deriv.resize_array(p_N, p_N) ;
}
void CDynProg::set_a_id(INT *a, INT p_M, INT p_N)
{
ASSERT(p_N==N) ;
ASSERT(p_M==p_N) ;
transition_matrix_a_id.set_array(a, p_N, p_N, true, true) ;
max_a_id = 0 ;
for (INT i=0; i<p_N; i++)
for (INT j=0; j<p_N; j++)
max_a_id = CMath::max(max_a_id, transition_matrix_a_id.element(i,j)) ;
}
void CDynProg::set_a_trans_matrix(DREAL *a_trans, INT num_trans, INT p_N)
{
ASSERT((p_N==3) || (p_N==4)) ;
delete[] trans_list_forward ;
delete[] trans_list_forward_cnt ;
delete[] trans_list_forward_val ;
delete[] trans_list_forward_id ;
trans_list_forward = NULL ;
trans_list_forward_cnt = NULL ;
trans_list_forward_val = NULL ;
trans_list_len = 0 ;
transition_matrix_a.zero() ;
transition_matrix_a_id.zero() ;
mem_initialized = true ;
trans_list_forward_cnt=NULL ;
trans_list_len = N ;
trans_list_forward = new T_STATES*[N] ;
trans_list_forward_cnt = new T_STATES[N] ;
trans_list_forward_val = new DREAL*[N] ;
trans_list_forward_id = new INT*[N] ;
INT start_idx=0;
for (INT j=0; j<N; j++)
{
INT old_start_idx=start_idx;
while (start_idx<num_trans && a_trans[start_idx+num_trans]==j)
{
start_idx++;
if (start_idx>1 && start_idx<num_trans)
ASSERT(a_trans[start_idx+num_trans-1] <= a_trans[start_idx+num_trans]);
}
if (start_idx>1 && start_idx<num_trans)
ASSERT(a_trans[start_idx+num_trans-1] <= a_trans[start_idx+num_trans]);
INT len=start_idx-old_start_idx;
ASSERT(len>=0);
trans_list_forward_cnt[j] = 0 ;
if (len>0)
{
trans_list_forward[j] = new T_STATES[len] ;
trans_list_forward_val[j] = new DREAL[len] ;
trans_list_forward_id[j] = new INT[len] ;
}
else
{
trans_list_forward[j] = NULL;
trans_list_forward_val[j] = NULL;
trans_list_forward_id[j] = NULL;
}
}
for (INT i=0; i<num_trans; i++)
{
INT from_state = (INT)a_trans[i] ;
INT to_state = (INT)a_trans[i+num_trans] ;
DREAL val = a_trans[i+num_trans*2] ;
INT id = 0 ;
if (p_N==4)
id = (INT)a_trans[i+num_trans*3] ;
//SG_DEBUG( "id=%i\n", id) ;
ASSERT(to_state>=0 && to_state<N) ;
ASSERT(from_state>=0 && from_state<N) ;
trans_list_forward[to_state][trans_list_forward_cnt[to_state]]=from_state ;
trans_list_forward_val[to_state][trans_list_forward_cnt[to_state]]=val ;
trans_list_forward_id[to_state][trans_list_forward_cnt[to_state]]=id ;
trans_list_forward_cnt[to_state]++ ;
transition_matrix_a.element(from_state, to_state) = val ;
transition_matrix_a_id.element(from_state, to_state) = id ;
} ;
max_a_id = 0 ;
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
//if (transition_matrix_a_id.element(i,j))
//SG_DEBUG( "(%i,%i)=%i\n", i,j, transition_matrix_a_id.element(i,j)) ;
max_a_id = CMath::max(max_a_id, transition_matrix_a_id.element(i,j)) ;
}
//SG_DEBUG( "max_a_id=%i\n", max_a_id) ;
}
void CDynProg::init_svm_arrays(INT p_num_degrees, INT p_num_svms)
{
svm_arrays_clean=false ;
word_degree.resize_array(num_degrees) ;
cum_num_words.resize_array(num_degrees+1) ;
cum_num_words_array=cum_num_words.get_array() ;
num_words.resize_array(num_degrees) ;
num_words_array=num_words.get_array() ;
//svm_values_unnormalized.resize_array(num_degrees, num_svms) ;
svm_pos_start.resize_array(num_degrees) ;
num_unique_words.resize_array(num_degrees) ;
}
void CDynProg::init_word_degree_array(INT * p_word_degree_array, INT num_elem)
{
svm_arrays_clean=false ;
word_degree.resize_array(num_degrees) ;
ASSERT(num_degrees==num_elem) ;
for (INT i=0; i<num_degrees; i++)
word_degree[i]=p_word_degree_array[i] ;
}
void CDynProg::init_cum_num_words_array(INT * p_cum_num_words_array, INT num_elem)
{
svm_arrays_clean=false ;
cum_num_words.resize_array(num_degrees+1) ;
cum_num_words_array=cum_num_words.get_array() ;
ASSERT(num_degrees+1==num_elem) ;
for (INT i=0; i<num_degrees+1; i++)
cum_num_words[i]=p_cum_num_words_array[i] ;
}
void CDynProg::init_num_words_array(INT * p_num_words_array, INT num_elem)
{
svm_arrays_clean=false ;
num_words.resize_array(num_degrees) ;
num_words_array=num_words.get_array() ;
ASSERT(num_degrees==num_elem) ;
for (INT i=0; i<num_degrees; i++)
num_words[i]=p_num_words_array[i] ;
//word_used.resize_array(num_degrees, num_words[num_degrees-1], num_strings) ;
//word_used_array=word_used.get_array() ;
}
void CDynProg::init_mod_words_array(INT * p_mod_words_array, INT num_elem, INT num_columns)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
ASSERT(num_columns==2) ;
mod_words.set_array(p_mod_words_array, num_elem, 2, true, true) ;
mod_words_array = mod_words.get_array() ;
/*SG_DEBUG( "mod_words=[") ;
for (INT i=0; i<num_elem; i++)
SG_DEBUG( "%i, ", p_mod_words_array[i]) ;
SG_DEBUG( "]\n") ;*/
}
void CDynProg::init_sign_words_array(bool* p_sign_words_array, INT num_elem)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
sign_words.set_array(p_sign_words_array, num_elem, true, true) ;
sign_words_array = sign_words.get_array() ;
}
void CDynProg::init_string_words_array(INT* p_string_words_array, INT num_elem)
{
svm_arrays_clean=false ;
ASSERT(num_svms==num_elem) ;
string_words.set_array(p_string_words_array, num_elem, true, true) ;
string_words_array = string_words.get_array() ;
}
bool CDynProg::check_svm_arrays()
{
//SG_DEBUG( "wd_dim1=%d, cum_num_words=%d, num_words=%d, svm_pos_start=%d, num_uniq_w=%d, mod_words_dims=(%d,%d), sign_w=%d,string_w=%d\n num_degrees=%d, num_svms=%d, num_strings=%d", word_degree.get_dim1(), cum_num_words.get_dim1(), num_words.get_dim1(), svm_pos_start.get_dim1(), num_unique_words.get_dim1(), mod_words.get_dim1(), mod_words.get_dim2(), sign_words.get_dim1(), string_words.get_dim1(), num_degrees, num_svms, num_strings);
if ((word_degree.get_dim1()==num_degrees) &&
(cum_num_words.get_dim1()==num_degrees+1) &&
(num_words.get_dim1()==num_degrees) &&
//(word_used.get_dim1()==num_degrees) &&
//(word_used.get_dim2()==num_words[num_degrees-1]) &&
//(word_used.get_dim3()==num_strings) &&
// (svm_values_unnormalized.get_dim1()==num_degrees) &&
// (svm_values_unnormalized.get_dim2()==num_svms) &&
(svm_pos_start.get_dim1()==num_degrees) &&
(num_unique_words.get_dim1()==num_degrees) &&
(mod_words.get_dim1()==num_svms) &&
(mod_words.get_dim2()==2) &&
(sign_words.get_dim1()==num_svms) &&
(string_words.get_dim1()==num_svms))
{
svm_arrays_clean=true ;
return true ;
}
else
{
if ((num_unique_words.get_dim1()==num_degrees) &&
(mod_words.get_dim1()==num_svms) &&
(mod_words.get_dim2()==2) &&
(sign_words.get_dim1()==num_svms) &&
(string_words.get_dim1()==num_svms))
fprintf(stderr, "OK\n") ;
else
fprintf(stderr, "not OK\n") ;
if (!(word_degree.get_dim1()==num_degrees))
SG_WARNING("SVM array: word_degree.get_dim1()!=num_degrees") ;
if (!(cum_num_words.get_dim1()==num_degrees+1))
SG_WARNING("SVM array: cum_num_words.get_dim1()!=num_degrees+1") ;
if (!(num_words.get_dim1()==num_degrees))
SG_WARNING("SVM array: num_words.get_dim1()==num_degrees") ;
if (!(svm_pos_start.get_dim1()==num_degrees))
SG_WARNING("SVM array: svm_pos_start.get_dim1()!=num_degrees") ;
if (!(num_unique_words.get_dim1()==num_degrees))
SG_WARNING("SVM array: num_unique_words.get_dim1()!=num_degrees") ;
if (!(mod_words.get_dim1()==num_svms))
SG_WARNING("SVM array: mod_words.get_dim1()!=num_svms") ;
if (!(mod_words.get_dim2()==2))
SG_WARNING("SVM array: mod_words.get_dim2()!=2") ;
if (!(sign_words.get_dim1()==num_svms))
SG_WARNING("SVM array: sign_words.get_dim1()!=num_svms") ;
if (!(string_words.get_dim1()==num_svms))
SG_WARNING("SVM array: string_words.get_dim1()!=num_svms") ;
svm_arrays_clean=false ;
return false ;
}
}
void CDynProg::best_path_set_seq(DREAL *seq, INT p_N, INT seq_len)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
ASSERT(p_N==N) ;
ASSERT(initial_state_distribution_p.get_dim1()==N) ;
ASSERT(end_state_distribution_q.get_dim1()==N) ;
m_seq.set_array(seq, N, seq_len, 1, true, true) ;
this->N=N ;
m_call=3 ;
m_step=2 ;
}
void CDynProg::best_path_set_seq3d(DREAL *seq, INT p_N, INT seq_len, INT max_num_signals)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
ASSERT(p_N==N) ;
ASSERT(initial_state_distribution_p.get_dim1()==N) ;
ASSERT(end_state_distribution_q.get_dim1()==N) ;
m_seq.set_array(seq, N, seq_len, max_num_signals, true, true) ;
this->N=N ;
m_call=3 ;
m_step=2 ;
}
void CDynProg::best_path_set_pos(INT *pos, INT seq_len)
{
if (m_step!=2)
SG_ERROR( "please call best_path_set_seq first\n") ;
if (seq_len!=m_seq.get_dim2())
SG_ERROR( "pos size does not match previous info %i!=%i\n", seq_len, m_seq.get_dim2()) ;
m_pos.set_array(pos, seq_len, true, true) ;
m_step=3 ;
}
void CDynProg::best_path_set_orf_info(INT *orf_info, INT m, INT n)
{
if (m_step!=3)
SG_ERROR( "please call best_path_set_pos first\n") ;
if (m!=N)
SG_ERROR( "orf_info size does not match previous info %i!=%i\n", m, N) ;
if (n!=2)
SG_ERROR( "orf_info size incorrect %i!=2\n", n) ;
m_orf_info.set_array(orf_info, m, n, true, true) ;
m_call=1 ;
m_step=4 ;
}
void CDynProg::best_path_set_segment_sum_weights(DREAL *segment_sum_weights, INT num_states, INT seq_len)
{
if (m_step!=3)
SG_ERROR( "please call best_path_set_pos first\n") ;
if (num_states!=N)
SG_ERROR( "segment_sum_weights size does not match previous info %i!=%i\n", num_states, N) ;
if (seq_len!=m_pos.get_dim1())
SG_ERROR( "segment_sum_weights size incorrect %i!=%i\n", seq_len, m_pos.get_dim1()) ;
m_segment_sum_weights.set_array(segment_sum_weights, num_states, seq_len, true, true) ;
m_call=2 ;
m_step=4 ;
}
void CDynProg::best_path_set_plif_list(CDynamicArray<CPlifBase*>* plifs)
{
ASSERT(plifs);
CPlifBase** plif_list=plifs->get_array();
INT num_plif=plifs->get_num_elements();
if (m_step!=4)
SG_ERROR( "please call best_path_set_orf_info or best_path_segment_sum_weights first\n") ;
m_plif_list.set_array(plif_list, num_plif, true, true) ;
m_step=5 ;
}
void CDynProg::best_path_set_plif_id_matrix(INT *plif_id_matrix, INT m, INT n)
{
if (m_step!=5)
SG_ERROR( "please call best_path_set_plif_list first\n") ;
if ((m!=N) || (n!=N))
SG_ERROR( "plif_id_matrix size does not match previous info %i!=%i or %i!=%i\n", m, N, n, N) ;
CArray2<INT> id_matrix(plif_id_matrix, N, N, false, false) ;
#ifdef DYNPROG_DEBUG
id_matrix.set_name("id_matrix");
id_matrix.display_array();
#endif //DYNPROG_DEBUG
m_PEN.resize_array(N, N) ;
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
if (id_matrix.element(i,j)>=0)
m_PEN.element(i,j)=m_plif_list[id_matrix.element(i,j)] ;
else
m_PEN.element(i,j)=NULL ;
m_step=6 ;
}
void CDynProg::best_path_set_plif_state_signal_matrix(INT *plif_id_matrix, INT m, INT max_num_signals)
{
if (m_step!=6)
SG_ERROR( "please call best_path_set_plif_id_matrix first\n") ;
if (m!=N)
SG_ERROR( "plif_state_signal_matrix size does not match previous info %i!=%i\n", m, N) ;
if (m_seq.get_dim3() != max_num_signals)
SG_ERROR( "size(plif_state_signal_matrix,2) does not match with size(m_seq,3): %i!=%i\nSorry, Soeren... interface changed\n", m_seq.get_dim3(), max_num_signals) ;
CArray2<INT> id_matrix(plif_id_matrix, N, max_num_signals, false, false) ;
m_PEN_state_signals.resize_array(N, max_num_signals) ;
for (INT i=0; i<N; i++)
{
for (INT j=0; j<max_num_signals; j++)
{
if (id_matrix.element(i,j)>=0)
m_PEN_state_signals.element(i,j)=m_plif_list[id_matrix.element(i,j)] ;
else
m_PEN_state_signals.element(i,j)=NULL ;
}
}
m_step=6 ;
}
void CDynProg::best_path_set_genestr(CHAR* genestr, INT genestr_len, INT genestr_num)
{
if (m_step!=6)
SG_ERROR( "please call best_path_set_plif_id_matrix first\n") ;
ASSERT(genestr);
ASSERT(genestr_len>0);
ASSERT(genestr_num>0);
m_genestr.set_array(genestr, genestr_len, genestr_num, true, true) ;
m_step=7 ;
}
void CDynProg::best_path_set_my_state_seq(INT* my_state_seq, INT seq_len)
{
ASSERT(my_state_seq && seq_len>0);
m_my_state_seq.resize_array(seq_len);
for (INT i=0; i<seq_len; i++)
m_my_state_seq[i]=my_state_seq[i];
}
void CDynProg::best_path_set_my_pos_seq(INT* my_pos_seq, INT seq_len)
{
ASSERT(my_pos_seq && seq_len>0);
m_my_pos_seq.resize_array(seq_len);
for (INT i=0; i<seq_len; i++)
m_my_pos_seq[i]=my_pos_seq[i];
}
void CDynProg::best_path_set_dict_weights(DREAL* dictionary_weights, INT dict_len, INT n)
{
if (m_step!=7)
SG_ERROR( "please call best_path_set_genestr first\n") ;
if (num_svms!=n)
SG_ERROR( "dict_weights array does not match num_svms=%i!=%i\n", num_svms, n) ;
m_dict_weights.set_array(dictionary_weights, dict_len, num_svms, true, true) ;
// initialize, so it does not bother when not used
m_segment_loss.resize_array(max_a_id+1, max_a_id+1, 2) ;
m_segment_loss.zero() ;
m_segment_ids_mask.resize_array(2, m_seq.get_dim2()) ;
m_segment_ids_mask.zero() ;
m_step=8 ;
}
void CDynProg::best_path_set_segment_loss(DREAL* segment_loss, INT m, INT n)
{
// here we need two matrices. Store it in one: 2N x N
if (2*m!=n)
SG_ERROR( "segment_loss should be 2 x quadratic matrix: %i!=%i\n", m, 2*n) ;
if (m!=max_a_id+1)
SG_ERROR( "segment_loss size should match max_a_id: %i!=%i\n", m, max_a_id+1) ;
m_segment_loss.set_array(segment_loss, m, n/2, 2, true, true) ;
/*for (INT i=0; i<n; i++)
for (INT j=0; j<n; j++)
SG_DEBUG( "loss(%i,%i)=%f\n", i,j, m_segment_loss.element(0,i,j)) ;*/
}
void CDynProg::best_path_set_segment_ids_mask(INT* segment_ids_mask, INT m, INT n)
{
if (m!=2)// || n!=m_seq.get_dim2())
SG_ERROR( "segment_ids_mask should be a 2 x seq_len matrix: %i!=2 and %i!=%i\n", m, m_seq.get_dim2(), n) ;
m_segment_ids_mask.set_array(segment_ids_mask, m, n, true, true) ;
}
void CDynProg::best_path_call(INT nbest, bool use_orf)
{
if (m_step!=8)
SG_ERROR( "please call best_path_set_dict_weights first\n") ;
if (m_call!=1)
SG_ERROR( "please call best_path_set_orf_info first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_positions.resize_array(nbest, m_seq.get_dim2()) ;
m_call=1 ;
assert(nbest==1|nbest==2) ;
assert(m_genestr.get_dim2()==1) ;
if (nbest==1)
best_path_trans<1,false,false>(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_orf_info.get_array(), m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
use_orf) ;
else
best_path_trans<2,false,false>(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_orf_info.get_array(), m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
use_orf) ;
m_step=9 ;
}
void CDynProg::best_path_deriv_call()
{
//if (m_step!=8)
//SG_ERROR( "please call best_path_set_dict_weights first\n") ;
//if (m_call!=1)
//SG_ERROR( "please call best_path_set_orf_info first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_call=5 ; // or so ...
m_my_scores.resize_array(m_my_state_seq.get_array_size()) ;
m_my_losses.resize_array(m_my_state_seq.get_array_size()) ;
best_path_trans_deriv(m_my_state_seq.get_array(), m_my_pos_seq.get_array(),
m_my_scores.get_array(), m_my_losses.get_array(), m_my_state_seq.get_array_size(),
m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_PEN.get_array(),
m_PEN_state_signals.get_array(), m_PEN_state_signals.get_dim2(),
m_genestr.get_array(), m_genestr.get_dim1(), m_genestr.get_dim2(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2()) ;
m_step=12 ;
}
void CDynProg::best_path_2struct_call(INT nbest)
{
if (m_step!=8)
SG_ERROR( "please call best_path_set_orf_dict_weights first\n") ;
if (m_call!=2)
SG_ERROR( "please call best_path_set_segment_sum_weights first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
ASSERT(m_seq.get_dim2()==m_pos.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_positions.resize_array(nbest, m_seq.get_dim2()) ;
m_call=2 ;
best_path_2struct(m_seq.get_array(), m_seq.get_dim2(), m_pos.get_array(),
m_PEN.get_array(),
m_genestr.get_array(), m_genestr.get_dim1(),
nbest,
m_scores.get_array(), m_states.get_array(), m_positions.get_array(),
m_dict_weights.get_array(), m_dict_weights.get_dim1()*m_dict_weights.get_dim2(),
m_segment_sum_weights.get_array()) ;
m_step=9 ;
}
void CDynProg::best_path_simple_call(INT nbest)
{
if (m_step!=2)
SG_ERROR( "please call best_path_set_seq first\n") ;
if (m_call!=3)
SG_ERROR( "please call best_path_set_seq first\n") ;
ASSERT(N==m_seq.get_dim1()) ;
m_scores.resize_array(nbest) ;
m_states.resize_array(nbest, m_seq.get_dim2()) ;
m_call=3 ;
best_path_trans_simple(m_seq.get_array(), m_seq.get_dim2(),
nbest,
m_scores.get_array(), m_states.get_array()) ;
m_step=9 ;
}
void CDynProg::best_path_deriv_call(INT nbest)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
//FIXME
}
void CDynProg::best_path_get_scores(DREAL **scores, INT *m)
{
if (m_step!=9 && m_step!=12)
SG_ERROR( "please call best_path*_call first\n") ;
if (m_step==9)
{
*scores=m_scores.get_array() ;
*m=m_scores.get_dim1() ;
} else
{
*scores=m_my_scores.get_array() ;
*m=m_my_scores.get_dim1() ;
}
m_step=10 ;
}
void CDynProg::best_path_get_states(INT **states, INT *m, INT *n)
{
if (m_step!=10)
SG_ERROR( "please call best_path_get_score first\n") ;
*states=m_states.get_array() ;
*m=m_states.get_dim1() ;
*n=m_states.get_dim2() ;
m_step=11 ;
}
void CDynProg::best_path_get_positions(INT **positions, INT *m, INT *n)
{
if (m_step!=11)
SG_ERROR( "please call best_path_get_positions first\n") ;
if (m_call==3)
SG_ERROR( "no position information for best_path_simple\n") ;
*positions=m_positions.get_array() ;
*m=m_positions.get_dim1() ;
*n=m_positions.get_dim2() ;
}
void CDynProg::best_path_get_losses(DREAL** losses, INT* seq_len)
{
ASSERT(losses && seq_len);
*losses=m_my_losses.get_array();
*seq_len=m_my_losses.get_dim1();
}
////////////////////////////////////////////////////////////////////////////////
DREAL CDynProg::best_path_no_b(INT max_iter, INT &best_iter, INT *my_path)
{
CArray2<T_STATES> psi(max_iter, N) ;
CArray<DREAL>* delta = new CArray<DREAL>(N) ;
CArray<DREAL>* delta_new = new CArray<DREAL>(N) ;
{ // initialization
for (INT i=0; i<N; i++)
{
delta->element(i) = get_p(i) ;
psi.element(0, i)= 0 ;
}
}
DREAL best_iter_prob = CMath::ALMOST_NEG_INFTY ;
best_iter = 0 ;
// recursion
for (INT t=1; t<max_iter; t++)
{
CArray<DREAL>* dummy;
INT NN=N ;
for (INT j=0; j<NN; j++)
{
DREAL maxj = delta->element(0) + transition_matrix_a.element(0,j);
INT argmax=0;
for (INT i=1; i<NN; i++)
{
DREAL temp = delta->element(i) + transition_matrix_a.element(i,j);
if (temp>maxj)
{
maxj=temp;
argmax=i;
}
}
delta_new->element(j)=maxj ;
psi.element(t, j)=argmax ;
}
dummy=delta;
delta=delta_new;
delta_new=dummy; //switch delta/delta_new
{ //termination
DREAL maxj=delta->element(0)+get_q(0);
INT argmax=0;
for (INT i=1; i<N; i++)
{
DREAL temp=delta->element(i)+get_q(i);
if (temp>maxj)
{
maxj=temp;
argmax=i;
}
}
//pat_prob=maxj;
if (maxj>best_iter_prob)
{
my_path[t]=argmax;
best_iter=t ;
best_iter_prob = maxj ;
} ;
} ;
}
{ //state sequence backtracking
for (INT t = best_iter; t>0; t--)
{
my_path[t-1]=psi.element(t, my_path[t]);
}
}
delete delta ;
delete delta_new ;
return best_iter_prob ;
}
void CDynProg::best_path_no_b_trans(INT max_iter, INT &max_best_iter, short int nbest, DREAL *prob_nbest, INT *my_paths)
{
//T_STATES *psi=new T_STATES[max_iter*N*nbest] ;
CArray3<T_STATES> psi(max_iter, N, nbest) ;
CArray3<short int> ktable(max_iter, N, nbest) ;
CArray2<short int> ktable_ends(max_iter, nbest) ;
CArray<DREAL> tempvv(nbest*N) ;
CArray<INT> tempii(nbest*N) ;
CArray2<T_STATES> path_ends(max_iter, nbest) ;
CArray2<DREAL> *delta=new CArray2<DREAL>(N, nbest) ;
CArray2<DREAL> *delta_new=new CArray2<DREAL>(N, nbest) ;
CArray2<DREAL> delta_end(max_iter, nbest) ;
CArray2<INT> paths(max_iter, nbest) ;
paths.set_array(my_paths, max_iter, nbest, false, false) ;
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta->element(i,0) = get_p(i) ;
for (short int k=1; k<nbest; k++)
{
delta->element(i,k)=-CMath::INFTY ;
ktable.element(0,i,k)=0 ;
}
}
}
// recursion
for (INT t=1; t<max_iter; t++)
{
CArray2<DREAL>* dummy=NULL;
for (T_STATES j=0; j<N; j++)
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT list_len=0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
tempvv.element(list_len) = -(delta->element(ii,diff) + elem_val[i]) ;
tempii.element(list_len) = diff*N + ii ;
list_len++ ;
}
}
CMath::qsort_index(tempvv.get_array(), tempii.get_array(), list_len) ;
for (short int k=0; k<nbest; k++)
{
if (k<list_len)
{
delta_new->element(j,k) = -tempvv[k] ;
psi.element(t,j,k) = (tempii[k]%N) ;
ktable.element(t,j,k) = (tempii[k]-(tempii[k]%N))/N ;
}
else
{
delta_new->element(j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
}
}
}
dummy=delta;
delta=delta_new;
delta_new=dummy; //switch delta/delta_new
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
tempvv.element(list_len) = -(delta->element(i,diff)+get_q(i));
tempii.element(list_len) = diff*N + i ;
list_len++ ;
}
}
CMath::qsort_index(tempvv.get_array(), tempii.get_array(), list_len) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(t-1,k) = -tempvv[k] ;
path_ends.element(t-1,k) = (tempii[k]%N) ;
ktable_ends.element(t-1,k) = (tempii[k]-(tempii[k]%N))/N ;
}
}
}
{ //state sequence backtracking
max_best_iter=0 ;
CArray<DREAL> sort_delta_end(max_iter*nbest) ;
CArray<short int> sort_k(max_iter*nbest) ;
CArray<INT> sort_t(max_iter*nbest) ;
CArray<INT> sort_idx(max_iter*nbest) ;
INT i=0 ;
for (INT iter=0; iter<max_iter-1; iter++)
for (short int k=0; k<nbest; k++)
{
sort_delta_end[i]=-delta_end.element(iter,k) ;
sort_k[i]=k ;
sort_t[i]=iter+1 ;
sort_idx[i]=i ;
i++ ;
}
CMath::qsort_index(sort_delta_end.get_array(), sort_idx.get_array(), (max_iter-1)*nbest) ;
for (short int n=0; n<nbest; n++)
{
short int k=sort_k[sort_idx[n]] ;
INT iter=sort_t[sort_idx[n]] ;
prob_nbest[n]=-sort_delta_end[n] ;
if (iter>max_best_iter)
max_best_iter=iter ;
ASSERT(k<nbest) ;
ASSERT(iter<max_iter) ;
paths.element(iter,n) = path_ends.element(iter-1, k) ;
short int q = ktable_ends.element(iter-1, k) ;
for (INT t = iter; t>0; t--)
{
paths.element(t-1,n)=psi.element(t, paths.element(t,n), q);
q = ktable.element(t, paths.element(t,n), q) ;
}
}
}
delete delta ;
delete delta_new ;
}
void CDynProg::translate_from_single_order(WORD* obs, INT sequence_length,
INT start, INT order,
INT max_val)
{
INT i,j;
WORD value=0;
for (i=sequence_length-1; i>= ((int) order)-1; i--) //convert interval of size T
{
value=0;
for (j=i; j>=i-((int) order)+1; j--)
value= (value >> max_val) | (obs[j] << (max_val * (order-1)));
obs[i]= (WORD) value;
}
for (i=order-2;i>=0;i--)
{
value=0;
for (j=i; j>=i-order+1; j--)
{
value= (value >> max_val);
if (j>=0)
value|=obs[j] << (max_val * (order-1));
}
obs[i]=value;
//ASSERT(value<num_words) ;
}
if (start>0)
for (i=start; i<sequence_length; i++)
obs[i-start]=obs[i];
}
void CDynProg::reset_svm_value(INT pos, INT & last_svm_pos, DREAL * svm_value)
{
for (int i=0; i<num_words_single; i++)
word_used_single[i]=false ;
for (INT s=0; s<num_svms; s++)
svm_value_unnormalized_single[s] = 0 ;
for (INT s=0; s<num_svms; s++)
svm_value[s] = 0 ;
last_svm_pos = pos - 6+1 ;
num_unique_words_single=0 ;
}
void CDynProg::extend_svm_value(WORD* wordstr, INT pos, INT &last_svm_pos, DREAL* svm_value)
{
bool did_something = false ;
for (int i=last_svm_pos-1; (i>=pos) && (i>=0); i--)
{
if (wordstr[i]>=num_words_single)
SG_DEBUG( "wordstr[%i]=%i\n", i, wordstr[i]) ;
if (!word_used_single[wordstr[i]])
{
for (INT s=0; s<num_svms_single; s++)
svm_value_unnormalized_single[s]+=dict_weights.element(wordstr[i],s) ;
word_used_single[wordstr[i]]=true ;
num_unique_words_single++ ;
did_something=true ;
}
} ;
if (num_unique_words_single>0)
{
last_svm_pos=pos ;
if (did_something)
for (INT s=0; s<num_svms; s++)
svm_value[s]= svm_value_unnormalized_single[s]/sqrt((double)num_unique_words_single) ; // full normalization
}
else
{
// what should I do?
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
}
void CDynProg::reset_segment_sum_value(INT num_states, INT pos, INT & last_segment_sum_pos, DREAL * segment_sum_value)
{
for (INT s=0; s<num_states; s++)
segment_sum_value[s] = 0 ;
last_segment_sum_pos = pos ;
//SG_DEBUG( "start: %i\n", pos) ;
}
void CDynProg::extend_segment_sum_value(DREAL *segment_sum_weights, INT seqlen, INT num_states,
INT pos, INT &last_segment_sum_pos, DREAL* segment_sum_value)
{
for (int i=last_segment_sum_pos-1; (i>=pos) && (i>=0); i--)
{
for (INT s=0; s<num_states; s++)
segment_sum_value[s] += segment_sum_weights[i*num_states+s] ;
} ;
//SG_DEBUG( "extend %i: %f\n", pos, segment_sum_value[0]) ;
last_segment_sum_pos = pos ;
}
void CDynProg::best_path_2struct(const DREAL *seq_array, INT seq_len, const INT *pos,
CPlifBase **Plif_matrix,
const char *genestr, INT genestr_len,
short int nbest,
DREAL *prob_nbest, INT *my_state_seq, INT *my_pos_seq,
DREAL *dictionary_weights, INT dict_len, DREAL *segment_sum_weights)
{
const INT default_look_back = 100 ;
INT max_look_back = default_look_back ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*num_words_single) ;
dict_weights.set_array(dictionary_weights, dict_len, num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false) ;
CArray2<DREAL> seq((DREAL *)seq_array, N, seq_len, false) ;
DREAL svm_value[num_svms] ;
DREAL segment_sum_value[N] ;
{ // initialize svm_svalue
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
{ // determine maximal length of look-back
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->get_max_value()>max_look_back)
max_look_back=(INT) CMath::ceil(penij->get_max_value());
if (penij->uses_svm_values())
use_svm=true ;
}
}
max_look_back = CMath::min(genestr_len, max_look_back) ;
//SG_DEBUG("use_svm=%i\n", use_svm) ;
//SG_DEBUG("max_look_back=%i\n", max_look_back) ;
const INT look_back_buflen = (max_look_back+1)*nbest*N ;
//SG_DEBUG("look_back_buflen=%i\n", look_back_buflen) ;
const DREAL mem_use = (DREAL)(seq_len*N*nbest*(sizeof(T_STATES)+sizeof(short int)+sizeof(INT))+
look_back_buflen*(2*sizeof(DREAL)+sizeof(INT))+
seq_len*(sizeof(T_STATES)+sizeof(INT))+
genestr_len*sizeof(bool))/(1024*1024)
;
bool is_big = (mem_use>200) || (seq_len>5000) ;
if (is_big)
{
SG_DEBUG("calling best_path_2struct: seq_len=%i, N=%i, lookback=%i nbest=%i\n",
seq_len, N, max_look_back, nbest) ;
SG_DEBUG("allocating %1.2fMB of memory\n",
mem_use) ;
}
ASSERT(nbest<32000) ;
CArray3<DREAL> delta(max_look_back+1, N, nbest) ;
CArray3<T_STATES> psi(seq_len,N,nbest) ;
CArray3<short int> ktable(seq_len,N,nbest) ;
CArray3<INT> ptable(seq_len,N,nbest) ;
CArray<DREAL> delta_end(nbest) ;
CArray<T_STATES> path_ends(nbest) ;
CArray<short int> ktable_end(nbest) ;
CArray<DREAL> tempvv(look_back_buflen) ;
CArray<INT> tempii(look_back_buflen) ;
CArray<T_STATES> state_seq(seq_len) ;
CArray<INT> pos_seq(seq_len) ;
// translate to words, if svm is used
WORD* wordstr=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[i]=0 ; break ;
case 'C':
case 'c': wordstr[i]=1 ; break ;
case 'G':
case 'g': wordstr[i]=2 ; break ;
case 'T':
case 't': wordstr[i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr, genestr_len, word_degree_single-1, word_degree_single) ;
}
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta.element(0,i,0) = get_p(i) + seq.element(i,0) ;
psi.element(0,i,0) = 0 ;
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
delta.element(0,i,k) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ;
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
// recursion
for (INT t=1; t<seq_len; t++)
{
if (is_big && t%(seq_len/10000)==1)
SG_PROGRESS(t, 0, seq_len);
//fprintf(stderr, "%i\n", t) ;
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(t%max_look_back,j,k) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT list_len=0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
//SG_DEBUG( "i=%i ii=%i num_elem=%i PEN=%ld\n", i, ii, num_elem, PEN(j,ii)) ;
const CPlifBase * penalty = PEN.element(j,ii) ;
INT look_back = default_look_back ;
if (penalty!=NULL)
look_back=(INT) (CMath::ceil(penalty->get_max_value()));
INT last_svm_pos ;
if (use_svm)
reset_svm_value(pos[t], last_svm_pos, svm_value) ;
INT last_segment_sum_pos ;
reset_segment_sum_value(N, pos[t], last_segment_sum_pos, segment_sum_value) ;
for (INT ts=t-1; ts>=0 && pos[t]-pos[ts]<=look_back; ts--)
{
if (use_svm)
extend_svm_value(wordstr, pos[ts], last_svm_pos, svm_value) ;
extend_segment_sum_value(segment_sum_weights, seq_len, N, pos[ts], last_segment_sum_pos, segment_sum_value) ;
DREAL pen_val = 0.0 ;
if (penalty)
pen_val=penalty->lookup_penalty(pos[t]-pos[ts], svm_value) + segment_sum_value[j] ;
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = delta.element(ts%max_look_back,ii,diff) + elem_val[i] ;
val += pen_val ;
tempvv[list_len] = -val ;
tempii[list_len] = ii + diff*N + ts*N*nbest;
//SG_DEBUG( "%i (%i,%i,%i, %i, %i) ", list_len, diff, ts, i, pos[t]-pos[ts], look_back) ;
list_len++ ;
}
}
}
CMath::nmin<INT>(tempvv.get_array(), tempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
if (k<list_len)
{
delta.element(t%max_look_back,j,k) = -tempvv[k] + seq.element(j,t);
psi.element(t,j,k) = (tempii[k]%N) ;
ktable.element(t,j,k) = (tempii[k]%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (tempii[k]-(tempii[k]%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(t%max_look_back,j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
tempvv[list_len] = -(delta.element((seq_len-1)%max_look_back,i,diff)+get_q(i)) ;
tempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(tempvv.get_array(), tempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -tempvv[k] ;
path_ends.element(k) = (tempii[k]%N) ;
ktable_end.element(k) = (tempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*(seq_len+1)] = state_seq[num_states-i-1] ;
my_pos_seq[i+k*(seq_len+1)] = pos_seq[num_states-i-1] ;
}
my_state_seq[num_states+k*(seq_len+1)]=-1 ;
my_pos_seq[num_states+k*(seq_len+1)]=-1 ;
}
}
if (is_big)
SG_PRINT( "DONE. \n") ;
}
/*void CDynProg::reset_svm_values(INT pos, INT * last_svm_pos, DREAL * svm_value)
{
for (INT j=0; j<num_degrees; j++)
{
for (INT i=0; i<num_words_array[j]; i++)
word_used.element(word_used_array, j, i, num_degrees)=false ;
for (INT s=0; s<num_svms; s++)
svm_values_unnormalized.element(j,s) = 0 ;
num_unique_words[j]=0 ;
last_svm_pos[j] = pos - word_degree[j]+1 ;
svm_pos_start[j] = pos - word_degree[j] ;
}
for (INT s=0; s<num_svms; s++)
svm_value[s] = 0 ;
}
void CDynProg::extend_svm_values(WORD** wordstr, INT pos, INT *last_svm_pos, DREAL* svm_value)
{
bool did_something = false ;
for (INT j=0; j<num_degrees; j++)
{
for (int i=last_svm_pos[j]-1; (i>=pos) && (i>=0); i--)
{
if (wordstr[j][i]>=num_words_array[j])
SG_DEBUG( "wordstr[%i]=%i\n", i, wordstr[j][i]) ;
ASSERT(wordstr[j][i]<num_words_array[j]) ;
if (!word_used.element(word_used_array, j, wordstr[j][i], num_degrees))
{
for (INT s=0; s<num_svms; s++)
svm_values_unnormalized.element(j,s)+=dict_weights_array[wordstr[j][i]+cum_num_words_array[j]+s*cum_num_words_array[num_degrees]] ;
//svm_values_unnormalized.element(j,s)+=dict_weights.element(wordstr[j][i]+cum_num_words_array[j],s) ;
//word_used.element(j,wordstr[j][i])=true ;
word_used.element(word_used_array, j, wordstr[j][i], num_degrees)=true ;
num_unique_words[j]++ ;
did_something=true ;
} ;
} ;
if (num_unique_words[j]>0)
last_svm_pos[j]=pos ;
} ;
if (did_something)
for (INT s=0; s<num_svms; s++)
{
svm_value[s]=0.0 ;
for (INT j=0; j<num_degrees; j++)
if (num_unique_words[j]>0)
svm_value[s]+= svm_values_unnormalized.element(j,s)/sqrt((double)num_unique_words[j]) ; // full normalization
}
}
*/
void CDynProg::init_segment_loss(struct segment_loss_struct & loss, INT seqlen, INT howmuchlookback)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
INT clear_size = CMath::min(howmuchlookback,seqlen) ;
if (!loss.num_segment_id)
{
loss.segments_changed = new INT[seqlen] ;
loss.num_segment_id = new INT[(max_a_id+1)*seqlen] ;
loss.length_segment_id = new INT[(max_a_id+1)*seqlen] ;
clear_size = seqlen ;
}
for (INT j=0; j<clear_size; j++)
{
loss.segments_changed[j]=0 ;
for (INT i=0; i<max_a_id+1; i++)
{
loss.num_segment_id[i*seqlen+j] = 0;
loss.length_segment_id[i*seqlen+j] = 0;
}
}
loss.maxlookback = howmuchlookback ;
loss.seqlen = seqlen;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_init_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::clear_segment_loss(struct segment_loss_struct & loss)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (loss.num_segment_id != NULL)
{
delete[] loss.segments_changed ;
delete[] loss.num_segment_id ;
delete[] loss.length_segment_id ;
loss.segments_changed = NULL ;
loss.num_segment_id = NULL ;
loss.length_segment_id = NULL ;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_clean_time += MyTime.time_diff_sec() ;
#endif
}
DREAL CDynProg::extend_segment_loss(struct segment_loss_struct & loss, const INT * pos_array, INT segment_id, INT pos, INT & last_pos, DREAL &last_value)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (pos==last_pos)
return last_value ;
ASSERT(pos<last_pos) ;
last_pos-- ;
bool changed = false ;
while (last_pos>=pos)
{
if (loss.segments_changed[last_pos])
{
changed=true ;
break ;
}
last_pos-- ;
}
if (last_pos<pos)
last_pos = pos ;
if (!changed)
{
ASSERT(last_pos>=0) ;
ASSERT(last_pos<loss.seqlen) ;
DREAL length_contrib = (pos_array[last_pos]-pos_array[pos])*m_segment_loss.element(m_segment_ids_mask.element(0, pos), segment_id, 1) ;
DREAL ret = last_value + length_contrib ;
last_pos = pos ;
return ret ;
}
CArray2<INT> num_segment_id(loss.num_segment_id, loss.seqlen, max_a_id+1, false, false) ;
CArray2<INT> length_segment_id(loss.length_segment_id, loss.seqlen, max_a_id+1, false, false) ;
DREAL ret = 0.0 ;
for (INT i=0; i<max_a_id+1; i++)
{
//SG_DEBUG( "%i: %i, %i, %f (%f), %f (%f)\n", pos, num_segment_id.element(pos, i), length_segment_id.element(pos, i), num_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id,0), m_segment_loss.element(i, segment_id, 0), length_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 1), m_segment_loss.element(i, segment_id,1)) ;
if (num_segment_id.element(pos, i)!=0)
ret += num_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 0) ;
if (length_segment_id.element(pos, i)!=0)
ret += length_segment_id.element(pos, i)*m_segment_loss.element(i, segment_id, 1) ;
}
last_pos = pos ;
last_value = ret ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_extend_time += MyTime.time_diff_sec() ;
#endif
return ret ;
}
void CDynProg::find_segment_loss_till_pos(const INT * pos, INT t_end, CArray2<INT>& segment_ids_mask, struct segment_loss_struct & loss)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
CArray2<INT> num_segment_id(loss.num_segment_id, loss.seqlen, max_a_id+1, false, false) ;
CArray2<INT> length_segment_id(loss.length_segment_id, loss.seqlen, max_a_id+1, false, false) ;
for (INT i=0; i<max_a_id+1; i++)
{
num_segment_id.element(t_end, i) = 0 ;
length_segment_id.element(t_end, i) = 0 ;
}
INT wobble_pos_segment_id_switch = 0 ;
INT last_segment_id = -1 ;
INT ts = t_end-1 ;
while ((ts>=0) && (pos[t_end] - pos[ts] <= loss.maxlookback))
{
INT cur_segment_id = segment_ids_mask.element(0, ts) ;
// allow at most one wobble
bool wobble_pos = (segment_ids_mask.element(1, ts)==0) && (wobble_pos_segment_id_switch==0) ;
ASSERT(cur_segment_id<=max_a_id) ;
ASSERT(cur_segment_id>=0) ;
for (INT i=0; i<max_a_id+1; i++)
{
num_segment_id.element(ts, i) = num_segment_id.element(ts+1, i) ;
length_segment_id.element(ts, i) = length_segment_id.element(ts+1, i) ;
}
if (cur_segment_id!=last_segment_id)
{
if (wobble_pos)
{
//SG_DEBUG( "no change at %i: %i, %i\n", ts, last_segment_id, cur_segment_id) ;
wobble_pos_segment_id_switch++ ;
//ASSERT(wobble_pos_segment_id_switch<=1) ;
}
else
{
//SG_DEBUG( "change at %i: %i, %i\n", ts, last_segment_id, cur_segment_id) ;
loss.segments_changed[ts] = true ;
num_segment_id.element(ts, cur_segment_id) += segment_ids_mask.element(1, ts) ;
length_segment_id.element(ts, cur_segment_id) += (pos[ts+1]-pos[ts])*segment_ids_mask.element(1, ts) ;
wobble_pos_segment_id_switch = 0 ;
}
last_segment_id = cur_segment_id ;
}
else
if (!wobble_pos)
length_segment_id.element(ts, cur_segment_id) += pos[ts+1] - pos[ts] ;
ts--;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
segment_pos_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::init_svm_values(struct svm_values_struct & svs, INT start_pos, INT seqlen, INT maxlookback)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
See find_svm_values_till_pos for comments
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
where t_end is the end of all segments we are currently looking at
*/
INT clear_size = CMath::min(maxlookback,seqlen) ;
if (!svs.svm_values)
{
svs.svm_values = new DREAL[seqlen*num_svms] ;
svs.num_unique_words = new INT*[num_degrees] ;
svs.svm_values_unnormalized = new DREAL*[num_degrees] ;
svs.word_used = new bool**[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
svs.word_used[j] = new bool*[num_svms] ;
for (INT s=0; s<num_svms; s++)
svs.word_used[j][s] = new bool[num_words_array[j]] ;
}
for (INT j=0; j<num_degrees; j++)
{
svs.svm_values_unnormalized[j] = new DREAL[num_svms] ;
svs.num_unique_words[j] = new INT[num_svms] ;
}
svs.start_pos = new INT[num_svms] ;
clear_size = seqlen ;
}
//for (INT i=0; i<maxlookback*num_svms; i++) // initializing this for safety, though we should be able to live without it
// svs.svm_values[i] = 0;
memset(svs.svm_values, 0, clear_size*num_svms*sizeof(DREAL)) ;
for (INT j=0; j<num_degrees; j++)
{
//for (INT s=0; s<num_svms; s++)
// svs.svm_values_unnormalized[j][s] = 0 ;
memset(svs.svm_values_unnormalized[j], 0, num_svms*sizeof(DREAL)) ;
//for (INT s=0; s<num_svms; s++)
// svs.num_unique_words[j][s] = 0 ;
memset(svs.num_unique_words[j], 0, num_svms*sizeof(INT)) ;
}
for (INT j=0; j<num_degrees; j++)
for (INT s=0; s<num_svms; s++)
{
//for (INT i=0; i<num_words_array[j]; i++)
// svs.word_used[j][s][i] = false ;
memset(svs.word_used[j][s], 0, num_words_array[j]*sizeof(bool)) ;
}
for (INT s=0; s<num_svms; s++)
svs.start_pos[s] = start_pos - mod_words.element(s,1) ;
svs.maxlookback = maxlookback ;
svs.seqlen = seqlen ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_init_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::clear_svm_values(struct svm_values_struct & svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (NULL != svs.svm_values)
{
for (INT j=0; j<num_degrees; j++)
{
for (INT s=0; s<num_svms; s++)
delete[] svs.word_used[j][s] ;
delete[] svs.word_used[j];
}
delete[] svs.word_used;
for (INT j=0; j<num_degrees; j++)
delete[] svs.svm_values_unnormalized[j] ;
for (INT j=0; j<num_degrees; j++)
delete[] svs.num_unique_words[j] ;
delete[] svs.svm_values_unnormalized;
delete[] svs.svm_values;
delete[] svs.num_unique_words ;
svs.word_used=NULL ;
svs.svm_values=NULL ;
svs.svm_values_unnormalized=NULL ;
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_clean_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::find_svm_values_till_pos(WORD*** wordstr, const INT *pos, INT t_end, struct svm_values_struct &svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
wordstr is a vector of L n-gram indices, with wordstr(i) representing a number betweeen 0 and 4095
corresponding to the 6-mer in genestr(i-5:i)
pos is a vector of candidate transition positions (it is input to best_path_trans)
t_end is some index in pos
svs has been initialized by init_svm_values
At the end of this procedure,
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
The SVM weights are precomputed in dict_weights
*/
for (INT j=0; j<num_degrees; j++)
{
INT plen = 1;
INT ts = t_end-1; // index in pos; pos(ts) and pos(t) are indices of wordstr
INT offset;
INT posprev = pos[t_end]-word_degree[j]+1;
INT poscurrent = pos[ts];
//SG_DEBUG( "j=%i seqlen=%i posprev = %i, poscurrent = %i", j, svs.seqlen, posprev, poscurrent) ;
if (poscurrent<0)
poscurrent = 0;
DREAL * my_svm_values_unnormalized = svs.svm_values_unnormalized[j] ;
INT * my_num_unique_words = svs.num_unique_words[j] ;
bool ** my_word_used = svs.word_used[j] ;
INT len = pos[t_end] - poscurrent;
while ((ts>=0) && (len <= svs.maxlookback))
{
for (int i=posprev-1 ; (i>=poscurrent) && (i>=0) ; i--)
{
//fprintf(stderr, "string_words_array[0]=%i (%ld), j=%i (%ld) i=%i\n", string_words_array[0], wordstr[string_words_array[0]], j, wordstr[string_words_array[0]][j], i) ;
WORD word = wordstr[string_words_array[0]][j][i] ;
INT last_string = string_words_array[0] ;
for (INT s=0; s<num_svms; s++)
{
// try to avoid memory accesses
if (last_string != string_words_array[s])
{
last_string = string_words_array[s] ;
word = wordstr[last_string][j][i] ;
}
// do not consider k-mer, if seen before and in signum mode
if (sign_words_array[s] && my_word_used[s][word])
continue ;
// only count k-mer if in frame (if applicable)
if ((svs.start_pos[s]-i>0) && ((svs.start_pos[s]-i)%mod_words_array[s]==0))
{
my_svm_values_unnormalized[s] += dict_weights_array[(word+cum_num_words_array[j])+s*cum_num_words_array[num_degrees]] ;
//svs.svm_values_unnormalized[j][s]+=dict_weights.element(word+cum_num_words_array[j], s) ;
my_num_unique_words[s]++ ;
if (sign_words_array[s])
my_word_used[s][word]=true ;
}
}
}
offset = plen*num_svms ;
for (INT s=0; s<num_svms; s++)
{
double normalization_factor = 1.0;
if (my_num_unique_words[s] > 0)
if (sign_words_array[s])
normalization_factor = sqrt((double)my_num_unique_words[s]);
else
normalization_factor = (double)my_num_unique_words[s];
if (j==0)
svs.svm_values[offset+s]=0 ;
svs.svm_values[offset+s] += my_svm_values_unnormalized[s] / normalization_factor;
}
if (posprev > poscurrent) // remember posprev initially set to pos[t_end]-word_degree+1... pos[ts] could be e.g. pos[t_end]-2
posprev = poscurrent;
ts--;
plen++;
if (ts>=0)
{
poscurrent=pos[ts];
if (poscurrent<0)
poscurrent = 0;
len = pos[t_end] - poscurrent;
}
}
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_pos_time += MyTime.time_diff_sec() ;
#endif
}
void CDynProg::find_svm_values_till_pos(WORD** wordstr, const INT *pos, INT t_end, struct svm_values_struct &svs)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
/*
wordstr is a vector of L n-gram indices, with wordstr(i) representing a number betweeen 0 and 4095
corresponding to the 6-mer in genestr(i-5:i)
pos is a vector of candidate transition positions (it is input to best_path_trans)
t_end is some index in pos
svs has been initialized by init_svm_values
At the end of this procedure,
svs.svm_values[i+s*svs.seqlen] has the value of the s-th SVM on genestr(pos(t_end-i):pos(t_end))
for every i satisfying pos(t_end)-pos(t_end-i) <= svs.maxlookback
The SVM weights are precomputed in dict_weights
*/
for (INT j=0; j<num_degrees; j++)
{
INT plen = 1;
INT ts = t_end-1; // index in pos; pos(ts) and pos(t) are indices of wordstr
INT offset;
INT posprev = pos[t_end]-word_degree[j]+1;
INT poscurrent = pos[ts];
//SG_DEBUG( "j=%i seqlen=%i posprev = %i, poscurrent = %i", j, svs.seqlen, posprev, poscurrent) ;
if (poscurrent<0)
poscurrent = 0;
DREAL * my_svm_values_unnormalized = svs.svm_values_unnormalized[j] ;
INT * my_num_unique_words = svs.num_unique_words[j] ;
bool ** my_word_used = svs.word_used[j] ;
INT len = pos[t_end] - poscurrent;
while ((ts>=0) && (len <= svs.maxlookback))
{
for (int i=posprev-1 ; (i>=poscurrent) && (i>=0) ; i--)
{
//fprintf(stderr, "string_words_array[0]=%i (%ld), j=%i (%ld) i=%i\n", string_words_array[0], wordstr[string_words_array[0]], j, wordstr[string_words_array[0]][j], i) ;
WORD word = wordstr[j][i] ;
for (INT s=0; s<num_svms; s++)
{
// do not consider k-mer, if seen before and in signum mode
if (sign_words_array[s] && my_word_used[s][word])
continue ;
// only count k-mer if in frame (if applicable)
if ((svs.start_pos[s]-i>0) && ((svs.start_pos[s]-i)%mod_words_array[s]==0))
{
my_svm_values_unnormalized[s] += dict_weights_array[(word+cum_num_words_array[j])+s*cum_num_words_array[num_degrees]] ;
//svs.svm_values_unnormalized[j][s]+=dict_weights.element(word+cum_num_words_array[j], s) ;
my_num_unique_words[s]++ ;
if (sign_words_array[s])
my_word_used[s][word]=true ;
}
}
}
offset = plen*num_svms ;
for (INT s=0; s<num_svms; s++)
{
double normalization_factor = 1.0;
if (my_num_unique_words[s] > 0)
if (sign_words_array[s])
normalization_factor = sqrt((double)my_num_unique_words[s]);
else
normalization_factor = (double)my_num_unique_words[s];
if (j==0)
svs.svm_values[offset+s]=0 ;
svs.svm_values[offset+s] += my_svm_values_unnormalized[s] / normalization_factor;
}
if (posprev > poscurrent) // remember posprev initially set to pos[t_end]-word_degree+1... pos[ts] could be e.g. pos[t_end]-2
posprev = poscurrent;
ts--;
plen++;
if (ts>=0)
{
poscurrent=pos[ts];
if (poscurrent<0)
poscurrent = 0;
len = pos[t_end] - poscurrent;
}
}
}
#ifdef DYNPROG_TIMING
MyTime.stop() ;
svm_pos_time += MyTime.time_diff_sec() ;
#endif
}
bool CDynProg::extend_orf(const CArray<bool>& genestr_stop, INT orf_from, INT orf_to, INT start, INT &last_pos, INT to)
{
#ifdef DYNPROG_TIMING
MyTime.start() ;
#endif
if (start<0)
start=0 ;
if (to<0)
to=0 ;
INT orf_target = orf_to-orf_from ;
if (orf_target<0) orf_target+=3 ;
INT pos ;
if (last_pos==to)
pos = to-orf_to-3 ;
else
pos=last_pos ;
if (pos<0)
return true ;
for (; pos>=start; pos-=3)
if (genestr_stop[pos])
return false ;
last_pos = CMath::min(pos+3,to-orf_to-3) ;
#ifdef DYNPROG_TIMING
MyTime.stop() ;
orf_time += MyTime.time_diff_sec() ;
#endif
return true ;
}
template <short int nbest, bool with_loss, bool with_multiple_sequences>
void CDynProg::best_path_trans(const DREAL *seq_array, INT seq_len, const INT *pos,
const INT *orf_info_array, CPlifBase **Plif_matrix,
CPlifBase **Plif_state_signals, INT max_num_signals,
const char *genestr, INT genestr_len, INT genestr_num,
DREAL *prob_nbest, INT *my_state_seq, INT *my_pos_seq,
DREAL *dictionary_weights, INT dict_len, bool use_orf)
{
#ifdef DYNPROG_TIMING
segment_init_time = 0.0 ;
segment_pos_time = 0.0 ;
segment_extend_time = 0.0 ;
segment_clean_time = 0.0 ;
orf_time = 0.0 ;
svm_init_time = 0.0 ;
svm_pos_time = 0.0 ;
svm_clean_time = 0.0 ;
MyTime2.start() ;
#endif
//SG_PRINT( "best_path_trans:%x\n", seq_array);
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
}
#ifdef DYNPROG_DEBUG
transition_matrix_a.set_name("transition_matrix");
transition_matrix_a.display_array();
mod_words.display_array() ;
sign_words.display_array() ;
string_words.display_array() ;
fprintf(stderr, "use_orf = %i\n", use_orf) ;
#endif
const INT default_look_back = 30000 ;
INT max_look_back = default_look_back ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*cum_num_words_array[num_degrees]) ;
dict_weights.set_array(dictionary_weights, cum_num_words_array[num_degrees], num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false, false) ;
CArray2<CPlifBase*> PEN_state_signals(Plif_state_signals, N, max_num_signals, false, false) ;
CArray3<DREAL> seq_input(seq_array, N, seq_len, max_num_signals) ;
seq_input.set_name("seq_input") ;
//seq_input.display_array() ;
CArray2<DREAL> seq(N, seq_len) ;
seq.set_name("seq") ;
seq.zero() ;
CArray2<INT> orf_info(orf_info_array, N, 2) ;
orf_info.set_name("orf_info") ;
//g_orf_info = orf_info ;
//orf_info.display_array() ;
DREAL svm_value[num_svms] ;
{ // initialize svm_svalue
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
}
{ // convert seq_input to seq
// this is independent of the svm values
for (INT i=0; i<N; i++)
for (INT j=0; j<seq_len; j++)
seq.element(i,j) = 0 ;
for (INT i=0; i<N; i++)
for (INT j=0; j<seq_len; j++)
for (INT k=0; k<max_num_signals; k++)
{
if ((PEN_state_signals.element(i,k)==NULL) && (k==0))
{
// no plif
seq.element(i,j) = seq_input.element(i,j,k) ;
break ;
}
if (PEN_state_signals.element(i,k)!=NULL)
{
// just one plif
if (finite(seq_input.element(i,j,k)))
seq.element(i,j) += PEN_state_signals.element(i,k)->lookup_penalty(seq_input.element(i,j,k), svm_value) ;
else
// keep infinity values
seq.element(i,j) = seq_input.element(i, j, k) ;
}
else
break ;
}
}
{ // determine maximal length of look-back
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->get_max_value()>max_look_back)
{
SG_DEBUG( "%d %d -> value: %f\n", i,j,penij->get_max_value());
max_look_back=(INT) (CMath::ceil(penij->get_max_value()));
}
if (penij->uses_svm_values())
use_svm=true ;
}
}
max_look_back = CMath::min(genestr_len, max_look_back) ;
SG_DEBUG("use_svm=%i\n", use_svm) ;
SG_DEBUG("maxlook: %d N: %d nbest: %d genestrlen:%d\n", max_look_back, N, nbest, genestr_len);
const INT look_back_buflen = (max_look_back*N+1)*nbest ;
SG_DEBUG("look_back_buflen=%i\n", look_back_buflen) ;
const DREAL mem_use = (DREAL)(seq_len*N*nbest*(sizeof(T_STATES)+sizeof(short int)+sizeof(INT))+
look_back_buflen*(2*sizeof(DREAL)+sizeof(INT))+
seq_len*(sizeof(T_STATES)+sizeof(INT))+
genestr_len*sizeof(bool))/(1024*1024);
bool is_big = (mem_use>200) || (seq_len>5000) ;
if (is_big)
{
SG_DEBUG("calling best_path_trans: seq_len=%i, N=%i, lookback=%i nbest=%i\n",
seq_len, N, max_look_back, nbest) ;
SG_DEBUG("allocating %1.2fMB of memory\n",
mem_use) ;
}
ASSERT(nbest<32000) ;
//char* xx=strndup(genestr, genestr_len) ;
//fprintf(stderr, "genestr='%s'\n", xx) ;
CArray<bool> genestr_stop(genestr_len) ;
//genestr_stop.zero() ;
CArray3<DREAL> delta(seq_len, N, nbest) ;
DREAL* delta_array = delta.get_array() ;
//delta.zero() ;
CArray3<T_STATES> psi(seq_len, N, nbest) ;
//psi.zero() ;
CArray3<short int> ktable(seq_len, N, nbest) ;
//ktable.zero() ;
CArray3<INT> ptable(seq_len, N, nbest) ;
//ptable.zero() ;
CArray<DREAL> delta_end(nbest) ;
//delta_end.zero() ;
CArray<T_STATES> path_ends(nbest) ;
//path_ends.zero() ;
CArray<short int> ktable_end(nbest) ;
//ktable_end.zero() ;
DREAL * fixedtempvv=new DREAL[look_back_buflen] ;
memset(fixedtempvv, 0, look_back_buflen*sizeof(DREAL)) ;
INT * fixedtempii=new INT[look_back_buflen] ;
memset(fixedtempii, 0, look_back_buflen*sizeof(INT)) ;
CArray<DREAL> oldtempvv(look_back_buflen) ;
CArray<DREAL> oldtempvv2(look_back_buflen) ;
//oldtempvv.zero() ;
//oldtempvv.display_size() ;
CArray<INT> oldtempii(look_back_buflen) ;
CArray<INT> oldtempii2(look_back_buflen) ;
//oldtempii.zero() ;
CArray<T_STATES> state_seq(seq_len) ;
//state_seq.zero() ;
CArray<INT> pos_seq(seq_len) ;
//pos_seq.zero() ;
dict_weights.set_name("dict_weights") ;
word_degree.set_name("word_degree") ;
cum_num_words.set_name("cum_num_words") ;
num_words.set_name("num_words") ;
//word_used.set_name("word_used") ;
//svm_values_unnormalized.set_name("svm_values_unnormalized") ;
svm_pos_start.set_name("svm_pos_start") ;
num_unique_words.set_name("num_unique_words") ;
PEN.set_name("PEN") ;
seq.set_name("seq") ;
orf_info.set_name("orf_info") ;
genestr_stop.set_name("genestr_stop") ;
delta.set_name("delta") ;
psi.set_name("psi") ;
ktable.set_name("ktable") ;
ptable.set_name("ptable") ;
delta_end.set_name("delta_end") ;
path_ends.set_name("path_ends") ;
ktable_end.set_name("ktable_end") ;
#ifdef USE_TMP_ARRAYCLASS
fixedtempvv.set_name("fixedtempvv") ;
fixedtempii.set_name("fixedtempvv") ;
#endif
oldtempvv.set_name("oldtempvv") ;
oldtempvv2.set_name("oldtempvv2") ;
oldtempii.set_name("oldtempii") ;
oldtempii2.set_name("oldtempii2") ;
////////////////////////////////////////////////////////////////////////////////
#ifdef DYNPROG_DEBUG
state_seq.display_size() ;
pos_seq.display_size() ;
dict_weights.display_size() ;
word_degree.display_array() ;
cum_num_words.display_array() ;
num_words.display_array() ;
//word_used.display_size() ;
//svm_values_unnormalized.display_size() ;
svm_pos_start.display_array() ;
num_unique_words.display_array() ;
PEN.display_size() ;
PEN_state_signals.display_size() ;
seq.display_size() ;
orf_info.display_size() ;
genestr_stop.display_size() ;
delta.display_size() ;
psi.display_size() ;
ktable.display_size() ;
ptable.display_size() ;
delta_end.display_size() ;
path_ends.display_size() ;
ktable_end.display_size() ;
#ifdef USE_TMP_ARRAYCLASS
fixedtempvv.display_size() ;
fixedtempii.display_size() ;
#endif
//oldtempvv.display_size() ;
//oldtempii.display_size() ;
state_seq.display_size() ;
pos_seq.display_size() ;
CArray<INT>pp = CArray<INT>(pos, seq_len) ;
pp.display_array() ;
//seq.zero() ;
//seq_input.display_array() ;
#endif //DYNPROG_DEBUG
////////////////////////////////////////////////////////////////////////////////
{ // precompute stop codons
for (INT i=0; i<genestr_len-2; i++)
if ((genestr[i]=='t' || genestr[i]=='T') &&
(((genestr[i+1]=='a' || genestr[i+1]=='A') &&
(genestr[i+2]=='a' || genestr[i+2]=='g' || genestr[i+2]=='A' || genestr[i+2]=='G')) ||
((genestr[i+1]=='g'||genestr[i+1]=='G') && (genestr[i+2]=='a' || genestr[i+2]=='A') )))
genestr_stop[i]=true ;
else
genestr_stop[i]=false ;
genestr_stop[genestr_len-1]=false ;
genestr_stop[genestr_len-1]=false ;
}
{
for (INT s=0; s<num_svms; s++)
ASSERT(string_words_array[s]<genestr_num) ;
}
// translate to words, if svm is used
SG_DEBUG("genestr_num = %i, genestr_len = %i, num_degree=%i, use_svm=%i\n", genestr_num, genestr_len, num_degrees, use_svm) ;
WORD** wordstr[genestr_num] ;
for (INT k=0; k<genestr_num; k++)
{
wordstr[k]=new WORD*[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
wordstr[k][j]=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr[k][j]=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[k][j][i]=0 ; break ;
case 'C':
case 'c': wordstr[k][j][i]=1 ; break ;
case 'G':
case 'g': wordstr[k][j][i]=2 ; break ;
case 'T':
case 't': wordstr[k][j][i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr[k][j], genestr_len,
word_degree[j]-1, word_degree[j]) ;
}
}
}
{ // initialization
for (T_STATES i=0; i<N; i++)
{
//delta.element(0, i, 0) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
delta.element(delta_array, 0, i, 0, seq_len, N) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
psi.element(0,i,0) = 0 ;
if (nbest>1)
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
INT dim1, dim2, dim3 ;
delta.get_array_size(dim1, dim2, dim3) ;
//SG_DEBUG("i=%i, k=%i -- %i, %i, %i\n", i, k, dim1, dim2, dim3) ;
//delta.element(0, i, k) = -CMath::INFTY ;
delta.element(delta_array, 0, i, k, seq_len, N) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ; // <--- what's this for?
if (nbest>1)
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
struct svm_values_struct svs;
svs.num_unique_words = NULL;
svs.svm_values = NULL;
svs.svm_values_unnormalized = NULL;
svs.word_used = NULL;
struct segment_loss_struct loss;
loss.segments_changed = NULL;
loss.num_segment_id = NULL;
// recursion
for (INT t=1; t<seq_len; t++)
{
if (is_big && t%(1+(seq_len/1000))==1)
SG_PROGRESS(t, 0, seq_len);
//fprintf(stderr, "%i\n", t) ;
init_svm_values(svs, pos[t], seq_len, max_look_back) ;
if (with_multiple_sequences)
find_svm_values_till_pos(wordstr, pos, t, svs);
else
find_svm_values_till_pos(wordstr[0], pos, t, svs);
if (with_loss)
{
init_segment_loss(loss, seq_len, max_look_back);
find_segment_loss_till_pos(pos, t, m_segment_ids_mask, loss);
}
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<=-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(delta_array, t, j, k, seq_len, N) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
if (nbest>1)
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
const INT *elem_id = trans_list_forward_id[j] ;
INT fixed_list_len = 0 ;
DREAL fixedtempvv_ = CMath::INFTY ;
INT fixedtempii_ = 0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
const CPlifBase * penalty = PEN.element(j,ii) ;
INT look_back = default_look_back ;
{ // find lookback length
CPlifBase *pen = (CPlifBase*) penalty ;
if (pen!=NULL)
look_back=(INT) (CMath::ceil(pen->get_max_value()));
ASSERT(look_back<1e6);
}
INT orf_from = orf_info.element(ii,0) ;
INT orf_to = orf_info.element(j,1) ;
if((orf_from!=-1)!=(orf_to!=-1))
SG_DEBUG("j=%i ii=%i orf_from=%i orf_to=%i p=%1.2f\n", j, ii, orf_from, orf_to, elem_val[i]) ;
ASSERT((orf_from!=-1)==(orf_to!=-1)) ;
INT orf_target = -1 ;
if (orf_from!=-1)
{
orf_target=orf_to-orf_from ;
if (orf_target<0)
orf_target+=3 ;
ASSERT(orf_target>=0 && orf_target<3) ;
}
INT orf_last_pos = pos[t] ;
INT loss_last_pos = t ;
DREAL last_loss = 0.0 ;
for (INT ts=t-1; ts>=0 && pos[t]-pos[ts]<=look_back; ts--)
{
bool ok ;
int plen=t-ts;
/*for (INT s=0; s<num_svms; s++)
if ((fabs(svs.svm_values[s*svs.seqlen+plen]-svs2.svm_values[s*svs.seqlen+plen])>1e-6) ||
(fabs(svs.svm_values[s*svs.seqlen+plen]-svs3.svm_values[s*svs.seqlen+plen])>1e-6))
{
SG_DEBUG( "s=%i, t=%i, ts=%i, %1.5e, %1.5e, %1.5e\n", s, t, ts, svs.svm_values[s*svs.seqlen+plen], svs2.svm_values[s*svs.seqlen+plen], svs3.svm_values[s*svs.seqlen+plen]);
}*/
if (orf_target==-1)
ok=true ;
else if (pos[ts]!=-1 && (pos[t]-pos[ts])%3==orf_target)
ok=(!use_orf) || extend_orf(genestr_stop, orf_from, orf_to, pos[ts], orf_last_pos, pos[t]) ;
else
ok=false ;
if (ok)
{
DREAL segment_loss = 0.0 ;
if (with_loss)
segment_loss = extend_segment_loss(loss, pos, elem_id[i], ts, loss_last_pos, last_loss) ;
INT offset = plen*num_svms ;
for (INT ss=0; ss<num_svms; ss++)
svm_value[ss]=svs.svm_values[offset+ss];
DREAL pen_val = 0.0 ;
if (penalty)
pen_val = penalty->lookup_penalty(pos[t]-pos[ts], svm_value) ;
if (nbest==1)
{
DREAL val = elem_val[i] + pen_val ;
if (with_loss)
val += segment_loss ;
DREAL mval = -(val + delta.element(delta_array, ts, ii, 0, seq_len, N)) ;
if (mval<fixedtempvv_)
{
fixedtempvv_ = mval ;
fixedtempii_ = ii + ts*N;
fixed_list_len = 1 ;
}
}
else
{
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = elem_val[i] ;
val += pen_val ;
if (with_loss)
val += segment_loss ;
DREAL mval = -(val + delta.element(delta_array, ts, ii, diff, seq_len, N)) ;
/* only place -val in fixedtempvv if it is one of the nbest lowest values in there */
/* fixedtempvv[i], i=0:nbest-1, is sorted so that fixedtempvv[0] <= fixedtempvv[1] <= ...*/
/* fixed_list_len has the number of elements in fixedtempvv */
if ((fixed_list_len < nbest) || ((0==fixed_list_len) || (mval < fixedtempvv[fixed_list_len-1])))
{
if ( (fixed_list_len<nbest) && ((0==fixed_list_len) || (mval>fixedtempvv[fixed_list_len-1])) )
{
fixedtempvv[fixed_list_len] = mval ;
fixedtempii[fixed_list_len] = ii + diff*N + ts*N*nbest;
fixed_list_len++ ;
}
else // must have mval < fixedtempvv[fixed_list_len-1]
{
int addhere = fixed_list_len;
while ((addhere > 0) && (mval < fixedtempvv[addhere-1]))
addhere--;
// move everything from addhere+1 one forward
for (int jj=fixed_list_len-1; jj>addhere; jj--)
{
fixedtempvv[jj] = fixedtempvv[jj-1];
fixedtempii[jj] = fixedtempii[jj-1];
}
fixedtempvv[addhere] = mval;
fixedtempii[addhere] = ii + diff*N + ts*N*nbest;
if (fixed_list_len < nbest)
fixed_list_len++;
}
}
}
}
}
}
}
int numEnt = fixed_list_len;
double minusscore;
long int fromtjk;
for (short int k=0; k<nbest; k++)
{
if (k<numEnt)
{
if (nbest==1)
{
minusscore = fixedtempvv_ ;
fromtjk = fixedtempii_ ;
}
else
{
minusscore = fixedtempvv[k];
fromtjk = fixedtempii[k];
}
delta.element(delta_array, t, j, k, seq_len, N) = -minusscore + seq.element(j,t);
psi.element(t,j,k) = (fromtjk%N) ;
if (nbest>1)
ktable.element(t,j,k) = (fromtjk%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (fromtjk-(fromtjk%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(delta_array, t, j, k, seq_len, N) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
if (nbest>1)
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
clear_svm_values(svs);
if (with_loss)
clear_segment_loss(loss);
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
oldtempvv[list_len] = -(delta.element(delta_array, (seq_len-1), i, diff, seq_len, N)+get_q(i)) ;
oldtempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(oldtempvv.get_array(), oldtempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -oldtempvv[k] ;
path_ends.element(k) = (oldtempii[k]%N) ;
if (nbest>1)
ktable_end.element(k) = (oldtempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = 0 ;
if (nbest>1)
q=ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
if (nbest>1)
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*seq_len] = state_seq[num_states-i-1] ;
my_pos_seq[i+k*seq_len] = pos_seq[num_states-i-1] ;
}
my_state_seq[num_states+k*seq_len]=-1 ;
my_pos_seq[num_states+k*seq_len]=-1 ;
}
}
if (is_big)
SG_PRINT( "DONE. \n") ;
for (INT k=0; k<genestr_num; k++)
{
for (INT j=0; j<num_degrees; j++)
delete[] wordstr[k][j] ;
delete[] wordstr[k] ;
}
#ifdef DYNPROG_TIMING
MyTime2.stop() ;
if (is_big)
SG_PRINT("Timing: orf=%1.2f s \n Segment_init=%1.2f s Segment_pos=%1.2f s Segment_extend=%1.2f s Segment_clean=%1.2f s\nsvm_init=%1.2f s svm_pos=%1.2f svm_clean=%1.2f\n total=%1.2f\n", orf_time, segment_init_time, segment_pos_time, segment_extend_time, segment_clean_time, svm_init_time, svm_pos_time, svm_clean_time, MyTime2.time_diff_sec()) ;
#endif
delete[] fixedtempvv ;
delete[] fixedtempii ;
}
void CDynProg::best_path_trans_deriv(INT *my_state_seq, INT *my_pos_seq, DREAL *my_scores, DREAL* my_losses,
INT my_seq_len,
const DREAL *seq_array, INT seq_len, const INT *pos,
CPlifBase **Plif_matrix,
CPlifBase **Plif_state_signals, INT max_num_signals,
const char *genestr, INT genestr_len, INT genestr_num,
DREAL *dictionary_weights, INT dict_len)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
//SG_DEBUG( "genestr_len=%i, genestr_num=%i\n", genestr_len, genestr_num) ;
//mod_words.display() ;
//sign_words.display() ;
//string_words.display() ;
bool use_svm = false ;
ASSERT(dict_len==num_svms*cum_num_words_array[num_degrees]) ;
dict_weights.set_array(dictionary_weights, cum_num_words_array[num_degrees], num_svms, false, false) ;
dict_weights_array=dict_weights.get_array() ;
CArray2<CPlifBase*> PEN(Plif_matrix, N, N, false, false) ;
CArray2<CPlifBase*> PEN_state_signals(Plif_state_signals, N, max_num_signals, false, false) ;
CArray3<DREAL> seq_input(seq_array, N, seq_len, max_num_signals) ;
{ // determine whether to use svm outputs and clear derivatives
for (INT i=0; i<N; i++)
for (INT j=0; j<N; j++)
{
CPlifBase *penij=PEN.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->uses_svm_values())
use_svm=true ;
penij->penalty_clear_derivative() ;
}
for (INT i=0; i<N; i++)
for (INT j=0; j<max_num_signals; j++)
{
CPlifBase *penij=PEN_state_signals.element(i,j) ;
if (penij==NULL)
continue ;
if (penij->uses_svm_values())
use_svm=true ;
penij->penalty_clear_derivative() ;
}
}
// translate to words, if svm is used
WORD** wordstr[genestr_num] ;
for (INT k=0; k<genestr_num; k++)
{
wordstr[k]=new WORD*[num_degrees] ;
for (INT j=0; j<num_degrees; j++)
{
wordstr[k][j]=NULL ;
if (use_svm)
{
ASSERT(dictionary_weights!=NULL) ;
wordstr[k][j]=new WORD[genestr_len] ;
for (INT i=0; i<genestr_len; i++)
switch (genestr[i])
{
case 'A':
case 'a': wordstr[k][j][i]=0 ; break ;
case 'C':
case 'c': wordstr[k][j][i]=1 ; break ;
case 'G':
case 'g': wordstr[k][j][i]=2 ; break ;
case 'T':
case 't': wordstr[k][j][i]=3 ; break ;
default: ASSERT(0) ;
}
translate_from_single_order(wordstr[k][j], genestr_len,
word_degree[j]-1, word_degree[j]) ;
}
}
}
{ // set derivatives of p, q and a to zero
for (INT i=0; i<N; i++)
{
initial_state_distribution_p_deriv.element(i)=0 ;
end_state_distribution_q_deriv.element(i)=0 ;
for (INT j=0; j<N; j++)
transition_matrix_a_deriv.element(i,j)=0 ;
}
}
{ // clear score vector
for (INT i=0; i<my_seq_len; i++)
{
my_scores[i]=0.0 ;
my_losses[i]=0.0 ;
}
}
//INT total_len = 0 ;
//transition_matrix_a.display_array() ;
//transition_matrix_a_id.display_array() ;
{ // compute derivatives for given path
DREAL svm_value[num_svms] ;
for (INT s=0; s<num_svms; s++)
svm_value[s]=0 ;
for (INT i=0; i<my_seq_len; i++)
{
my_scores[i]=0.0 ;
my_losses[i]=0.0 ;
}
#ifdef DYNPROG_DEBUG
DREAL total_score = 0.0 ;
DREAL total_loss = 0.0 ;
#endif
ASSERT(my_state_seq[0]>=0) ;
initial_state_distribution_p_deriv.element(my_state_seq[0])++ ;
my_scores[0] += initial_state_distribution_p.element(my_state_seq[0]) ;
ASSERT(my_state_seq[my_seq_len-1]>=0) ;
end_state_distribution_q_deriv.element(my_state_seq[my_seq_len-1])++ ;
my_scores[my_seq_len-1] += end_state_distribution_q.element(my_state_seq[my_seq_len-1]);
#ifdef DYNPROG_DEBUG
total_score += my_scores[0] + my_scores[my_seq_len-1] ;
#endif
struct svm_values_struct svs;
svs.num_unique_words = NULL;
svs.svm_values = NULL;
svs.svm_values_unnormalized = NULL;
svs.word_used = NULL;
init_svm_values(svs, my_state_seq[0], seq_len, 100);
struct segment_loss_struct loss;
loss.segments_changed = NULL;
loss.num_segment_id = NULL;
//SG_DEBUG( "seq_len=%i\n", my_seq_len) ;
for (INT i=0; i<my_seq_len-1; i++)
{
if (my_state_seq[i+1]==-1)
break ;
INT from_state = my_state_seq[i] ;
INT to_state = my_state_seq[i+1] ;
INT from_pos = my_pos_seq[i] ;
INT to_pos = my_pos_seq[i+1] ;
// compute loss relative to another segmentation using the segment_loss function
init_segment_loss(loss, seq_len, pos[to_pos]-pos[from_pos]+10);
find_segment_loss_till_pos(pos, to_pos, m_segment_ids_mask, loss);
INT loss_last_pos = to_pos ;
DREAL last_loss = 0.0 ;
//INT elem_id = transition_matrix_a_id.element(to_state, from_state) ;
INT elem_id = transition_matrix_a_id.element(from_state, to_state) ;
my_losses[i] = extend_segment_loss(loss, pos, elem_id, from_pos, loss_last_pos, last_loss) ;
#ifdef DYNPROG_DEBUG
io.set_loglevel(M_DEBUG) ;
SG_DEBUG( "%i. segment loss %f (id=%i): from=%i(%i), to=%i(%i)\n", i, my_losses[i], elem_id, from_pos, from_state, to_pos, to_state) ;
#endif
// increase usage of this transition
transition_matrix_a_deriv.element(from_state, to_state)++ ;
my_scores[i] += transition_matrix_a.element(from_state, to_state) ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f\n", i, my_scores[i]) ;
#endif
/*INT last_svm_pos[num_degrees] ;
for (INT qq=0; qq<num_degrees; qq++)
last_svm_pos[qq]=-1 ;*/
if (use_svm)
{
//reset_svm_values(pos[to_pos], last_svm_pos, svm_value) ;
//extend_svm_values(wordstr, pos[from_pos], last_svm_pos, svm_value) ;
init_svm_values(svs, pos[to_pos], seq_len, pos[to_pos]-pos[from_pos]+100);
find_svm_values_till_pos(wordstr, pos, to_pos, svs);
INT plen = to_pos - from_pos ;
INT offset = plen*num_svms ;
for (INT ss=0; ss<num_svms; ss++)
{
svm_value[ss]=svs.svm_values[offset+ss];
#ifdef DYNPROG_DEBUG
SG_DEBUG( "svm[%i]: %f\n", ss, svm_value[ss]) ;
#endif
}
}
if (PEN.element(to_state, from_state)!=NULL)
{
DREAL nscore = PEN.element(to_state, from_state)->lookup_penalty(pos[to_pos]-pos[from_pos], svm_value) ;
my_scores[i] += nscore ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. transition penalty: from_state=%i to_state=%i from_pos=%i [%i] to_pos=%i [%i] value=%i\n", i, from_state, to_state, from_pos, pos[from_pos], to_pos, pos[to_pos], pos[to_pos]-pos[from_pos]) ;
/*
INT orf_from = g_orf_info.element(from_state,0) ;
INT orf_to = g_orf_info.element(to_state,1) ;
ASSERT((orf_from!=-1)==(orf_to!=-1)) ;
if (orf_from != -1)
total_len = total_len + pos[to_pos]-pos[from_pos] ;
SG_DEBUG( "%i. orf_info: from_orf=%i to_orf=%i orf_diff=%i, len=%i, lenmod3=%i, total_len=%i, total_lenmod3=%i\n", i, orf_from, orf_to, (orf_to-orf_from)%3, pos[to_pos]-pos[from_pos], (pos[to_pos]-pos[from_pos])%3, total_len, total_len%3) ;
*/
#endif
PEN.element(to_state, from_state)->penalty_add_derivative(pos[to_pos]-pos[from_pos], svm_value) ;
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f\n", i, my_scores[i]) ;
#endif
//SG_DEBUG( "emmission penalty skipped: to_state=%i to_pos=%i value=%1.2f score=%1.2f\n", to_state, to_pos, seq_input.element(to_state, to_pos), 0.0) ;
for (INT k=0; k<max_num_signals; k++)
{
if ((PEN_state_signals.element(to_state,k)==NULL)&&(k==0))
{
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. emmission penalty: to_state=%i to_pos=%i score=%1.2f (no signal plif)\n", i, to_state, to_pos, seq_input.element(to_state, to_pos, k)) ;
#endif
my_scores[i] += seq_input.element(to_state, to_pos, k) ;
break ;
}
if (PEN_state_signals.element(to_state, k)!=NULL)
{
DREAL nscore = PEN_state_signals.element(to_state,k)->lookup_penalty(seq_input.element(to_state, to_pos, k), svm_value) ;
my_scores[i] += nscore ;
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. emmission penalty: to_state=%i to_pos=%i value=%1.2f score=%1.2f k=%i\n", i, to_state, to_pos, seq_input.element(to_state, to_pos, k), nscore, k) ;
#endif
PEN_state_signals.element(to_state,k)->penalty_add_derivative(seq_input.element(to_state, to_pos, k), svm_value) ;
} else
break ;
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "%i. scores[i]=%f (final) \n", i, my_scores[i]) ;
total_score += my_scores[i] ;
total_loss += my_losses[i] ;
#endif
}
#ifdef DYNPROG_DEBUG
SG_DEBUG( "total score = %f \n", total_score) ;
SG_DEBUG( "total loss = %f \n", total_loss) ;
#endif
clear_svm_values(svs);
clear_segment_loss(loss);
}
for (INT k=0; k<genestr_num; k++)
{
for (INT j=0; j<num_degrees; j++)
delete[] wordstr[k][j] ;
delete[] wordstr[k] ;
}
}
void CDynProg::best_path_trans_simple(const DREAL *seq_array, INT seq_len, short int nbest,
DREAL *prob_nbest, INT *my_state_seq)
{
if (!svm_arrays_clean)
{
SG_ERROR( "SVM arrays not clean") ;
return ;
} ;
INT max_look_back = 2 ;
const INT look_back_buflen = max_look_back*nbest*N ;
ASSERT(nbest<32000) ;
CArray2<DREAL> seq((DREAL *)seq_array, N, seq_len, false) ;
CArray3<DREAL> delta(max_look_back, N, nbest) ;
CArray3<T_STATES> psi(seq_len, N, nbest) ;
CArray3<short int> ktable(seq_len,N,nbest) ;
CArray3<INT> ptable(seq_len,N,nbest) ;
CArray<DREAL> delta_end(nbest) ;
CArray<T_STATES> path_ends(nbest) ;
CArray<short int> ktable_end(nbest) ;
CArray<DREAL> oldtempvv(look_back_buflen) ;
CArray<INT> oldtempii(look_back_buflen) ;
CArray<T_STATES> state_seq(seq_len) ;
CArray<INT> pos_seq(seq_len) ;
{ // initialization
for (T_STATES i=0; i<N; i++)
{
delta.element(0,i,0) = get_p(i) + seq.element(i,0) ; // get_p defined in HMM.h to be equiv to initial_state_distribution
psi.element(0,i,0) = 0 ;
ktable.element(0,i,0) = 0 ;
ptable.element(0,i,0) = 0 ;
for (short int k=1; k<nbest; k++)
{
delta.element(0,i,k) = -CMath::INFTY ;
psi.element(0,i,0) = 0 ; // <--- what's this for?
ktable.element(0,i,k) = 0 ;
ptable.element(0,i,k) = 0 ;
}
}
}
// recursion
for (INT t=1; t<seq_len; t++)
{
for (T_STATES j=0; j<N; j++)
{
if (seq.element(j,t)<-1e20)
{ // if we cannot observe the symbol here, then we can omit the rest
for (short int k=0; k<nbest; k++)
{
delta.element(t%max_look_back,j,k) = seq.element(j,t) ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
else
{
const T_STATES num_elem = trans_list_forward_cnt[j] ;
const T_STATES *elem_list = trans_list_forward[j] ;
const DREAL *elem_val = trans_list_forward_val[j] ;
INT old_list_len = 0 ;
for (INT i=0; i<num_elem; i++)
{
T_STATES ii = elem_list[i] ;
INT ts=t-1;
if (ts>=0)
{
bool ok=true ;
if (ok)
{
for (short int diff=0; diff<nbest; diff++)
{
DREAL val = delta.element(ts%max_look_back,ii,diff) + elem_val[i] ;
DREAL mval = -val;
oldtempvv[old_list_len] = mval ;
oldtempii[old_list_len] = ii + diff*N + ts*N*nbest;
old_list_len++ ;
}
}
}
}
CMath::nmin<INT>(oldtempvv.get_array(), oldtempii.get_array(), old_list_len, nbest) ;
int numEnt = 0;
numEnt = old_list_len;
double minusscore;
long int fromtjk;
for (short int k=0; k<nbest; k++)
{
if (k<numEnt)
{
minusscore = oldtempvv[k];
fromtjk = oldtempii[k];
delta.element(t%max_look_back,j,k) = -minusscore + seq.element(j,t);
psi.element(t,j,k) = (fromtjk%N) ;
ktable.element(t,j,k) = (fromtjk%(N*nbest)-psi.element(t,j,k))/N ;
ptable.element(t,j,k) = (fromtjk-(fromtjk%(N*nbest)))/(N*nbest) ;
}
else
{
delta.element(t%max_look_back,j,k) = -CMath::INFTY ;
psi.element(t,j,k) = 0 ;
ktable.element(t,j,k) = 0 ;
ptable.element(t,j,k) = 0 ;
}
}
}
}
}
{ //termination
INT list_len = 0 ;
for (short int diff=0; diff<nbest; diff++)
{
for (T_STATES i=0; i<N; i++)
{
oldtempvv[list_len] = -(delta.element((seq_len-1)%max_look_back,i,diff)+get_q(i)) ;
oldtempii[list_len] = i + diff*N ;
list_len++ ;
}
}
CMath::nmin(oldtempvv.get_array(), oldtempii.get_array(), list_len, nbest) ;
for (short int k=0; k<nbest; k++)
{
delta_end.element(k) = -oldtempvv[k] ;
path_ends.element(k) = (oldtempii[k]%N) ;
ktable_end.element(k) = (oldtempii[k]-path_ends.element(k))/N ;
}
}
{ //state sequence backtracking
for (short int k=0; k<nbest; k++)
{
prob_nbest[k]= delta_end.element(k) ;
INT i = 0 ;
state_seq[i] = path_ends.element(k) ;
short int q = ktable_end.element(k) ;
pos_seq[i] = seq_len-1 ;
while (pos_seq[i]>0)
{
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
state_seq[i+1] = psi.element(pos_seq[i], state_seq[i], q);
pos_seq[i+1] = ptable.element(pos_seq[i], state_seq[i], q) ;
q = ktable.element(pos_seq[i], state_seq[i], q) ;
i++ ;
}
//SG_DEBUG("s=%i p=%i q=%i\n", state_seq[i], pos_seq[i], q) ;
INT num_states = i+1 ;
for (i=0; i<num_states;i++)
{
my_state_seq[i+k*seq_len] = state_seq[num_states-i-1] ;
}
//my_state_seq[num_states+k*seq_len]=-1 ;
}
}
}
|
/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include <signal.h>
#include "php_module.h"
#include <Poco/Path.h>
#ifdef ZTS
void ***tsrm_ls;
#endif
namespace kroll
{
KROLL_MODULE(PhpModule, STRING(MODULE_NAME), STRING(MODULE_VERSION));
PhpModule* PhpModule::instance_ = NULL;
void PhpModule::Initialize()
{
PhpModule::instance_ = this;
int argc = 1;
char *argv[] = { NULL };
php_embed_init(argc, argv PTSRMLS_CC);
}
void PhpModule::Stop()
{
PhpModule::instance_ = NULL;
php_embed_shutdown(TSRMLS_C);
}
void PhpModule::InitializeBinding()
{
}
const static std::string php_suffix = "module.php";
bool PhpModule::IsModule(std::string& path)
{
return (path.substr(path.length()-php_suffix.length()) == php_suffix);
}
Module* PhpModule::CreateModule(std::string& path)
{
// TODO: Open and load the file path with PHP
Poco::Path p(path);
std::string basename = p.getBaseName();
std::string name = basename.substr(0,basename.length()-php_suffix.length()+4);
std::string moduledir = path.substr(0,path.length()-basename.length()-4);
Logger *logger = Logger::Get("PHP");
logger->Info("Loading PHP path=%s", path.c_str());
return new PhpModuleInstance(host, path, moduledir, name);
}
}
Loading and executing path.c_str() in the PHP module.
/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include <signal.h>
#include "php_module.h"
#include <Poco/Path.h>
#ifdef ZTS
void ***tsrm_ls;
#endif
namespace kroll
{
KROLL_MODULE(PhpModule, STRING(MODULE_NAME), STRING(MODULE_VERSION));
PhpModule* PhpModule::instance_ = NULL;
void PhpModule::Initialize()
{
PhpModule::instance_ = this;
int argc = 1;
char *argv[2] = { "php_kroll", NULL };
php_embed_init(argc, argv PTSRMLS_CC);
}
void PhpModule::Stop()
{
PhpModule::instance_ = NULL;
php_embed_shutdown(TSRMLS_C);
}
void PhpModule::InitializeBinding()
{
}
const static std::string php_suffix = "module.php";
bool PhpModule::IsModule(std::string& path)
{
return (path.substr(path.length()-php_suffix.length()) == php_suffix);
}
Module* PhpModule::CreateModule(std::string& path)
{
zend_first_try {
char *include_script;
spprintf(&include_script, 0, "include '%s';", path.c_str());
zend_eval_string(include_script, NULL, (char *) path.c_str() TSRMLS_CC);
efree(include_script);
} zend_end_try();
Poco::Path p(path);
std::string basename = p.getBaseName();
std::string name = basename.substr(0,basename.length()-php_suffix.length()+4);
std::string moduledir = path.substr(0,path.length()-basename.length()-4);
Logger *logger = Logger::Get("PHP");
logger->Info("Loading PHP path=%s", path.c_str());
return new PhpModuleInstance(host, path, moduledir, name);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.