text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser_shutdown.h" #include "base/file_util.h" #include "base/histogram.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/time.h" #include "base/waitable_event.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run.h" #include "chrome/browser/jankometer.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/plugin_service.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/resource_bundle.h" #include "chrome/browser/plugin_service.h" #include "net/dns_global.h" using base::Time; using base::TimeDelta; namespace browser_shutdown { Time shutdown_started_; ShutdownType shutdown_type_ = NOT_VALID; int shutdown_num_processes_; int shutdown_num_processes_slow_; const wchar_t* const kShutdownMsFile = L"chrome_shutdown_ms.txt"; void RegisterPrefs(PrefService* local_state) { local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID); local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0); local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0); } void OnShutdownStarting(ShutdownType type) { // TODO(erikkay): http://b/753080 when onbeforeunload is supported at // shutdown, fix this to allow these variables to be reset. if (shutdown_type_ == NOT_VALID) { shutdown_type_ = type; // For now, we're only counting the number of renderer processes // since we can't safely count the number of plugin processes from this // thread, and we'd really like to avoid anything which might add further // delays to shutdown time. shutdown_num_processes_ = static_cast<int>(RenderProcessHost::size()); shutdown_started_ = Time::Now(); // Call FastShutdown on all of the RenderProcessHosts. This will be // a no-op in some cases, so we still need to go through the normal // shutdown path for the ones that didn't exit here. shutdown_num_processes_slow_ = 0; for (RenderProcessHost::iterator hosts = RenderProcessHost::begin(); hosts != RenderProcessHost::end(); ++hosts) { RenderProcessHost* rph = hosts->second; if (!rph->FastShutdownIfPossible()) // TODO(ojan): I think now that we deal with beforeunload/unload // higher up, it's not possible to get here. Confirm this and change // FastShutdownIfPossible to just be FastShutdown. shutdown_num_processes_slow_++; } } } std::wstring GetShutdownMsPath() { std::wstring shutdown_ms_file; PathService::Get(base::DIR_TEMP, &shutdown_ms_file); file_util::AppendToPath(&shutdown_ms_file, kShutdownMsFile); return shutdown_ms_file; } void Shutdown() { // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough // time to get here. If you have something that *must* happen on end session, // consider putting it in BrowserProcessImpl::EndSession. DCHECK(g_browser_process); // Notifies we are going away. g_browser_process->shutdown_event()->Signal(); PluginService* plugin_service = PluginService::GetInstance(); if (plugin_service) { plugin_service->Shutdown(); } PrefService* prefs = g_browser_process->local_state(); chrome_browser_net::SaveHostNamesForNextStartup(prefs); MetricsService* metrics = g_browser_process->metrics_service(); if (metrics) { metrics->RecordCleanShutdown(); metrics->RecordCompletedSessionEnd(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Record the shutdown info so that we can put it into a histogram at next // startup. prefs->SetInteger(prefs::kShutdownType, shutdown_type_); prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, shutdown_num_processes_slow_); } prefs->SavePersistentPrefs(g_browser_process->file_thread()); // The jank'o'meter requires that the browser process has been destroyed // before calling UninstallJankometer(). delete g_browser_process; g_browser_process = NULL; // Uninstall Jank-O-Meter here after the IO thread is no longer running. UninstallJankometer(); ResourceBundle::CleanupSharedInstance(); if (!Upgrade::IsBrowserAlreadyRunning()) { Upgrade::SwapNewChromeExeIfPresent(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Measure total shutdown time as late in the process as possible // and then write it to a file to be read at startup. // We can't use prefs since all services are shutdown at this point. TimeDelta shutdown_delta = Time::Now() - shutdown_started_; std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds()); int len = static_cast<int>(shutdown_ms.length()) + 1; std::wstring shutdown_ms_file = GetShutdownMsPath(); file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len); } } void ReadLastShutdownInfo() { std::wstring shutdown_ms_file = GetShutdownMsPath(); std::string shutdown_ms_str; int64 shutdown_ms = 0; if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str)) shutdown_ms = StringToInt64(shutdown_ms_str); DeleteFile(shutdown_ms_file.c_str()); PrefService* prefs = g_browser_process->local_state(); ShutdownType type = static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType)); int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses); int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow); // clear the prefs immediately so we don't pick them up on a future run prefs->SetInteger(prefs::kShutdownType, NOT_VALID); prefs->SetInteger(prefs::kShutdownNumProcesses, 0); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0); if (type > NOT_VALID && shutdown_ms > 0 && num_procs > 0) { const wchar_t *time_fmt = L"Shutdown.%ls.time"; const wchar_t *time_per_fmt = L"Shutdown.%ls.time_per_process"; std::wstring time; std::wstring time_per; if (type == WINDOW_CLOSE) { time = StringPrintf(time_fmt, L"window_close"); time_per = StringPrintf(time_per_fmt, L"window_close"); } else if (type == BROWSER_EXIT) { time = StringPrintf(time_fmt, L"browser_exit"); time_per = StringPrintf(time_per_fmt, L"browser_exit"); } else if (type == END_SESSION) { time = StringPrintf(time_fmt, L"end_session"); time_per = StringPrintf(time_per_fmt, L"end_session"); } else { NOTREACHED(); } if (time.length()) { // TODO(erikkay): change these to UMA histograms after a bit more testing. UMA_HISTOGRAM_TIMES(time.c_str(), TimeDelta::FromMilliseconds(shutdown_ms)); UMA_HISTOGRAM_TIMES(time_per.c_str(), TimeDelta::FromMilliseconds(shutdown_ms / num_procs)); UMA_HISTOGRAM_COUNTS_100(L"Shutdown.renderers.total", num_procs); UMA_HISTOGRAM_COUNTS_100(L"Shutdown.renderers.slow", num_procs_slow); } } } } // namespace browser_shutdown <commit_msg>Adds call to unload plugins on shutdown.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser_shutdown.h" #include "base/file_util.h" #include "base/histogram.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/time.h" #include "base/waitable_event.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run.h" #include "chrome/browser/jankometer.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/plugin_service.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/chrome_plugin_lib.h" #include "chrome/common/resource_bundle.h" #include "chrome/browser/plugin_service.h" #include "net/dns_global.h" using base::Time; using base::TimeDelta; namespace browser_shutdown { Time shutdown_started_; ShutdownType shutdown_type_ = NOT_VALID; int shutdown_num_processes_; int shutdown_num_processes_slow_; const wchar_t* const kShutdownMsFile = L"chrome_shutdown_ms.txt"; void RegisterPrefs(PrefService* local_state) { local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID); local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0); local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0); } void OnShutdownStarting(ShutdownType type) { // TODO(erikkay): http://b/753080 when onbeforeunload is supported at // shutdown, fix this to allow these variables to be reset. if (shutdown_type_ == NOT_VALID) { shutdown_type_ = type; // For now, we're only counting the number of renderer processes // since we can't safely count the number of plugin processes from this // thread, and we'd really like to avoid anything which might add further // delays to shutdown time. shutdown_num_processes_ = static_cast<int>(RenderProcessHost::size()); shutdown_started_ = Time::Now(); // Call FastShutdown on all of the RenderProcessHosts. This will be // a no-op in some cases, so we still need to go through the normal // shutdown path for the ones that didn't exit here. shutdown_num_processes_slow_ = 0; for (RenderProcessHost::iterator hosts = RenderProcessHost::begin(); hosts != RenderProcessHost::end(); ++hosts) { RenderProcessHost* rph = hosts->second; if (!rph->FastShutdownIfPossible()) // TODO(ojan): I think now that we deal with beforeunload/unload // higher up, it's not possible to get here. Confirm this and change // FastShutdownIfPossible to just be FastShutdown. shutdown_num_processes_slow_++; } } } std::wstring GetShutdownMsPath() { std::wstring shutdown_ms_file; PathService::Get(base::DIR_TEMP, &shutdown_ms_file); file_util::AppendToPath(&shutdown_ms_file, kShutdownMsFile); return shutdown_ms_file; } void Shutdown() { // Unload plugins. This needs to happen on the IO thread. if (g_browser_process->io_thread()) { g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableFunction(&ChromePluginLib::UnloadAllPlugins)); } // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough // time to get here. If you have something that *must* happen on end session, // consider putting it in BrowserProcessImpl::EndSession. DCHECK(g_browser_process); // Notifies we are going away. g_browser_process->shutdown_event()->Signal(); PluginService* plugin_service = PluginService::GetInstance(); if (plugin_service) { plugin_service->Shutdown(); } PrefService* prefs = g_browser_process->local_state(); chrome_browser_net::SaveHostNamesForNextStartup(prefs); MetricsService* metrics = g_browser_process->metrics_service(); if (metrics) { metrics->RecordCleanShutdown(); metrics->RecordCompletedSessionEnd(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Record the shutdown info so that we can put it into a histogram at next // startup. prefs->SetInteger(prefs::kShutdownType, shutdown_type_); prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, shutdown_num_processes_slow_); } prefs->SavePersistentPrefs(g_browser_process->file_thread()); // The jank'o'meter requires that the browser process has been destroyed // before calling UninstallJankometer(). delete g_browser_process; g_browser_process = NULL; // Uninstall Jank-O-Meter here after the IO thread is no longer running. UninstallJankometer(); ResourceBundle::CleanupSharedInstance(); if (!Upgrade::IsBrowserAlreadyRunning()) { Upgrade::SwapNewChromeExeIfPresent(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Measure total shutdown time as late in the process as possible // and then write it to a file to be read at startup. // We can't use prefs since all services are shutdown at this point. TimeDelta shutdown_delta = Time::Now() - shutdown_started_; std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds()); int len = static_cast<int>(shutdown_ms.length()) + 1; std::wstring shutdown_ms_file = GetShutdownMsPath(); file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len); } } void ReadLastShutdownInfo() { std::wstring shutdown_ms_file = GetShutdownMsPath(); std::string shutdown_ms_str; int64 shutdown_ms = 0; if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str)) shutdown_ms = StringToInt64(shutdown_ms_str); DeleteFile(shutdown_ms_file.c_str()); PrefService* prefs = g_browser_process->local_state(); ShutdownType type = static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType)); int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses); int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow); // clear the prefs immediately so we don't pick them up on a future run prefs->SetInteger(prefs::kShutdownType, NOT_VALID); prefs->SetInteger(prefs::kShutdownNumProcesses, 0); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0); if (type > NOT_VALID && shutdown_ms > 0 && num_procs > 0) { const wchar_t *time_fmt = L"Shutdown.%ls.time"; const wchar_t *time_per_fmt = L"Shutdown.%ls.time_per_process"; std::wstring time; std::wstring time_per; if (type == WINDOW_CLOSE) { time = StringPrintf(time_fmt, L"window_close"); time_per = StringPrintf(time_per_fmt, L"window_close"); } else if (type == BROWSER_EXIT) { time = StringPrintf(time_fmt, L"browser_exit"); time_per = StringPrintf(time_per_fmt, L"browser_exit"); } else if (type == END_SESSION) { time = StringPrintf(time_fmt, L"end_session"); time_per = StringPrintf(time_per_fmt, L"end_session"); } else { NOTREACHED(); } if (time.length()) { // TODO(erikkay): change these to UMA histograms after a bit more testing. UMA_HISTOGRAM_TIMES(time.c_str(), TimeDelta::FromMilliseconds(shutdown_ms)); UMA_HISTOGRAM_TIMES(time_per.c_str(), TimeDelta::FromMilliseconds(shutdown_ms / num_procs)); UMA_HISTOGRAM_COUNTS_100(L"Shutdown.renderers.total", num_procs); UMA_HISTOGRAM_COUNTS_100(L"Shutdown.renderers.slow", num_procs_slow); } } } } // namespace browser_shutdown <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/find_bar_gtk.h" #include <gdk/gdkkeysyms.h> #include "app/l10n_util.h" #include "base/gfx/gtk_util.h" #include "base/string_util.h" #include "chrome/browser/find_bar_controller.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/gtk/custom_button.h" #include "chrome/browser/gtk/nine_box.h" #include "chrome/browser/gtk/slide_animator_gtk.h" #include "chrome/browser/gtk/tab_contents_container_gtk.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "grit/generated_resources.h" namespace { const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4); const GdkColor kFrameBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); const GdkColor kTextBorderColor = GDK_COLOR_RGB(0xa6, 0xaf, 0xba); const GdkColor kTextBorderColorAA = GDK_COLOR_RGB(0xee, 0xf4, 0xfb); // Padding around the container. const int kBarPaddingTopBottom = 4; const int kEntryPaddingLeft = 6; const int kCloseButtonPaddingLeft = 3; const int kBarPaddingRight = 4; // The height of the findbar dialog, as dictated by the size of the background // images. const int kFindBarHeight = 32; // Get the ninebox that draws the background of |container_|. It is also used // to change the shape of |container_|. The pointer is shared by all instances // of FindBarGtk. const NineBox* GetDialogBackground() { static NineBox* dialog_background = NULL; if (!dialog_background) { dialog_background = new NineBox( IDR_FIND_DLG_LEFT_BACKGROUND, IDR_FIND_DLG_MIDDLE_BACKGROUND, IDR_FIND_DLG_RIGHT_BACKGROUND, NULL, NULL, NULL, NULL, NULL, NULL); dialog_background->ChangeWhiteToTransparent(); } return dialog_background; } // Used to handle custom painting of |container_|. gboolean OnExpose(GtkWidget* widget, GdkEventExpose* e, gpointer userdata) { GetDialogBackground()->RenderToWidget(widget); GtkWidget* child = gtk_bin_get_child(GTK_BIN(widget)); if (child) gtk_container_propagate_expose(GTK_CONTAINER(widget), child, e); return TRUE; } } // namespace FindBarGtk::FindBarGtk(BrowserWindowGtk* browser) : container_shaped_(false) { InitWidgets(); // Insert the widget into the browser gtk hierarchy. browser->AddFindBar(this); // Hook up signals after the widget has been added to the hierarchy so the // widget will be realized. g_signal_connect(find_text_, "changed", G_CALLBACK(OnChanged), this); g_signal_connect(find_text_, "key-press-event", G_CALLBACK(OnKeyPressEvent), this); g_signal_connect(widget(), "size-allocate", G_CALLBACK(OnFixedSizeAllocate), this); // We can't call ContourWidget() until after |container_| has been // allocated, hence we connect to this signal. g_signal_connect(container_, "size-allocate", G_CALLBACK(OnContainerSizeAllocate), this); g_signal_connect(container_, "expose-event", G_CALLBACK(OnExpose), NULL); } FindBarGtk::~FindBarGtk() { fixed_.Destroy(); } void FindBarGtk::InitWidgets() { // The find bar is basically an hbox with a gtkentry (text box) followed by 3 // buttons (previous result, next result, close). We wrap the hbox in a gtk // alignment and a gtk event box to get the padding and light blue // background. We put that event box in a fixed in order to control its // lateral position. We put that fixed in a SlideAnimatorGtk in order to get // the slide effect. GtkWidget* hbox = gtk_hbox_new(false, 0); container_ = gfx::CreateGtkBorderBin(hbox, &kBackgroundColor, kBarPaddingTopBottom, kBarPaddingTopBottom, kEntryPaddingLeft, kBarPaddingRight); gtk_widget_set_app_paintable(container_, TRUE); slide_widget_.reset(new SlideAnimatorGtk(container_, SlideAnimatorGtk::DOWN, 0, false, NULL)); // |fixed_| has to be at least one pixel tall. We color this pixel the same // color as the border that separates the toolbar from the tab contents. fixed_.Own(gtk_fixed_new()); border_ = gtk_event_box_new(); gtk_widget_set_size_request(border_, 1, 1); gtk_widget_modify_bg(border_, GTK_STATE_NORMAL, &kFrameBorderColor); gtk_fixed_put(GTK_FIXED(widget()), border_, 0, 0); gtk_fixed_put(GTK_FIXED(widget()), slide_widget(), 0, 0); gtk_widget_set_size_request(widget(), -1, 0); close_button_.reset( CustomDrawButton::AddBarCloseButton(hbox, kCloseButtonPaddingLeft)); g_signal_connect(G_OBJECT(close_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(close_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP).c_str()); find_next_button_.reset(new CustomDrawButton(IDR_FINDINPAGE_NEXT, IDR_FINDINPAGE_NEXT_H, IDR_FINDINPAGE_NEXT_H, IDR_FINDINPAGE_NEXT_P)); g_signal_connect(G_OBJECT(find_next_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(find_next_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_NEXT_TOOLTIP).c_str()); gtk_box_pack_end(GTK_BOX(hbox), find_next_button_->widget(), FALSE, FALSE, 0); find_previous_button_.reset(new CustomDrawButton(IDR_FINDINPAGE_PREV, IDR_FINDINPAGE_PREV_H, IDR_FINDINPAGE_PREV_H, IDR_FINDINPAGE_PREV_P)); g_signal_connect(G_OBJECT(find_previous_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(find_previous_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP).c_str()); gtk_box_pack_end(GTK_BOX(hbox), find_previous_button_->widget(), FALSE, FALSE, 0); find_text_ = gtk_entry_new(); // Force the text widget height so it lines up with the buttons regardless of // font size. gtk_widget_set_size_request(find_text_, -1, 20); gtk_entry_set_has_frame(GTK_ENTRY(find_text_), FALSE); // We fake anti-aliasing by having two borders. GtkWidget* border_bin = gfx::CreateGtkBorderBin(find_text_, &kTextBorderColor, 1, 1, 1, 0); GtkWidget* border_bin_aa = gfx::CreateGtkBorderBin(border_bin, &kTextBorderColorAA, 1, 1, 1, 0); GtkWidget* centering_vbox = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(centering_vbox), border_bin_aa, TRUE, FALSE, 0); gtk_box_pack_end(GTK_BOX(hbox), centering_vbox, FALSE, FALSE, 0); // We show just the GtkFixed and |border_| (but not the dialog). gtk_widget_show(widget()); gtk_widget_show(border_); } GtkWidget* FindBarGtk::slide_widget() { return slide_widget_->widget(); } void FindBarGtk::Show() { gtk_widget_grab_focus(find_text_); slide_widget_->Open(); } void FindBarGtk::Hide(bool animate) { if (animate) slide_widget_->Close(); else slide_widget_->CloseWithoutAnimation(); } void FindBarGtk::SetFocusAndSelection() { gtk_widget_grab_focus(find_text_); // Select all the text. gtk_entry_select_region(GTK_ENTRY(find_text_), 0, -1); } void FindBarGtk::ClearResults(const FindNotificationDetails& results) { } void FindBarGtk::StopAnimation() { NOTIMPLEMENTED(); } void FindBarGtk::MoveWindowIfNecessary(const gfx::Rect& selection_rect, bool no_redraw) { // Not moving the window on demand, so do nothing. } void FindBarGtk::SetFindText(const string16& find_text) { std::string find_text_utf8 = UTF16ToUTF8(find_text); gtk_entry_set_text(GTK_ENTRY(find_text_), find_text_utf8.c_str()); } void FindBarGtk::UpdateUIForFindResult(const FindNotificationDetails& result, const string16& find_text) { } void FindBarGtk::AudibleAlert() { gtk_widget_error_bell(widget()); } gfx::Rect FindBarGtk::GetDialogPosition(gfx::Rect avoid_overlapping_rect) { // TODO(estade): Logic for the positioning of the find bar should be factored // out of here and browser/views/* and into FindBarController. int xposition = widget()->allocation.width - slide_widget()->allocation.width - 50; return gfx::Rect(xposition, 0, 1, 1); } void FindBarGtk::SetDialogPosition(const gfx::Rect& new_pos, bool no_redraw) { gtk_fixed_move(GTK_FIXED(widget()), slide_widget(), new_pos.x(), 0); slide_widget_->OpenWithoutAnimation(); } bool FindBarGtk::IsFindBarVisible() { return GTK_WIDGET_VISIBLE(widget()); } void FindBarGtk::RestoreSavedFocus() { } FindBarTesting* FindBarGtk::GetFindBarTesting() { return this; } bool FindBarGtk::GetFindBarWindowInfo(gfx::Point* position, bool* fully_visible) { NOTIMPLEMENTED(); return false; } void FindBarGtk::FindEntryTextInContents(bool forward_search) { TabContents* tab_contents = find_bar_controller_->tab_contents(); if (!tab_contents) return; std::string new_contents(gtk_entry_get_text(GTK_ENTRY(find_text_))); if (new_contents.length() > 0) { tab_contents->StartFinding(UTF8ToUTF16(new_contents), forward_search); } else { // The textbox is empty so we reset. tab_contents->StopFinding(true); // true = clear selection on page. } } // static gboolean FindBarGtk::OnChanged(GtkWindow* window, FindBarGtk* find_bar) { find_bar->FindEntryTextInContents(true); return FALSE; } // static gboolean FindBarGtk::OnKeyPressEvent(GtkWindow* window, GdkEventKey* event, FindBarGtk* find_bar) { if (GDK_Escape == event->keyval) { find_bar->find_bar_controller_->EndFindSession(); return TRUE; } else if (GDK_Return == event->keyval) { find_bar->FindEntryTextInContents(true); return TRUE; } return FALSE; } // static void FindBarGtk::OnButtonPressed(GtkWidget* button, FindBarGtk* find_bar) { if (button == find_bar->close_button_->widget()) { find_bar->find_bar_controller_->EndFindSession(); } else if (button == find_bar->find_previous_button_->widget() || button == find_bar->find_next_button_->widget()) { find_bar->FindEntryTextInContents( button == find_bar->find_next_button_->widget()); } else { NOTREACHED(); } } // static void FindBarGtk::OnFixedSizeAllocate(GtkWidget* fixed, GtkAllocation* allocation, FindBarGtk* findbar) { // Set the background widget to the size of |fixed|. if (findbar->border_->allocation.width != allocation->width) { // Typically it's not a good idea to use this function outside of container // implementations, but GtkFixed doesn't do any sizing on its children so // in this case it's safe. gtk_widget_size_allocate(findbar->border_, allocation); } // Reposition the dialog. GtkWidget* dialog = findbar->slide_widget(); if (!GTK_WIDGET_VISIBLE(dialog)) return; int xposition = findbar->GetDialogPosition(gfx::Rect()).x(); if (xposition == dialog->allocation.x) { return; } else { gtk_fixed_move(GTK_FIXED(fixed), findbar->slide_widget(), xposition, 0); } } // static void FindBarGtk::OnContainerSizeAllocate(GtkWidget* container, GtkAllocation* allocation, FindBarGtk* findbar) { if (!findbar->container_shaped_) { GetDialogBackground()->ContourWidget(container); findbar->container_shaped_ = true; } } <commit_msg>Raise the find bar window every time it's shown via Show().<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/find_bar_gtk.h" #include <gdk/gdkkeysyms.h> #include "app/l10n_util.h" #include "base/gfx/gtk_util.h" #include "base/string_util.h" #include "chrome/browser/find_bar_controller.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/gtk/custom_button.h" #include "chrome/browser/gtk/nine_box.h" #include "chrome/browser/gtk/slide_animator_gtk.h" #include "chrome/browser/gtk/tab_contents_container_gtk.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "grit/generated_resources.h" namespace { const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4); const GdkColor kFrameBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); const GdkColor kTextBorderColor = GDK_COLOR_RGB(0xa6, 0xaf, 0xba); const GdkColor kTextBorderColorAA = GDK_COLOR_RGB(0xee, 0xf4, 0xfb); // Padding around the container. const int kBarPaddingTopBottom = 4; const int kEntryPaddingLeft = 6; const int kCloseButtonPaddingLeft = 3; const int kBarPaddingRight = 4; // The height of the findbar dialog, as dictated by the size of the background // images. const int kFindBarHeight = 32; // Get the ninebox that draws the background of |container_|. It is also used // to change the shape of |container_|. The pointer is shared by all instances // of FindBarGtk. const NineBox* GetDialogBackground() { static NineBox* dialog_background = NULL; if (!dialog_background) { dialog_background = new NineBox( IDR_FIND_DLG_LEFT_BACKGROUND, IDR_FIND_DLG_MIDDLE_BACKGROUND, IDR_FIND_DLG_RIGHT_BACKGROUND, NULL, NULL, NULL, NULL, NULL, NULL); dialog_background->ChangeWhiteToTransparent(); } return dialog_background; } // Used to handle custom painting of |container_|. gboolean OnExpose(GtkWidget* widget, GdkEventExpose* e, gpointer userdata) { GetDialogBackground()->RenderToWidget(widget); GtkWidget* child = gtk_bin_get_child(GTK_BIN(widget)); if (child) gtk_container_propagate_expose(GTK_CONTAINER(widget), child, e); return TRUE; } } // namespace FindBarGtk::FindBarGtk(BrowserWindowGtk* browser) : container_shaped_(false) { InitWidgets(); // Insert the widget into the browser gtk hierarchy. browser->AddFindBar(this); // Hook up signals after the widget has been added to the hierarchy so the // widget will be realized. g_signal_connect(find_text_, "changed", G_CALLBACK(OnChanged), this); g_signal_connect(find_text_, "key-press-event", G_CALLBACK(OnKeyPressEvent), this); g_signal_connect(widget(), "size-allocate", G_CALLBACK(OnFixedSizeAllocate), this); // We can't call ContourWidget() until after |container_| has been // allocated, hence we connect to this signal. g_signal_connect(container_, "size-allocate", G_CALLBACK(OnContainerSizeAllocate), this); g_signal_connect(container_, "expose-event", G_CALLBACK(OnExpose), NULL); } FindBarGtk::~FindBarGtk() { fixed_.Destroy(); } void FindBarGtk::InitWidgets() { // The find bar is basically an hbox with a gtkentry (text box) followed by 3 // buttons (previous result, next result, close). We wrap the hbox in a gtk // alignment and a gtk event box to get the padding and light blue // background. We put that event box in a fixed in order to control its // lateral position. We put that fixed in a SlideAnimatorGtk in order to get // the slide effect. GtkWidget* hbox = gtk_hbox_new(false, 0); container_ = gfx::CreateGtkBorderBin(hbox, &kBackgroundColor, kBarPaddingTopBottom, kBarPaddingTopBottom, kEntryPaddingLeft, kBarPaddingRight); gtk_widget_set_app_paintable(container_, TRUE); slide_widget_.reset(new SlideAnimatorGtk(container_, SlideAnimatorGtk::DOWN, 0, false, NULL)); // |fixed_| has to be at least one pixel tall. We color this pixel the same // color as the border that separates the toolbar from the tab contents. fixed_.Own(gtk_fixed_new()); border_ = gtk_event_box_new(); gtk_widget_set_size_request(border_, 1, 1); gtk_widget_modify_bg(border_, GTK_STATE_NORMAL, &kFrameBorderColor); gtk_fixed_put(GTK_FIXED(widget()), border_, 0, 0); gtk_fixed_put(GTK_FIXED(widget()), slide_widget(), 0, 0); gtk_widget_set_size_request(widget(), -1, 0); close_button_.reset( CustomDrawButton::AddBarCloseButton(hbox, kCloseButtonPaddingLeft)); g_signal_connect(G_OBJECT(close_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(close_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP).c_str()); find_next_button_.reset(new CustomDrawButton(IDR_FINDINPAGE_NEXT, IDR_FINDINPAGE_NEXT_H, IDR_FINDINPAGE_NEXT_H, IDR_FINDINPAGE_NEXT_P)); g_signal_connect(G_OBJECT(find_next_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(find_next_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_NEXT_TOOLTIP).c_str()); gtk_box_pack_end(GTK_BOX(hbox), find_next_button_->widget(), FALSE, FALSE, 0); find_previous_button_.reset(new CustomDrawButton(IDR_FINDINPAGE_PREV, IDR_FINDINPAGE_PREV_H, IDR_FINDINPAGE_PREV_H, IDR_FINDINPAGE_PREV_P)); g_signal_connect(G_OBJECT(find_previous_button_->widget()), "clicked", G_CALLBACK(OnButtonPressed), this); gtk_widget_set_tooltip_text(find_previous_button_->widget(), l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP).c_str()); gtk_box_pack_end(GTK_BOX(hbox), find_previous_button_->widget(), FALSE, FALSE, 0); find_text_ = gtk_entry_new(); // Force the text widget height so it lines up with the buttons regardless of // font size. gtk_widget_set_size_request(find_text_, -1, 20); gtk_entry_set_has_frame(GTK_ENTRY(find_text_), FALSE); // We fake anti-aliasing by having two borders. GtkWidget* border_bin = gfx::CreateGtkBorderBin(find_text_, &kTextBorderColor, 1, 1, 1, 0); GtkWidget* border_bin_aa = gfx::CreateGtkBorderBin(border_bin, &kTextBorderColorAA, 1, 1, 1, 0); GtkWidget* centering_vbox = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(centering_vbox), border_bin_aa, TRUE, FALSE, 0); gtk_box_pack_end(GTK_BOX(hbox), centering_vbox, FALSE, FALSE, 0); // We show just the GtkFixed and |border_| (but not the dialog). gtk_widget_show(widget()); gtk_widget_show(border_); } GtkWidget* FindBarGtk::slide_widget() { return slide_widget_->widget(); } void FindBarGtk::Show() { if (container_->window) gdk_window_raise(container_->window); gtk_widget_grab_focus(find_text_); slide_widget_->Open(); } void FindBarGtk::Hide(bool animate) { if (animate) slide_widget_->Close(); else slide_widget_->CloseWithoutAnimation(); } void FindBarGtk::SetFocusAndSelection() { gtk_widget_grab_focus(find_text_); // Select all the text. gtk_entry_select_region(GTK_ENTRY(find_text_), 0, -1); } void FindBarGtk::ClearResults(const FindNotificationDetails& results) { } void FindBarGtk::StopAnimation() { NOTIMPLEMENTED(); } void FindBarGtk::MoveWindowIfNecessary(const gfx::Rect& selection_rect, bool no_redraw) { // Not moving the window on demand, so do nothing. } void FindBarGtk::SetFindText(const string16& find_text) { std::string find_text_utf8 = UTF16ToUTF8(find_text); gtk_entry_set_text(GTK_ENTRY(find_text_), find_text_utf8.c_str()); } void FindBarGtk::UpdateUIForFindResult(const FindNotificationDetails& result, const string16& find_text) { } void FindBarGtk::AudibleAlert() { gtk_widget_error_bell(widget()); } gfx::Rect FindBarGtk::GetDialogPosition(gfx::Rect avoid_overlapping_rect) { // TODO(estade): Logic for the positioning of the find bar should be factored // out of here and browser/views/* and into FindBarController. int xposition = widget()->allocation.width - slide_widget()->allocation.width - 50; return gfx::Rect(xposition, 0, 1, 1); } void FindBarGtk::SetDialogPosition(const gfx::Rect& new_pos, bool no_redraw) { gtk_fixed_move(GTK_FIXED(widget()), slide_widget(), new_pos.x(), 0); slide_widget_->OpenWithoutAnimation(); } bool FindBarGtk::IsFindBarVisible() { return GTK_WIDGET_VISIBLE(widget()); } void FindBarGtk::RestoreSavedFocus() { } FindBarTesting* FindBarGtk::GetFindBarTesting() { return this; } bool FindBarGtk::GetFindBarWindowInfo(gfx::Point* position, bool* fully_visible) { NOTIMPLEMENTED(); return false; } void FindBarGtk::FindEntryTextInContents(bool forward_search) { TabContents* tab_contents = find_bar_controller_->tab_contents(); if (!tab_contents) return; std::string new_contents(gtk_entry_get_text(GTK_ENTRY(find_text_))); if (new_contents.length() > 0) { tab_contents->StartFinding(UTF8ToUTF16(new_contents), forward_search); } else { // The textbox is empty so we reset. tab_contents->StopFinding(true); // true = clear selection on page. } } // static gboolean FindBarGtk::OnChanged(GtkWindow* window, FindBarGtk* find_bar) { find_bar->FindEntryTextInContents(true); return FALSE; } // static gboolean FindBarGtk::OnKeyPressEvent(GtkWindow* window, GdkEventKey* event, FindBarGtk* find_bar) { if (GDK_Escape == event->keyval) { find_bar->find_bar_controller_->EndFindSession(); return TRUE; } else if (GDK_Return == event->keyval) { find_bar->FindEntryTextInContents(true); return TRUE; } return FALSE; } // static void FindBarGtk::OnButtonPressed(GtkWidget* button, FindBarGtk* find_bar) { if (button == find_bar->close_button_->widget()) { find_bar->find_bar_controller_->EndFindSession(); } else if (button == find_bar->find_previous_button_->widget() || button == find_bar->find_next_button_->widget()) { find_bar->FindEntryTextInContents( button == find_bar->find_next_button_->widget()); } else { NOTREACHED(); } } // static void FindBarGtk::OnFixedSizeAllocate(GtkWidget* fixed, GtkAllocation* allocation, FindBarGtk* findbar) { // Set the background widget to the size of |fixed|. if (findbar->border_->allocation.width != allocation->width) { // Typically it's not a good idea to use this function outside of container // implementations, but GtkFixed doesn't do any sizing on its children so // in this case it's safe. gtk_widget_size_allocate(findbar->border_, allocation); } // Reposition the dialog. GtkWidget* dialog = findbar->slide_widget(); if (!GTK_WIDGET_VISIBLE(dialog)) return; int xposition = findbar->GetDialogPosition(gfx::Rect()).x(); if (xposition == dialog->allocation.x) { return; } else { gtk_fixed_move(GTK_FIXED(fixed), findbar->slide_widget(), xposition, 0); } } // static void FindBarGtk::OnContainerSizeAllocate(GtkWidget* container, GtkAllocation* allocation, FindBarGtk* findbar) { if (!findbar->container_shaped_) { GetDialogBackground()->ContourWidget(container); findbar->container_shaped_ = true; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/util/nigori.h" #if defined(OS_WIN) #include <winsock2.h> // for htonl #else #include <arpa/inet.h> #endif #include <sstream> #include <vector> #include "base/base64.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/string_util.h" #include "crypto/encryptor.h" #include "crypto/hmac.h" using base::Base64Encode; using base::Base64Decode; using base::RandInt; using crypto::Encryptor; using crypto::HMAC; using crypto::SymmetricKey; namespace browser_sync { // NigoriStream simplifies the concatenation operation of the Nigori protocol. class NigoriStream { public: // Append the big-endian representation of the length of |value| with 32 bits, // followed by |value| itself to the stream. NigoriStream& operator<<(const std::string& value) { uint32 size = htonl(value.size()); stream_.write((char *) &size, sizeof(uint32)); stream_ << value; return *this; } // Append the big-endian representation of the length of |type| with 32 bits, // followed by the big-endian representation of the value of |type|, with 32 // bits, to the stream. NigoriStream& operator<<(const Nigori::Type type) { uint32 size = htonl(sizeof(uint32)); stream_.write((char *) &size, sizeof(uint32)); uint32 value = htonl(type); stream_.write((char *) &value, sizeof(uint32)); return *this; } std::string str() { return stream_.str(); } private: std::ostringstream stream_; }; // static const char Nigori::kSaltSalt[] = "saltsalt"; Nigori::Nigori() { } Nigori::~Nigori() { } bool Nigori::InitByDerivation(const std::string& hostname, const std::string& username, const std::string& password) { NigoriStream salt_password; salt_password << username << hostname; // Suser = PBKDF2(Username || Servername, "saltsalt", Nsalt, 8) scoped_ptr<SymmetricKey> user_salt(SymmetricKey::DeriveKeyFromPassword( SymmetricKey::HMAC_SHA1, salt_password.str(), kSaltSalt, kSaltIterations, kSaltKeySizeInBits)); DCHECK(user_salt.get()); std::string raw_user_salt; if (!user_salt->GetRawKey(&raw_user_salt)) return false; // Kuser = PBKDF2(P, Suser, Nuser, 16) user_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, password, raw_user_salt, kUserIterations, kDerivedKeySizeInBits)); DCHECK(user_key_.get()); // Kenc = PBKDF2(P, Suser, Nenc, 16) encryption_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, password, raw_user_salt, kEncryptionIterations, kDerivedKeySizeInBits)); DCHECK(encryption_key_.get()); // Kmac = PBKDF2(P, Suser, Nmac, 16) mac_key_.reset(SymmetricKey::DeriveKeyFromPassword( SymmetricKey::HMAC_SHA1, password, raw_user_salt, kSigningIterations, kDerivedKeySizeInBits)); DCHECK(mac_key_.get()); return true; } bool Nigori::InitByImport(const std::string& user_key, const std::string& encryption_key, const std::string& mac_key) { user_key_.reset(SymmetricKey::Import(SymmetricKey::AES, user_key)); DCHECK(user_key_.get()); encryption_key_.reset(SymmetricKey::Import(SymmetricKey::AES, encryption_key)); DCHECK(encryption_key_.get()); mac_key_.reset(SymmetricKey::Import(SymmetricKey::HMAC_SHA1, mac_key)); DCHECK(mac_key_.get()); return user_key_.get() && encryption_key_.get() && mac_key_.get(); } // Permute[Kenc,Kmac](type || name) bool Nigori::Permute(Type type, const std::string& name, std::string* permuted) const { DCHECK_LT(0U, name.size()); NigoriStream plaintext; plaintext << type << name; Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, std::string(kIvSize, 0))) return false; std::string ciphertext; if (!encryptor.Encrypt(plaintext.str(), &ciphertext)) return false; std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> hash(kHashSize); if (!hmac.Sign(ciphertext, &hash[0], hash.size())) return false; std::string output; output.assign(ciphertext); output.append(hash.begin(), hash.end()); return Base64Encode(output, permuted); } std::string GenerateRandomString(size_t size) { // TODO(albertb): Use a secure random function. std::string random(size, 0); for (size_t i = 0; i < size; ++i) random[i] = RandInt(0, 0xff); return random; } // Enc[Kenc,Kmac](value) bool Nigori::Encrypt(const std::string& value, std::string* encrypted) const { DCHECK_LT(0U, value.size()); std::string iv = GenerateRandomString(kIvSize); Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) return false; std::string ciphertext; if (!encryptor.Encrypt(value, &ciphertext)) return false; std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> hash(kHashSize); if (!hmac.Sign(ciphertext, &hash[0], hash.size())) return false; std::string output; output.assign(iv); output.append(ciphertext); output.append(hash.begin(), hash.end()); return Base64Encode(output, encrypted); } bool Nigori::Decrypt(const std::string& encrypted, std::string* value) const { std::string input; if (!Base64Decode(encrypted, &input)) return false; if (input.size() < kIvSize * 2 + kHashSize) return false; // The input is: // * iv (16 bytes) // * ciphertext (multiple of 16 bytes) // * hash (32 bytes) std::string iv(input.substr(0, kIvSize)); std::string ciphertext(input.substr(kIvSize, input.size() - (kIvSize + kHashSize))); std::string hash(input.substr(input.size() - kHashSize, kHashSize)); std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> expected(kHashSize); if (!hmac.Sign(ciphertext, &expected[0], expected.size())) return false; if (hash.compare(0, hash.size(), reinterpret_cast<char *>(&expected[0]), expected.size())) return false; Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) return false; std::string plaintext; if (!encryptor.Decrypt(ciphertext, value)) return false; return true; } bool Nigori::ExportKeys(std::string* user_key, std::string* encryption_key, std::string* mac_key) const { DCHECK(user_key); DCHECK(encryption_key); DCHECK(mac_key); return user_key_->GetRawKey(user_key) && encryption_key_->GetRawKey(encryption_key) && mac_key_->GetRawKey(mac_key); } } // namespace browser_sync <commit_msg>Fix for crash in base::SymmetricKey::GetRawKey - SymmetricKey::DeriveKeyFromPassword and SymmetricKey::Import could return NULL. If they return NULL, return false from Nigori::InitByDerivation, Nigori::InitByImport methods.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/util/nigori.h" #if defined(OS_WIN) #include <winsock2.h> // for htonl #else #include <arpa/inet.h> #endif #include <sstream> #include <vector> #include "base/base64.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/string_util.h" #include "crypto/encryptor.h" #include "crypto/hmac.h" using base::Base64Encode; using base::Base64Decode; using base::RandInt; using crypto::Encryptor; using crypto::HMAC; using crypto::SymmetricKey; namespace browser_sync { // NigoriStream simplifies the concatenation operation of the Nigori protocol. class NigoriStream { public: // Append the big-endian representation of the length of |value| with 32 bits, // followed by |value| itself to the stream. NigoriStream& operator<<(const std::string& value) { uint32 size = htonl(value.size()); stream_.write((char *) &size, sizeof(uint32)); stream_ << value; return *this; } // Append the big-endian representation of the length of |type| with 32 bits, // followed by the big-endian representation of the value of |type|, with 32 // bits, to the stream. NigoriStream& operator<<(const Nigori::Type type) { uint32 size = htonl(sizeof(uint32)); stream_.write((char *) &size, sizeof(uint32)); uint32 value = htonl(type); stream_.write((char *) &value, sizeof(uint32)); return *this; } std::string str() { return stream_.str(); } private: std::ostringstream stream_; }; // static const char Nigori::kSaltSalt[] = "saltsalt"; Nigori::Nigori() { } Nigori::~Nigori() { } bool Nigori::InitByDerivation(const std::string& hostname, const std::string& username, const std::string& password) { NigoriStream salt_password; salt_password << username << hostname; // Suser = PBKDF2(Username || Servername, "saltsalt", Nsalt, 8) scoped_ptr<SymmetricKey> user_salt(SymmetricKey::DeriveKeyFromPassword( SymmetricKey::HMAC_SHA1, salt_password.str(), kSaltSalt, kSaltIterations, kSaltKeySizeInBits)); DCHECK(user_salt.get()); std::string raw_user_salt; if (!user_salt->GetRawKey(&raw_user_salt)) return false; // Kuser = PBKDF2(P, Suser, Nuser, 16) user_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, password, raw_user_salt, kUserIterations, kDerivedKeySizeInBits)); DCHECK(user_key_.get()); // Kenc = PBKDF2(P, Suser, Nenc, 16) encryption_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, password, raw_user_salt, kEncryptionIterations, kDerivedKeySizeInBits)); DCHECK(encryption_key_.get()); // Kmac = PBKDF2(P, Suser, Nmac, 16) mac_key_.reset(SymmetricKey::DeriveKeyFromPassword( SymmetricKey::HMAC_SHA1, password, raw_user_salt, kSigningIterations, kDerivedKeySizeInBits)); DCHECK(mac_key_.get()); return user_key_.get() && encryption_key_.get() && mac_key_.get(); } bool Nigori::InitByImport(const std::string& user_key, const std::string& encryption_key, const std::string& mac_key) { user_key_.reset(SymmetricKey::Import(SymmetricKey::AES, user_key)); DCHECK(user_key_.get()); encryption_key_.reset(SymmetricKey::Import(SymmetricKey::AES, encryption_key)); DCHECK(encryption_key_.get()); mac_key_.reset(SymmetricKey::Import(SymmetricKey::HMAC_SHA1, mac_key)); DCHECK(mac_key_.get()); return user_key_.get() && encryption_key_.get() && mac_key_.get(); } // Permute[Kenc,Kmac](type || name) bool Nigori::Permute(Type type, const std::string& name, std::string* permuted) const { DCHECK_LT(0U, name.size()); NigoriStream plaintext; plaintext << type << name; Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, std::string(kIvSize, 0))) return false; std::string ciphertext; if (!encryptor.Encrypt(plaintext.str(), &ciphertext)) return false; std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> hash(kHashSize); if (!hmac.Sign(ciphertext, &hash[0], hash.size())) return false; std::string output; output.assign(ciphertext); output.append(hash.begin(), hash.end()); return Base64Encode(output, permuted); } std::string GenerateRandomString(size_t size) { // TODO(albertb): Use a secure random function. std::string random(size, 0); for (size_t i = 0; i < size; ++i) random[i] = RandInt(0, 0xff); return random; } // Enc[Kenc,Kmac](value) bool Nigori::Encrypt(const std::string& value, std::string* encrypted) const { DCHECK_LT(0U, value.size()); std::string iv = GenerateRandomString(kIvSize); Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) return false; std::string ciphertext; if (!encryptor.Encrypt(value, &ciphertext)) return false; std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> hash(kHashSize); if (!hmac.Sign(ciphertext, &hash[0], hash.size())) return false; std::string output; output.assign(iv); output.append(ciphertext); output.append(hash.begin(), hash.end()); return Base64Encode(output, encrypted); } bool Nigori::Decrypt(const std::string& encrypted, std::string* value) const { std::string input; if (!Base64Decode(encrypted, &input)) return false; if (input.size() < kIvSize * 2 + kHashSize) return false; // The input is: // * iv (16 bytes) // * ciphertext (multiple of 16 bytes) // * hash (32 bytes) std::string iv(input.substr(0, kIvSize)); std::string ciphertext(input.substr(kIvSize, input.size() - (kIvSize + kHashSize))); std::string hash(input.substr(input.size() - kHashSize, kHashSize)); std::string raw_mac_key; if (!mac_key_->GetRawKey(&raw_mac_key)) return false; HMAC hmac(HMAC::SHA256); if (!hmac.Init(raw_mac_key)) return false; std::vector<unsigned char> expected(kHashSize); if (!hmac.Sign(ciphertext, &expected[0], expected.size())) return false; if (hash.compare(0, hash.size(), reinterpret_cast<char *>(&expected[0]), expected.size())) return false; Encryptor encryptor; if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) return false; std::string plaintext; if (!encryptor.Decrypt(ciphertext, value)) return false; return true; } bool Nigori::ExportKeys(std::string* user_key, std::string* encryption_key, std::string* mac_key) const { DCHECK(user_key); DCHECK(encryption_key); DCHECK(mac_key); return user_key_->GetRawKey(user_key) && encryption_key_->GetRawKey(encryption_key) && mac_key_->GetRawKey(mac_key); } } // namespace browser_sync <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "base/file_util.h" #include "base/registry.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout) { GURL url = GetTestUrl(test_case); NavigateToURL(url); WaitForFinish(timeout); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> GURL GetTestUrl(const std::wstring &test_case) { std::wstring path; PathService::Get(chrome::DIR_TEST_DATA, &path); file_util::AppendToPath(&path, L"plugin"); file_util::AppendToPath(&path, test_case); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done"); scoped_ptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin(L"Java.html", kShortWaitTimeout); } TEST_F(PluginTest, Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout); } typedef HRESULT (__stdcall* DllRegUnregServerFunc)(); class ActiveXTest : public PluginTest { public: ActiveXTest() { dll_registered = false; } protected: void TestActiveX(const std::wstring& test_case, int timeout, bool reg_dll) { if (reg_dll) { RegisterTestControl(true); dll_registered = true; } TestPlugin(test_case, timeout); } virtual void TearDown() { PluginTest::TearDown(); if (dll_registered) RegisterTestControl(false); } void RegisterTestControl(bool register_server) { std::wstring test_control_path = browser_directory_ + L"\\activex_test_control.dll"; HMODULE h = LoadLibrary(test_control_path.c_str()); ASSERT_TRUE(h != NULL) << "Failed to load activex_test_control.dll"; const char* func_name = register_server ? "DllRegisterServer" : "DllUnregisterServer"; DllRegUnregServerFunc func = reinterpret_cast<DllRegUnregServerFunc>( GetProcAddress(h, func_name)); // This should never happen actually. ASSERT_TRUE(func != NULL) << "Failed to find reg/unreg function."; HRESULT hr = func(); const char* error_message = register_server ? "Failed to register dll." : "Failed to unregister dll"; ASSERT_TRUE(SUCCEEDED(hr)) << error_message; FreeLibrary(h); } private: bool dll_registered; }; TEST_F(ActiveXTest, EmbeddedWMP) { TestActiveX(L"activex_embedded_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, WMP) { TestActiveX(L"activex_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, CustomScripting) { TestActiveX(L"activex_custom_scripting.html", kShortWaitTimeout, true); } <commit_msg>Rollback 11498<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "base/file_util.h" #include "base/registry.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout) { GURL url = GetTestUrl(test_case); NavigateToURL(url); WaitForFinish(timeout); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> GURL GetTestUrl(const std::wstring &test_case) { std::wstring path; PathService::Get(chrome::DIR_TEST_DATA, &path); file_util::AppendToPath(&path, L"plugin"); file_util::AppendToPath(&path, test_case); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done"); scoped_ptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, Java) { TestPlugin(L"Java.html", kShortWaitTimeout); } TEST_F(PluginTest, Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout); } typedef HRESULT (__stdcall* DllRegUnregServerFunc)(); class ActiveXTest : public PluginTest { public: ActiveXTest() { dll_registered = false; } protected: void TestActiveX(const std::wstring& test_case, int timeout, bool reg_dll) { if (reg_dll) { RegisterTestControl(true); dll_registered = true; } TestPlugin(test_case, timeout); } virtual void TearDown() { PluginTest::TearDown(); if (dll_registered) RegisterTestControl(false); } void RegisterTestControl(bool register_server) { std::wstring test_control_path = browser_directory_ + L"\\activex_test_control.dll"; HMODULE h = LoadLibrary(test_control_path.c_str()); ASSERT_TRUE(h != NULL) << "Failed to load activex_test_control.dll"; const char* func_name = register_server ? "DllRegisterServer" : "DllUnregisterServer"; DllRegUnregServerFunc func = reinterpret_cast<DllRegUnregServerFunc>( GetProcAddress(h, func_name)); // This should never happen actually. ASSERT_TRUE(func != NULL) << "Failed to find reg/unreg function."; HRESULT hr = func(); const char* error_message = register_server ? "Failed to register dll." : "Failed to unregister dll"; ASSERT_TRUE(SUCCEEDED(hr)) << error_message; FreeLibrary(h); } private: bool dll_registered; }; TEST_F(ActiveXTest, EmbeddedWMP) { TestActiveX(L"activex_embedded_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, WMP) { TestActiveX(L"activex_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, CustomScripting) { TestActiveX(L"activex_custom_scripting.html", kShortWaitTimeout, true); } <|endoftext|>
<commit_before>// Created on November 19, 2013 by Lu, Wangshan. #include <diffusion/factory.hpp> #include <boost/asio.hpp> namespace diffusion { class NetWriter : public Writer { public: NetWriter(std::string const & listening_ip_address, std::uint16_t listening_port); virtual void write(ByteBuffer const & data); private: }; NetWriter::NetWriter(std::string const & listening_ip_address, std::uint16_t listening_port) { } void NetWriter::write(ByteBuffer const & data) { } } // namespace diffusion <commit_msg>More net writer.<commit_after>// Created on November 19, 2013 by Lu, Wangshan. #include <diffusion/factory.hpp> #include <thread> #include <boost/asio.hpp> namespace diffusion { class Server { public: Server(boost::asio::io_service & input_io_service) : io_service_(input_io_service) {} void shut_down() { die_ = true; } private: bool die_; boost::asio::io_service & io_service_; }; class NetWriter : public Writer { public: NetWriter(std::string const & listening_ip_address, std::uint16_t listening_port); virtual ~NetWriter(); virtual void write(ByteBuffer const & data); private: boost::asio::io_service io_service_; Server server_; std::thread server_thread_; }; NetWriter::NetWriter(std::string const & listening_ip_address, std::uint16_t listening_port) : server_(io_service_) { } NetWriter::~NetWriter() { server_.shut_down(); server_thread_.join(); } void NetWriter::write(ByteBuffer const & data) { auto serialization = prefix(data, data.size()); } } // namespace diffusion <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #include "osm_tags_reader.h" #include "utils/functions.h" #include <boost/lexical_cast.hpp> #include <iostream> #include <algorithm> #include <boost/property_tree/json_parser.hpp> #include "utils/exception.h" #include "speed_parser.h" namespace ed { namespace connectors { static void update_if_unknown(int& target, const int& source) { if (target == -1) { target = source; } } boost::optional<float> parse_way_speed(const std::map<std::string, std::string>& tags, const SpeedsParser& default_speed) { if (!tags.count("highway")) { return boost::none; } boost::optional<std::string> max_speed; std::string highway; for (std::pair<std::string, std::string> pair : tags) { std::string key = pair.first, val = pair.second; std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::transform(val.begin(), val.end(), val.begin(), ::tolower); if (key == "maxspeed") { max_speed = val; } if (key == "highway") { highway = val; } } return default_speed.get_speed(highway, max_speed); } std::bitset<8> parse_way_tags(const std::map<std::string, std::string>& tags) { // if no highway tag, we can do nothing on it if (!tags.count("highway")) { return {}; } constexpr int unknown = -1; constexpr int foot_forbiden = 0; constexpr int foot_allowed = 1; constexpr int car_forbiden = 0; constexpr int car_residential = 1; constexpr int car_tertiary = 2; constexpr int car_secondary = 3; constexpr int car_primary = 4; constexpr int car_trunk = 5; constexpr int car_motorway = 6; constexpr int bike_forbiden = 0; constexpr int bike_allowed = 2; constexpr int bike_lane = 3; constexpr int bike_busway = 4; constexpr int bike_track = 5; int car_direct = unknown; int car_reverse = unknown; int bike_direct = unknown; int bike_reverse = unknown; int foot = unknown; bool visible = true; for (std::pair<std::string, std::string> pair : tags) { std::string key = pair.first, val = pair.second; std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::transform(val.begin(), val.end(), val.begin(), ::tolower); if (key == "highway") { if (navitia::contains({"footway", "pedestrian"}, val)) { update_if_unknown(foot, foot_allowed); } else if (val == "cycleway") { update_if_unknown(bike_direct, bike_track); update_if_unknown(foot, foot_allowed); } else if (val == "path") { // http://www.cyclestreets.net/journey/help/osmconversion/#toc6 // highway = path => might mean lots of different things, so we allow bike and foot update_if_unknown(bike_direct, bike_track); update_if_unknown(foot, foot_allowed); } else if (val == "steps") { update_if_unknown(foot, foot_allowed); } else if (navitia::contains({"primary", "primary_link"}, val)) { update_if_unknown(car_direct, car_primary); update_if_unknown(foot, foot_allowed); update_if_unknown(bike_direct, bike_allowed); } else if (navitia::contains({"secondary", "secondary_link"}, val)) { update_if_unknown(car_direct, car_secondary); update_if_unknown(foot, foot_allowed); update_if_unknown(bike_direct, bike_allowed); } else if (navitia::contains({"tertiary", "tertiary_link"}, val)) { update_if_unknown(car_direct, car_tertiary); update_if_unknown(foot, foot_allowed); update_if_unknown(bike_direct, bike_allowed); } else if (navitia::contains({"unclassified", "residential", "living_street", "road", "service", "track"}, val)) { update_if_unknown(car_direct, car_residential); update_if_unknown(foot, foot_allowed); update_if_unknown(bike_direct, bike_allowed); } else if (navitia::contains({"motorway", "motorway_link"}, val)) { update_if_unknown(car_direct, car_motorway); update_if_unknown(foot, foot_forbiden); update_if_unknown(bike_direct, bike_forbiden); } else if (navitia::contains({"trunk", "trunk_link"}, val)) { update_if_unknown(car_direct, car_trunk); update_if_unknown(foot, foot_forbiden); update_if_unknown(bike_direct, bike_forbiden); } } else if (navitia::contains({"pedestrian", "foot"}, key)) { if (navitia::contains({"yes", "designated", "permissive", "lane", "official", "allowed", "destination"}, val)) { foot = foot_allowed; } else if (navitia::contains({"no", "private"}, val)) { foot = foot_forbiden; } else { std::cerr << "I don't know what to do with: " << key << "=" << val << std::endl; } } // http://wiki.openstreetmap.org/wiki/Cycleway // http://wiki.openstreetmap.org/wiki/Map_Features#Cycleway else if (key == "cycleway") { if (val == "lane" || val == "yes" || val == "true" || val == "lane_in_the_middle") bike_direct = bike_lane; else if (val == "track") bike_direct = bike_track; else if (val == "opposite_lane") bike_reverse = bike_lane; else if (val == "opposite_track") bike_reverse = bike_track; else if (val == "opposite") bike_reverse = bike_allowed; else if (val == "share_busway") bike_direct = bike_busway; else if (val == "lane_left") bike_reverse = bike_lane; else bike_direct = bike_lane; } else if (key == "bicycle") { if (val == "yes" || val == "permissive" || val == "destination" || val == "designated" || val == "private" || val == "true" || val == "allowed" || val == "official") bike_direct = bike_allowed; else if (val == "no" || val == "dismount" || val == "VTT") bike_direct = bike_forbiden; else if (val == "share_busway") bike_direct = bike_busway; else if (val == "opposite_lane" || val == "opposite") bike_reverse = bike_allowed; else std::cerr << "I don't know what to do with: " << key << "=" << val << std::endl; } else if (key == "busway") { if (navitia::contains({"yes", "track", "lane"}, val)) { update_if_unknown(bike_direct, bike_busway); } else if (navitia::contains({"opposite_lane", "opposite_track"}, val)) { update_if_unknown(bike_reverse, bike_busway); } else { update_if_unknown(bike_direct, bike_busway); } } else if (key == "oneway") { if (val == "yes" || val == "true" || val == "1") { car_reverse = car_forbiden; update_if_unknown(bike_reverse, bike_forbiden); } } else if (key == "junction") { if (val == "roundabout") { car_reverse = car_forbiden; update_if_unknown(bike_reverse, bike_forbiden); } } else if (key == "access") { if (val == "yes") { foot = foot_allowed; } else if (val == "no") { foot = foot_forbiden; } } else if (key == "public_transport") { if (val == "platform") { foot = foot_allowed; } } else if (key == "railway") { if (val == "platform") { foot = foot_allowed; } } // We do not want to autocomplete on public transport objects if (key == "public_transport") { visible = false; } else if (key == "railway") { if (val == "platform") { visible = false; } } else if (key == "highway") { if (val == "trunk" || val == "trunk_link" || val == "motorway" || val == "motorway_link") { visible = false; } } else if (key == "tunnel") { visible = false; } } update_if_unknown(car_reverse, car_direct); update_if_unknown(bike_reverse, bike_direct); update_if_unknown(car_direct, car_forbiden); update_if_unknown(bike_direct, bike_forbiden); update_if_unknown(car_reverse, car_forbiden); update_if_unknown(bike_reverse, bike_forbiden); update_if_unknown(foot, foot_forbiden); std::bitset<8> result; result[CYCLE_FWD] = (bike_direct != bike_forbiden); result[CYCLE_BWD] = (bike_reverse != bike_forbiden); result[CAR_FWD] = (car_direct != car_forbiden); result[CAR_BWD] = (car_reverse != car_forbiden); result[FOOT_FWD] = (foot != foot_forbiden); result[FOOT_BWD] = (foot != foot_forbiden); if (result.any()) { // only set visibility if the road is usable result[VISIBLE] = visible; } return result; } PoiTypeParams::PoiTypeParams(const std::string& json_params) { namespace pt = boost::property_tree; pt::ptree poi_root; std::istringstream iss(json_params); pt::read_json(iss, poi_root); for (const pt::ptree::value_type& json_poi_type : poi_root.get_child("poi_types")) { const auto& poi_type_id = json_poi_type.second.get<std::string>("id"); const auto& poi_type_name = json_poi_type.second.get<std::string>("name"); if (!poi_types.insert({poi_type_id, poi_type_name}).second) { throw std::invalid_argument("POI type id " + poi_type_id + " is defined multiple times"); } } if (poi_types.find("amenity:parking") == poi_types.end() || poi_types.find("amenity:bicycle_rental") == poi_types.end()) { throw std::invalid_argument( "The 2 POI types id=amenity:parking and " "id=amenity:bicycle_rental must be defined"); } for (const pt::ptree::value_type& json_rule : poi_root.get_child("rules")) { rules.emplace_back(); auto& rule = rules.back(); rule.poi_type_id = json_rule.second.get<std::string>("poi_type_id"); if (poi_types.find(rule.poi_type_id) == poi_types.end()) { throw std::invalid_argument("Using an undefined POI type id (" + rule.poi_type_id + ") in rules"); } for (const pt::ptree::value_type& json_filter : json_rule.second.get_child("osm_tags_filters")) { rule.osm_tag_filters[json_filter.second.get<std::string>("key")] = json_filter.second.get<std::string>("value"); } } } /** * the first rule that matches OSM object decides POI-type * match : OSM object has all OSM tags required by rule */ const RuleOsmTag2PoiType* PoiTypeParams::get_applicable_poi_rule(const CanalTP::Tags& tags) const { auto poi_misses_a_tag = [&](const std::pair<const std::string, std::string>& osm_rule_tag) { const auto it_poi_tag = tags.find(osm_rule_tag.first); return (it_poi_tag == tags.end() || it_poi_tag->second != osm_rule_tag.second); }; for (const auto& osm_rule : rules) { if (!navitia::contains_if(osm_rule.osm_tag_filters, poi_misses_a_tag)) { return &osm_rule; } } return nullptr; } const std::string get_postal_code_from_tags(const CanalTP::Tags& tags) { if (tags.find("addr:postcode") != tags.end()) { return tags.at("addr:postcode"); } if (tags.find("postal_code") != tags.end()) { return tags.at("postal_code"); } return std::string(); } } // namespace connectors } // namespace ed <commit_msg>Refactoring of parse_way_tags function<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #include "osm_tags_reader.h" #include "utils/functions.h" #include <boost/lexical_cast.hpp> #include <iostream> #include <algorithm> #include <unordered_map> #include <boost/property_tree/json_parser.hpp> #include "utils/exception.h" #include "speed_parser.h" namespace ed { namespace connectors { static void update_if_unknown(int& target, const int& source) { if (target == -1) { target = source; } } boost::optional<float> parse_way_speed(const std::map<std::string, std::string>& tags, const SpeedsParser& default_speed) { if (!tags.count("highway")) { return boost::none; } boost::optional<std::string> max_speed; std::string highway; for (std::pair<std::string, std::string> pair : tags) { std::string key = pair.first, val = pair.second; std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::transform(val.begin(), val.end(), val.begin(), ::tolower); if (key == "maxspeed") { max_speed = val; } if (key == "highway") { highway = val; } } return default_speed.get_speed(highway, max_speed); } std::bitset<8> parse_way_tags(const std::map<std::string, std::string>& tags) { // if no highway tag, we can do nothing on it if (!tags.count("highway")) { return {}; } constexpr int unknown = -1; constexpr int foot_forbidden = 0; constexpr int foot_allowed = 1; constexpr int car_forbidden = 0; constexpr int car_residential = 1; constexpr int car_tertiary = 2; constexpr int car_secondary = 3; constexpr int car_primary = 4; constexpr int car_trunk = 5; constexpr int car_motorway = 6; constexpr int bike_forbidden = 0; constexpr int bike_allowed = 2; constexpr int bike_lane = 3; constexpr int bike_busway = 4; constexpr int bike_track = 5; int car_direct = unknown; int car_reverse = unknown; int bike_direct = unknown; int bike_reverse = unknown; int foot = unknown; bool visible = true; auto set_visible_false = [&]() { visible = false; }; auto update_foot_allowed = [&]() { update_if_unknown(foot, foot_allowed); }; auto set_foot_allowed = [&]() { foot = foot_allowed; }; auto set_foot_forbidden = [&]() { foot = foot_forbidden; }; auto update_bike_direct_track = [&]() { update_if_unknown(bike_direct, bike_track); }; auto update_bike_direct_busway = [&]() { update_if_unknown(bike_direct, bike_busway); }; auto update_bike_reverse_busway = [&]() { update_if_unknown(bike_reverse, bike_busway); }; auto update_bike_reverse_forbidden = [&]() { update_if_unknown(bike_reverse, bike_forbidden); }; auto set_bike_reverse_allowed = [&] { bike_reverse = bike_allowed; }; auto set_bike_reverse_track = [&] { bike_reverse = bike_track; }; auto set_bike_reverse_lane = [&] { bike_reverse = bike_lane; }; auto set_bike_direct_allowed = [&]() { bike_direct = bike_allowed; }; auto set_bike_direct_forbidden = [&]() { bike_direct = bike_forbidden; }; auto set_bike_direct_track = [&] { bike_direct = bike_track; }; auto set_bike_direct_lane = [&]() { bike_direct = bike_lane; }; auto set_bike_direct_busway = [&]() { bike_direct = bike_busway; }; auto update_car_direct_primary = [&]() { update_if_unknown(car_direct, car_primary); update_foot_allowed(); update_if_unknown(bike_direct, bike_allowed); }; auto update_car_direct_secondary = [&]() { update_if_unknown(car_direct, car_secondary); update_foot_allowed(); update_if_unknown(bike_direct, bike_allowed); }; auto update_car_direct_tertiary = [&]() { update_if_unknown(car_direct, car_tertiary); update_foot_allowed(); update_if_unknown(bike_direct, bike_allowed); }; auto update_car_direct_residentiary = [&]() { update_if_unknown(car_direct, car_residential); update_foot_allowed(); update_if_unknown(bike_direct, bike_allowed); }; auto update_car_direct_motorway = [&]() { update_if_unknown(car_direct, car_motorway); update_if_unknown(foot, foot_forbidden); update_if_unknown(bike_direct, bike_forbidden); }; auto update_car_direct_trunk = [&]() { update_if_unknown(car_direct, car_trunk); update_if_unknown(foot, foot_forbidden); update_if_unknown(bike_direct, bike_forbidden); }; auto set_car_reverse_forbidden = [&]() { car_reverse = car_forbidden; }; for (std::pair<std::string, std::string> pair : tags) { std::unordered_map<std::string, std::unordered_map<std::string, std::function<void()>>> key_map = { {"highway", { {"footway", update_foot_allowed}, {"pedestrian", update_foot_allowed}, {"cycleway", [&]() { update_bike_direct_track(); update_foot_allowed(); }}, {"path", [&]() { // http://www.cyclestreets.net/journey/help/osmconversion/#toc6 // highway = path => might mean lots of different things, so we allow bike and foot update_bike_direct_track(); update_foot_allowed(); }}, {"steps", update_foot_allowed}, {"primary", update_car_direct_primary}, {"primary_link", update_car_direct_primary}, {"secondary", update_car_direct_secondary}, {"secondary_link", update_car_direct_secondary}, {"tertiary", update_car_direct_tertiary}, {"tertiary_link", update_car_direct_tertiary}, {"unclassified", update_car_direct_residentiary}, {"residential", update_car_direct_residentiary}, {"living_street", update_car_direct_residentiary}, {"road", update_car_direct_residentiary}, {"service", update_car_direct_residentiary}, {"track", update_car_direct_residentiary}, {"motorway", [&]() { update_car_direct_motorway(); set_visible_false(); }}, {"motorway_link", [&]() { update_car_direct_motorway(); set_visible_false(); }}, {"trunk", [&]() { update_car_direct_trunk(); set_visible_false(); }}, {"trunk_link", [&]() { update_car_direct_trunk(); set_visible_false(); }}, }}, {"pedestrian", { {"yes", set_foot_allowed}, {"designated", set_foot_allowed}, {"permissive", set_foot_allowed}, {"lane", set_foot_allowed}, {"official", set_foot_allowed}, {"allowed", set_foot_allowed}, {"destination", set_foot_allowed}, {"no", set_foot_forbidden}, {"private", set_foot_forbidden}, }}, {"foot", { {"yes", set_foot_allowed}, {"designated", set_foot_allowed}, {"permissive", set_foot_allowed}, {"lane", set_foot_allowed}, {"official", set_foot_allowed}, {"allowed", set_foot_allowed}, {"destination", set_foot_allowed}, {"no", set_foot_forbidden}, {"private", set_foot_forbidden}, }}, // http://wiki.openstreetmap.org/wiki/Cycleway // http://wiki.openstreetmap.org/wiki/Map_Features#Cycleway {"cycleway", { {"lane", set_bike_direct_lane}, {"yes", set_bike_direct_lane}, {"true", set_bike_direct_lane}, {"lane_in_the_middle", set_bike_direct_lane}, {"track", set_bike_direct_track}, {"opposite_lane", set_bike_reverse_lane}, {"opposite_track", set_bike_reverse_track}, {"opposite", set_bike_reverse_allowed}, {"share_busway", set_bike_direct_busway}, {"lane_left", set_bike_reverse_lane}, {"_default", set_bike_direct_lane}, }}, {"bicycle", { {"yes", set_bike_direct_allowed}, {"permissive", set_bike_direct_allowed}, {"destination", set_bike_direct_allowed}, {"designated", set_bike_direct_allowed}, {"private", set_bike_direct_allowed}, {"true", set_bike_direct_allowed}, {"allowed", set_bike_direct_allowed}, {"official", set_bike_direct_allowed}, {"no", set_bike_direct_forbidden}, {"dismount", set_bike_direct_forbidden}, {"VTT", set_bike_direct_forbidden}, {"share_busway", set_bike_direct_busway}, {"opposite_lane", set_bike_reverse_allowed}, {"opposite", set_bike_reverse_allowed}, }}, {"busway", { {"yes", update_bike_direct_busway}, {"track", update_bike_direct_busway}, {"lane", update_bike_direct_busway}, {"opposite_lane", update_bike_reverse_busway}, {"opposite_track", update_bike_reverse_busway}, {"_default", update_bike_direct_busway}, }}, {"oneway", { {"yes", [&]() { set_car_reverse_forbidden(); update_bike_reverse_forbidden(); }}, {"true", [&]() { set_car_reverse_forbidden(); update_bike_reverse_forbidden(); }}, {"1", [&]() { set_car_reverse_forbidden(); update_bike_reverse_forbidden(); }}, }}, {"junction", { {"roundabout", [&]() { set_car_reverse_forbidden(); update_bike_reverse_forbidden(); }}, }}, {"access", { {"yes", set_foot_allowed}, {"no", set_foot_forbidden}, }}, {"public_transport", { {"platform", set_foot_allowed}, }}, {"railway", { {"platform", [&]() { set_foot_allowed(); set_visible_false(); }}, }}, }; std::string key = pair.first, val = pair.second; std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::transform(val.begin(), val.end(), val.begin(), ::tolower); // We do not want to autocomplete on public transport objects and tunnels if (key == "public_transport" || key == "tunnel") { set_visible_false(); } try { key_map[key].at(val)(); } catch (...) { try { key_map[key].at("_default")(); } catch (...) { std::cerr << "I don't know what to do with: " << key << "=" << val << std::endl; } } } update_if_unknown(car_reverse, car_direct); update_if_unknown(bike_reverse, bike_direct); update_if_unknown(car_direct, car_forbidden); update_if_unknown(bike_direct, bike_forbidden); update_if_unknown(car_reverse, car_forbidden); update_if_unknown(bike_reverse, bike_forbidden); update_if_unknown(foot, foot_forbidden); std::bitset<8> result; result[CYCLE_FWD] = (bike_direct != bike_forbidden); result[CYCLE_BWD] = (bike_reverse != bike_forbidden); result[CAR_FWD] = (car_direct != car_forbidden); result[CAR_BWD] = (car_reverse != car_forbidden); result[FOOT_FWD] = (foot != foot_forbidden); result[FOOT_BWD] = (foot != foot_forbidden); if (result.any()) { // only set visibility if the road is usable result[VISIBLE] = visible; } return result; } PoiTypeParams::PoiTypeParams(const std::string& json_params) { namespace pt = boost::property_tree; pt::ptree poi_root; std::istringstream iss(json_params); pt::read_json(iss, poi_root); for (const pt::ptree::value_type& json_poi_type : poi_root.get_child("poi_types")) { const auto& poi_type_id = json_poi_type.second.get<std::string>("id"); const auto& poi_type_name = json_poi_type.second.get<std::string>("name"); if (!poi_types.insert({poi_type_id, poi_type_name}).second) { throw std::invalid_argument("POI type id " + poi_type_id + " is defined multiple times"); } } if (poi_types.find("amenity:parking") == poi_types.end() || poi_types.find("amenity:bicycle_rental") == poi_types.end()) { throw std::invalid_argument( "The 2 POI types id=amenity:parking and " "id=amenity:bicycle_rental must be defined"); } for (const pt::ptree::value_type& json_rule : poi_root.get_child("rules")) { rules.emplace_back(); auto& rule = rules.back(); rule.poi_type_id = json_rule.second.get<std::string>("poi_type_id"); if (poi_types.find(rule.poi_type_id) == poi_types.end()) { throw std::invalid_argument("Using an undefined POI type id (" + rule.poi_type_id + ") in rules"); } for (const pt::ptree::value_type& json_filter : json_rule.second.get_child("osm_tags_filters")) { rule.osm_tag_filters[json_filter.second.get<std::string>("key")] = json_filter.second.get<std::string>("value"); } } } /** * the first rule that matches OSM object decides POI-type * match : OSM object has all OSM tags required by rule */ const RuleOsmTag2PoiType* PoiTypeParams::get_applicable_poi_rule(const CanalTP::Tags& tags) const { auto poi_misses_a_tag = [&](const std::pair<const std::string, std::string>& osm_rule_tag) { const auto it_poi_tag = tags.find(osm_rule_tag.first); return (it_poi_tag == tags.end() || it_poi_tag->second != osm_rule_tag.second); }; for (const auto& osm_rule : rules) { if (!navitia::contains_if(osm_rule.osm_tag_filters, poi_misses_a_tag)) { return &osm_rule; } } return nullptr; } const std::string get_postal_code_from_tags(const CanalTP::Tags& tags) { if (tags.find("addr:postcode") != tags.end()) { return tags.at("addr:postcode"); } if (tags.find("postal_code") != tags.end()) { return tags.at("postal_code"); } return std::string(); } } // namespace connectors } // namespace ed <|endoftext|>
<commit_before>#include "Character.h" #include "Ship.h" #include "Gang.h" #include "Engine.h" #include "Area.h" #include "Skill.h" #include "Attribute.h" #include "Modifier.h" #include "LocationGroupModifier.h" #include "LocationRequiredSkillModifier.h" #include "Implant.h" #include "Booster.h" #include <algorithm> #include <limits> #include "Structure.h" using namespace dgmpp; static const TypeID CHARACTER_TYPE_ID = 1381; Character::Character(std::shared_ptr<Engine> const& engine, std::shared_ptr<Gang> const& owner, const char* characterName) : Item(engine, CHARACTER_TYPE_ID, owner), characterName_(characterName), ship_(nullptr) { } Character::~Character(void) { } std::shared_ptr<Ship> Character::getShip() { return ship_; } std::shared_ptr<Ship> Character::setShip(TypeID typeID) { try { loadIfNeeded(); auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Ship> ship = std::make_shared<Ship>(engine, typeID, shared_from_this()); if (ship_) removeEffects(Effect::CATEGORY_GENERIC); ship_ = ship; if (ship_) addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return ship; } catch(Item::UnknownTypeIDException) { return nullptr; } } std::shared_ptr<Structure> Character::setStructure(TypeID typeID) { try { loadIfNeeded(); auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Structure> structure = std::make_shared<Structure>(engine, typeID, shared_from_this()); if (structure_) removeEffects(Effect::CATEGORY_GENERIC); structure_ = structure; if (structure_) addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return structure_; } catch(Item::UnknownTypeIDException) { return nullptr; } } std::shared_ptr<Structure> Character::getStructure() { return structure_; } void Character::reset() { Item::reset(); if (ship_ != nullptr) ship_->reset(); if (structure_ != nullptr) structure_->reset(); //for (const std::pair<int, const std::shared_ptr<Skill>&>& i: skills_) for (const auto& i: skills_) i.second->reset(); for (const auto& i: implants_) i->reset(); for (const auto& i: boosters_) i->reset(); } std::shared_ptr<Skill> Character::addSkill(TypeID typeID, int skillLevel, bool isLearned) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Skill> skill = std::make_shared<Skill>(engine, typeID, skillLevel, isLearned, shared_from_this()); skills_[typeID] = skill; // if (getOwner() && ship_ != nullptr) if (ship_ || structure_) skill->addEffects(Effect::CATEGORY_GENERIC); return skill; } catch(Item::UnknownTypeIDException) { return nullptr; } } void Character::removeSkill(std::shared_ptr<Skill> const& skill) { // if (getOwner() && ship_ != NULL) if (ship_ || structure_) skill->removeEffects(Effect::CATEGORY_GENERIC); skills_.erase(skill->getTypeID()); } std::shared_ptr<Skill> Character::getSkill(TypeID typeID) { return skills_[typeID]; } const SkillsMap& Character::getSkills() { return skills_; } bool Character::emptyImplantSlot(int slot) { return !getImplant(slot); } bool Character::emptyBoosterSlot(int slot) { return !getBooster(slot); } std::shared_ptr<Implant> Character::getImplant(int slot) { auto i = std::find_if(implants_.begin(), implants_.end(), [=](std::shared_ptr<Implant> implant) { return implant->getSlot() == slot; }); return i != implants_.end() ? *i : nullptr; } std::shared_ptr<Booster> Character::getBooster(int slot) { auto i = std::find_if(boosters_.begin(), boosters_.end(), [=](std::shared_ptr<Booster> booster) { return booster->getSlot() == slot; }); return i != boosters_.end() ? *i : nullptr; } std::shared_ptr<Implant> Character::addImplant(TypeID typeID, bool forced) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Implant> implant = std::make_shared<Implant>(engine, typeID, shared_from_this()); std::shared_ptr<Implant> currentImplant = getImplant(implant->getSlot()); if (currentImplant) { if (forced) removeImplant(currentImplant); else return currentImplant; } implants_.push_back(implant); if (ship_) implant->addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return implant; } catch(Item::UnknownTypeIDException) { return NULL; } } std::shared_ptr<Booster> Character::addBooster(TypeID typeID, bool forced) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Booster> booster = std::make_shared<Booster>(engine, typeID, shared_from_this()); std::shared_ptr<Booster> currentBooster = getBooster(booster->getSlot()); if (currentBooster) { if (forced) removeBooster(currentBooster); else return currentBooster; } boosters_.push_back(booster); if (ship_) booster->addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return booster; } catch(Item::UnknownTypeIDException) { return NULL; } } void Character::removeImplant(std::shared_ptr<Implant> const& implant) { if (implant != NULL) { if (ship_) implant->removeEffects(Effect::CATEGORY_GENERIC); //implants_.remove(implant); implants_.erase(std::find(implants_.begin(), implants_.end(), implant)); auto engine = getEngine(); if (engine) engine->reset(); } } void Character::removeBooster(std::shared_ptr<Booster> const& booster) { if (booster != NULL) { if (ship_) booster->removeEffects(Effect::CATEGORY_GENERIC); //boosters_.remove(booster); boosters_.erase(std::find(boosters_.begin(), boosters_.end(), booster)); auto engine = getEngine(); if (engine) engine->reset(); } } const ImplantsList& Character::getImplants() { return implants_; } const BoostersList& Character::getBoosters() { return boosters_; } void Character::addEffects(Effect::Category category) { if (ship_ || structure_) { Item::addEffects(category); if (category == Effect::CATEGORY_GENERIC) { if (ship_) ship_->addEffects(Effect::CATEGORY_GENERIC); if (structure_) structure_->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: skills_) i.second->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: implants_) i->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: boosters_) i->addEffects(Effect::CATEGORY_GENERIC); } } } void Character::removeEffects(Effect::Category category) { if (ship_ || structure_) { Item::removeEffects(category); if (category == Effect::CATEGORY_GENERIC) { if (ship_) ship_->removeEffects(Effect::CATEGORY_GENERIC); if (structure_) structure_->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: skills_) i.second->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: implants_) i->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: boosters_) i->removeEffects(Effect::CATEGORY_GENERIC); } } } void Character::setCharacterName(const char* characterName) { characterName_ = characterName ? characterName : ""; } const char* Character::getCharacterName() { return characterName_.c_str(); } void Character::setSkillLevels(const std::map<TypeID, int>& levels) { auto engine = getEngine(); if (!engine) return; std::map<TypeID, int>::const_iterator j, endj = levels.end(); for (const auto& i: skills_) { j = levels.find(i.first); if (j != endj) i.second->setSkillLevel(j->second); else i.second->setSkillLevel(0); } engine->reset(); } void Character::setAllSkillsLevel(int level) { auto engine = getEngine(); if (!engine) return; for (const auto& i: skills_) i.second->setSkillLevel(level); engine->reset(); } Float Character::getDroneControlDistance() { return getAttribute(DRONE_CONTROL_DISTANCE_ATTRIBUTE_ID)->getValue(); } std::insert_iterator<ModifiersList> Character::getLocationModifiers(Attribute* attribute, std::insert_iterator<ModifiersList> outIterator) { outIterator = Item::getLocationModifiers(attribute, outIterator); auto owner = getOwner(); if (owner) outIterator = owner->getLocationModifiers(attribute, outIterator); return outIterator; } void Character::lazyLoad() { auto engine = getEngine(); if (!engine) return; Item::lazyLoad(); //std::shared_ptr<FetchResult> result = engine->getSqlConnector()->exec("SELECT typeID FROM invTypes, invGroups WHERE invTypes.groupID = invGroups.groupID AND invGroups.categoryID = 16 AND invTypes.published = 1"); auto stmt = engine->getSqlConnector()->getReusableFetchRequest("SELECT typeID FROM invTypes, invGroups WHERE invTypes.groupID = invGroups.groupID AND invGroups.categoryID = 16 AND invTypes.published = 1"); std::shared_ptr<FetchResult> result = engine->getSqlConnector()->exec(stmt); while (result->next()) { TypeID skillID = result->getInt(0); addSkill(skillID, 0, false); } } Item* Character::character() { return this; } Item* Character::ship() { return getShip().get(); } Item* Character::structure() { return getStructure().get(); } std::ostream& dgmpp::operator<<(std::ostream& os, dgmpp::Character& character) { os << "{\"typeName\":\"Character\",\"ship\":" << *character.ship_ << ", \"attributes\":["; if (character.attributes_.size() > 0) { bool isFirst = true; for (const auto& i: character.attributes_) { if (isFirst) isFirst = false; else os << ','; os << *i.second; } } os << "], \"effects\":["; if (character.effects_.size() > 0) { bool isFirst = true; for (const auto& i: character.effects_) { if (isFirst) isFirst = false; else os << ','; os << *i; } } os << "], \"itemModifiers\":["; if (character.itemModifiers_.size() > 0) { bool isFirst = true; for (const auto& list: character.itemModifiers_) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } os << "], \"locationModifiers\":["; if (character.locationModifiers_.size() > 0) { bool isFirst = true; for (const auto& list: character.locationModifiers_) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } os << "], \"locationGroupModifiers\":["; if (character.locationGroupModifiers_.size() > 0) { bool isFirst = true; for (const auto& map: character.locationGroupModifiers_) { for (const auto& list: map.second) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } } os << "], \"locationRequiredSkillModifiers\":["; if (character.locationRequiredSkillModifiers_.size() > 0) { bool isFirst = true; for (const auto& map: character.locationRequiredSkillModifiers_) { for (const auto& list: map.second) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } } /* os << "],\"skills\":["; if (character.skills_.size() > 0) { SkillsMap::const_iterator i, end = character.skills_.end(); bool isFirst = true; for (i = character.skills_.begin(); i != end; i++) { if (isFirst) isFirst = false; else os << ','; os << *(i->second); } }*/ os << "]}"; return os; } <commit_msg>Character skills loading fix<commit_after>#include "Character.h" #include "Ship.h" #include "Gang.h" #include "Engine.h" #include "Area.h" #include "Skill.h" #include "Attribute.h" #include "Modifier.h" #include "LocationGroupModifier.h" #include "LocationRequiredSkillModifier.h" #include "Implant.h" #include "Booster.h" #include <algorithm> #include <limits> #include "Structure.h" using namespace dgmpp; static const TypeID CHARACTER_TYPE_ID = 1381; Character::Character(std::shared_ptr<Engine> const& engine, std::shared_ptr<Gang> const& owner, const char* characterName) : Item(engine, CHARACTER_TYPE_ID, owner), characterName_(characterName), ship_(nullptr) { } Character::~Character(void) { } std::shared_ptr<Ship> Character::getShip() { return ship_; } std::shared_ptr<Ship> Character::setShip(TypeID typeID) { try { loadIfNeeded(); auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Ship> ship = std::make_shared<Ship>(engine, typeID, shared_from_this()); if (ship_) removeEffects(Effect::CATEGORY_GENERIC); ship_ = ship; if (ship_) addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return ship; } catch(Item::UnknownTypeIDException) { return nullptr; } } std::shared_ptr<Structure> Character::setStructure(TypeID typeID) { try { loadIfNeeded(); auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Structure> structure = std::make_shared<Structure>(engine, typeID, shared_from_this()); if (structure_) removeEffects(Effect::CATEGORY_GENERIC); structure_ = structure; if (structure_) addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return structure_; } catch(Item::UnknownTypeIDException) { return nullptr; } } std::shared_ptr<Structure> Character::getStructure() { return structure_; } void Character::reset() { Item::reset(); if (ship_ != nullptr) ship_->reset(); if (structure_ != nullptr) structure_->reset(); //for (const std::pair<int, const std::shared_ptr<Skill>&>& i: skills_) for (const auto& i: skills_) i.second->reset(); for (const auto& i: implants_) i->reset(); for (const auto& i: boosters_) i->reset(); } std::shared_ptr<Skill> Character::addSkill(TypeID typeID, int skillLevel, bool isLearned) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Skill> skill = std::make_shared<Skill>(engine, typeID, skillLevel, isLearned, shared_from_this()); skills_[typeID] = skill; // if (getOwner() && ship_ != nullptr) if (ship_ || structure_) skill->addEffects(Effect::CATEGORY_GENERIC); return skill; } catch(Item::UnknownTypeIDException) { return nullptr; } } void Character::removeSkill(std::shared_ptr<Skill> const& skill) { // if (getOwner() && ship_ != NULL) if (ship_ || structure_) skill->removeEffects(Effect::CATEGORY_GENERIC); skills_.erase(skill->getTypeID()); } std::shared_ptr<Skill> Character::getSkill(TypeID typeID) { return skills_[typeID]; } const SkillsMap& Character::getSkills() { return skills_; } bool Character::emptyImplantSlot(int slot) { return !getImplant(slot); } bool Character::emptyBoosterSlot(int slot) { return !getBooster(slot); } std::shared_ptr<Implant> Character::getImplant(int slot) { auto i = std::find_if(implants_.begin(), implants_.end(), [=](std::shared_ptr<Implant> implant) { return implant->getSlot() == slot; }); return i != implants_.end() ? *i : nullptr; } std::shared_ptr<Booster> Character::getBooster(int slot) { auto i = std::find_if(boosters_.begin(), boosters_.end(), [=](std::shared_ptr<Booster> booster) { return booster->getSlot() == slot; }); return i != boosters_.end() ? *i : nullptr; } std::shared_ptr<Implant> Character::addImplant(TypeID typeID, bool forced) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Implant> implant = std::make_shared<Implant>(engine, typeID, shared_from_this()); std::shared_ptr<Implant> currentImplant = getImplant(implant->getSlot()); if (currentImplant) { if (forced) removeImplant(currentImplant); else return currentImplant; } implants_.push_back(implant); if (ship_) implant->addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return implant; } catch(Item::UnknownTypeIDException) { return NULL; } } std::shared_ptr<Booster> Character::addBooster(TypeID typeID, bool forced) { try { auto engine = getEngine(); if (!engine) return nullptr; std::shared_ptr<Booster> booster = std::make_shared<Booster>(engine, typeID, shared_from_this()); std::shared_ptr<Booster> currentBooster = getBooster(booster->getSlot()); if (currentBooster) { if (forced) removeBooster(currentBooster); else return currentBooster; } boosters_.push_back(booster); if (ship_) booster->addEffects(Effect::CATEGORY_GENERIC); engine->reset(); return booster; } catch(Item::UnknownTypeIDException) { return NULL; } } void Character::removeImplant(std::shared_ptr<Implant> const& implant) { if (implant != NULL) { if (ship_) implant->removeEffects(Effect::CATEGORY_GENERIC); //implants_.remove(implant); implants_.erase(std::find(implants_.begin(), implants_.end(), implant)); auto engine = getEngine(); if (engine) engine->reset(); } } void Character::removeBooster(std::shared_ptr<Booster> const& booster) { if (booster != NULL) { if (ship_) booster->removeEffects(Effect::CATEGORY_GENERIC); //boosters_.remove(booster); boosters_.erase(std::find(boosters_.begin(), boosters_.end(), booster)); auto engine = getEngine(); if (engine) engine->reset(); } } const ImplantsList& Character::getImplants() { return implants_; } const BoostersList& Character::getBoosters() { return boosters_; } void Character::addEffects(Effect::Category category) { if (ship_ || structure_) { Item::addEffects(category); if (category == Effect::CATEGORY_GENERIC) { if (ship_) ship_->addEffects(Effect::CATEGORY_GENERIC); if (structure_) structure_->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: skills_) i.second->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: implants_) i->addEffects(Effect::CATEGORY_GENERIC); for (const auto& i: boosters_) i->addEffects(Effect::CATEGORY_GENERIC); } } } void Character::removeEffects(Effect::Category category) { if (ship_ || structure_) { Item::removeEffects(category); if (category == Effect::CATEGORY_GENERIC) { if (ship_) ship_->removeEffects(Effect::CATEGORY_GENERIC); if (structure_) structure_->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: skills_) i.second->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: implants_) i->removeEffects(Effect::CATEGORY_GENERIC); for (const auto& i: boosters_) i->removeEffects(Effect::CATEGORY_GENERIC); } } } void Character::setCharacterName(const char* characterName) { characterName_ = characterName ? characterName : ""; } const char* Character::getCharacterName() { return characterName_.c_str(); } void Character::setSkillLevels(const std::map<TypeID, int>& levels) { loadIfNeeded(); auto engine = getEngine(); if (!engine) return; std::map<TypeID, int>::const_iterator j, endj = levels.end(); for (const auto& i: skills_) { j = levels.find(i.first); if (j != endj) i.second->setSkillLevel(j->second); else i.second->setSkillLevel(0); } engine->reset(); } void Character::setAllSkillsLevel(int level) { loadIfNeeded(); auto engine = getEngine(); if (!engine) return; for (const auto& i: skills_) i.second->setSkillLevel(level); engine->reset(); } Float Character::getDroneControlDistance() { return getAttribute(DRONE_CONTROL_DISTANCE_ATTRIBUTE_ID)->getValue(); } std::insert_iterator<ModifiersList> Character::getLocationModifiers(Attribute* attribute, std::insert_iterator<ModifiersList> outIterator) { outIterator = Item::getLocationModifiers(attribute, outIterator); auto owner = getOwner(); if (owner) outIterator = owner->getLocationModifiers(attribute, outIterator); return outIterator; } void Character::lazyLoad() { auto engine = getEngine(); if (!engine) return; Item::lazyLoad(); //std::shared_ptr<FetchResult> result = engine->getSqlConnector()->exec("SELECT typeID FROM invTypes, invGroups WHERE invTypes.groupID = invGroups.groupID AND invGroups.categoryID = 16 AND invTypes.published = 1"); auto stmt = engine->getSqlConnector()->getReusableFetchRequest("SELECT typeID FROM invTypes, invGroups WHERE invTypes.groupID = invGroups.groupID AND invGroups.categoryID = 16 AND invTypes.published = 1"); std::shared_ptr<FetchResult> result = engine->getSqlConnector()->exec(stmt); while (result->next()) { TypeID skillID = result->getInt(0); addSkill(skillID, 0, false); } } Item* Character::character() { return this; } Item* Character::ship() { return getShip().get(); } Item* Character::structure() { return getStructure().get(); } std::ostream& dgmpp::operator<<(std::ostream& os, dgmpp::Character& character) { os << "{\"typeName\":\"Character\",\"ship\":" << *character.ship_ << ", \"attributes\":["; if (character.attributes_.size() > 0) { bool isFirst = true; for (const auto& i: character.attributes_) { if (isFirst) isFirst = false; else os << ','; os << *i.second; } } os << "], \"effects\":["; if (character.effects_.size() > 0) { bool isFirst = true; for (const auto& i: character.effects_) { if (isFirst) isFirst = false; else os << ','; os << *i; } } os << "], \"itemModifiers\":["; if (character.itemModifiers_.size() > 0) { bool isFirst = true; for (const auto& list: character.itemModifiers_) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } os << "], \"locationModifiers\":["; if (character.locationModifiers_.size() > 0) { bool isFirst = true; for (const auto& list: character.locationModifiers_) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } os << "], \"locationGroupModifiers\":["; if (character.locationGroupModifiers_.size() > 0) { bool isFirst = true; for (const auto& map: character.locationGroupModifiers_) { for (const auto& list: map.second) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } } os << "], \"locationRequiredSkillModifiers\":["; if (character.locationRequiredSkillModifiers_.size() > 0) { bool isFirst = true; for (const auto& map: character.locationRequiredSkillModifiers_) { for (const auto& list: map.second) { for (const auto& i: list.second) { if (isFirst) isFirst = false; else os << ','; os << *i; } } } } /* os << "],\"skills\":["; if (character.skills_.size() > 0) { SkillsMap::const_iterator i, end = character.skills_.end(); bool isFirst = true; for (i = character.skills_.begin(); i != end; i++) { if (isFirst) isFirst = false; else os << ','; os << *(i->second); } }*/ os << "]}"; return os; } <|endoftext|>
<commit_before>// // UniformBuffer.cpp // Epsilon // // Created by Scott Porter on 21/04/2014. // Copyright (c) 2014 Scott Porter. All rights reserved. // // For OGL includes #include "EpsilonCore.h" #include "render/RenderUtilities.h" #include "render/material/UniformBuffer.h" namespace epsilon { UniformBuffer::UniformBuffer(const private_struct &, std::string bufferName, GLuint index) : bufferId(-1), bufferSize(0), bindingIndex(index), name(bufferName), bound(false) { } UniformBuffer::~UniformBuffer() { Destroy(); } void UniformBuffer::Bind(GLuint shaderId, GLuint blockId) { GLuint uniformBlockIndex; if (!bound) { // Build the Buffer Info by extracting it from the Shader. int nameLen = -1; char tempName[100]; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_NAME_LENGTH, &nameLen); glGetActiveUniformBlockName(shaderId, blockId, nameLen, NULL, &tempName[0]); CheckOpenGLError("Extracting Uniform Block Name"); tempName[nameLen] = 0; uniformBlockIndex = glGetUniformBlockIndex(shaderId, tempName); name = std::string(tempName); CheckOpenGLError("Getting Uniform Block Index for: " + name); Log("Found Uniform Block Index for: " + name); int dataSize = 0; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize); int activeBlockUniforms = 0; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &activeBlockUniforms); GLint blockUniformIndices[UniformBuffer::MAX_BLOCK_INDICIES]; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, blockUniformIndices); // Query the uniforms and build the uniforms for the buffer. for (int i = 0; i < activeBlockUniforms; i++) { ShaderUniform::Ptr newUniform = ShaderUniform::CreateFromShader(shaderId, blockUniformIndices[i]); AddUniform(newUniform); } // If there are uniforms assigned to this buffer if (uniforms.size() > 0) { // Create the buffer glGenBuffers(1, &bufferId); CheckOpenGLError("Gen Uniform Buffer"); // Bind it for access glBindBuffer(GL_UNIFORM_BUFFER, bufferId); CheckOpenGLError("Binding Uniform Buffer"); int alignSize = 0; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &alignSize); int maxblockSize = 0; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxblockSize); // Use the data size extracted from the Uniform Buffer info bufferSize = dataSize; bufferSize += alignSize - (bufferSize % alignSize); // Create the necessary space on the GPU glBufferData(GL_UNIFORM_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW | GL_MAP_WRITE_BIT); CheckOpenGLError("Binding Uniform Buffer Data"); // Bind the buffer data to it's assigned uniform binding point glBindBufferRange(GL_UNIFORM_BUFFER, bindingIndex, bufferId, 0, bufferSize); CheckOpenGLError("Binding Uniform Buffer to the Uniform Binding Point"); // Disable this buffer for now glBindBuffer(GL_UNIFORM_BUFFER, 0); CheckOpenGLError("Disabling Uniform Buffer"); // Mark this buffer as successfully bound. bound = true; } else { Log("UniformBuffer", "Warning: Cannot build buffer without any uniforms set."); } } else { // If the Uniform is already bound, then just extract the block index for this shader // using the name that has already been determined. uniformBlockIndex = glGetUniformBlockIndex(shaderId, name.c_str()); CheckOpenGLError("Extracting the block index: " + std::string(name)); } // Bind the current shader uniform block to the uniform buffer glUniformBlockBinding(shaderId, uniformBlockIndex, bindingIndex); CheckOpenGLError("Binding to Uniform Block: " + std::string(name)); Log("Found Uniform Block Index for: " + name); } void UniformBuffer::Update() { if ( bound ) { glBindBuffer(GL_UNIFORM_BUFFER, bufferId); CheckOpenGLError("Binding Uniform Buffer"); // Cycle through each of the uniforms and if they have changed, copy their data to the GPU for_each(uniforms.begin(), uniforms.end(), [&](std::pair<std::string, ShaderUniform::Ptr> uniform){ if ( uniform.second->HasChanged()) { uniform.second->SetUniformBufferValue(); } }); CheckOpenGLError("Updating Uniform Buffer"); // glUnmapBuffer(GL_UNIFORM_BUFFER); CheckOpenGLError("Unmapping Uniform Buffer"); glBindBuffer(GL_UNIFORM_BUFFER, 0); CheckOpenGLError("Disabling Uniform Buffer"); } } void UniformBuffer::Destroy() { if ( bound ) { if ( bufferId != 0 ) { glDeleteBuffers(1, &bufferId); bufferId = 0; } } } UniformBuffer::Ptr UniformBuffer::AddUniform(ShaderUniform::Ptr newUniform) { uniforms[newUniform->GetName()] = newUniform; return ThisPtr(); } ShaderUniform::Ptr UniformBuffer::GetUniform(std::string name) { ShaderUniform::Ptr foundUniform; if (uniforms.find(name) != uniforms.end()) { foundUniform = uniforms[name]; } return foundUniform; } } <commit_msg>M Removed unnecessary logs<commit_after>// // UniformBuffer.cpp // Epsilon // // Created by Scott Porter on 21/04/2014. // Copyright (c) 2014 Scott Porter. All rights reserved. // // For OGL includes #include "EpsilonCore.h" #include "render/RenderUtilities.h" #include "render/material/UniformBuffer.h" namespace epsilon { UniformBuffer::UniformBuffer(const private_struct &, std::string bufferName, GLuint index) : bufferId(-1), bufferSize(0), bindingIndex(index), name(bufferName), bound(false) { } UniformBuffer::~UniformBuffer() { Destroy(); } void UniformBuffer::Bind(GLuint shaderId, GLuint blockId) { GLuint uniformBlockIndex; if (!bound) { // Build the Buffer Info by extracting it from the Shader. int nameLen = -1; char tempName[100]; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_NAME_LENGTH, &nameLen); glGetActiveUniformBlockName(shaderId, blockId, nameLen, NULL, &tempName[0]); CheckOpenGLError("Extracting Uniform Block Name"); tempName[nameLen] = 0; uniformBlockIndex = glGetUniformBlockIndex(shaderId, tempName); name = std::string(tempName); CheckOpenGLError("Getting Uniform Block Index for: " + name); int dataSize = 0; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize); int activeBlockUniforms = 0; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &activeBlockUniforms); GLint blockUniformIndices[UniformBuffer::MAX_BLOCK_INDICIES]; glGetActiveUniformBlockiv(shaderId, blockId, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, blockUniformIndices); // Query the uniforms and build the uniforms for the buffer. for (int i = 0; i < activeBlockUniforms; i++) { ShaderUniform::Ptr newUniform = ShaderUniform::CreateFromShader(shaderId, blockUniformIndices[i]); AddUniform(newUniform); } // If there are uniforms assigned to this buffer if (uniforms.size() > 0) { // Create the buffer glGenBuffers(1, &bufferId); CheckOpenGLError("Gen Uniform Buffer"); // Bind it for access glBindBuffer(GL_UNIFORM_BUFFER, bufferId); CheckOpenGLError("Binding Uniform Buffer"); int alignSize = 0; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &alignSize); int maxblockSize = 0; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxblockSize); // Use the data size extracted from the Uniform Buffer info bufferSize = dataSize; bufferSize += alignSize - (bufferSize % alignSize); // Create the necessary space on the GPU glBufferData(GL_UNIFORM_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW | GL_MAP_WRITE_BIT); CheckOpenGLError("Binding Uniform Buffer Data"); // Bind the buffer data to it's assigned uniform binding point glBindBufferRange(GL_UNIFORM_BUFFER, bindingIndex, bufferId, 0, bufferSize); CheckOpenGLError("Binding Uniform Buffer to the Uniform Binding Point"); // Disable this buffer for now glBindBuffer(GL_UNIFORM_BUFFER, 0); CheckOpenGLError("Disabling Uniform Buffer"); // Mark this buffer as successfully bound. bound = true; } else { Log("UniformBuffer", "Warning: Cannot build buffer without any uniforms set."); } } else { // If the Uniform is already bound, then just extract the block index for this shader // using the name that has already been determined. uniformBlockIndex = glGetUniformBlockIndex(shaderId, name.c_str()); CheckOpenGLError("Extracting the block index: " + std::string(name)); } // Bind the current shader uniform block to the uniform buffer glUniformBlockBinding(shaderId, uniformBlockIndex, bindingIndex); CheckOpenGLError("Binding to Uniform Block: " + std::string(name)); } void UniformBuffer::Update() { if ( bound ) { glBindBuffer(GL_UNIFORM_BUFFER, bufferId); CheckOpenGLError("Binding Uniform Buffer"); // Cycle through each of the uniforms and if they have changed, copy their data to the GPU for_each(uniforms.begin(), uniforms.end(), [&](std::pair<std::string, ShaderUniform::Ptr> uniform){ if ( uniform.second->HasChanged()) { uniform.second->SetUniformBufferValue(); } }); CheckOpenGLError("Updating Uniform Buffer"); // glUnmapBuffer(GL_UNIFORM_BUFFER); CheckOpenGLError("Unmapping Uniform Buffer"); glBindBuffer(GL_UNIFORM_BUFFER, 0); CheckOpenGLError("Disabling Uniform Buffer"); } } void UniformBuffer::Destroy() { if ( bound ) { if ( bufferId != 0 ) { glDeleteBuffers(1, &bufferId); bufferId = 0; } } } UniformBuffer::Ptr UniformBuffer::AddUniform(ShaderUniform::Ptr newUniform) { uniforms[newUniform->GetName()] = newUniform; return ThisPtr(); } ShaderUniform::Ptr UniformBuffer::GetUniform(std::string name) { ShaderUniform::Ptr foundUniform; if (uniforms.find(name) != uniforms.end()) { foundUniform = uniforms[name]; } return foundUniform; } } <|endoftext|>
<commit_before>#include <geometry_msgs/PoseStamped.h> #include "util.h" #include "wall_markers.h" WallMarkers::WallMarkers(ros::NodeHandle handle) : nh(handle), markerPublisher(handle.advertise<visualization_msgs::Marker>("localization/viz/wall_markers", 1000)), positionSubscriber(handle.subscribe("position/estimate", 1, &WallMarkers::positionCallback, this)), wallSubscriber(handle.subscribe("sonar/scan/walls", 1, &WallMarkers::wallCallback, this)) { havePosition = false; frameID = 0; } void WallMarkers::positionCallback(const geometry_msgs::PoseStamped &position) { this->position = position.pose; } void WallMarkers::wallCallback(const hanse_msgs::WallDetection &wall) { if (wall.wallDetected) { visualization_msgs::Marker m; m.header.stamp = ros::Time::now(); m.header.frame_id = "/map"; m.ns = "scan_lines"; m.id = frameID; m.type = visualization_msgs::Marker::LINE_STRIP; m.action = visualization_msgs::Marker::ADD; m.pose = position; m.scale.x = 0.1; m.color.a = 1.0; m.color.r = 0; m.color.g = 0; m.color.b = 1; geometry_msgs::Point start, end; start.x = 0; start.y = 0; start.z = 0; float maxDistance = 0; for (auto d : wall.distances) maxDistance = std::max(maxDistance, (float)d); end.x = maxDistance * cos(wall.headPosition); end.y = maxDistance * sin(wall.headPosition); end.z = 0; m.points.push_back(start); m.points.push_back(end); lineMarkers.push_back(m); m.ns = "wall_points"; m.type = visualization_msgs::Marker::SPHERE_LIST; m.points.clear(); m.scale.x = 0.5; m.scale.y = 0.5; m.scale.z = 0.5; m.color.r = 1; for (float d : wall.distances) { geometry_msgs::Point p; p.x = d * cos(wall.headPosition); p.y = d * sin(wall.headPosition); m.points.push_back(p); } wallMarkers.push_back(m); } frameID++; if (!lineMarkers.empty() && lineMarkers.front().id < frameID - 60) { visualization_msgs::Marker &m = lineMarkers.front(); m.action = visualization_msgs::Marker::DELETE; markerPublisher.publish(m); lineMarkers.pop_front(); visualization_msgs::Marker &m2 = wallMarkers.front(); m2.action = visualization_msgs::Marker::DELETE; markerPublisher.publish(m2); wallMarkers.pop_front(); } for (auto &m : lineMarkers) { if (m.id < frameID - 10) m.color.b = 0.5; markerPublisher.publish(m); } for (auto &m : wallMarkers) { markerPublisher.publish(m); } } int main(int argc, char *argv[]) { ros::init(argc, argv, "wall_markers"); ros::NodeHandle n; WallMarkers wallMarkers(n); ros::spin(); return 0; } <commit_msg>localization: faster visualization<commit_after>#include <geometry_msgs/PoseStamped.h> #include "util.h" #include "wall_markers.h" WallMarkers::WallMarkers(ros::NodeHandle handle) : nh(handle), markerPublisher(handle.advertise<visualization_msgs::Marker>("localization/viz/wall_markers", 1000)), positionSubscriber(handle.subscribe("position/estimate", 1, &WallMarkers::positionCallback, this)), wallSubscriber(handle.subscribe("sonar/scan/walls", 1, &WallMarkers::wallCallback, this)) { havePosition = false; frameID = 0; } void WallMarkers::positionCallback(const geometry_msgs::PoseStamped &position) { this->position = position.pose; } void WallMarkers::wallCallback(const hanse_msgs::WallDetection &wall) { if (wall.wallDetected) { visualization_msgs::Marker m; m.header.stamp = ros::Time::now(); m.header.frame_id = "/map"; m.ns = "scan_lines"; m.id = frameID; m.type = visualization_msgs::Marker::LINE_STRIP; m.action = visualization_msgs::Marker::ADD; m.pose = position; m.scale.x = 0.1; m.color.a = 1.0; m.color.r = 0; m.color.g = 0; m.color.b = 1; geometry_msgs::Point start, end; start.x = 0; start.y = 0; start.z = 0; float maxDistance = 0; for (auto d : wall.distances) maxDistance = std::max(maxDistance, (float)d); end.x = maxDistance * cos(wall.headPosition); end.y = maxDistance * sin(wall.headPosition); end.z = 0; m.points.push_back(start); m.points.push_back(end); lineMarkers.push_back(m); m.ns = "wall_points"; m.type = visualization_msgs::Marker::LINE_LIST; m.points.clear(); m.scale.x = 0.1; m.scale.y = 0.5; m.scale.z = 0.5; m.color.r = 1; for (float d : wall.distances) { geometry_msgs::Point p; p.x = d * cos(wall.headPosition+M_PI/50); p.y = d * sin(wall.headPosition+M_PI/50); m.points.push_back(p); p.x = d * cos(wall.headPosition-M_PI/50); p.y = d * sin(wall.headPosition-M_PI/50); m.points.push_back(p); } wallMarkers.push_back(m); } frameID++; if (!lineMarkers.empty() && lineMarkers.front().id < frameID - 60) { visualization_msgs::Marker &m = lineMarkers.front(); m.action = visualization_msgs::Marker::DELETE; markerPublisher.publish(m); lineMarkers.pop_front(); visualization_msgs::Marker &m2 = wallMarkers.front(); m2.action = visualization_msgs::Marker::DELETE; markerPublisher.publish(m2); wallMarkers.pop_front(); } for (auto &m : lineMarkers) { if (m.id < frameID - 10) m.color.b = 0.5; markerPublisher.publish(m); } for (auto &m : wallMarkers) { markerPublisher.publish(m); } } int main(int argc, char *argv[]) { ros::init(argc, argv, "wall_markers"); ros::NodeHandle n; WallMarkers wallMarkers(n); ros::spin(); return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> #include "factorencoder.hh" #include "io.hh" int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << "usage: " << argv[0] << " <vocabulary> <infile> <outfile>" << std::endl; exit(0); } int maxlen; std::map<std::string, double> vocab; std::cerr << "Reading vocabulary " << argv[1] << std::endl; int retval = read_vocab(argv[1], vocab, maxlen); if (retval < 0) { std::cerr << "something went wrong reading vocabulary" << std::endl; exit(0); } std::cerr << "\t" << "size: " << vocab.size() << std::endl; std::cerr << "\t" << "maximum string length: " << maxlen << std::endl; std::cerr << "Segmenting corpus" << std::endl; std::string line; io::Stream infile, outfile; try { infile.open(argv[2], "r"); outfile.open(argv[3], "w"); } catch (io::Stream::OpenError oe) { std::cerr << "Something went wrong opening the files." << std::endl; exit(0); } char linebuffer[8192]; while (fgets(linebuffer, 8192 , infile.file) != NULL) { linebuffer[strlen(linebuffer)-1] = '\0'; std::string line(linebuffer); std::vector<std::string> best_path; viterbi(vocab, maxlen, line, best_path); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for line: " << line << std::endl; continue; } // Print out the best path for (int i=0; i<best_path.size()-1; i++) { fwrite(best_path[i].c_str(), 1, best_path[i].length(), outfile.file); fwrite(" ", 1, 1, outfile.file); } fwrite(best_path[best_path.size()-1].c_str(), 1, best_path[best_path.size()-1].length(), outfile.file); fwrite("\n", 1, 1, outfile.file); } infile.close() outfile.close() exit(1); } <commit_msg>small fixes.<commit_after>#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> #include "factorencoder.hh" #include "io.hh" int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << "usage: " << argv[0] << " <vocabulary> <infile> <outfile>" << std::endl; exit(0); } int maxlen; std::map<std::string, double> vocab; std::cerr << "Reading vocabulary " << argv[1] << std::endl; int retval = read_vocab(argv[1], vocab, maxlen); if (retval < 0) { std::cerr << "something went wrong reading vocabulary" << std::endl; exit(0); } std::cerr << "\t" << "size: " << vocab.size() << std::endl; std::cerr << "\t" << "maximum string length: " << maxlen << std::endl; std::cerr << "Segmenting corpus" << std::endl; std::string line; io::Stream infile, outfile; try { infile.open(argv[2], "r"); outfile.open(argv[3], "w"); } catch (io::Stream::OpenError oe) { std::cerr << "Something went wrong opening the files." << std::endl; exit(0); } char linebuffer[8192]; while (fgets(linebuffer, 8192 , infile.file) != NULL) { linebuffer[strlen(linebuffer)-1] = '\0'; std::string line(linebuffer); std::vector<std::string> best_path; viterbi(vocab, maxlen, line, best_path); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for line: " << line << std::endl; continue; } // Print out the best path for (int i=0; i<best_path.size()-1; i++) { fwrite(best_path[i].c_str(), 1, best_path[i].length(), outfile.file); fwrite(" ", 1, 1, outfile.file); } fwrite(best_path[best_path.size()-1].c_str(), 1, best_path[best_path.size()-1].length(), outfile.file); fwrite("\n", 1, 1, outfile.file); } infile.close(); outfile.close(); exit(1); } <|endoftext|>
<commit_before>#include <boost/filesystem.hpp> #include <util/parser.hpp> #include <util/string.hpp> #include <util/ninja.hpp> #include <algorithm> #include <iostream> namespace fs = boost::filesystem; void make_default_shinobi() { std::ofstream out("Shinobi"); out << "# The default Shinobi file. See README.md for syntax help.\n\n" "PROJECT_NAME := untitled\n" "CXX := g++\n" "CXXFLAGS += -std=c++11 -pedantic -pedantic-errors -Wextra -Wall -O2\n" "INCLUDE_FLAGS += -I.\n" "LIBRARY_PATHS +=\n" "LIBRARY_FLAGS +=\n" "DEFINES += -DNDEBUG"; } std::string remove_symlink(const fs::path& p) noexcept { // Remove ./ auto result = p.string(); auto pos = result.find("./"); if(pos == std::string::npos) { pos = result.find(".\\"); if(pos == std::string::npos) { return result; } } result.replace(pos, 2, ""); return result; } int main() { auto dir = fs::current_path(); util::parser shinobi; if(!shinobi.is_open()) { make_default_shinobi(); shinobi.reopen(); } shinobi.parse(); std::ofstream out("build.ninja"); util::ninja maker(out); maker.variable("cxx", shinobi.get("CXX", "g++")); maker.variable("cxxflags", shinobi.get("CXXFLAGS", "-std=c++11 -pedantic -Wall -O3 -static-libstdc++")); maker.variable("incflags", shinobi.get("INCLUDE_FLAGS", "-I.")); maker.variable("libpath", shinobi.get("LIBRARY_PATHS", "")); maker.variable("lib", shinobi.get("LIBRARY_FLAGS", "")); maker.variable("def", shinobi.get("DEFINES", "-DNDEBUG")); maker.rule("bd", "deps = gcc", "depfile = $out.d", "command = $cxx -MMD -MF $out.d $cxxflags $def -c $in -o $out $incflags"); maker.rule("ld", "command = $cxx $in -o $out $libpath $lib"); std::vector<fs::path> input; std::vector<std::string> output; for(fs::recursive_directory_iterator it("."), end; it != end; ++it) { auto p = it->path(); if(util::extension_is(p.string(), ".cpp", ".cxx", ".cc", ".c", ".c++")) { input.push_back(p); } } fs::path bin("bin"); if(!fs::is_directory(bin)) { fs::create_directory(bin); } // Generate build sequences for(auto&& p : input) { auto file_dir = fs::path("obj") / p; auto appended_dir = (dir / file_dir).parent_path(); if(!fs::is_directory(appended_dir)) { fs::create_directories(appended_dir); } std::string output_file = remove_symlink(file_dir.replace_extension(".o")); output.push_back(output_file); maker.build(remove_symlink(p), output_file, "bd"); } // Generate link sequence maker.build(util::stringify_list(output), (bin / shinobi.get("PROJECT_NAME", "untitled")).string(), "ld"); }<commit_msg>Add descriptions, make required ninja version 1.3, rename ld and bd to link and compile<commit_after>#include <boost/filesystem.hpp> #include <util/parser.hpp> #include <util/string.hpp> #include <util/ninja.hpp> #include <algorithm> #include <iostream> namespace fs = boost::filesystem; void make_default_shinobi() { std::ofstream out("Shinobi"); out << "# The default Shinobi file. See README.md for syntax help.\n\n" "PROJECT_NAME := untitled\n" "CXX := g++\n" "CXXFLAGS += -std=c++11 -pedantic -pedantic-errors -Wextra -Wall -O2\n" "INCLUDE_FLAGS += -I.\n" "LIBRARY_PATHS +=\n" "LIBRARY_FLAGS +=\n" "DEFINES += -DNDEBUG"; } std::string remove_symlink(const fs::path& p) noexcept { // Remove ./ auto result = p.string(); auto pos = result.find("./"); if(pos == std::string::npos) { pos = result.find(".\\"); if(pos == std::string::npos) { return result; } } result.replace(pos, 2, ""); return result; } int main() { auto dir = fs::current_path(); util::parser shinobi; if(!shinobi.is_open()) { make_default_shinobi(); shinobi.reopen(); } shinobi.parse(); std::ofstream out("build.ninja"); util::ninja maker(out); maker.variable("ninja_required_version", "1.3"); maker.variable("cxx", shinobi.get("CXX", "g++")); maker.variable("cxxflags", shinobi.get("CXXFLAGS", "-std=c++11 -pedantic -Wall -O3 -static-libstdc++")); maker.variable("incflags", shinobi.get("INCLUDE_FLAGS", "-I.")); maker.variable("libpath", shinobi.get("LIBRARY_PATHS", "")); maker.variable("lib", shinobi.get("LIBRARY_FLAGS", "")); maker.variable("def", shinobi.get("DEFINES", "-DNDEBUG")); maker.rule("compile", "deps = gcc", "depfile = $out.d", "command = $cxx -MMD -MF $out.d $cxxflags $def -c $in -o $out $incflags", "description = Building $out"); maker.rule("link", "command = $cxx $in -o $out $libpath $lib", "description = Linking $out"); std::vector<fs::path> input; std::vector<std::string> output; for(fs::recursive_directory_iterator it("."), end; it != end; ++it) { auto p = it->path(); if(util::extension_is(p.string(), ".cpp", ".cxx", ".cc", ".c", ".c++")) { input.push_back(p); } } fs::path bin("bin"); if(!fs::is_directory(bin)) { fs::create_directory(bin); } // Generate build sequences for(auto&& p : input) { auto file_dir = fs::path("obj") / p; auto appended_dir = (dir / file_dir).parent_path(); if(!fs::is_directory(appended_dir)) { fs::create_directories(appended_dir); } std::string output_file = remove_symlink(file_dir.replace_extension(".o")); output.push_back(output_file); maker.build(remove_symlink(p), output_file, "compile"); } // Generate link sequence maker.build(util::stringify_list(output), (bin / shinobi.get("PROJECT_NAME", "untitled")).string(), "link"); }<|endoftext|>
<commit_before>/* flappy.cc --- ncurses flappy bird clone * This is free and unencumbered software released into the public domain. */ #include <algorithm> #include <thread> #include <deque> #include <ctime> #include <cmath> #include <cstring> #include <ncurses.h> #include <unistd.h> #include "sqlite3.h" #include "highscores.hh" #define STR_(x) #x #define STR(x) STR_(x) struct Display { Display(int width = 40, int height = 20) : height{height}, width{width} { initscr(); raw(); timeout(0); noecho(); curs_set(0); keypad(stdscr, TRUE); erase(); } ~Display() { endwin(); } void erase() { ::erase(); for (int y = 0; y < height; y++) { mvaddch(y, 0, '|'); mvaddch(y, width - 1, '|'); } for (int x = 0; x < width; x++) { mvaddch(0, x, '-'); mvaddch(height - 1, x, '-'); } mvaddch(0, 0, '/'); mvaddch(height - 1, 0, '\\'); mvaddch(0, width - 1, '\\'); mvaddch(height - 1, width - 1, '/'); } void refresh() { ::refresh(); } const int height, width; int block_getch() { refresh(); timeout(-1); int c = getch(); timeout(0); return c; } void read_name(int y, int x, char *target, size_t n) { int p = 0; timeout(-1); curs_set(1); bool reading = true; while (reading) { move(y, x + p); refresh(); int c = getch(); switch (c) { case KEY_ENTER: case '\n': case '\r': case ERR: reading = false; break; case KEY_LEFT: case KEY_BACKSPACE: if (p > 0) mvaddch(y, x + --p, ' '); break; case ' ': if (p == 0) { break; } default: if (p < n - 1) { target[p] = c; mvaddch(y, x + p++, c); } } } target[p + 1] = '\0'; timeout(0); curs_set(0); } void center(int yoff, const char *str) { mvprintw(height / 2 + yoff, width / 2 - std::strlen(str) / 2, "%s", str); } }; struct World { World(Display *display) : display{display} { for (int x = 1; x < display->width - 1; x++) { walls.push_back(0); } } std::deque<int> walls; Display *display; int steps = 0; constexpr static int kRate = 2, kVGap = 2, kHGap = 10; int rand_wall() { int h = display->height; return (rand() % h / 2) + h / 4; } void step() { steps++; if (steps % kRate == 0) { walls.pop_front(); switch (steps % (kRate * kHGap)) { case 0: walls.push_back(rand_wall()); break; case kRate * 1: case kRate * 2: walls.push_back(walls.back()); break; default: walls.push_back(0); } } } void draw() { for (int i = 0; i < walls.size(); i++) { int wall = walls[i]; if (wall != 0) { for (int y = 1; y < display->height - 1; y++) { if (y == wall - kVGap - 1 || y == wall + kVGap + 1) { mvaddch(y, i + 1, '='); } else if (y < wall - kVGap || y > wall + kVGap) { mvaddch(y, i + 1, '*'); } } } } mvprintw(display->height, 0, "Score: %d", score()); } int score() { return std::max(0, (steps - 2) / (kRate * kHGap) - 2); } }; struct Bird { Bird(Display *display) : y{display->height / 2.0}, display{display} {} static constexpr double kImpulse = -0.8, kGravity = 0.1; double y, dy = kImpulse; Display *display; void gravity() { dy += kGravity; y += dy; } void poke() { dy = kImpulse; } void draw() { draw('@'); } void draw(int c) { int h = std::round(y); h = std::max(1, std::min(h, display->height - 2)); mvaddch(h, display->width / 2, c); } bool is_alive(World &world) { if (y <= 0 || y >= display->height) { return false; } int wall = world.walls[display->width / 2 - 1]; if (wall != 0) { return y > wall - World::kVGap && y < wall + World::kVGap; } return true; } }; struct Game { Game(Display *display) : display{display}, bird{display}, world{display} {} Display *display; Bird bird; World world; int run() { display->erase(); const char *title = "Flappy Curses", *version = "v" STR(VERSION), *intro = "[Press SPACE to hop upwards]"; display->center(-3, title); display->center(-2, version); display->center(2, intro); bird.draw(); if (display->block_getch() == 'q') return -1; while (bird.is_alive(world)) { int c = getch(); if (c == 'q') { return -1; } else if (c != ERR) { while (getch() != ERR) ; // clear repeat buffer bird.poke(); } display->erase(); world.step(); world.draw(); bird.gravity(); bird.draw(); display->refresh(); std::this_thread::sleep_for(std::chrono::milliseconds{67}); } bird.draw('X'); display->refresh(); return world.score(); } }; void print_scores(Display &display, HighScores &scores) { mvprintw(0, display.width + 4, "== High Scores =="); int i = 1; for (auto &line : scores.top_scores()) { mvprintw(i, display.width + 1, "%s", line.name.c_str()); clrtoeol(); mvprintw(i, display.width + 24, "%d", line.score); i++; } } int main(int argc, char **argv) { srand(std::time(NULL)); /* Parse command line arguments. */ int opt; const char *filename = "/tmp/flappy-scores.db", *host = "localhost"; while ((opt = getopt(argc, argv, "d:h:p")) != -1) { switch (opt) { case 'd': filename = optarg; break; case 'h': host = optarg; break; case 'p': // ignore break; } } Display display; HighScores scores{filename, display.height - 1}; while (true) { Game game{&display}; int score = game.run(); if (score < 0) { return 0; // game quit early } /* Game over */ mvprintw(display.height + 1, 0, "Game over!"); print_scores(display, scores); /* Enter new high score */ if (scores.is_best(score)) { mvprintw(display.height + 2, 0, "You have a high score!"); mvprintw(display.height + 3, 0, "Enter name: "); char name[23] = {0}; display.read_name(display.height + 3, 12, name, sizeof(name)); if (std::strlen(name) == 0) { std::strcpy(name, "(anonymous)"); } scores.insert_score(name, score); move(display.height + 3, 0); clrtoeol(); print_scores(display, scores); } /* Handle quit/restart */ mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry."); int c; while ((c = display.block_getch()) != 'r') { if (c == 'q' || c == ERR) { return 0; } } } return 0; } <commit_msg>Pay attention to ctrl+c.<commit_after>/* flappy.cc --- ncurses flappy bird clone * This is free and unencumbered software released into the public domain. */ #include <algorithm> #include <thread> #include <deque> #include <ctime> #include <cmath> #include <cstring> #include <ncurses.h> #include <unistd.h> #include "sqlite3.h" #include "highscores.hh" #define STR_(x) #x #define STR(x) STR_(x) struct Display { Display(int width = 40, int height = 20) : height{height}, width{width} { initscr(); raw(); timeout(0); noecho(); curs_set(0); keypad(stdscr, TRUE); erase(); } ~Display() { endwin(); } void erase() { ::erase(); for (int y = 0; y < height; y++) { mvaddch(y, 0, '|'); mvaddch(y, width - 1, '|'); } for (int x = 0; x < width; x++) { mvaddch(0, x, '-'); mvaddch(height - 1, x, '-'); } mvaddch(0, 0, '/'); mvaddch(height - 1, 0, '\\'); mvaddch(0, width - 1, '\\'); mvaddch(height - 1, width - 1, '/'); } void refresh() { ::refresh(); } const int height, width; int block_getch() { refresh(); timeout(-1); int c = getch(); timeout(0); return c; } void read_name(int y, int x, char *target, size_t n) { int p = 0; timeout(-1); curs_set(1); bool reading = true; while (reading) { move(y, x + p); refresh(); int c = getch(); switch (c) { case KEY_ENTER: case '\n': case '\r': case '': case ERR: reading = false; break; case KEY_LEFT: case KEY_BACKSPACE: if (p > 0) mvaddch(y, x + --p, ' '); break; case ' ': if (p == 0) { break; } default: if (p < n - 1) { target[p] = c; mvaddch(y, x + p++, c); } } } target[p + 1] = '\0'; timeout(0); curs_set(0); } void center(int yoff, const char *str) { mvprintw(height / 2 + yoff, width / 2 - std::strlen(str) / 2, "%s", str); } }; bool is_exit(int c) { return c == 'q' || c == ''; } struct World { World(Display *display) : display{display} { for (int x = 1; x < display->width - 1; x++) { walls.push_back(0); } } std::deque<int> walls; Display *display; int steps = 0; constexpr static int kRate = 2, kVGap = 2, kHGap = 10; int rand_wall() { int h = display->height; return (rand() % h / 2) + h / 4; } void step() { steps++; if (steps % kRate == 0) { walls.pop_front(); switch (steps % (kRate * kHGap)) { case 0: walls.push_back(rand_wall()); break; case kRate * 1: case kRate * 2: walls.push_back(walls.back()); break; default: walls.push_back(0); } } } void draw() { for (int i = 0; i < walls.size(); i++) { int wall = walls[i]; if (wall != 0) { for (int y = 1; y < display->height - 1; y++) { if (y == wall - kVGap - 1 || y == wall + kVGap + 1) { mvaddch(y, i + 1, '='); } else if (y < wall - kVGap || y > wall + kVGap) { mvaddch(y, i + 1, '*'); } } } } mvprintw(display->height, 0, "Score: %d", score()); } int score() { return std::max(0, (steps - 2) / (kRate * kHGap) - 2); } }; struct Bird { Bird(Display *display) : y{display->height / 2.0}, display{display} {} static constexpr double kImpulse = -0.8, kGravity = 0.1; double y, dy = kImpulse; Display *display; void gravity() { dy += kGravity; y += dy; } void poke() { dy = kImpulse; } void draw() { draw('@'); } void draw(int c) { int h = std::round(y); h = std::max(1, std::min(h, display->height - 2)); mvaddch(h, display->width / 2, c); } bool is_alive(World &world) { if (y <= 0 || y >= display->height) { return false; } int wall = world.walls[display->width / 2 - 1]; if (wall != 0) { return y > wall - World::kVGap && y < wall + World::kVGap; } return true; } }; struct Game { Game(Display *display) : display{display}, bird{display}, world{display} {} Display *display; Bird bird; World world; int run() { display->erase(); const char *title = "Flappy Curses", *version = "v" STR(VERSION), *intro = "[Press SPACE to hop upwards]"; display->center(-3, title); display->center(-2, version); display->center(2, intro); bird.draw(); if (is_exit(display->block_getch())) return -1; while (bird.is_alive(world)) { int c = getch(); if (is_exit(c)) { return -1; } else if (c != ERR) { while (getch() != ERR) ; // clear repeat buffer bird.poke(); } display->erase(); world.step(); world.draw(); bird.gravity(); bird.draw(); display->refresh(); std::this_thread::sleep_for(std::chrono::milliseconds{67}); } bird.draw('X'); display->refresh(); return world.score(); } }; void print_scores(Display &display, HighScores &scores) { mvprintw(0, display.width + 4, "== High Scores =="); int i = 1; for (auto &line : scores.top_scores()) { mvprintw(i, display.width + 1, "%s", line.name.c_str()); clrtoeol(); mvprintw(i, display.width + 24, "%d", line.score); i++; } } int main(int argc, char **argv) { srand(std::time(NULL)); /* Parse command line arguments. */ int opt; const char *filename = "/tmp/flappy-scores.db", *host = "localhost"; while ((opt = getopt(argc, argv, "d:h:p")) != -1) { switch (opt) { case 'd': filename = optarg; break; case 'h': host = optarg; break; case 'p': // ignore break; } } Display display; HighScores scores{filename, display.height - 1}; while (true) { Game game{&display}; int score = game.run(); if (score < 0) { return 0; // game quit early } /* Game over */ mvprintw(display.height + 1, 0, "Game over!"); print_scores(display, scores); /* Enter new high score */ if (scores.is_best(score)) { mvprintw(display.height + 2, 0, "You have a high score!"); mvprintw(display.height + 3, 0, "Enter name: "); char name[23] = {0}; display.read_name(display.height + 3, 12, name, sizeof(name)); if (std::strlen(name) == 0) { std::strcpy(name, "(anonymous)"); } scores.insert_score(name, score); move(display.height + 3, 0); clrtoeol(); print_scores(display, scores); } /* Handle quit/restart */ mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry."); int c; while ((c = display.block_getch()) != 'r') { if (is_exit(c) || c == ERR) { return 0; } } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- c-library modules used --------------------------------------------------- //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "AnythingUtils.h" #include "Renderer.h" #include "Dbg.h" //--- interface include -------------------------------------------------------- #include "RemoveAction.h" //---- RemoveAction --------------------------------------------------------------- RegisterAction(RemoveAction); RemoveAction::RemoveAction(const char *name) : Action(name) { } RemoveAction::~RemoveAction() { } bool RemoveAction::DoExecAction(String &transitionToken, Context &ctx, const ROAnything &config) { StartTrace(RemoveAction.DoExecAction); String slotName; Renderer::RenderOnString(slotName, ctx, config["Slot"]); if (slotName.Length()) { // first of all, get the correct store Anything anyParent; String store = config["Store"].AsString(""); char delim = config["Delim"].AsCharPtr(".")[0L]; char indexdelim = config["IndexDelim"].AsCharPtr(":")[0L]; Trace(String("store used [") << (store.Length() >= 0L ? (const char *)store : "TmpStore") << "]"); anyParent = StoreFinder::FindStore(ctx, store); // test if the path to be deleted exists in the store, avoids creation of nonexisting slot Anything anySlotTest; if (anyParent.LookupPath(anySlotTest, slotName, delim, indexdelim)) { // use SlotFinders IntOperate to get the correct parent anything and the slotname/index // to remove from long slotIndex = -1L; if (SlotFinder::IntOperate(anyParent, slotName, slotIndex, delim, indexdelim)) { if (slotName.Length()) { Trace("removing named slot [" << slotName << "]"); anyParent.Remove(slotName); } else if (slotIndex != -1L) { Trace("removing index slot [" << slotIndex << "]"); anyParent.Remove(slotIndex); } return true; } } else { Trace("path to be deleted not found! [" << slotName << "]"); // as we do not have to delete anything we return true anyway return true; } } return false; } <commit_msg>error correction for stores/slots not in same allocator - slots were not removed when the caller got called from a different allocator-storage this is due to the fact that an Anything copies itself when it detects the assignee to have a different allocator -> this can be solved using a reference to the store, but care must be taken not to change the entry-reference to point to somewhere else<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- c-library modules used --------------------------------------------------- //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "AnythingUtils.h" #include "Renderer.h" #include "Dbg.h" //--- interface include -------------------------------------------------------- #include "RemoveAction.h" //---- RemoveAction --------------------------------------------------------------- RegisterAction(RemoveAction); RemoveAction::RemoveAction(const char *name) : Action(name) { } RemoveAction::~RemoveAction() { } bool RemoveAction::DoExecAction(String &transitionToken, Context &ctx, const ROAnything &config) { StartTrace(RemoveAction.DoExecAction); String slotName; Renderer::RenderOnString(slotName, ctx, config["Slot"]); if (slotName.Length()) { // first of all, get the correct store String store = config["Store"].AsString("TmpStore"); char delim = config["Delim"].AsCharPtr(".")[0L]; char indexdelim = config["IndexDelim"].AsCharPtr(":")[0L]; // must use reference here to prevent copying the content due to different allocator locations Anything &anyStore = StoreFinder::FindStore(ctx, store), anyParent(anyStore, anyStore.GetAllocator()); SubTraceAny(TraceContent, anyParent, String("content in store [") << store << "], looking for slot [" << slotName << "]"); // test if the path to be deleted exists in the store, avoids creation of nonexisting slot // also avoid content copying here using same allocator as parent any Anything anySlotTest(anyParent.GetAllocator()); if (anyParent.LookupPath(anySlotTest, slotName, delim, indexdelim)) { // use SlotFinders IntOperate to get the correct parent anything and the slotname/index // to remove from long slotIndex = -1L; if (SlotFinder::IntOperate(anyParent, slotName, slotIndex, delim, indexdelim)) { if (slotName.Length()) { Trace("removing named slot [" << slotName << "]"); anyParent.Remove(slotName); } else if (slotIndex != -1L) { Trace("removing index slot [" << slotIndex << "]"); anyParent.Remove(slotIndex); } return true; } } else { Trace("path to be deleted not found! [" << slotName << "]"); // as we do not have to delete anything we return true anyway return true; } } return false; } <|endoftext|>
<commit_before>#ifndef ARABICA_XSLT_COMPILED_STYLESHEET_HPP #define ARABICA_XSLT_COMPILED_STYLESHEET_HPP #include <vector> #include <iostream> #include <XPath/XPath.hpp> #include "xslt_execution_context.hpp" #include "xslt_template.hpp" #include "xslt_top_level_param.hpp" #include "xslt_key.hpp" #include "xslt_stylesheet.hpp" namespace Arabica { namespace XSLT { template<class string_type, class string_adaptor> class CompiledStylesheet : public Stylesheet<string_type, string_adaptor> { typedef Arabica::XPath::BoolValue<string_type, string_adaptor> BoolValue; typedef Arabica::XPath::NumericValue<string_type, string_adaptor> NumericValue; typedef Arabica::XPath::StringValue<string_type, string_adaptor> StringValue; typedef Arabica::XPath::XPathValue<string_type, string_adaptor> Value; typedef Arabica::XPath::NodeSet<string_type, string_adaptor> NodeSet; typedef DOM::Node<string_type, string_adaptor> DOMNode; typedef DOM::NodeList<string_type, string_adaptor> DOMNodeList; public: CompiledStylesheet() : output_(new StreamSink<string_type, string_adaptor>(std::cout)), error_output_(&std::cerr) { } // CompiledStylesheet virtual ~CompiledStylesheet() { // let's clean up! for(VariableDeclList::const_iterator ci = topLevelVars_.begin(), ce = topLevelVars_.end(); ci != ce; ++ci) delete *ci; for(ParamListIterator pi = params_.begin(), pe = params_.end(); pi != pe; ++pi) delete *pi; for(TemplateList::const_iterator ti = all_templates_.begin(), te = all_templates_.end(); ti != te; ++ti) delete *ti; } // ~CompiledStylesheet virtual void set_parameter(const string_type& name, bool value) { set_parameter(name, Value(new BoolValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, double value) { set_parameter(name, Value(new NumericValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, const char* value) { set_parameter(name, Value(new StringValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, const string_type& value) { set_parameter(name, Value(new StringValue(value))); } // set_parameter virtual void set_output(Sink<string_type, string_adaptor>& sink) { output_.reset(sink); } // set_output virtual void set_error_output(std::ostream& os) { error_output_ = &os; } // set_error_output virtual void execute(const DOMNode& initialNode) const { if(initialNode == 0) throw std::runtime_error("Input document is empty"); NodeSet ns; ns.push_back(initialNode); ExecutionContext context(*this, output_.get(), *error_output_); // set up variables and so forth for(ParamListIterator pi = params_.begin(), pe = params_.end(); pi != pe; ++pi) (*pi)->declare(context); for(VariableDeclList::const_iterator ci = topLevelVars_.begin(), ce = topLevelVars_.end(); ci != ce; ++ci) (*ci)->execute(initialNode, context); context.freezeTopLevel(); // go! output_.get().asOutput().start_document(output_settings_, output_cdata_elements_); applyTemplates(ns, context, ""); output_.get().asOutput().end_document(); } // execute //////////////////////////////////////// const DeclaredKeys<string_type, string_adaptor>& keys() const { return keys_; } void add_template(Template<string_type, string_adaptor>* templat) { typedef typename Template<string_type, string_adaptor>::MatchExprList MatchExprList; typedef typename MatchExprList::const_iterator MatchIterator; all_templates_.push_back(templat); for(MatchIterator e = templat->compiled_matches().begin(), ee = templat->compiled_matches().end(); e != ee; ++e) templates_[templat->precedence()][templat->mode()].push_back(MatchTemplate(*e, templat)); if(!templat->has_name()) return; NamedTemplatesIterator named_template = named_templates_.find(templat->name()); if(named_template != named_templates_.end()) { const Precedence& existing_precedence = named_template->second->precedence(); if(existing_precedence > templat->precedence()) return; if(existing_precedence == templat->precedence()) throw SAX::SAXException("Template named '" + templat->name() + "' already defined"); } // if ... named_templates_[templat->name()] = templat; } // add_template void add_variable(Item* item) { topLevelVars_.push_back(item); } // add_item void add_key(const string_type& name, Key<string_type, string_adaptor>* key) { keys_.add(name, key); } // add_key void output_settings(const typename Output<string_type, string_adaptor>::Settings& settings, const typename Output<string_type, string_adaptor>::CDATAElements& cdata_elements) { output_settings_ = settings; output_cdata_elements_.insert(cdata_elements.begin(), cdata_elements.end()); } // output_settingsp void prepare() { for(typename TemplateStack::iterator ts = templates_.begin(), tse = templates_.end(); ts != tse; ++ts) for(typename ModeTemplates::iterator ms = ts->second.begin(), mse = ts->second.end(); ms != mse; ++ms) { MatchTemplates& matches = ms->second; std::reverse(matches.begin(), matches.end()); std::stable_sort(matches.begin(), matches.end()); } // for ... } // prepare //////////////////////////////////////// void applyTemplates(const NodeSet& nodes, ExecutionContext& context, const string_type& mode) const { // entirely simple so far LastFrame last(context, nodes.size()); int p = 1; for(typename NodeSet::const_iterator n = nodes.begin(), ne = nodes.end(); n != ne; ++n) { context.setPosition(*n, p++); doApplyTemplates(*n, context, mode, Precedence::FrozenPrecedence()); } } // applyTemplates void applyTemplates(const DOMNodeList& nodes, ExecutionContext& context, const string_type& mode) const { // entirely simple so far LastFrame last(context, (size_t)nodes.getLength()); for(int i = 0, ie = nodes.getLength(); i != ie; ++i) { context.setPosition(nodes.item(i), i+1); doApplyTemplates(nodes.item(i), context, mode, Precedence::FrozenPrecedence()); } } // applyTemplates void applyTemplates(const DOMNode& node, ExecutionContext& context, const string_type& mode) const { LastFrame last(context, -1); context.setPosition(node, 1); doApplyTemplates(node, context, mode, Precedence::FrozenPrecedence()); } // applyTemplates void callTemplate(const string_type& name, const DOMNode& node, ExecutionContext& context) const { StackFrame frame(context); NamedTemplatesIterator t = named_templates_.find(name); if(t == named_templates_.end()) { std::cerr << "No template named '"; std::cerr << name << "'. I should be a compile-time error!" << std::endl; throw SAX::SAXException("No template named " + name + ". I should be a compile-time error. Sorry!"); return; } t->second->execute(node, context); } // callTemplate void applyImports(const DOMNode& node, ExecutionContext& context) const { doApplyTemplates(node, context, current_mode_, current_generation_); } // applyImports private: void doApplyTemplates(const DOMNode& node, ExecutionContext& context, const string_type& mode, const Precedence& generation) const { StackFrame frame(context); std::vector<Precedence> lower_precedences; for(TemplateStackIterator ts = templates_.begin(), tse = templates_.end(); ts != tse; ++ts) if(generation.is_descendant(ts->first)) lower_precedences.push_back(ts->first); std::sort(lower_precedences.rbegin(), lower_precedences.rend()); current_mode_ = mode; for(std::vector<Precedence>::const_iterator p = lower_precedences.begin(), pe = lower_precedences.end(); p != pe; ++p) { current_generation_ = *p; ModeTemplates ts = templates_.find(current_generation_)->second; ModeTemplatesIterator mt = ts.find(mode); if(mt != ts.end()) { const MatchTemplates& templates = mt->second; for(MatchTemplatesIterator t = templates.begin(), te = templates.end(); t != te; ++t) if(t->match().evaluate(node, context.xpathContext())) { t->action()->execute(node, context); return; } // if ... } // if ... } // for ... defaultAction(node, context, mode); } // doApplyTemplates void defaultAction(const DOMNode& node, ExecutionContext& context, const string_type& mode) const { switch(node.getNodeType()) { case DOM::Node_base::DOCUMENT_NODE: case DOM::Node_base::DOCUMENT_FRAGMENT_NODE: case DOM::Node_base::ELEMENT_NODE: applyTemplates(node.getChildNodes(), context, mode); break; case DOM::Node_base::ATTRIBUTE_NODE: case DOM::Node_base::TEXT_NODE: case DOM::Node_base::CDATA_SECTION_NODE: context.sink().characters(node.getNodeValue()); /* { const string_type& ch = node.getNodeValue(); for(string_type::const_iterator i = ch.begin(), e = ch.end(); i != e; ++i) if(!Arabica::XML::is_space(*i)) { context.sink().characters(ch); return; } // if ... } */ break; default: ;// nothing! } // switch } // defaultAction void set_parameter(const string_type& name, Value value) { params_.push_back(new TopLevelParam<string_type, string_adaptor>("", name, value)); } // set_parameter void set_parameter(const string_type& namespace_uri, const string_type& name, Value value) { params_.push_back(new TopLevelParam<string_type, string_adaptor>(namespace_uri, name, value)); } // set_parameter private: class MatchTemplate { public: MatchTemplate(const Arabica::XPath::MatchExpr<string_type, string_adaptor>& matchExpr, Template<string_type, string_adaptor>* templat) : match_(matchExpr), template_(templat) { } // MatchTemplate MatchTemplate(const MatchTemplate& rhs) : match_(rhs.match_), template_(rhs.template_) { } // MatchTemplate const Arabica::XPath::MatchExpr<string_type, string_adaptor>& match() const { return match_; } Template<string_type, string_adaptor>* action() const { return template_; } bool operator<(const MatchTemplate& rhs) const { // high priority first! return match_.priority() > rhs.match_.priority(); } // operator< private: Arabica::XPath::MatchExpr<string_type, string_adaptor> match_; Template<string_type, string_adaptor>* template_; }; // struct MatchTemplate typedef std::vector<Template<string_type, string_adaptor>*> TemplateList; typedef std::vector<MatchTemplate> MatchTemplates; typedef typename MatchTemplates::const_iterator MatchTemplatesIterator; typedef std::map<string_type, MatchTemplates> ModeTemplates; typedef typename ModeTemplates::const_iterator ModeTemplatesIterator; typedef std::map<Precedence, ModeTemplates> TemplateStack; typedef typename TemplateStack::const_iterator TemplateStackIterator; typedef std::map<string_type, Template<string_type, string_adaptor>*> NamedTemplates; typedef typename NamedTemplates::const_iterator NamedTemplatesIterator; typedef std::vector<Item*> VariableDeclList; typedef std::vector<TopLevelParam<string_type, string_adaptor>*> ParamList; typedef typename ParamList::const_iterator ParamListIterator; TemplateList all_templates_; NamedTemplates named_templates_; TemplateStack templates_; VariableDeclList topLevelVars_; DeclaredKeys<string_type, string_adaptor> keys_; ParamList params_; mutable string_type current_mode_; mutable Precedence current_generation_; typename Output<string_type, string_adaptor>::Settings output_settings_; typename Output<string_type, string_adaptor>::CDATAElements output_cdata_elements_; SinkHolder<string_type, string_adaptor> output_; mutable std::ostream* error_output_; }; // class CompiledStylesheet } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_COMPILED_STYLESHEET_HPP <commit_msg>stylesheet<commit_after>#ifndef ARABICA_XSLT_COMPILED_STYLESHEET_HPP #define ARABICA_XSLT_COMPILED_STYLESHEET_HPP #include <vector> #include <iostream> #include <XPath/XPath.hpp> #include "xslt_execution_context.hpp" #include "xslt_template.hpp" #include "xslt_top_level_param.hpp" #include "xslt_key.hpp" #include "xslt_stylesheet.hpp" namespace Arabica { namespace XSLT { template<class string_type, class string_adaptor> class CompiledStylesheet : public Stylesheet<string_type, string_adaptor> { typedef Arabica::XPath::BoolValue<string_type, string_adaptor> BoolValue; typedef Arabica::XPath::NumericValue<string_type, string_adaptor> NumericValue; typedef Arabica::XPath::StringValue<string_type, string_adaptor> StringValue; typedef Arabica::XPath::XPathValue<string_type, string_adaptor> Value; typedef Arabica::XPath::NodeSet<string_type, string_adaptor> NodeSet; typedef DOM::Node<string_type, string_adaptor> DOMNode; typedef DOM::NodeList<string_type, string_adaptor> DOMNodeList; public: CompiledStylesheet() : output_(new StreamSink<string_type, string_adaptor>(std::cout)), error_output_(&std::cerr) { } // CompiledStylesheet virtual ~CompiledStylesheet() { // let's clean up! for(VariableDeclList::const_iterator ci = topLevelVars_.begin(), ce = topLevelVars_.end(); ci != ce; ++ci) delete *ci; for(ParamListIterator pi = params_.begin(), pe = params_.end(); pi != pe; ++pi) delete *pi; for(TemplateListIterator ti = all_templates_.begin(), te = all_templates_.end(); ti != te; ++ti) delete *ti; } // ~CompiledStylesheet virtual void set_parameter(const string_type& name, bool value) { set_parameter(name, Value(new BoolValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, double value) { set_parameter(name, Value(new NumericValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, const char* value) { set_parameter(name, Value(new StringValue(value))); } // set_parameter virtual void set_parameter(const string_type& name, const string_type& value) { set_parameter(name, Value(new StringValue(value))); } // set_parameter virtual void set_output(Sink<string_type, string_adaptor>& sink) { output_.reset(sink); } // set_output virtual void set_error_output(std::ostream& os) { error_output_ = &os; } // set_error_output virtual void execute(const DOMNode& initialNode) const { if(initialNode == 0) throw std::runtime_error("Input document is empty"); NodeSet ns; ns.push_back(initialNode); ExecutionContext context(*this, output_.get(), *error_output_); // set up variables and so forth for(ParamListIterator pi = params_.begin(), pe = params_.end(); pi != pe; ++pi) (*pi)->declare(context); for(VariableDeclList::const_iterator ci = topLevelVars_.begin(), ce = topLevelVars_.end(); ci != ce; ++ci) (*ci)->execute(initialNode, context); context.freezeTopLevel(); // go! output_.get().asOutput().start_document(output_settings_, output_cdata_elements_); applyTemplates(ns, context, ""); output_.get().asOutput().end_document(); } // execute //////////////////////////////////////// const DeclaredKeys<string_type, string_adaptor>& keys() const { return keys_; } void add_template(Template<string_type, string_adaptor>* templat) { typedef typename Template<string_type, string_adaptor>::MatchExprList MatchExprList; typedef typename MatchExprList::const_iterator MatchIterator; all_templates_.push_back(templat); for(MatchIterator e = templat->compiled_matches().begin(), ee = templat->compiled_matches().end(); e != ee; ++e) templates_[templat->precedence()][templat->mode()].push_back(MatchTemplate(*e, templat)); if(!templat->has_name()) return; NamedTemplatesIterator named_template = named_templates_.find(templat->name()); if(named_template != named_templates_.end()) { const Precedence& existing_precedence = named_template->second->precedence(); if(existing_precedence > templat->precedence()) return; if(existing_precedence == templat->precedence()) throw SAX::SAXException("Template named '" + templat->name() + "' already defined"); } // if ... named_templates_[templat->name()] = templat; } // add_template void add_variable(Item* item) { topLevelVars_.push_back(item); } // add_item void add_key(const string_type& name, Key<string_type, string_adaptor>* key) { keys_.add(name, key); } // add_key void output_settings(const typename Output<string_type, string_adaptor>::Settings& settings, const typename Output<string_type, string_adaptor>::CDATAElements& cdata_elements) { output_settings_ = settings; output_cdata_elements_.insert(cdata_elements.begin(), cdata_elements.end()); } // output_settingsp void prepare() { for(typename TemplateStack::iterator ts = templates_.begin(), tse = templates_.end(); ts != tse; ++ts) for(typename ModeTemplates::iterator ms = ts->second.begin(), mse = ts->second.end(); ms != mse; ++ms) { MatchTemplates& matches = ms->second; std::reverse(matches.begin(), matches.end()); std::stable_sort(matches.begin(), matches.end()); } // for ... } // prepare //////////////////////////////////////// void applyTemplates(const NodeSet& nodes, ExecutionContext& context, const string_type& mode) const { // entirely simple so far LastFrame last(context, nodes.size()); int p = 1; for(typename NodeSet::const_iterator n = nodes.begin(), ne = nodes.end(); n != ne; ++n) { context.setPosition(*n, p++); doApplyTemplates(*n, context, mode, Precedence::FrozenPrecedence()); } } // applyTemplates void applyTemplates(const DOMNodeList& nodes, ExecutionContext& context, const string_type& mode) const { // entirely simple so far LastFrame last(context, (size_t)nodes.getLength()); for(int i = 0, ie = nodes.getLength(); i != ie; ++i) { context.setPosition(nodes.item(i), i+1); doApplyTemplates(nodes.item(i), context, mode, Precedence::FrozenPrecedence()); } } // applyTemplates void applyTemplates(const DOMNode& node, ExecutionContext& context, const string_type& mode) const { LastFrame last(context, -1); context.setPosition(node, 1); doApplyTemplates(node, context, mode, Precedence::FrozenPrecedence()); } // applyTemplates void callTemplate(const string_type& name, const DOMNode& node, ExecutionContext& context) const { StackFrame frame(context); NamedTemplatesIterator t = named_templates_.find(name); if(t == named_templates_.end()) { std::cerr << "No template named '"; std::cerr << name << "'. I should be a compile-time error!" << std::endl; throw SAX::SAXException("No template named " + name + ". I should be a compile-time error. Sorry!"); return; } t->second->execute(node, context); } // callTemplate void applyImports(const DOMNode& node, ExecutionContext& context) const { doApplyTemplates(node, context, current_mode_, current_generation_); } // applyImports private: void doApplyTemplates(const DOMNode& node, ExecutionContext& context, const string_type& mode, const Precedence& generation) const { StackFrame frame(context); std::vector<Precedence> lower_precedences; for(TemplateStackIterator ts = templates_.begin(), tse = templates_.end(); ts != tse; ++ts) if(generation.is_descendant(ts->first)) lower_precedences.push_back(ts->first); std::sort(lower_precedences.rbegin(), lower_precedences.rend()); current_mode_ = mode; for(std::vector<Precedence>::const_iterator p = lower_precedences.begin(), pe = lower_precedences.end(); p != pe; ++p) { current_generation_ = *p; ModeTemplates ts = templates_.find(current_generation_)->second; ModeTemplatesIterator mt = ts.find(mode); if(mt != ts.end()) { const MatchTemplates& templates = mt->second; for(MatchTemplatesIterator t = templates.begin(), te = templates.end(); t != te; ++t) if(t->match().evaluate(node, context.xpathContext())) { t->action()->execute(node, context); return; } // if ... } // if ... } // for ... defaultAction(node, context, mode); } // doApplyTemplates void defaultAction(const DOMNode& node, ExecutionContext& context, const string_type& mode) const { switch(node.getNodeType()) { case DOM::Node_base::DOCUMENT_NODE: case DOM::Node_base::DOCUMENT_FRAGMENT_NODE: case DOM::Node_base::ELEMENT_NODE: applyTemplates(node.getChildNodes(), context, mode); break; case DOM::Node_base::ATTRIBUTE_NODE: case DOM::Node_base::TEXT_NODE: case DOM::Node_base::CDATA_SECTION_NODE: context.sink().characters(node.getNodeValue()); /* { const string_type& ch = node.getNodeValue(); for(string_type::const_iterator i = ch.begin(), e = ch.end(); i != e; ++i) if(!Arabica::XML::is_space(*i)) { context.sink().characters(ch); return; } // if ... } */ break; default: ;// nothing! } // switch } // defaultAction void set_parameter(const string_type& name, Value value) { params_.push_back(new TopLevelParam<string_type, string_adaptor>("", name, value)); } // set_parameter void set_parameter(const string_type& namespace_uri, const string_type& name, Value value) { params_.push_back(new TopLevelParam<string_type, string_adaptor>(namespace_uri, name, value)); } // set_parameter private: class MatchTemplate { public: MatchTemplate(const Arabica::XPath::MatchExpr<string_type, string_adaptor>& matchExpr, Template<string_type, string_adaptor>* templat) : match_(matchExpr), template_(templat) { } // MatchTemplate MatchTemplate(const MatchTemplate& rhs) : match_(rhs.match_), template_(rhs.template_) { } // MatchTemplate const Arabica::XPath::MatchExpr<string_type, string_adaptor>& match() const { return match_; } Template<string_type, string_adaptor>* action() const { return template_; } bool operator<(const MatchTemplate& rhs) const { // high priority first! return match_.priority() > rhs.match_.priority(); } // operator< private: Arabica::XPath::MatchExpr<string_type, string_adaptor> match_; Template<string_type, string_adaptor>* template_; }; // struct MatchTemplate typedef std::vector<Template<string_type, string_adaptor>*> TemplateList; typedef typename TemplateList::const_iterator TemplateListIterator; typedef std::vector<MatchTemplate> MatchTemplates; typedef typename MatchTemplates::const_iterator MatchTemplatesIterator; typedef std::map<string_type, MatchTemplates> ModeTemplates; typedef typename ModeTemplates::const_iterator ModeTemplatesIterator; typedef std::map<Precedence, ModeTemplates> TemplateStack; typedef typename TemplateStack::const_iterator TemplateStackIterator; typedef std::map<string_type, Template<string_type, string_adaptor>*> NamedTemplates; typedef typename NamedTemplates::const_iterator NamedTemplatesIterator; typedef std::vector<Item*> VariableDeclList; typedef std::vector<TopLevelParam<string_type, string_adaptor>*> ParamList; typedef typename ParamList::const_iterator ParamListIterator; TemplateList all_templates_; NamedTemplates named_templates_; TemplateStack templates_; VariableDeclList topLevelVars_; DeclaredKeys<string_type, string_adaptor> keys_; ParamList params_; mutable string_type current_mode_; mutable Precedence current_generation_; typename Output<string_type, string_adaptor>::Settings output_settings_; typename Output<string_type, string_adaptor>::CDATAElements output_cdata_elements_; SinkHolder<string_type, string_adaptor> output_; mutable std::ostream* error_output_; }; // class CompiledStylesheet } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_COMPILED_STYLESHEET_HPP <|endoftext|>
<commit_before>#ifndef ARABICA_XSLT_STYLESHEETCONSTANT_HPP #define ARABICA_XSLT_STYLESHEETCONSTANT_HPP #include <XML/XMLCharacterClasses.hpp> #include <XPath/impl/xpath_namespace_context.hpp> #include <memory> #include "xslt_stylesheet_parser.hpp" #include "xslt_compiled_stylesheet.hpp" #include "xslt_compilation_context.hpp" #include "handler/xslt_template_handler.hpp" #include "handler/xslt_include_handler.hpp" #include "handler/xslt_output_handler.hpp" #include "handler/xslt_namespace_alias_handler.hpp" #include "handler/xslt_key_handler.hpp" namespace Arabica { namespace XSLT { class StylesheetHandler : public SAX::DefaultHandler<std::string> { public: StylesheetHandler(CompilationContext& context) : context_(context), top_(false), foreign_(0) { context_.root(*this); includer_.context(context_, this); } // StylesheetHandler virtual void startDocument() { top_ = true; } // startDocument virtual void startElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { if(foreign_) { ++foreign_; return; } // if(foreign_) if(top_) { if(namespaceURI != StylesheetConstant::NamespaceURI()) throw SAX::SAXException("The source file does not look like a stylesheet."); if(localName != "stylesheet" && localName != "transform") throw SAX::SAXException("Top-level element must be 'stylesheet' or 'transform'."); static const ValueRule rules[] = { { "version", true, 0 }, { "extension-element-prefixes", false, 0 }, { "exclude-result-prefixes", false, 0 }, { 0, false, 0 } }; std::map<std::string, std::string> attributes = gatherAttributes(qName, atts, rules); if(attributes["version"] != StylesheetConstant::Version()) throw SAX::SAXException("I'm only a poor version 1.0 XSLT Transformer."); top_ = false; return; } // if(top_) if(namespaceURI == StylesheetConstant::NamespaceURI()) { if((localName == "import") || (localName == "include")) { include_stylesheet(namespaceURI, localName, qName, atts); return; } // if ... for(const ChildElement* c = allowedChildren; c->name != 0; ++c) if(c->name == localName) { context_.push(0, c->createHandler(context_), namespaceURI, qName, localName, atts); return; } // if ... } // if ... else if(!namespaceURI.empty()) { ++foreign_; return; } // if(!namespaceURI.empty()) throw SAX::SAXException("xsl:stylesheet does not allow " + qName + " here."); } // startElement virtual void endElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName) { if(foreign_) --foreign_; } // endElement virtual void characters(const std::string& ch) { if(foreign_) return; for(std::string::const_iterator s = ch.begin(), e = ch.end(); s != e; ++s) if(!Arabica::XML::is_space(*s)) throw SAX::SAXException("stylesheet element can not contain character data :'" + ch +"'"); } // characters virtual void endDocument() { includer_.unwind_imports(); context_.stylesheet().prepare(); } // endDocument private: void include_stylesheet(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { includer_.start_include(namespaceURI, localName, qName, atts); } // include_stylesheet CompilationContext& context_; SAX::DefaultHandler<std::string>* child_; IncludeHandler includer_; bool top_; unsigned int foreign_; static const ChildElement allowedChildren[]; }; // class StylesheetHandler const ChildElement StylesheetHandler::allowedChildren[] = { { "attribute-set", CreateHandler<NotImplementedYetHandler>}, { "decimal-format", CreateHandler<NotImplementedYetHandler>}, //"import" //"include" { "key", CreateHandler<KeyHandler>}, { "namespace-alias", CreateHandler<NamespaceAliasHandler>}, { "output", CreateHandler<OutputHandler>}, { "param", CreateHandler<TopLevelVariableHandler<Param> >}, { "preserve-space", CreateHandler<NotImplementedYetHandler>}, { "strip-space", CreateHandler<NotImplementedYetHandler>}, { "template", CreateHandler<TemplateHandler> }, { "variable", CreateHandler<TopLevelVariableHandler<Variable> > }, { 0, 0 } }; // StylesheetHandler::allowedChildren class StylesheetCompiler { public: StylesheetCompiler() { } // StylesheetCompiler ~StylesheetCompiler() { } // ~StylesheetCompiler std::auto_ptr<Stylesheet> compile(SAX::InputSource<std::string>& source) { error_ = ""; std::auto_ptr<CompiledStylesheet> stylesheet(new CompiledStylesheet()); StylesheetParser parser; CompilationContext context(parser, *stylesheet.get()); StylesheetHandler stylesheetHandler(context); parser.setContentHandler(stylesheetHandler); //parser.setErrorHandler(*this); //if(entityResolver_) // parser.setEntityResolver(*entityResolver_); try { parser.parse(source); } // try catch(std::exception& ex) { error_ = ex.what(); //std::cerr << "Compilation Failed : " << ex.what() << std::endl; stylesheet.reset(); } // catch return std::auto_ptr<Stylesheet>(stylesheet.release()); } // compile const std::string& error() const { return error_; } // error private: std::string error_; }; // class StylesheetCompiler } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_STYLESHEETCOMPILER_HPP <commit_msg>xsl:stylesheet can have an id attribute<commit_after>#ifndef ARABICA_XSLT_STYLESHEETCONSTANT_HPP #define ARABICA_XSLT_STYLESHEETCONSTANT_HPP #include <XML/XMLCharacterClasses.hpp> #include <XPath/impl/xpath_namespace_context.hpp> #include <memory> #include "xslt_stylesheet_parser.hpp" #include "xslt_compiled_stylesheet.hpp" #include "xslt_compilation_context.hpp" #include "handler/xslt_template_handler.hpp" #include "handler/xslt_include_handler.hpp" #include "handler/xslt_output_handler.hpp" #include "handler/xslt_namespace_alias_handler.hpp" #include "handler/xslt_key_handler.hpp" namespace Arabica { namespace XSLT { class StylesheetHandler : public SAX::DefaultHandler<std::string> { public: StylesheetHandler(CompilationContext& context) : context_(context), top_(false), foreign_(0) { context_.root(*this); includer_.context(context_, this); } // StylesheetHandler virtual void startDocument() { top_ = true; } // startDocument virtual void startElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { if(foreign_) { ++foreign_; return; } // if(foreign_) if(top_) { if(namespaceURI != StylesheetConstant::NamespaceURI()) throw SAX::SAXException("The source file does not look like a stylesheet."); if(localName != "stylesheet" && localName != "transform") throw SAX::SAXException("Top-level element must be 'stylesheet' or 'transform'."); static const ValueRule rules[] = { { "version", true, 0 }, { "extension-element-prefixes", false, 0 }, { "exclude-result-prefixes", false, 0 }, { "id", false, 0 }, { 0, false, 0 } }; std::map<std::string, std::string> attributes = gatherAttributes(qName, atts, rules); if(attributes["version"] != StylesheetConstant::Version()) throw SAX::SAXException("I'm only a poor version 1.0 XSLT Transformer."); top_ = false; return; } // if(top_) if(namespaceURI == StylesheetConstant::NamespaceURI()) { if((localName == "import") || (localName == "include")) { include_stylesheet(namespaceURI, localName, qName, atts); return; } // if ... for(const ChildElement* c = allowedChildren; c->name != 0; ++c) if(c->name == localName) { context_.push(0, c->createHandler(context_), namespaceURI, qName, localName, atts); return; } // if ... } // if ... else if(!namespaceURI.empty()) { ++foreign_; return; } // if(!namespaceURI.empty()) throw SAX::SAXException("xsl:stylesheet does not allow " + qName + " here."); } // startElement virtual void endElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName) { if(foreign_) --foreign_; } // endElement virtual void characters(const std::string& ch) { if(foreign_) return; for(std::string::const_iterator s = ch.begin(), e = ch.end(); s != e; ++s) if(!Arabica::XML::is_space(*s)) throw SAX::SAXException("stylesheet element can not contain character data :'" + ch +"'"); } // characters virtual void endDocument() { includer_.unwind_imports(); context_.stylesheet().prepare(); } // endDocument private: void include_stylesheet(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { includer_.start_include(namespaceURI, localName, qName, atts); } // include_stylesheet CompilationContext& context_; SAX::DefaultHandler<std::string>* child_; IncludeHandler includer_; bool top_; unsigned int foreign_; static const ChildElement allowedChildren[]; }; // class StylesheetHandler const ChildElement StylesheetHandler::allowedChildren[] = { { "attribute-set", CreateHandler<NotImplementedYetHandler>}, { "decimal-format", CreateHandler<NotImplementedYetHandler>}, //"import" //"include" { "key", CreateHandler<KeyHandler>}, { "namespace-alias", CreateHandler<NamespaceAliasHandler>}, { "output", CreateHandler<OutputHandler>}, { "param", CreateHandler<TopLevelVariableHandler<Param> >}, { "preserve-space", CreateHandler<NotImplementedYetHandler>}, { "strip-space", CreateHandler<NotImplementedYetHandler>}, { "template", CreateHandler<TemplateHandler> }, { "variable", CreateHandler<TopLevelVariableHandler<Variable> > }, { 0, 0 } }; // StylesheetHandler::allowedChildren class StylesheetCompiler { public: StylesheetCompiler() { } // StylesheetCompiler ~StylesheetCompiler() { } // ~StylesheetCompiler std::auto_ptr<Stylesheet> compile(SAX::InputSource<std::string>& source) { error_ = ""; std::auto_ptr<CompiledStylesheet> stylesheet(new CompiledStylesheet()); StylesheetParser parser; CompilationContext context(parser, *stylesheet.get()); StylesheetHandler stylesheetHandler(context); parser.setContentHandler(stylesheetHandler); //parser.setErrorHandler(*this); //if(entityResolver_) // parser.setEntityResolver(*entityResolver_); try { parser.parse(source); } // try catch(std::exception& ex) { error_ = ex.what(); //std::cerr << "Compilation Failed : " << ex.what() << std::endl; stylesheet.reset(); } // catch return std::auto_ptr<Stylesheet>(stylesheet.release()); } // compile const std::string& error() const { return error_; } // error private: std::string error_; }; // class StylesheetCompiler } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_STYLESHEETCOMPILER_HPP <|endoftext|>
<commit_before>/* -*- C++ -*- */ /** * @file GraphBuilder.cpp * @author Roman Schindlauer * @date Wed Jan 18 17:43:14 CET 2006 * * @brief Abstract strategy class for finding the dependency edges of a program. * * */ #include "dlvhex/GraphBuilder.h" #include "dlvhex/Component.h" #include "dlvhex/globals.h" #include "dlvhex/Registry.h" #include "dlvhex/Atom.h" void GraphBuilder::run(const Program& program, NodeGraph& nodegraph) { // // in this multimap, we will store the input arguments of type PREDICATE // of the external atoms. see below. // std::multimap<Term, AtomNodePtr> extinputs; // we start with rule-id 1, 0 is reserved for EXTERNAL and UNIFYING unsigned ruleID = 1; // // go through all rules of the given program // for (Program::iterator r = program.begin(); r != program.end(); ++r, ++ruleID) { // // all nodes of the current rule's head // std::vector<AtomNodePtr> currentHeadNodes; // // go through entire head disjunction // const RuleHead_t& head = (*r)->getHead(); for (RuleHead_t::const_iterator hi = head.begin(); hi != head.end(); ++hi) { // // add a head atom node. This function will take care of also adding // the appropriate unifying dependency for all existing nodes. // AtomNodePtr hn = nodegraph.addUniqueHeadNode(*hi); // // go through all head atoms that were alreay created for this rule // for (std::vector<AtomNodePtr>::iterator currhead = currentHeadNodes.begin(); currhead != currentHeadNodes.end(); ++currhead) { // // and add disjunctive dependency // Dependency::addDep(ruleID, hn, *currhead, Dependency::DISJUNCTIVE); Dependency::addDep(ruleID, *currhead, hn, Dependency::DISJUNCTIVE); } // // add this atom to current head // currentHeadNodes.push_back(hn); } // // constraint: create virtual head node to keep the rule // if (head.size() == 0) { AtomPtr va = Registry::Instance()->storeAtom(new boolAtom); AtomNodePtr vn = nodegraph.addUniqueHeadNode(va); currentHeadNodes.push_back(vn); } //std::vector<AtomNodePtr> currentOrdinaryBodyNodes; std::vector<AtomNodePtr> currentBodyNodes; std::vector<AtomNodePtr> currentExternalBodyNodes; // // go through rule body // const RuleBody_t& body = (*r)->getBody(); for (RuleBody_t::const_iterator li = body.begin(); li != body.end(); ++li) { // // add a body atom node. This function will take care of also adding the appropriate // unifying dependency for all existing nodes. // AtomNodePtr bn = nodegraph.addUniqueBodyNode((*li)->getAtom()); // // save all and - separately - external atoms of this body - after we // are through the entire body, we might have to update EXTERNAL // dependencies inside the rule and build auxiliary rules! // //if ((typeid(*((*li)->getAtom())) == typeid(Atom)) && if (!(*li)->isNAF()) currentBodyNodes.push_back(bn); if (typeid(*((*li)->getAtom())) == typeid(ExternalAtom)) { // not yet: //assert(!(*li)->isNAF()); currentExternalBodyNodes.push_back(bn); } // // add dependency from this body atom to each head atom // for (std::vector<AtomNodePtr>::iterator currhead = currentHeadNodes.begin(); currhead != currentHeadNodes.end(); ++currhead) { if ((*li)->isNAF()) Dependency::addDep(ruleID, bn, *currhead, Dependency::NEG_PRECEDING); else Dependency::addDep(ruleID, bn, *currhead, Dependency::PRECEDING); // // if an external atom is in the body, we have to take care of the // external dependencies - between its arguments (but only those of type // PREDICATE) and any other atom in the program that matches this argument. // // What we will do here is to build a multimap, which stores each input // predicate symbol together with the AtomNode of this external atom. // If we are through all rules, we will go through the complete set // of AtomNodes and search for matches with this multimap. // if (typeid(*((*li)->getAtom())) == typeid(ExternalAtom)) { ExternalAtom* ext = dynamic_cast<ExternalAtom*>((*li)->getAtom().get()); // // go through all input terms of this external atom // for (unsigned s = 0; s < ext->getInputTerms().size(); s++) { // // consider only PREDICATE input terms (naturally, for constant // input terms we won't have any dependencies!) // if (ext->getInputType(s) == PluginAtom::PREDICATE) { // // store the AtomNode of this external atom together will // all the predicate input terms // // e.g., if we had an external atom '&ext[a,b](X)', where // 'a' is of type PREDICATE, and the atom was store in Node n1, // then the map will get an entry <'a', n1>. Below, we will // then search for those AtomNodes with a Predicate 'a' - those // will be assigned a dependency relation with n1! // extinputs.insert(std::pair<Term, AtomNodePtr>(ext->getInputTerms()[s], bn)); } } } } } // body finished // // now we go through the ordinary and external atoms of the body again // and see if we have to add any EXTERNAL_AUX dependencies. // An EXTERNAL_AUX dependency arises, if an external atom has variable // input arguments, which makes it necessary to create an auxiliary // rule. // for (std::vector<AtomNodePtr>::iterator currextbody = currentExternalBodyNodes.begin(); currextbody != currentExternalBodyNodes.end(); ++currextbody) { ExternalAtom* ext = dynamic_cast<ExternalAtom*>((*currextbody)->getAtom().get()); // // does this external atom have any variable input parameters? // if (!ext->pureGroundInput()) { // // ok, get the parameters // Tuple extinput = ext->getInputTerms(); // // make a new atom with the ext-parameters as arguments, will be // the head of the auxiliary rule and add this atom to the // global atom store // AtomPtr auxheadatom = Registry::Instance()->storeAtom(new Atom(ext->getAuxPredicate(), extinput)); // // add a new head node with this atom // AtomNodePtr auxheadnode = nodegraph.addUniqueHeadNode(auxheadatom); // // add aux dependency from this new head to the external atom // node // Dependency::addDep(ruleID, auxheadnode, *currextbody, Dependency::EXTERNAL_AUX); RuleBody_t auxbody; // // the body of the auxiliary rule are all body literals // (ordinary or external) that have variables with the aux_head // in common and that are not weakly negated! // std::vector<AtomNodePtr> allbodynodes; for (std::vector<AtomNodePtr>::iterator currbody = currentBodyNodes.begin(); currbody != currentBodyNodes.end(); ++currbody) { // // don't consider the external atom itself, the input must // be bound by other atoms // if (*currextbody == *currbody) continue; bool thisAtomIsRelevant = false; Tuple currentAtomArguments = (*currbody)->getAtom()->getArguments(); // // go through all variables of the external atom // Tuple::const_iterator inb = extinput.begin(), ine = extinput.end(); while (inb != ine) { // // now see if any of the current ordinary body atom // arguments has a common variable with the external // atom // Tuple::const_iterator bodb = currentAtomArguments.begin(); Tuple::const_iterator bode = currentAtomArguments.end(); while (bodb != bode) { if (*(bodb++) == *inb) { thisAtomIsRelevant = true; } } inb++; } // // should this atom be in the auxiliary rule body? // (i.e., does one of its arguments occur in the input list // of the external atom?) // if (thisAtomIsRelevant) { // // make new literals with the (ordinary) body atoms of the current rule // Literal* l = new Literal((*currbody)->getAtom()); Registry::Instance()->storeObject(l); auxbody.insert(l); // // make a node for each of these new atoms // AtomNodePtr auxbodynode = nodegraph.addUniqueBodyNode(l->getAtom()); // // add the usual body->head dependency // Dependency::addDep(ruleID, auxbodynode, auxheadnode, Dependency::PRECEDING); } } } } } // // Now we will build the EXTERNAL dependencies: // typedef std::multimap<Term, AtomNodePtr>::iterator mi; // // Go through all AtomNodes // for (std::vector<AtomNodePtr>::const_iterator node = nodegraph.getNodes().begin(); node != nodegraph.getNodes().end(); ++node) { // // do this only for ordinary atoms, external atoms can't be in the input // list! // if (typeid(*(*node)->getAtom()) != typeid(ExternalAtom)) { // // For this AtomNode: take the predicate term of its atom and extract all // entries in the multimap that match this predicate. Those entries contain // now the AtomNodes of the external atoms that have such an input predicate. // std::pair<mi, mi> range = extinputs.equal_range((*node)->getAtom()->getPredicate()); // // add dependency: from this node to the external atom (second in the pair of the // multimap) // for (mi i = range.first; i != range.second; ++i) { ///@todo this should work right now, but maybe we ///should add the correct rule-id to this dependency Dependency::addDep(0, *node, i->second, Dependency::EXTERNAL); } } } } void GraphBuilder::dumpGraph(const NodeGraph& nodegraph, std::ostream& out) const { out << "Dependency graph - Program Nodes:" << std::endl; for (std::vector<AtomNodePtr>::const_iterator node = nodegraph.getNodes().begin(); node != nodegraph.getNodes().end(); ++node) { out << **node << std::endl; } out << std::endl; } <commit_msg>Use Rule* instead of rule-id in Dependency.<commit_after>/* -*- C++ -*- */ /** * @file GraphBuilder.cpp * @author Roman Schindlauer * @date Wed Jan 18 17:43:14 CET 2006 * * @brief Abstract strategy class for finding the dependency edges of a program. * * */ #include "dlvhex/GraphBuilder.h" #include "dlvhex/Component.h" #include "dlvhex/globals.h" #include "dlvhex/Registry.h" #include "dlvhex/Atom.h" void GraphBuilder::run(const Program& program, NodeGraph& nodegraph) { // // in this multimap, we will store the input arguments of type PREDICATE // of the external atoms. see below. // std::multimap<Term, AtomNodePtr> extinputs; // // empty the NodeGraph // nodegraph.reset(); // we start with rule-id 1, 0 is reserved for EXTERNAL and UNIFYING // unsigned ruleID = 1; // // go through all rules of the given program // for (Program::iterator r = program.begin(); r != program.end(); ++r) { // // all nodes of the current rule's head // std::vector<AtomNodePtr> currentHeadNodes; // // go through entire head disjunction // const RuleHead_t& head = (*r)->getHead(); for (RuleHead_t::const_iterator hi = head.begin(); hi != head.end(); ++hi) { // // add a head atom node. This function will take care of also adding // the appropriate unifying dependency for all existing nodes. // AtomNodePtr hn = nodegraph.addUniqueHeadNode(*hi); // // go through all head atoms that were alreay created for this rule // for (std::vector<AtomNodePtr>::iterator currhead = currentHeadNodes.begin(); currhead != currentHeadNodes.end(); ++currhead) { // // and add disjunctive dependency // Dependency::addDep(*r, hn, *currhead, Dependency::DISJUNCTIVE); Dependency::addDep(*r, *currhead, hn, Dependency::DISJUNCTIVE); } // // add this atom to current head // currentHeadNodes.push_back(hn); } // // constraint: create virtual head node to keep the rule // if (head.size() == 0) { AtomPtr va = Registry::Instance()->storeAtom(new boolAtom); AtomNodePtr vn = nodegraph.addUniqueHeadNode(va); currentHeadNodes.push_back(vn); } //std::vector<AtomNodePtr> currentOrdinaryBodyNodes; std::vector<AtomNodePtr> currentBodyNodes; std::vector<AtomNodePtr> currentExternalBodyNodes; // // go through rule body // const RuleBody_t& body = (*r)->getBody(); for (RuleBody_t::const_iterator li = body.begin(); li != body.end(); ++li) { // // add a body atom node. This function will take care of also adding the appropriate // unifying dependency for all existing nodes. // AtomNodePtr bn = nodegraph.addUniqueBodyNode((*li)->getAtom()); // // save all and - separately - external atoms of this body - after we // are through the entire body, we might have to update EXTERNAL // dependencies inside the rule and build auxiliary rules! // //if ((typeid(*((*li)->getAtom())) == typeid(Atom)) && if (!(*li)->isNAF()) currentBodyNodes.push_back(bn); if (typeid(*((*li)->getAtom())) == typeid(ExternalAtom)) { // not yet: //assert(!(*li)->isNAF()); currentExternalBodyNodes.push_back(bn); } // // add dependency from this body atom to each head atom // for (std::vector<AtomNodePtr>::iterator currhead = currentHeadNodes.begin(); currhead != currentHeadNodes.end(); ++currhead) { if ((*li)->isNAF()) Dependency::addDep(*r, bn, *currhead, Dependency::NEG_PRECEDING); else Dependency::addDep(*r, bn, *currhead, Dependency::PRECEDING); // // if an external atom is in the body, we have to take care of the // external dependencies - between its arguments (but only those of type // PREDICATE) and any other atom in the program that matches this argument. // // What we will do here is to build a multimap, which stores each input // predicate symbol together with the AtomNode of this external atom. // If we are through all rules, we will go through the complete set // of AtomNodes and search for matches with this multimap. // if (typeid(*((*li)->getAtom())) == typeid(ExternalAtom)) { ExternalAtom* ext = dynamic_cast<ExternalAtom*>((*li)->getAtom().get()); // // go through all input terms of this external atom // for (unsigned s = 0; s < ext->getInputTerms().size(); s++) { // // consider only PREDICATE input terms (naturally, for constant // input terms we won't have any dependencies!) // if (ext->getInputType(s) == PluginAtom::PREDICATE) { // // store the AtomNode of this external atom together will // all the predicate input terms // // e.g., if we had an external atom '&ext[a,b](X)', where // 'a' is of type PREDICATE, and the atom was store in Node n1, // then the map will get an entry <'a', n1>. Below, we will // then search for those AtomNodes with a Predicate 'a' - those // will be assigned a dependency relation with n1! // extinputs.insert(std::pair<Term, AtomNodePtr>(ext->getInputTerms()[s], bn)); } } } } } // body finished // // now we go through the ordinary and external atoms of the body again // and see if we have to add any EXTERNAL_AUX dependencies. // An EXTERNAL_AUX dependency arises, if an external atom has variable // input arguments, which makes it necessary to create an auxiliary // rule. // for (std::vector<AtomNodePtr>::iterator currextbody = currentExternalBodyNodes.begin(); currextbody != currentExternalBodyNodes.end(); ++currextbody) { ExternalAtom* ext = dynamic_cast<ExternalAtom*>((*currextbody)->getAtom().get()); // // does this external atom have any variable input parameters? // if (!ext->pureGroundInput()) { // // ok, get the parameters // Tuple extinput = ext->getInputTerms(); // // make a new atom with the ext-parameters as arguments, will be // the head of the auxiliary rule and add this atom to the // global atom store // AtomPtr auxheadatom = Registry::Instance()->storeAtom(new Atom(ext->getAuxPredicate(), extinput)); // // add a new head node with this atom // AtomNodePtr auxheadnode = nodegraph.addUniqueHeadNode(auxheadatom); // // add aux dependency from this new head to the external atom // node // Dependency::addDep(*r, auxheadnode, *currextbody, Dependency::EXTERNAL_AUX); RuleBody_t auxbody; // // the body of the auxiliary rule are all body literals // (ordinary or external) that have variables with the aux_head // in common and that are not weakly negated! // std::vector<AtomNodePtr> allbodynodes; for (std::vector<AtomNodePtr>::iterator currbody = currentBodyNodes.begin(); currbody != currentBodyNodes.end(); ++currbody) { // // don't consider the external atom itself, the input must // be bound by other atoms // if (*currextbody == *currbody) continue; bool thisAtomIsRelevant = false; Tuple currentAtomArguments = (*currbody)->getAtom()->getArguments(); // // go through all variables of the external atom // Tuple::const_iterator inb = extinput.begin(), ine = extinput.end(); while (inb != ine) { // // now see if any of the current ordinary body atom // arguments has a common variable with the external // atom // Tuple::const_iterator bodb = currentAtomArguments.begin(); Tuple::const_iterator bode = currentAtomArguments.end(); while (bodb != bode) { if (*(bodb++) == *inb) { thisAtomIsRelevant = true; } } inb++; } // // should this atom be in the auxiliary rule body? // (i.e., does one of its arguments occur in the input list // of the external atom?) // if (thisAtomIsRelevant) { // // make new literals with the (ordinary) body atoms of the current rule // Literal* l = new Literal((*currbody)->getAtom()); Registry::Instance()->storeObject(l); auxbody.insert(l); // // make a node for each of these new atoms // AtomNodePtr auxbodynode = nodegraph.addUniqueBodyNode(l->getAtom()); // // add the usual body->head dependency // Dependency::addDep(*r, auxbodynode, auxheadnode, Dependency::PRECEDING); } } } } } // // Now we will build the EXTERNAL dependencies: // typedef std::multimap<Term, AtomNodePtr>::iterator mi; // // Go through all AtomNodes // for (std::vector<AtomNodePtr>::const_iterator node = nodegraph.getNodes().begin(); node != nodegraph.getNodes().end(); ++node) { // // do this only for ordinary atoms, external atoms can't be in the input // list! // if (typeid(*(*node)->getAtom()) != typeid(ExternalAtom)) { // // For this AtomNode: take the predicate term of its atom and extract all // entries in the multimap that match this predicate. Those entries contain // now the AtomNodes of the external atoms that have such an input predicate. // std::pair<mi, mi> range = extinputs.equal_range((*node)->getAtom()->getPredicate()); // // add dependency: from this node to the external atom (second in the pair of the // multimap) // for (mi i = range.first; i != range.second; ++i) { Dependency::addDep(0, *node, i->second, Dependency::EXTERNAL); } } } } void GraphBuilder::dumpGraph(const NodeGraph& nodegraph, std::ostream& out) const { out << "Dependency graph - Program Nodes:" << std::endl; for (std::vector<AtomNodePtr>::const_iterator node = nodegraph.getNodes().begin(); node != nodegraph.getNodes().end(); ++node) { out << **node << std::endl; } out << std::endl; } <|endoftext|>
<commit_before>#include <QSqlQuery> #include <QSqlError> #include <QUrl> #include <QSqlRecord> #include "kernel.h" #include "identity.h" #include "resource.h" #include "mastercatalog.h" #include "connectorinterface.h" #include "containerconnector.h" #include "catalogconnector.h" #include "internalcatalogconnector.h" using namespace Ilwis; using namespace Internal; ConnectorInterface *InternalCatalogConnector::create(const Resource&, bool ) { return new InternalCatalogConnector(); } InternalCatalogConnector::InternalCatalogConnector() :ContainerConnector(Resource(QUrl("ilwis://internalcatalog"),itCONTAINER)) { } bool InternalCatalogConnector::prepare() { QSqlQuery db(kernel()->database()); bool ok = createItems(db,"projection", itPROJECTION); ok &= createItems(db,"ellipsoid", itELLIPSOID); ok &= createItems(db,"datum", itGEODETICDATUM); ok &= createItems(db,"numericdomain", itNUMERICDOMAIN); ok &= createPcs(db); ok &= createSpecialDomains(); return ok; } std::vector<QUrl> InternalCatalogConnector::sources(const QStringList &, int ) const { //TODO full list?? return std::vector<QUrl>(); } bool InternalCatalogConnector::createSpecialDomains() { QString url = QString("ilwis://internalcatalog/code=domain:text"); Resource resource(url, itTEXTDOMAIN); resource.setCode("text"); resource.setName("Text domain", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); return mastercatalog()->addItems({resource}); } bool InternalCatalogConnector::canUse(const Resource &res) const { return res.url().scheme() == "ilwis"; } QString InternalCatalogConnector::provider() const { return "internal"; } QFileInfo InternalCatalogConnector::toLocalFile(const QUrl& url) const { return url.toLocalFile(); } bool InternalCatalogConnector::isValid() const{ return true; } bool InternalCatalogConnector::createPcs(QSqlQuery& db) { QString query = QString("Select * from projectedcsy"); if ( db.exec(query)) { QList<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); QString name = rec.value("name").toString(); QString url = QString("ilwis://tables/projectedcsy?code=%1").arg(code); Resource resource(url, itCONVENTIONALCOORDSYSTEM); resource.setCode(code); resource.setName(name, false); resource["wkt"] = name; resource.addContainer(QUrl("ilwis://system")); items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } bool InternalCatalogConnector::createItems(QSqlQuery& db, const QString& table, IlwisTypes type) { QString query = QString("Select * from %1").arg(table); if ( db.exec(query)) { QList<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); IlwisTypes extType = rec.value("extendedtype").toLongLong(); QString url = QString("ilwis://tables/%1?code=%2").arg(table,code); Resource resource(url, type); if ( type == itNUMERICDOMAIN) // for valuedomain name=code resource.setName(rec.value("code").toString(), false); else resource.setName(rec.value("name").toString(), false); resource.setCode(code); resource.setExtendedType(extType); resource.setDescription(rec.value("description").toString()); resource.addContainer(QUrl("ilwis://system")); QString wkt = rec.value("wkt").toString(); if ( wkt != "" && wkt != sUNDEF) resource["wkt"] = wkt; items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } <commit_msg>toLocalFile now simply returns the url as file. If this is not possible the client of this method should ahndle it. At this level nothing better can be done<commit_after>#include <QSqlQuery> #include <QSqlError> #include <QUrl> #include <QSqlRecord> #include "kernel.h" #include "identity.h" #include "resource.h" #include "mastercatalog.h" #include "connectorinterface.h" #include "containerconnector.h" #include "catalogconnector.h" #include "internalcatalogconnector.h" using namespace Ilwis; using namespace Internal; ConnectorInterface *InternalCatalogConnector::create(const Resource&, bool ) { return new InternalCatalogConnector(); } InternalCatalogConnector::InternalCatalogConnector() :ContainerConnector(Resource(QUrl("ilwis://internalcatalog"),itCONTAINER)) { } bool InternalCatalogConnector::prepare() { QSqlQuery db(kernel()->database()); bool ok = createItems(db,"projection", itPROJECTION); ok &= createItems(db,"ellipsoid", itELLIPSOID); ok &= createItems(db,"datum", itGEODETICDATUM); ok &= createItems(db,"numericdomain", itNUMERICDOMAIN); ok &= createPcs(db); ok &= createSpecialDomains(); return ok; } std::vector<QUrl> InternalCatalogConnector::sources(const QStringList &, int ) const { //TODO full list?? return std::vector<QUrl>(); } bool InternalCatalogConnector::createSpecialDomains() { QString url = QString("ilwis://internalcatalog/code=domain:text"); Resource resource(url, itTEXTDOMAIN); resource.setCode("text"); resource.setName("Text domain", false); resource.addContainer(QUrl("ilwis://internalcatalog")); resource.prepare(); return mastercatalog()->addItems({resource}); } bool InternalCatalogConnector::canUse(const Resource &res) const { return res.url().scheme() == "ilwis"; } QString InternalCatalogConnector::provider() const { return "internal"; } QFileInfo InternalCatalogConnector::toLocalFile(const QUrl& url) const { QFileInfo inf = url.toLocalFile(); return inf; } bool InternalCatalogConnector::isValid() const{ return true; } bool InternalCatalogConnector::createPcs(QSqlQuery& db) { QString query = QString("Select * from projectedcsy"); if ( db.exec(query)) { QList<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); QString name = rec.value("name").toString(); QString url = QString("ilwis://tables/projectedcsy?code=%1").arg(code); Resource resource(url, itCONVENTIONALCOORDSYSTEM); resource.setCode(code); resource.setName(name, false); resource["wkt"] = name; resource.addContainer(QUrl("ilwis://system")); items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } bool InternalCatalogConnector::createItems(QSqlQuery& db, const QString& table, IlwisTypes type) { QString query = QString("Select * from %1").arg(table); if ( db.exec(query)) { QList<Resource> items; while (db.next()) { QSqlRecord rec = db.record(); QString code = rec.value("code").toString(); IlwisTypes extType = rec.value("extendedtype").toLongLong(); QString url = QString("ilwis://tables/%1?code=%2").arg(table,code); Resource resource(url, type); if ( type == itNUMERICDOMAIN) // for valuedomain name=code resource.setName(rec.value("code").toString(), false); else resource.setName(rec.value("name").toString(), false); resource.setCode(code); resource.setExtendedType(extType); resource.setDescription(rec.value("description").toString()); resource.addContainer(QUrl("ilwis://system")); QString wkt = rec.value("wkt").toString(); if ( wkt != "" && wkt != sUNDEF) resource["wkt"] = wkt; items.push_back(resource); } return mastercatalog()->addItems(items); } else { kernel()->issues()->logSql(db.lastError()); } return false; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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 copyright holder(s) 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. * * $Id$ */ #ifndef PCL_PCA_IMPL_HPP #define PCL_PCA_IMPL_HPP #include <pcl/point_types.h> #include <pcl/common/centroid.h> #include <pcl/common/eigen.h> #include <pcl/common/transforms.h> #include <pcl/exceptions.h> ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> bool pcl::PCA<PointT>::initCompute () { if(!Base::initCompute ()) { PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] failed"); return (false); } if(indices_->size () < 3) { PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] number of points < 3"); return (false); } // Compute mean mean_ = Eigen::Vector4f::Zero (); compute3DCentroid (*input_, *indices_, mean_); // Compute demeanished cloud Eigen::MatrixXf cloud_demean; demeanPointCloud (*input_, *indices_, mean_, cloud_demean); assert (cloud_demean.cols () == int (indices_->size ())); // Compute the product cloud_demean * cloud_demean^T Eigen::Matrix3f alpha = static_cast<Eigen::Matrix3f> (cloud_demean.topRows<3> () * cloud_demean.topRows<3> ().transpose ()); // Compute eigen vectors and values Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> evd (alpha); // Organize eigenvectors and eigenvalues in ascendent order for (int i = 0; i < 3; ++i) { eigenvalues_[i] = evd.eigenvalues () [2-i]; eigenvectors_.col (i) = evd.eigenvectors ().col (2-i); } // If not basis only then compute the coefficients if (!basis_only_) coefficients_ = eigenvectors_.transpose() * cloud_demean.topRows<3> (); compute_done_ = true; return (true); } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::update (const PointT& input_point, FLAG flag) { if (!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::update] PCA initCompute failed"); Eigen::Vector3f input (input_point.x, input_point.y, input_point.z); const size_t n = eigenvectors_.cols ();// number of eigen vectors Eigen::VectorXf meanp = (float(n) * (mean_.head<3>() + input)) / float(n + 1); Eigen::VectorXf a = eigenvectors_.transpose() * (input - mean_.head<3>()); Eigen::VectorXf y = (eigenvectors_ * a) + mean_.head<3>(); Eigen::VectorXf h = y - input; if (h.norm() > 0) h.normalize (); else h.setZero (); float gamma = h.dot(input - mean_.head<3>()); Eigen::MatrixXf D = Eigen::MatrixXf::Zero (a.size() + 1, a.size() + 1); D.block(0,0,n,n) = a * a.transpose(); D /= float(n)/float((n+1) * (n+1)); for(std::size_t i=0; i < a.size(); i++) { D(i,i)+= float(n)/float(n+1)*eigenvalues_(i); D(D.rows()-1,i) = float(n) / float((n+1) * (n+1)) * gamma * a(i); D(i,D.cols()-1) = D(D.rows()-1,i); D(D.rows()-1,D.cols()-1) = float(n)/float((n+1) * (n+1)) * gamma * gamma; } Eigen::MatrixXf R(D.rows(), D.cols()); Eigen::EigenSolver<Eigen::MatrixXf> D_evd (D, false); Eigen::VectorXf alphap = D_evd.eigenvalues().real(); eigenvalues_.resize(eigenvalues_.size() +1); for(std::size_t i=0;i<eigenvalues_.size();i++) { eigenvalues_(i) = alphap(eigenvalues_.size()-i-1); R.col(i) = D.col(D.cols()-i-1); } Eigen::MatrixXf Up = Eigen::MatrixXf::Zero(eigenvectors_.rows(), eigenvectors_.cols()+1); Up.topLeftCorner(eigenvectors_.rows(),eigenvectors_.cols()) = eigenvectors_; Up.rightCols<1>() = h; eigenvectors_ = Up*R; if (!basis_only_) { Eigen::Vector3f etha = Up.transpose() * (mean_.head<3>() - meanp); coefficients_.resize(coefficients_.rows()+1,coefficients_.cols()+1); for(std::size_t i=0; i < (coefficients_.cols() - 1); i++) { coefficients_(coefficients_.rows()-1,i) = 0; coefficients_.col(i) = (R.transpose() * coefficients_.col(i)) + etha; } a.resize(a.size()+1); a(a.size()-1) = 0; coefficients_.col(coefficients_.cols()-1) = (R.transpose() * a) + etha; } mean_.head<3>() = meanp; switch (flag) { case increase: if (eigenvectors_.rows() >= eigenvectors_.cols()) break; case preserve: if (!basis_only_) coefficients_ = coefficients_.topRows(coefficients_.rows() - 1); eigenvectors_ = eigenvectors_.leftCols(eigenvectors_.cols() - 1); eigenvalues_.resize(eigenvalues_.size()-1); break; default: PCL_ERROR("[pcl::PCA] unknown flag\n"); } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::project (const PointT& input, PointT& projection) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed"); Eigen::Vector3f demean_input = input.getVector3fMap () - mean_.head<3> (); projection.getVector3fMap () = eigenvectors_.transpose() * demean_input; } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::project (const PointCloud& input, PointCloud& projection) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed"); if (input.is_dense) { projection.resize (input.size ()); for (size_t i = 0; i < input.size (); ++i) project (input[i], projection[i]); } else { PointT p; for (size_t i = 0; i < input.size (); ++i) { if (!pcl_isfinite (input[i].x) || !pcl_isfinite (input[i].y) || !pcl_isfinite (input[i].z)) continue; project (input[i], p); projection.push_back (p); } } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::reconstruct (const PointT& projection, PointT& input) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed"); input.getVector3fMap ()= eigenvectors_ * projection.getVector3fMap (); input.getVector3fMap ()+= mean_.head<3> (); } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::reconstruct (const PointCloud& projection, PointCloud& input) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed"); if (input.is_dense) { input.resize (projection.size ()); for (size_t i = 0; i < projection.size (); ++i) reconstruct (projection[i], input[i]); } else { PointT p; for (size_t i = 0; i < input.size (); ++i) { if (!pcl_isfinite (input[i].x) || !pcl_isfinite (input[i].y) || !pcl_isfinite (input[i].z)) continue; reconstruct (projection[i], p); input.push_back (p); } } } #endif <commit_msg>Fix covariance calculation in PCA<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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 copyright holder(s) 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. * * $Id$ */ #ifndef PCL_PCA_IMPL_HPP #define PCL_PCA_IMPL_HPP #include <pcl/point_types.h> #include <pcl/common/centroid.h> #include <pcl/common/eigen.h> #include <pcl/common/transforms.h> #include <pcl/exceptions.h> ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> bool pcl::PCA<PointT>::initCompute () { if(!Base::initCompute ()) { PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] failed"); return (false); } if(indices_->size () < 3) { PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::initCompute] number of points < 3"); return (false); } // Compute mean mean_ = Eigen::Vector4f::Zero (); compute3DCentroid (*input_, *indices_, mean_); // Compute demeanished cloud Eigen::MatrixXf cloud_demean; demeanPointCloud (*input_, *indices_, mean_, cloud_demean); assert (cloud_demean.cols () == int (indices_->size ())); // Compute the product cloud_demean * cloud_demean^T const Eigen::Matrix3f alpha = (1.f / (float (indices_->size ()) - 1.f)) * cloud_demean.topRows<3> () * cloud_demean.topRows<3> ().transpose (); // Compute eigen vectors and values Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> evd (alpha); // Organize eigenvectors and eigenvalues in ascendent order for (int i = 0; i < 3; ++i) { eigenvalues_[i] = evd.eigenvalues () [2-i]; eigenvectors_.col (i) = evd.eigenvectors ().col (2-i); } // If not basis only then compute the coefficients if (!basis_only_) coefficients_ = eigenvectors_.transpose() * cloud_demean.topRows<3> (); compute_done_ = true; return (true); } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::update (const PointT& input_point, FLAG flag) { if (!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::update] PCA initCompute failed"); Eigen::Vector3f input (input_point.x, input_point.y, input_point.z); const size_t n = eigenvectors_.cols ();// number of eigen vectors Eigen::VectorXf meanp = (float(n) * (mean_.head<3>() + input)) / float(n + 1); Eigen::VectorXf a = eigenvectors_.transpose() * (input - mean_.head<3>()); Eigen::VectorXf y = (eigenvectors_ * a) + mean_.head<3>(); Eigen::VectorXf h = y - input; if (h.norm() > 0) h.normalize (); else h.setZero (); float gamma = h.dot(input - mean_.head<3>()); Eigen::MatrixXf D = Eigen::MatrixXf::Zero (a.size() + 1, a.size() + 1); D.block(0,0,n,n) = a * a.transpose(); D /= float(n)/float((n+1) * (n+1)); for(std::size_t i=0; i < a.size(); i++) { D(i,i)+= float(n)/float(n+1)*eigenvalues_(i); D(D.rows()-1,i) = float(n) / float((n+1) * (n+1)) * gamma * a(i); D(i,D.cols()-1) = D(D.rows()-1,i); D(D.rows()-1,D.cols()-1) = float(n)/float((n+1) * (n+1)) * gamma * gamma; } Eigen::MatrixXf R(D.rows(), D.cols()); Eigen::EigenSolver<Eigen::MatrixXf> D_evd (D, false); Eigen::VectorXf alphap = D_evd.eigenvalues().real(); eigenvalues_.resize(eigenvalues_.size() +1); for(std::size_t i=0;i<eigenvalues_.size();i++) { eigenvalues_(i) = alphap(eigenvalues_.size()-i-1); R.col(i) = D.col(D.cols()-i-1); } Eigen::MatrixXf Up = Eigen::MatrixXf::Zero(eigenvectors_.rows(), eigenvectors_.cols()+1); Up.topLeftCorner(eigenvectors_.rows(),eigenvectors_.cols()) = eigenvectors_; Up.rightCols<1>() = h; eigenvectors_ = Up*R; if (!basis_only_) { Eigen::Vector3f etha = Up.transpose() * (mean_.head<3>() - meanp); coefficients_.resize(coefficients_.rows()+1,coefficients_.cols()+1); for(std::size_t i=0; i < (coefficients_.cols() - 1); i++) { coefficients_(coefficients_.rows()-1,i) = 0; coefficients_.col(i) = (R.transpose() * coefficients_.col(i)) + etha; } a.resize(a.size()+1); a(a.size()-1) = 0; coefficients_.col(coefficients_.cols()-1) = (R.transpose() * a) + etha; } mean_.head<3>() = meanp; switch (flag) { case increase: if (eigenvectors_.rows() >= eigenvectors_.cols()) break; case preserve: if (!basis_only_) coefficients_ = coefficients_.topRows(coefficients_.rows() - 1); eigenvectors_ = eigenvectors_.leftCols(eigenvectors_.cols() - 1); eigenvalues_.resize(eigenvalues_.size()-1); break; default: PCL_ERROR("[pcl::PCA] unknown flag\n"); } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::project (const PointT& input, PointT& projection) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed"); Eigen::Vector3f demean_input = input.getVector3fMap () - mean_.head<3> (); projection.getVector3fMap () = eigenvectors_.transpose() * demean_input; } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::project (const PointCloud& input, PointCloud& projection) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::project] PCA initCompute failed"); if (input.is_dense) { projection.resize (input.size ()); for (size_t i = 0; i < input.size (); ++i) project (input[i], projection[i]); } else { PointT p; for (size_t i = 0; i < input.size (); ++i) { if (!pcl_isfinite (input[i].x) || !pcl_isfinite (input[i].y) || !pcl_isfinite (input[i].z)) continue; project (input[i], p); projection.push_back (p); } } } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::reconstruct (const PointT& projection, PointT& input) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed"); input.getVector3fMap ()= eigenvectors_ * projection.getVector3fMap (); input.getVector3fMap ()+= mean_.head<3> (); } ///////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> inline void pcl::PCA<PointT>::reconstruct (const PointCloud& projection, PointCloud& input) { if(!compute_done_) initCompute (); if (!compute_done_) PCL_THROW_EXCEPTION (InitFailedException, "[pcl::PCA::reconstruct] PCA initCompute failed"); if (input.is_dense) { input.resize (projection.size ()); for (size_t i = 0; i < projection.size (); ++i) reconstruct (projection[i], input[i]); } else { PointT p; for (size_t i = 0; i < input.size (); ++i) { if (!pcl_isfinite (input[i].x) || !pcl_isfinite (input[i].y) || !pcl_isfinite (input[i].z)) continue; reconstruct (projection[i], p); input.push_back (p); } } } #endif <|endoftext|>
<commit_before>//Adapted from sites.google.com/site/stevenhalim/home/material //or cpbook.net #include <cmath> #include <vector> #define EPS 0.000000001; #define COLLINEAR 0 #define LEFT 1 #define RIGHT -1 #define polygon vector<point> using namespace std; bool equal(double a, double b) { return fabs(a-b) < EPS; } struct point; struct line; struct vec; // use this whenever possible //struct point { int x, y struct point { double x,y; point(); point(double _x, double _y); bool operator == (const point& o); bool operator< (const point& other); vec operator- (const point& other); point operator+ (const vec& v); }; struct line { double a, b, c; line (const point& p1, const point& p2); bool operator== (const line& other); //are they parallel bool operator|| (const line& other); }; //struct vec { int dx, dy; struct vec { double dx, dy, mag; vec(double x, double y); vec(const point& from, const point& to) // convert 2 points to vector vec normalize(); vec operator+ (const vec& other); //scale vec operator* (double s); //dot product double operator* (const vec& other); }; point::point() :x(0), y(0) {} point::point(double _x, double _y) :x(_x), y(_y) {} bool point::operator == (const point& o) { return equal(x,o.x) && equal(y,o.y); } bool point::operator < (const point& other) { if (fabs(x - other.x) > EPS) return x < other.x; return y < other.y; } vec point::operator- (const point& other){ return vec(other,*this); } point point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); } double dist(const point& p1, const point& p2) { return hypot(p1.x - p2.x, p1.y - p2.y); } line::line (const point& p1, const point& p2) { // vertical line is handled nicely below //if (p1.x == p2.x) { if (equal(p1.x, p2.x)) { a = 1.0; b = 0.0; c = -p1.x; } else { a = -(double)(p1.y - p2.y) / (p1.x - p2.x); b = 1.0; c = -(double)(a * p1.x) - (b * p1.y); } } bool line::operator== (const line& other) { return (*this || other) && (fabs(c - other.c) < EPS); } bool line::operator|| (const line& other){ // check coefficient a + b return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS); } bool intersect(const line& l1, const line& l2, point& p) { // all points same if (l1 == l2) { return false; } // no intersection if (l1 || l2) { return false; } // solve system of 2 linear algebraic equations with 2 unknowns p.x = (double)(l2.b * l1.c - l1 b * l2.c) / (l2.a * l1.b - l1.a * l2.b); // test for vertical line (avoid div by zero) if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) / l1.b; } else { p.y = - (l2.a * p.x + l2.c) / l2.b; } return true; } vec::vec(double deltaX, double deltaY) : dx(deltaX), dy(deltaY) { double magX = fabs(dx); double magY = fabs(dy); if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); } else if (magX < EPS) { mag = magY; } else if (magY < EPS) { mag = magX; } else { mag = 0; } } vec::vec(const point& from, const point& to) :vec(to.x - from.x, to.y - from.y) {} vec::normalize() { return vec(dx / mag, dy / mag); } vec vec::operator+ (const vec & other){ return vec(dx + other.dx, dy + other.dy); } vec vec::operator* (double s){ return vec(s * dx, s * dy); } double vec::operator* (const vec & other){ return dx * other.dx + dy * other.dy; } //square of triangle area /* int area2(point a, point b, point c) { return a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x; } */ // square of distance between 2 points int dist2(point a, point b) { int dx = a.x - b.x, dy = a.y - b.y; return dx * dx + dy * dy; } int turn(const point& a, const point& b, const point& c) { double result = (c.x - b.x) * (a.y - b.y) - (c.y - b.y) * (a.x - b.x); if (result < 0) return RIGHT; // a->B->C is a right turn if (result > 0) return LEFT; // a->B->C is a left turn return COLLINEAR; // a->B->C is a straight line, i.e. a, B, C are collinear } //important angle-sorting functor class LeftTurnCmp{ private: point pivot; public: LeftTurnCmp(const point& pivot) :pivot(pivot) {} bool operator()(const point& a, const& point b){ if (turn(pivot, a, b) == COLLINEAR) return dist2(pivot, a) < dist2(pivot, b); // which one closer int d1x = a.x - pivot.x, d1y = a.y - pivot.y; int d2x = b.x - pivot.x, d2y = b.y - pivot.y; return (atan2((double)d1y, (double)d1x) - atan2((double)d2y, (double)d2x)) < 0; } }; //Counterclockwise starting from bottom-most point void orderByAngle(polygon& p){ // first, find p0 = point with lowest Y and if tie: rightmost X int lowestIndex = 0; int n = p.size(); for (int i = 1; i < n; i++) { if (p[i].y < p[lowestIndex].y || (p[i].y == p[lowestIndex].y && p[i].x > p[lowestIndex].x)) { lowestIndex = i; } } swap(p[0],p[lowestIndex]); // second, sort points by angle w.r.t. lowest LeftTurnCmp angle_cmp(p[0]); sort(++p.begin(), p.end(), angle_cmp); } /* The following code assumes you have ordered the points! */ double perimeter(polygon& p) { double result = 0.0; //double x1, y1, x2, y2, dx, dy; for (int i = 0; i < p.size(); i++) { result += distance(p[i],p[(i+1)%p.size()]); } return result; } double determinant(polygon& p) { double result = 0; double x1, y1, x2, y2; for (int i = 0; i < p.size(); i++) { x1 = p[i].x; x2 = p[(i + 1) % p.size()].x; y1 = p[i].y; y2 = p[(i + 1) % p.size()].y; result += (x1 * y2 - x2 * y1); } return result; } // area is half of the determinant and the result may be a non-integer double area(polygon& p) { return fabs(determinant(p)) / 2.0); } //n must be >= 3 for this method to work void getConvexHull(polygon& p, polygon& convexHull){ int n = p.size(); stack<point> S; point prev, now; S.push(p[n - 1]); // put two starting vertices into stack S S.push(p[0]); int i = 1; // and start checking the rest while (i < n) { // get the 2nd item from top of S now = S.top(); S.pop(); prev = S.top(); S.push(now); if (turn(prev, now, p[i]) == LEFT) { S.push(p[i]); // accept i++; } // otherwise pop this point until we have a left turn else { S.pop(); } } while (!S.empty()) { // from stack back to vector convexHull.push_back(S.top()); S.pop(); } convexHull.pop_back(); // the last one is a duplicate of first one } <commit_msg>Area and perimeter pass a sanity check<commit_after>//Adapted from sites.google.com/site/stevenhalim/home/material //or cpbook.net #include <cmath> #include <vector> #include <stack> #include <algorithm> #include <iostream> #include <cstdio> #define COLLINEAR 0 #define LEFT 1 #define RIGHT -1 #define polygon vector<point> using namespace std; const double EPS = 0.000000001; bool equal(double a, double b) { return fabs(a-b) < EPS; } struct point; struct line; struct vec; // use this whenever possible //struct point { int x, y struct point { double x,y; point(); point(double _x, double _y); point(pair<double,double> p); bool operator == (const point& o); bool operator< (const point& other); vec operator- (const point& other); point operator+ (const vec& v); }; struct line { double a, b, c; line (const point& p1, const point& p2); bool equivalent(const line& other) const; bool operator== (const line& other) const; //are they parallel bool parallel(const line& other) const; bool operator|| (const line& other) const; }; //struct vec { int dx, dy; struct vec { double dx, dy, mag; vec(double x, double y); vec(const point& from, const point& to); // convert 2 points to vector vec(pair<double,double> p); vec normalize(); vec operator+ (const vec& other); //scale vec operator* (double s); //dot product double operator* (const vec& other); }; point::point() :x(0), y(0) {} point::point(double _x, double _y) :x(_x), y(_y) {} point::point(pair<double,double> p) :x(p.first), y(p.second) {} bool point::operator == (const point& o) { return equal(x,o.x) && equal(y,o.y); } bool point::operator < (const point& other) { if (fabs(x - other.x) > EPS) return x < other.x; return y < other.y; } vec point::operator- (const point& other){ return vec(other,*this); } point point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); } double distance(const point& p1, const point& p2) { return hypot(p1.x - p2.x, p1.y - p2.y); } line::line (const point& p1, const point& p2) { // vertical line is handled nicely below //if (p1.x == p2.x) { if (equal(p1.x, p2.x)) { a = 1.0; b = 0.0; c = -p1.x; } else { a = -(double)(p1.y - p2.y) / (p1.x - p2.x); b = 1.0; c = -(double)(a * p1.x) - (b * p1.y); } } bool line::parallel(const line& other) const { // check coefficient a + b return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS); } bool line::operator|| (const line& other) const { return parallel(other); } bool line::equivalent(const line& other) const { return parallel(other) && (fabs(c - other.c) < EPS); } bool line::operator== (const line& other) const { return equivalent(other); } bool intersect(const line& l1, const line& l2, point& p) { // all points same if (l1 == l2) { return false; } // no intersection if (l1 || l2) { return false; } // solve system of 2 linear algebraic equations with 2 unknowns p.x = (double)(l2.b * l1.c - l1.b * l2.c) / (l2.a * l1.b - l1.a * l2.b); // test for vertical line (avoid div by zero) if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) / l1.b; } else { p.y = - (l2.a * p.x + l2.c) / l2.b; } return true; } vec::vec(double deltaX, double deltaY) : dx(deltaX), dy(deltaY) { double magX = fabs(dx); double magY = fabs(dy); if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); } else if (magX < EPS) { mag = magY; } else if (magY < EPS) { mag = magX; } else { mag = 0; } } vec::vec(const point& from, const point& to) :vec(to.x - from.x, to.y - from.y) {} vec::vec(pair<double,double> p) :vec(p.first, p.second) {} vec vec::normalize() { return vec(dx / mag, dy / mag); } vec vec::operator+ (const vec & other){ return vec(dx + other.dx, dy + other.dy); } vec vec::operator* (double s){ return vec(s * dx, s * dy); } double vec::operator* (const vec & other){ return dx * other.dx + dy * other.dy; } //square of triangle area /* int area2(point a, point b, point c) { return a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x; } */ // square of distance between 2 points int dist2(point a, point b) { int dx = a.x - b.x, dy = a.y - b.y; return dx * dx + dy * dy; } int turn(const point& a, const point& b, const point& c) { double result = (c.x - b.x) * (a.y - b.y) - (c.y - b.y) * (a.x - b.x); if (result < 0) return RIGHT; // a->B->C is a right turn if (result > 0) return LEFT; // a->B->C is a left turn return COLLINEAR; // a->B->C is a straight line, i.e. a, B, C are collinear } //important angle-sorting functor class LeftTurnCmp{ private: point pivot; public: LeftTurnCmp(const point& pivot) :pivot(pivot) {} bool operator()(const point& a, const point& b){ if (turn(pivot, a, b) == COLLINEAR) return dist2(pivot, a) < dist2(pivot, b); // which one closer int d1x = a.x - pivot.x, d1y = a.y - pivot.y; int d2x = b.x - pivot.x, d2y = b.y - pivot.y; return (atan2((double)d1y, (double)d1x) - atan2((double)d2y, (double)d2x)) < 0; } }; //Counterclockwise starting from bottom-most point void orderByAngle(polygon& p){ // first, find p0 = point with lowest Y and if tie: rightmost X int lowestIndex = 0; int n = p.size(); for (int i = 1; i < n; i++) { if (p[i].y < p[lowestIndex].y || (p[i].y == p[lowestIndex].y && p[i].x > p[lowestIndex].x)) { lowestIndex = i; } } swap(p[0],p[lowestIndex]); // second, sort points by angle w.r.t. lowest LeftTurnCmp angle_cmp(p[0]); sort(++p.begin(), p.end(), angle_cmp); } /* The following code assumes you have ordered the points! */ double perimeter(polygon& p) { double result = 0.0; //double x1, y1, x2, y2, dx, dy; for (int i = 0; i < p.size(); i++) { result += distance(p[i],p[(i+1)%p.size()]); } return result; } double determinant(polygon& p) { double result = 0; double x1, y1, x2, y2; for (int i = 0; i < p.size(); i++) { x1 = p[i].x; x2 = p[(i + 1) % p.size()].x; y1 = p[i].y; y2 = p[(i + 1) % p.size()].y; result += (x1 * y2 - x2 * y1); } return result; } // area is half of the determinant and the result may be a non-integer double area(polygon& p) { return fabs(determinant(p)) / 2.0; } //n must be >= 3 for this method to work void getConvexHull(polygon& p, polygon& convexHull){ int n = p.size(); stack<point> S; point prev, now; S.push(p[n - 1]); // put two starting vertices into stack S S.push(p[0]); int i = 1; // and start checking the rest while (i < n) { // get the 2nd item from top of S now = S.top(); S.pop(); prev = S.top(); S.push(now); if (turn(prev, now, p[i]) == LEFT) { S.push(p[i]); // accept i++; } // otherwise pop this point until we have a left turn else { S.pop(); } } while (!S.empty()) { // from stack back to vector convexHull.push_back(S.top()); S.pop(); } convexHull.pop_back(); // the last one is a duplicate of first one } int main(){ polygon p = {{0,0}, {5,0}, {0,5}, {2,7}, {5,5} }; orderByAngle(p); cout << perimeter(p) << ' ' << area(p) << endl; } <|endoftext|>
<commit_before>#ifndef __LSH_HASHSET_HPP__ #define __LSH_HASHSET_HPP__ #include <functional> #include <limits> #include "../Containers/Array.hpp" #include "../Containers/StaticHashMap.hpp" #include "../MetricSpace/Generic/HashFunction.hpp" #include "../MetricSpace/Generic/DistanceFunction.hpp" #include "../MetricSpace/Generic/DataSet.hpp" namespace lsh { template<typename PointType> class HashSet { public: using Point = typename PointType::Type; using PointRef = typename PointType::RefType; using DataSet = MetricSpace::Generic::DataSet<PointType>; using HashFunction = MetricSpace::Generic::HashFunction<PointType>; using DistanceFunction = MetricSpace::Generic::DistanceFunction<PointType>; private: const HashFunction& mHashFunc; const DistanceFunction& mDistFunc; Array<StaticHashMap<unsigned int>> mHashMapArray; /* TODO: Upgrade to a more cache friendly data structure */ const DataSet& mDataSet; public: HashSet (const HashFunction& hashFunc, const DistanceFunction& distFunc, unsigned int hashMapSize, const DataSet& dataSet) : mHashFunc(hashFunc), mDistFunc(distFunc), mHashMapArray(), mDataSet(dataSet) { mHashMapArray.reserve(mHashFunc.getKeyNum()); for (unsigned int i = 0; i < mHashFunc.getKeyNum(); ++i) { mHashMapArray.emplaceBack(hashMapSize); } } void add (unsigned int value, const PointRef x) /* NOTE: can be removed */ { auto keySet = mHashFunc(x); for (unsigned int i = 0; i < mHashMapArray.getLength(); ++i) { mHashMapArray[i].add(keySet[i], value); } } void add (const DataSet& data) { for (unsigned int i = 0; i < data.getPointNum(); ++i) { add(i, data[i]); } } unsigned int forEachPointInRange (double R, const PointRef p, std::function<void (unsigned int, double)> func) { auto keySet = mHashFunc(p); unsigned int sum = 0; bool checked[mDataSet.getPointNum()] = { false }; for (unsigned int i = 0; i < mHashMapArray.getLength(); ++i) { auto key = keySet[i]; for (auto& x : mHashMapArray[i][key]) { //std::cout << x.target << std::endl; if (x.key == key && !checked[x.target]) { ++sum; double dist = mDistFunc(mDataSet[x.target], p); if (dist < R) { func(x.target, dist); //sum++; } checked[x.target] = true; } } } return sum; } unsigned int operator[] (const PointRef p); }; } #endif /* end of include guard: __LSH_HASHSET_HPP__ */ <commit_msg>operator []<commit_after>#ifndef __LSH_HASHSET_HPP__ #define __LSH_HASHSET_HPP__ #include <functional> #include <limits> #include "../Containers/Array.hpp" #include "../Containers/StaticHashMap.hpp" #include "../MetricSpace/Generic/HashFunction.hpp" #include "../MetricSpace/Generic/DistanceFunction.hpp" #include "../MetricSpace/Generic/DataSet.hpp" namespace lsh { template<typename PointType> class HashSet { public: using Point = typename PointType::Type; using PointRef = typename PointType::RefType; using DataSet = MetricSpace::Generic::DataSet<PointType>; using HashFunction = MetricSpace::Generic::HashFunction<PointType>; using DistanceFunction = MetricSpace::Generic::DistanceFunction<PointType>; struct QueryResult { bool found; unsigned int index; unsigned int sum; }; private: const HashFunction& mHashFunc; const DistanceFunction& mDistFunc; Array<StaticHashMap<unsigned int>> mHashMapArray; /* TODO: Upgrade to a more cache friendly data structure */ const DataSet& mDataSet; public: HashSet (const HashFunction& hashFunc, const DistanceFunction& distFunc, unsigned int hashMapSize, const DataSet& dataSet) : mHashFunc(hashFunc), mDistFunc(distFunc), mHashMapArray(), mDataSet(dataSet) { mHashMapArray.reserve(mHashFunc.getKeyNum()); for (unsigned int i = 0; i < mHashFunc.getKeyNum(); ++i) { mHashMapArray.emplaceBack(hashMapSize); } } void add (unsigned int value, const PointRef x) /* NOTE: can be removed */ { auto keySet = mHashFunc(x); for (unsigned int i = 0; i < mHashMapArray.getLength(); ++i) { mHashMapArray[i].add(keySet[i], value); } } void add (const DataSet& data) { for (unsigned int i = 0; i < data.getPointNum(); ++i) { add(i, data[i]); } } unsigned int forEachPointInRange (double R, const PointRef p, std::function<void (unsigned int, double)> func) { auto keySet = mHashFunc(p); unsigned int sum = 0; bool checked[mDataSet.getPointNum()] = { false }; for (unsigned int i = 0; i < mHashMapArray.getLength(); ++i) { auto key = keySet[i]; for (auto& x : mHashMapArray[i][key]) { if (x.key == key && !checked[x.target]) { sum++; double dist = mDistFunc(mDataSet[x.target], p); if (dist < R) { func(x.target, dist); } checked[x.target] = true; } } } return sum; } QueryResult operator[] (const PointRef p) { auto keySet = mHashFunc(p); bool checked[mDataSet.getPointNum()] = { false }; bool found = false; double sDist = 0; unsigned int r = 0; unsigned int sum = 0; for (unsigned int i = 0; i < mHashMapArray.getLength(); ++i) { auto key = keySet[i]; for (auto& x : mHashMapArray[i][key]) { if (x.key == key && !checked[x.target]) { sum++; double dist = mDistFunc(mDataSet[x.target], p); if (dist < sDist || !found) { found = true; sDist = dist; r = x.target; } checked[x.target] = true; } } } return {found, r, sum}; } }; } #endif /* end of include guard: __LSH_HASHSET_HPP__ */ <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> int main (int argc, char **argv) { IplImage *src_img = 0; IplImage *dst_img_1, *dst_img_2, *dst_img_3; // (1)画像を読み込み,同じサイズの出力画像を用意する if (argc >= 2) src_img = cvLoadImage (argv[1], CV_LOAD_IMAGE_COLOR); if (src_img == 0) return -1; dst_img_1 = cvCloneImage (src_img); dst_img_2 = cvCloneImage (src_img); dst_img_3 = cvCloneImage (src_img); // (2)画像の水平軸反転・垂直軸反転・両軸反転を行う cvFlip (src_img, dst_img_1, 0); cvFlip (src_img, dst_img_2, 1); cvFlip (src_img, dst_img_3, -1); // (3)結果を表示する cvNamedWindow ("src", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_1", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_2", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_3", CV_WINDOW_AUTOSIZE); cvShowImage ("src", src_img); cvShowImage ("dst_1", dst_img_1); cvShowImage ("dst_2", dst_img_2); cvShowImage ("dst_3", dst_img_3); cvWaitKey (0); cvDestroyWindow ("src"); cvDestroyWindow ("dst_1"); cvDestroyWindow ("dst_2"); cvDestroyWindow ("dst_3"); cvReleaseImage (&src_img); cvReleaseImage (&dst_img_1); cvReleaseImage (&dst_img_2); cvReleaseImage (&dst_img_3); return 1; } <commit_msg>Update flip_image.cpp to return0<commit_after>#include <opencv2/opencv.hpp> int main (int argc, char **argv) { IplImage *src_img = 0; IplImage *dst_img_1, *dst_img_2, *dst_img_3; // (1)画像を読み込み,同じサイズの出力画像を用意する if (argc >= 2) src_img = cvLoadImage (argv[1], CV_LOAD_IMAGE_COLOR); if (src_img == 0) return -1; dst_img_1 = cvCloneImage (src_img); dst_img_2 = cvCloneImage (src_img); dst_img_3 = cvCloneImage (src_img); // (2)画像の水平軸反転・垂直軸反転・両軸反転を行う cvFlip (src_img, dst_img_1, 0); cvFlip (src_img, dst_img_2, 1); cvFlip (src_img, dst_img_3, -1); // (3)結果を表示する cvNamedWindow ("src", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_1", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_2", CV_WINDOW_AUTOSIZE); cvNamedWindow ("dst_3", CV_WINDOW_AUTOSIZE); cvShowImage ("src", src_img); cvShowImage ("dst_1", dst_img_1); cvShowImage ("dst_2", dst_img_2); cvShowImage ("dst_3", dst_img_3); cvWaitKey (0); cvDestroyWindow ("src"); cvDestroyWindow ("dst_1"); cvDestroyWindow ("dst_2"); cvDestroyWindow ("dst_3"); cvReleaseImage (&src_img); cvReleaseImage (&dst_img_1); cvReleaseImage (&dst_img_2); cvReleaseImage (&dst_img_3); return 0; } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <unistd.h> #include "fnord/base/io/filerepository.h" #include "fnord/base/io/fileutil.h" #include "fnord/base/application.h" #include "fnord/base/logging.h" #include "fnord/base/random.h" #include "fnord/base/thread/eventloop.h" #include "fnord/base/thread/threadpool.h" #include "fnord/base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord/cli/flagparser.h" #include "fnord/json/json.h" #include "fnord/json/jsonrpc.h" #include "fnord/net/http/httprouter.h" #include "fnord/net/http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord/stats/statsdagent.h" #include "fnord-mdb/MDB.h" #include "cm-common/CustomerNamespace.h" #include "cm-logjoin/LogJoin.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "statefile", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "statefile", "<filename>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "max_spread_secs", fnord::cli::FlagParser::T_INTEGER, false, NULL, "10", "max_spread_secs", "<num>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t max_spread_secs = flags.getInt("max_spread_secs"); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(max_spread_secs * kMicrosPerSecond); /* get source urls */ Vector<String> uris = flags.getArgv(); if (flags.isSet("statefile")) { auto statefile = FileUtil::read(flags.getString("statefile")).toString(); for (const auto& uri : StringUtil::split(statefile, "\n")) { if (uri.size() > 0) { uris.emplace_back(uri); } } } HashMap<String, String> feed_urls; for (const auto& uri_raw : uris) { URI uri(uri_raw); const auto& params = uri.queryParams(); std::string feed; if (!URI::getParam(params, "feed", &feed)) { RAISEF( kIllegalArgumentError, "feed url missing ?feed query param: $0", uri_raw); } feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?"))); std::string offset_str; uint64_t offset = 0; if (URI::getParam(params, "offset", &offset_str)) { if (offset_str == "HEAD") { offset = std::numeric_limits<uint64_t>::max(); } else { offset = std::stoul(offset_str); } } feed_reader.addSourceFeed( uri, feed, offset, batch_size, buffer_size); } DateTime last_iter; uint64_t rate_limit_micros = 1 * kMicrosPerSecond; for (int i = 0; i < commit_size; ++i) { last_iter = WallClock::now(); feed_reader.waitForNextEntry(); for (;;) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } fnord::iputs("$0", entry.get().data); } if (flags.isSet("statefile")) { auto stream_offsets = feed_reader.streamOffsets(); Buffer statefile; for (const auto& soff : stream_offsets) { statefile.append( StringUtil::format( "$0?feed=$1&offset=$2\n", feed_urls[soff.first], soff.first, soff.second)); } FileUtil::write(flags.getString("statefile") + "~", statefile); FileUtil::mv( flags.getString("statefile") + "~", flags.getString("statefile")); } auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } evloop_thread.join(); return 0; } <commit_msg>fn-feedtail: --print_time flag<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <unistd.h> #include "fnord/base/io/filerepository.h" #include "fnord/base/io/fileutil.h" #include "fnord/base/application.h" #include "fnord/base/logging.h" #include "fnord/base/random.h" #include "fnord/base/thread/eventloop.h" #include "fnord/base/thread/threadpool.h" #include "fnord/base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord/cli/flagparser.h" #include "fnord/json/json.h" #include "fnord/json/jsonrpc.h" #include "fnord/net/http/httprouter.h" #include "fnord/net/http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord/stats/statsdagent.h" #include "fnord-mdb/MDB.h" #include "cm-common/CustomerNamespace.h" #include "cm-logjoin/LogJoin.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "statefile", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "statefile", "<filename>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "max_spread_secs", fnord::cli::FlagParser::T_INTEGER, false, NULL, "10", "max_spread_secs", "<num>"); flags.defineFlag( "print_time", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "print_time", ""); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t max_spread_secs = flags.getInt("max_spread_secs"); size_t print_time = flags.isSet("print_time"); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(max_spread_secs * kMicrosPerSecond); /* get source urls */ Vector<String> uris = flags.getArgv(); if (flags.isSet("statefile")) { auto statefile = FileUtil::read(flags.getString("statefile")).toString(); for (const auto& uri : StringUtil::split(statefile, "\n")) { if (uri.size() > 0) { uris.emplace_back(uri); } } } HashMap<String, String> feed_urls; for (const auto& uri_raw : uris) { URI uri(uri_raw); const auto& params = uri.queryParams(); std::string feed; if (!URI::getParam(params, "feed", &feed)) { RAISEF( kIllegalArgumentError, "feed url missing ?feed query param: $0", uri_raw); } feed_urls.emplace(feed, uri_raw.substr(0, uri_raw.find("?"))); std::string offset_str; uint64_t offset = 0; if (URI::getParam(params, "offset", &offset_str)) { if (offset_str == "HEAD") { offset = std::numeric_limits<uint64_t>::max(); } else { offset = std::stoul(offset_str); } } feed_reader.addSourceFeed( uri, feed, offset, batch_size, buffer_size); } DateTime last_iter; uint64_t rate_limit_micros = 1 * kMicrosPerSecond; for (int i = 0; i < commit_size; ++i) { last_iter = WallClock::now(); feed_reader.waitForNextEntry(); for (;;) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } if (print_time) { fnord::iputs("[$0] $1", entry.get().time, entry.get().data); } else { fnord::iputs("$0", entry.get().data); } } if (flags.isSet("statefile")) { auto stream_offsets = feed_reader.streamOffsets(); Buffer statefile; for (const auto& soff : stream_offsets) { statefile.append( StringUtil::format( "$0?feed=$1&offset=$2\n", feed_urls[soff.first], soff.first, soff.second)); } FileUtil::write(flags.getString("statefile") + "~", statefile); FileUtil::mv( flags.getString("statefile") + "~", flags.getString("statefile")); } auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } evloop_thread.join(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2005-2008 Damien Stehle. Copyright (C) 2007 David Cade. Copyright (C) 2011 Xavier Pujol. This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ /* Template source file */ #include "hlll.h" #include "util.h" FPLLL_BEGIN_NAMESPACE template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll() { int k = 1; int k_max = 0; FT s; FT tmp; FT sum; /* TODO: not exactly the good value * delta_ in (delta + 2^(-p + p0), 1 - 2^(-p + p0)) */ FT delta_ = delta; int start_time = cputime(); long expo_k1_k1, expo_k_k1, expo_k_k; m.update_R(0); if (verbose) print_params(); while (k < m.get_d()) { if (k > k_max) { if (verbose) { cerr << "Discovering vector " << k + 1 << "/" << m.get_d() << " cputime=" << cputime() - start_time << endl; } k_max = k; } size_reduction(k); m.get_R(s, k, k - 1, expo_k_k1); s.mul(s, s); // s = R(k, k - 1)^2 m.get_R(tmp, k, k, expo_k_k); tmp.mul(tmp, tmp); // tmp = R(k, k)^2 s.add(tmp, s); // s = R(k, k - 1)^2 + R(k, k)^2 // Here, s = R(k, k - 1)^2 + R(k, k)^2 = ||b_k||^2 - sum_{i in [0, k-2)} R(k, i)^2 m.get_R(tmp, k - 1, k - 1, expo_k1_k1); tmp.mul(tmp, tmp); tmp.mul(delta_, tmp); // tmp = delta_ * R(k - 1, k - 1)^2 if (expo_k1_k1 > -1) s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1)); if (tmp <= s) k++; else { m.swap(k - 1, k); k = max(k - 1, 1); } } } template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa) { vector<FT> xf(kappa); FT ftmp0, ftmp1; long expo0 = -1; long expo1 = -1; // for all i > max_index, xf[i] == 0. int max_index; bool reduce = true; m.update_R(kappa, kappa); // cout << "root: R[" << kappa << "] = " << m.get_R(kappa, expo0) << endl; /* Most likely, at this step, the next update_R(kappa, kappa) must modify some coefficients since * b will most likely * be changed. If b is not modified during the size reduction, there will be only a call to * update_R_last(kappa), * which automatically must set updated_R to false. * TODO: find a best place to use this function. */ m.set_updated_R_false(); do { max_index = -1; for (int i = kappa - 1; i >= 0; i--) { m.get_R(ftmp1, kappa, i, expo0); // expo0 = row_expo[kappa] m.get_R(ftmp0, i, i, expo1); // expo1 = row_expo[i] ftmp1.div(ftmp1, ftmp0); // x[i] = R(kappa, i) / R(i, i) /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by * rnd_we with this types) */ ftmp1.rnd_we(ftmp1, expo0 - expo1); xf[i].neg(ftmp1); if (ftmp1.cmp(0.0) != 0) { for (int j = 0; j < i; j++) { m.get_R(ftmp1, i, j, expo0); // expo0 = row_expo[i] ftmp1.mul(xf[i], ftmp1); // ftmp1 = x[i] * R(i, j) m.get_R(ftmp0, kappa, j, expo0); // expo0 = row_expo[kappa] ftmp0.add(ftmp0, ftmp1); // ftmp0 = R(kappa, j) + x[i] * R(i, j) m.set_R(ftmp0, kappa, j); } max_index = max(max_index, i); } } m.norm_square_b_row(ftmp1, kappa, expo0); // ftmp1 = ||b[kappa]||^2 m.addmul_b_rows(kappa, xf); m.norm_square_b_row(ftmp0, kappa, expo1); // ftmp0 = ||b[kappa]||^2 ftmp1.mul(sr, ftmp1); // ftmp1 = 2^(-cd) * ftmp1 if (expo1 > -1) ftmp0.mul_2si(ftmp0, expo1 - expo0); if (ftmp0.cmp(ftmp1) <= 0) m.update_R(kappa, kappa); else reduce = false; } while (reduce); if (max_index == -1) m.update_R_last(kappa); else m.update_R(kappa); } // Works only there is no row_expo. template <class ZT, class FT> bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta) { FT ftmp0; FT ftmp1; FT delta_ = delta; m.update_R(); long expo; for (int i = 0; i < m.get_d(); i++) { for (int j = 0; j < i; j++) { m.get_R(ftmp0, i, j, expo); m.get_R(ftmp1, j, j, expo); ftmp1.div(ftmp0, ftmp1); ftmp1.abs(ftmp1); if (ftmp1.cmp(0.5) > 0) return false; } } for (int i = 1; i < m.get_d(); i++) { m.norm_square_b_row(ftmp0, i, expo); // ftmp0 = ||b[i]||^2 m.norm_square_R_row(ftmp1, i, i - 1, expo); ftmp1.sub(ftmp0, ftmp1); // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2 m.get_R(ftmp0, i - 1, i - 1, expo); ftmp0.mul(ftmp0, ftmp0); ftmp0.mul(delta_, ftmp0); // ftmp0 = delta_ * R(i - 1, i - 1)^2 if (ftmp0.cmp(ftmp1) > 0) return false; } return true; } /** instantiate functions **/ template class HLLLReduction<Z_NR<long>, FP_NR<double>>; template class HLLLReduction<Z_NR<double>, FP_NR<double>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m, double delta, double eta); #ifdef FPLLL_WITH_LONG_DOUBLE template class HLLLReduction<Z_NR<long>, FP_NR<long double>>; template class HLLLReduction<Z_NR<double>, FP_NR<long double>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>( MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta); #endif #ifdef FPLLL_WITH_QD template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>; template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m, double delta, double eta); #endif #ifdef FPLLL_WITH_DPE template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>; template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m, double delta, double eta); #endif template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>; template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m, double delta, double eta); FPLLL_END_NAMESPACE <commit_msg>Do not compute ||bk||^2 if not necessary.<commit_after>/* Copyright (C) 2005-2008 Damien Stehle. Copyright (C) 2007 David Cade. Copyright (C) 2011 Xavier Pujol. This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ /* Template source file */ #include "hlll.h" #include "util.h" FPLLL_BEGIN_NAMESPACE template <class ZT, class FT> void HLLLReduction<ZT, FT>::lll() { int k = 1; int k_max = 0; FT s; FT tmp; FT sum; /* TODO: not exactly the good value * delta_ in (delta + 2^(-p + p0), 1 - 2^(-p + p0)) */ FT delta_ = delta; int start_time = cputime(); long expo_k1_k1, expo_k_k1, expo_k_k; m.update_R(0); if (verbose) print_params(); while (k < m.get_d()) { if (k > k_max) { if (verbose) { cerr << "Discovering vector " << k + 1 << "/" << m.get_d() << " cputime=" << cputime() - start_time << endl; } k_max = k; } size_reduction(k); m.get_R(s, k, k - 1, expo_k_k1); s.mul(s, s); // s = R(k, k - 1)^2 m.get_R(tmp, k, k, expo_k_k); tmp.mul(tmp, tmp); // tmp = R(k, k)^2 s.add(tmp, s); // s = R(k, k - 1)^2 + R(k, k)^2 // Here, s = R(k, k - 1)^2 + R(k, k)^2 = ||b_k||^2 - sum_{i in [0, k-2)} R(k, i)^2 m.get_R(tmp, k - 1, k - 1, expo_k1_k1); tmp.mul(tmp, tmp); tmp.mul(delta_, tmp); // tmp = delta_ * R(k - 1, k - 1)^2 if (expo_k1_k1 > -1) s.mul_2si(s, 2 * (expo_k_k - expo_k1_k1)); if (tmp <= s) k++; else { m.swap(k - 1, k); k = max(k - 1, 1); } } } template <class ZT, class FT> void HLLLReduction<ZT, FT>::size_reduction(int kappa) { vector<FT> xf(kappa); FT ftmp0, ftmp1; long expo0 = -1; long expo1 = -1; // for all i > max_index, xf[i] == 0. int max_index; bool reduce = true; m.update_R(kappa, kappa); // cout << "root: R[" << kappa << "] = " << m.get_R(kappa, expo0) << endl; /* Most likely, at this step, the next update_R(kappa, kappa) must modify some coefficients since * b will most likely * be changed. If b is not modified during the size reduction, there will be only a call to * update_R_last(kappa), * which automatically must set updated_R to false. * TODO: find a best place to use this function. */ m.set_updated_R_false(); do { max_index = -1; for (int i = kappa - 1; i >= 0; i--) { m.get_R(ftmp1, kappa, i, expo0); // expo0 = row_expo[kappa] m.get_R(ftmp0, i, i, expo1); // expo1 = row_expo[i] ftmp1.div(ftmp1, ftmp0); // x[i] = R(kappa, i) / R(i, i) /* If T = mpfr or dpe, enable_row_expo must be false and then, expo0 - expo1 == 0 (required by * rnd_we with this types) */ ftmp1.rnd_we(ftmp1, expo0 - expo1); xf[i].neg(ftmp1); if (ftmp1.cmp(0.0) != 0) { for (int j = 0; j < i; j++) { m.get_R(ftmp1, i, j, expo0); // expo0 = row_expo[i] ftmp1.mul(xf[i], ftmp1); // ftmp1 = x[i] * R(i, j) m.get_R(ftmp0, kappa, j, expo0); // expo0 = row_expo[kappa] ftmp0.add(ftmp0, ftmp1); // ftmp0 = R(kappa, j) + x[i] * R(i, j) m.set_R(ftmp0, kappa, j); } max_index = max(max_index, i); } } if (max_index == -1) { // If max_index == -1, b(kappa) has not changed. Computing ||b[kappa]||^2 is not necessary. // 1 > 2^(-cd)=sr since cd > 0. Then, reduce = false. reduce = false; } else { m.norm_square_b_row(ftmp1, kappa, expo0); // ftmp1 = ||b[kappa]||^2 m.addmul_b_rows(kappa, xf); m.norm_square_b_row(ftmp0, kappa, expo1); // ftmp0 = ||b[kappa]||^2 ftmp1.mul(sr, ftmp1); // ftmp1 = 2^(-cd) * ftmp1 = sr * ftmp1 if (expo1 > -1) ftmp0.mul_2si(ftmp0, expo1 - expo0); if (ftmp0.cmp(ftmp1) <= 0) m.update_R(kappa, kappa); else reduce = false; } } while (reduce); if (max_index == -1) m.update_R_last(kappa); else m.update_R(kappa); } // Works only there is no row_expo. template <class ZT, class FT> bool is_hlll_reduced(MatHouseholder<ZT, FT> &m, double delta, double eta) { FT ftmp0; FT ftmp1; FT delta_ = delta; m.update_R(); long expo; for (int i = 0; i < m.get_d(); i++) { for (int j = 0; j < i; j++) { m.get_R(ftmp0, i, j, expo); m.get_R(ftmp1, j, j, expo); ftmp1.div(ftmp0, ftmp1); ftmp1.abs(ftmp1); if (ftmp1.cmp(0.5) > 0) return false; } } for (int i = 1; i < m.get_d(); i++) { m.norm_square_b_row(ftmp0, i, expo); // ftmp0 = ||b[i]||^2 m.norm_square_R_row(ftmp1, i, i - 1, expo); ftmp1.sub(ftmp0, ftmp1); // ftmp1 = ||b[i]||^2 - sum_{i = 0}^{i < i - 1}R[i][i]^2 m.get_R(ftmp0, i - 1, i - 1, expo); ftmp0.mul(ftmp0, ftmp0); ftmp0.mul(delta_, ftmp0); // ftmp0 = delta_ * R(i - 1, i - 1)^2 if (ftmp0.cmp(ftmp1) > 0) return false; } return true; } /** instantiate functions **/ template class HLLLReduction<Z_NR<long>, FP_NR<double>>; template class HLLLReduction<Z_NR<double>, FP_NR<double>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<double>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<double>>(MatHouseholder<Z_NR<long>, FP_NR<double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<double>>(MatHouseholder<Z_NR<double>, FP_NR<double>> &m, double delta, double eta); #ifdef FPLLL_WITH_LONG_DOUBLE template class HLLLReduction<Z_NR<long>, FP_NR<long double>>; template class HLLLReduction<Z_NR<double>, FP_NR<long double>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<long double>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<long double>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<long double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<long double>>(MatHouseholder<Z_NR<long>, FP_NR<long double>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<long double>>( MatHouseholder<Z_NR<double>, FP_NR<long double>> &m, double delta, double eta); #endif #ifdef FPLLL_WITH_QD template class HLLLReduction<Z_NR<long>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<double>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dd_real>>; template class HLLLReduction<Z_NR<long>, FP_NR<qd_real>>; template class HLLLReduction<Z_NR<double>, FP_NR<qd_real>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<qd_real>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<qd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<qd_real>>(MatHouseholder<Z_NR<long>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<qd_real>>(MatHouseholder<Z_NR<double>, FP_NR<qd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dd_real>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<dd_real>>(MatHouseholder<Z_NR<long>, FP_NR<dd_real>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<dd_real>>(MatHouseholder<Z_NR<double>, FP_NR<dd_real>> &m, double delta, double eta); #endif #ifdef FPLLL_WITH_DPE template class HLLLReduction<Z_NR<long>, FP_NR<dpe_t>>; template class HLLLReduction<Z_NR<double>, FP_NR<dpe_t>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<dpe_t>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<dpe_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<long>, FP_NR<dpe_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<dpe_t>>(MatHouseholder<Z_NR<double>, FP_NR<dpe_t>> &m, double delta, double eta); #endif template class HLLLReduction<Z_NR<long>, FP_NR<mpfr_t>>; template class HLLLReduction<Z_NR<double>, FP_NR<mpfr_t>>; template class HLLLReduction<Z_NR<mpz_t>, FP_NR<mpfr_t>>; template bool is_hlll_reduced<Z_NR<mpz_t>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<mpz_t>, FP_NR<mpfr_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<long>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<long>, FP_NR<mpfr_t>> &m, double delta, double eta); template bool is_hlll_reduced<Z_NR<double>, FP_NR<mpfr_t>>(MatHouseholder<Z_NR<double>, FP_NR<mpfr_t>> &m, double delta, double eta); FPLLL_END_NAMESPACE <|endoftext|>
<commit_before>//========================================================= // //A C++ program to implement the mRMR selection using mutual information // written by Hanchuan Peng. // //Disclaimer: The author of program is Hanchuan Peng // at <penghanchuan@yahoo.com>. // //The CopyRight is reserved by the author.#include <math.h> #include <omp.h> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <string> #include <unistd.h> #include <vector> #include "pbetai.cpp" #include "sort2.cpp" /* use S__LINE__ instead of __LINE__ */ #define S(x) #x #define S_(x) S(x) #define S__LINE__ S_(__LINE__) using namespace std; double calMutualInfo (std::vector< std::vector<int> > data, unsigned long v1, unsigned long v2); double compute_mutualinfo (double *pab, long pabhei, long pabwid); template < class T > void copyvecdata (T * srcdata, long len, int *desdata, int &nstate); template < class T > double *compute_jointprob (T * img1, T * img2, long len, long maxstatenum, int &nstate1, int &nstate2); enum Method { MID, MIQ }; void printPaperInfo() { printf ("\n\n *** This program and the respective minimum Redundancy Maximum Relevance (mRMR) \n"); printf( " algorithm were developed by Hanchuan Peng <hanchuan.peng@gmail.com>for\n"); printf( " the paper \n"); printf( " \"Feature selection based on mutual information: criteria of \n"); printf( " max-dependency, max-relevance, and min-redundancy,\"\n"); printf( " Hanchuan Peng, Fuhui Long, and Chris Ding, \n"); printf( " IEEE Transactions on Pattern Analysis and Machine Intelligence,\n"); printf( " Vol. 27, No. 8, pp.1226-1238, 2005.\n\n"); return; } template < class T > void copyvecdata (T * srcdata, long len, int *desdata, int &nstate) { if (!srcdata || !desdata) throw std::runtime_error("Line " S__LINE__ ": NULL points in copyvecdata()!"); //copy data int minn, maxx; if (srcdata[0] > 0) { maxx = minn = int (srcdata[0] + 0.5); } else { maxx = minn = int (srcdata[0] - 0.5); } int tmp; double tmp1; for (long i = 0; i < len; i++) { tmp1 = double (srcdata[i]); //round to integers tmp = (tmp1 > 0) ? (int) (tmp1 + 0.5) : (int) (tmp1 - 0.5); minn = (minn < tmp) ? minn : tmp; maxx = (maxx > tmp) ? maxx : tmp; desdata[i] = tmp; } //make the vector data begin from 0 (i.e. 1st state) for (long i = 0; i < len; i++) { desdata[i] -= minn; } //return the #state nstate = (maxx - minn + 1); return; } template < class T > double * compute_jointprob (T * img1, T * img2, long len, long maxstatenum, int &nstate1, int &nstate2) { //get and check size information long i, j; if (!img1 || !img2 || len < 0) throw std::runtime_error("Line " S__LINE__ " At least one of the input vectors is invalid."); int b_returnprob = 1; //copy data into new INT type array (hence quantization) and then reange them begin from 0 (i.e. state1) int *vec1 = new int[len]; int *vec2 = new int[len]; if (!vec1 || !vec2) throw std::runtime_error("Line " S__LINE__ " At least one of the input vectors is invalid."); int nrealstate1 = 0, nrealstate2 = 0; copyvecdata (img1, len, vec1, nrealstate1); copyvecdata (img2, len, vec2, nrealstate2); //update the #state when necessary nstate1 = (nstate1 < nrealstate1) ? nrealstate1 : nstate1; nstate2 = (nstate2 < nrealstate2) ? nrealstate2 : nstate2; //generate the joint-distribution table double *hab = new double[nstate1 * nstate2]; double **hab2d = new double *[nstate2]; if (!hab || !hab2d) throw std::runtime_error("Line " S__LINE__ " Fail to allocate memory."); for (j = 0; j < nstate2; j++) hab2d[j] = hab + (long) j *nstate1; for (i = 0; i < nstate1; i++) for (j = 0; j < nstate2; j++) { hab2d[j][i] = 0; } for (i = 0; i < len; i++) { hab2d[vec2[i]][vec1[i]] += 1; } //return the probabilities, otherwise return count numbers if (b_returnprob) { for (i = 0; i < nstate1; i++) for (j = 0; j < nstate2; j++) { hab2d[j][i] /= len; } } //finish if (hab2d) { delete[]hab2d; hab2d = 0; } if (vec1) { delete[]vec1; vec1 = 0; } if (vec2) { delete[]vec2; vec2 = 0; } return hab; } double compute_mutualinfo (double *pab, long pabhei, long pabwid) { //check if parameters are correct if (!pab) throw std::runtime_error("Line " S__LINE__ " Got illegal parameter in compute_mutualinfo()."); long i, j; double **pab2d = new double *[pabwid]; for (j = 0; j < pabwid; j++) pab2d[j] = pab + (long) j *pabhei; double *p1 = 0, *p2 = 0; long p1len = 0, p2len = 0; int b_findmarginalprob = 1; //generate marginal probability arrays if (b_findmarginalprob != 0) { p1len = pabhei; p2len = pabwid; p1 = new double[p1len]; p2 = new double[p2len]; for (i = 0; i < p1len; i++) p1[i] = 0; for (j = 0; j < p2len; j++) p2[j] = 0; for (i = 0; i < p1len; i++) for (j = 0; j < p2len; j++) { p1[i] += pab2d[j][i]; p2[j] += pab2d[j][i]; } } //calculate the mutual information double muInf = 0; muInf = 0.0; for (j = 0; j < pabwid; j++) { for (i = 0; i < pabhei; i++) { if (pab2d[j][i] != 0 && p1[i] != 0 && p2[j] != 0) { muInf += pab2d[j][i] * log (pab2d[j][i] / p1[i] / p2[j]); } } } muInf /= log (2); //free memory if (pab2d) { delete[]pab2d; } if (b_findmarginalprob != 0) { if (p1) { delete[]p1; } if (p2) { delete[]p2; } } return muInf; } double calMutualInfo (std::vector< std::vector<int> > data, unsigned long v1, unsigned long v2) { double mi = -1; //initialized as an illegal value if (v1 >= data[0].size() || v2 >= data[0].size()) throw std::runtime_error("Line " S__LINE__ "Input variable indexes are invalid (out of range)"); //copy data int *v1data = new int[data.size()]; int *v2data = new int[data.size()]; if (!v1data || !v2data) throw std::runtime_error("Line " S__LINE__ "Fail to allocate memory"); #pragma omp parallel num_threads(4) #pragma omp parallel for for (unsigned long i = 0; i < data.size(); i++) { v1data[i] = data[i][v1]; v2data[i] = data[i][v2]; } //compute mutual info //always true for DataTable, which was discretized as three states long nstate = 3; int nstate1 = 0, nstate2 = 0; double *pab = compute_jointprob (v1data, v2data, data.size(), nstate, nstate1, nstate2); mi = compute_mutualinfo (pab, nstate1, nstate2); //free memory and return if (v1data) { delete[]v1data; v1data = 0; } if (v2data) { delete[]v2data; v2data = 0; } if (pab) { delete[]pab; pab = 0; } return mi; } std::vector<unsigned long> _select (std::vector< std::vector<int> > _data, std::vector<string> _names, unsigned long _nfeats, Method _method) { std::vector<unsigned long> _feats_ixs(_nfeats); unsigned long poolUseFeaLen = 5000; // there is a target variable (the first one), that is why must remove one if (poolUseFeaLen > _data[0].size() - 1) poolUseFeaLen = _data[0].size() - 1; if (_nfeats > poolUseFeaLen) _nfeats = poolUseFeaLen; //determine the pool float *mival = new float[_data[0].size()]; float *poolInd = new float[_data[0].size()]; char *poolIndMask = new char[_data[0].size()]; if (!mival || !poolInd || !poolIndMask) throw std::runtime_error("Line " S__LINE__ "Fail to allocate memory"); //the mival[0] is the entropy of target classification variable for (unsigned long i = 0; i < _data[0].size(); i++) { mival[i] = -calMutualInfo (_data, 0, i);//set as negative for sorting purpose poolInd[i] = i; poolIndMask[i] = 1;//initialized to be everything in pool would be considered } float *NR_mival = mival; //vector_phc(1,_data->_nvars-1); float *NR_poolInd = poolInd; //vector_phc(1,_data->_nvars-1); sort2 (_data[0].size() - 1, NR_mival, NR_poolInd); // note that poolIndMask is not needed to be sorted, as everything in it is 1 up to this point mival[0] = -mival[0]; printf ("\n*** MaxRel features ***\n"); printf ("Order \t Fea \t Name \t Score\n"); for (unsigned long i = 1; i < _data[0].size() - 1; i++) { mival[i] = -mival[i]; if (i <= _nfeats) printf ("%ld \t %d \t %s \t %5.3f\n", i, int (poolInd[i]), _names[int (poolInd[i])].c_str(), mival[i]); } //mRMR selection unsigned long poolFeaIndMin = 1; unsigned long poolFeaIndMax = poolFeaIndMin + poolUseFeaLen - 1; _feats_ixs[0] = long (poolInd[1]); poolIndMask[_feats_ixs[0]] = 0; //after selection, no longer consider this feature poolIndMask[0] = 0; // of course the first one, which corresponds to the classification variable, should not be considered. Just set the mask as 0 for safety. printf ("\n*** mRMR features *** \n"); printf ("Order \t Fea \t Name \t Score\n"); printf ("%d \t %ld \t %s \t %5.3f\n", 1, _feats_ixs[0], _names[_feats_ixs[0]].c_str(), mival[1]); //the first one, _feats_ixs[0] has been determined already for (unsigned long k = 1; k < _nfeats; k++) { double relevanceVal, redundancyVal, tmpscore, selectscore; long selectind; int b_firstSelected = 0; for (unsigned long i = poolFeaIndMin; i <= poolFeaIndMax; i++) { if (poolIndMask[long (poolInd[i])] == 0) continue; //skip this feature as it was selected already relevanceVal = calMutualInfo (_data, 0, long (poolInd[i])); //actually no necessary to re-compute it, this value can be retrieved from mival vector redundancyVal = 0; for (unsigned long j = 0; j < k; j++) redundancyVal += calMutualInfo (_data, _feats_ixs[j], long (poolInd[i])); redundancyVal /= k; switch (_method) { case MID: tmpscore = relevanceVal - redundancyVal; break; case MIQ: tmpscore = relevanceVal / (redundancyVal + 0.0001); break; default: fprintf (stderr, "Undefined selection method=%d. Use MID instead.\n", _method); tmpscore = relevanceVal - redundancyVal; } if (b_firstSelected == 0) { selectscore = tmpscore; selectind = long (poolInd[i]); b_firstSelected = 1; } else { if (tmpscore > selectscore) {//update the best feature found and the score selectscore = tmpscore; selectind = long (poolInd[i]); } } } _feats_ixs[k] = selectind; poolIndMask[selectind] = 0; printf ("%ld \t %ld \t %s \t %5.3f\n", k + 1, _feats_ixs[k], _names[_feats_ixs[k]].c_str(), selectscore); } if (mival) { delete[]mival; mival = 0; } if (poolInd) { delete[]poolInd; poolInd = 0; } if (poolIndMask) { delete[]poolIndMask; poolIndMask = 0; } return _feats_ixs; } std::vector<unsigned long> _mRMR (std::vector< std::vector<int> > _data, std::vector<string> _names, int _method, unsigned long _nfeats) { if (_data.empty()) throw std::runtime_error("Line " S__LINE__ ": _data matrix is empty"); if (_names.empty()) throw std::runtime_error("Line " S__LINE__ ": _names array is empty"); printPaperInfo(); return _select (_data, _names, _nfeats, Method (_method)); } <commit_msg>Fix for Windows<commit_after>//========================================================= // //A C++ program to implement the mRMR selection using mutual information // written by Hanchuan Peng. // //Disclaimer: The author of program is Hanchuan Peng // at <penghanchuan@yahoo.com>. // //The CopyRight is reserved by the author.#include <math.h> #include <omp.h> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <string> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #include <vector> #include "pbetai.cpp" #include "sort2.cpp" /* use S__LINE__ instead of __LINE__ */ #define S(x) #x #define S_(x) S(x) #define S__LINE__ S_(__LINE__) using namespace std; double calMutualInfo (std::vector< std::vector<int> > data, unsigned long v1, unsigned long v2); double compute_mutualinfo (double *pab, long pabhei, long pabwid); template < class T > void copyvecdata (T * srcdata, long len, int *desdata, int &nstate); template < class T > double *compute_jointprob (T * img1, T * img2, long len, long maxstatenum, int &nstate1, int &nstate2); enum Method { MID, MIQ }; void printPaperInfo() { printf ("\n\n *** This program and the respective minimum Redundancy Maximum Relevance (mRMR) \n"); printf( " algorithm were developed by Hanchuan Peng <hanchuan.peng@gmail.com>for\n"); printf( " the paper \n"); printf( " \"Feature selection based on mutual information: criteria of \n"); printf( " max-dependency, max-relevance, and min-redundancy,\"\n"); printf( " Hanchuan Peng, Fuhui Long, and Chris Ding, \n"); printf( " IEEE Transactions on Pattern Analysis and Machine Intelligence,\n"); printf( " Vol. 27, No. 8, pp.1226-1238, 2005.\n\n"); return; } template < class T > void copyvecdata (T * srcdata, long len, int *desdata, int &nstate) { if (!srcdata || !desdata) throw std::runtime_error("Line " S__LINE__ ": NULL points in copyvecdata()!"); //copy data int minn, maxx; if (srcdata[0] > 0) { maxx = minn = int (srcdata[0] + 0.5); } else { maxx = minn = int (srcdata[0] - 0.5); } int tmp; double tmp1; for (long i = 0; i < len; i++) { tmp1 = double (srcdata[i]); //round to integers tmp = (tmp1 > 0) ? (int) (tmp1 + 0.5) : (int) (tmp1 - 0.5); minn = (minn < tmp) ? minn : tmp; maxx = (maxx > tmp) ? maxx : tmp; desdata[i] = tmp; } //make the vector data begin from 0 (i.e. 1st state) for (long i = 0; i < len; i++) { desdata[i] -= minn; } //return the #state nstate = (maxx - minn + 1); return; } template < class T > double * compute_jointprob (T * img1, T * img2, long len, long maxstatenum, int &nstate1, int &nstate2) { //get and check size information long i, j; if (!img1 || !img2 || len < 0) throw std::runtime_error("Line " S__LINE__ " At least one of the input vectors is invalid."); int b_returnprob = 1; //copy data into new INT type array (hence quantization) and then reange them begin from 0 (i.e. state1) int *vec1 = new int[len]; int *vec2 = new int[len]; if (!vec1 || !vec2) throw std::runtime_error("Line " S__LINE__ " At least one of the input vectors is invalid."); int nrealstate1 = 0, nrealstate2 = 0; copyvecdata (img1, len, vec1, nrealstate1); copyvecdata (img2, len, vec2, nrealstate2); //update the #state when necessary nstate1 = (nstate1 < nrealstate1) ? nrealstate1 : nstate1; nstate2 = (nstate2 < nrealstate2) ? nrealstate2 : nstate2; //generate the joint-distribution table double *hab = new double[nstate1 * nstate2]; double **hab2d = new double *[nstate2]; if (!hab || !hab2d) throw std::runtime_error("Line " S__LINE__ " Fail to allocate memory."); for (j = 0; j < nstate2; j++) hab2d[j] = hab + (long) j *nstate1; for (i = 0; i < nstate1; i++) for (j = 0; j < nstate2; j++) { hab2d[j][i] = 0; } for (i = 0; i < len; i++) { hab2d[vec2[i]][vec1[i]] += 1; } //return the probabilities, otherwise return count numbers if (b_returnprob) { for (i = 0; i < nstate1; i++) for (j = 0; j < nstate2; j++) { hab2d[j][i] /= len; } } //finish if (hab2d) { delete[]hab2d; hab2d = 0; } if (vec1) { delete[]vec1; vec1 = 0; } if (vec2) { delete[]vec2; vec2 = 0; } return hab; } double compute_mutualinfo (double *pab, long pabhei, long pabwid) { //check if parameters are correct if (!pab) throw std::runtime_error("Line " S__LINE__ " Got illegal parameter in compute_mutualinfo()."); long i, j; double **pab2d = new double *[pabwid]; for (j = 0; j < pabwid; j++) pab2d[j] = pab + (long) j *pabhei; double *p1 = 0, *p2 = 0; long p1len = 0, p2len = 0; int b_findmarginalprob = 1; //generate marginal probability arrays if (b_findmarginalprob != 0) { p1len = pabhei; p2len = pabwid; p1 = new double[p1len]; p2 = new double[p2len]; for (i = 0; i < p1len; i++) p1[i] = 0; for (j = 0; j < p2len; j++) p2[j] = 0; for (i = 0; i < p1len; i++) for (j = 0; j < p2len; j++) { p1[i] += pab2d[j][i]; p2[j] += pab2d[j][i]; } } //calculate the mutual information double muInf = 0; muInf = 0.0; for (j = 0; j < pabwid; j++) { for (i = 0; i < pabhei; i++) { if (pab2d[j][i] != 0 && p1[i] != 0 && p2[j] != 0) { muInf += pab2d[j][i] * log (pab2d[j][i] / p1[i] / p2[j]); } } } muInf /= log (2); //free memory if (pab2d) { delete[]pab2d; } if (b_findmarginalprob != 0) { if (p1) { delete[]p1; } if (p2) { delete[]p2; } } return muInf; } double calMutualInfo (std::vector< std::vector<int> > data, unsigned long v1, unsigned long v2) { double mi = -1; //initialized as an illegal value if (v1 >= data[0].size() || v2 >= data[0].size()) throw std::runtime_error("Line " S__LINE__ "Input variable indexes are invalid (out of range)"); //copy data int *v1data = new int[data.size()]; int *v2data = new int[data.size()]; if (!v1data || !v2data) throw std::runtime_error("Line " S__LINE__ "Fail to allocate memory"); #pragma omp parallel num_threads(4) #pragma omp parallel for for (unsigned long i = 0; i < data.size(); i++) { v1data[i] = data[i][v1]; v2data[i] = data[i][v2]; } //compute mutual info //always true for DataTable, which was discretized as three states long nstate = 3; int nstate1 = 0, nstate2 = 0; double *pab = compute_jointprob (v1data, v2data, data.size(), nstate, nstate1, nstate2); mi = compute_mutualinfo (pab, nstate1, nstate2); //free memory and return if (v1data) { delete[]v1data; v1data = 0; } if (v2data) { delete[]v2data; v2data = 0; } if (pab) { delete[]pab; pab = 0; } return mi; } std::vector<unsigned long> _select (std::vector< std::vector<int> > _data, std::vector<string> _names, unsigned long _nfeats, Method _method) { std::vector<unsigned long> _feats_ixs(_nfeats); unsigned long poolUseFeaLen = 5000; // there is a target variable (the first one), that is why must remove one if (poolUseFeaLen > _data[0].size() - 1) poolUseFeaLen = _data[0].size() - 1; if (_nfeats > poolUseFeaLen) _nfeats = poolUseFeaLen; //determine the pool float *mival = new float[_data[0].size()]; float *poolInd = new float[_data[0].size()]; char *poolIndMask = new char[_data[0].size()]; if (!mival || !poolInd || !poolIndMask) throw std::runtime_error("Line " S__LINE__ "Fail to allocate memory"); //the mival[0] is the entropy of target classification variable for (unsigned long i = 0; i < _data[0].size(); i++) { mival[i] = -calMutualInfo (_data, 0, i);//set as negative for sorting purpose poolInd[i] = i; poolIndMask[i] = 1;//initialized to be everything in pool would be considered } float *NR_mival = mival; //vector_phc(1,_data->_nvars-1); float *NR_poolInd = poolInd; //vector_phc(1,_data->_nvars-1); sort2 (_data[0].size() - 1, NR_mival, NR_poolInd); // note that poolIndMask is not needed to be sorted, as everything in it is 1 up to this point mival[0] = -mival[0]; printf ("\n*** MaxRel features ***\n"); printf ("Order \t Fea \t Name \t Score\n"); for (unsigned long i = 1; i < _data[0].size() - 1; i++) { mival[i] = -mival[i]; if (i <= _nfeats) printf ("%ld \t %d \t %s \t %5.3f\n", i, int (poolInd[i]), _names[int (poolInd[i])].c_str(), mival[i]); } //mRMR selection unsigned long poolFeaIndMin = 1; unsigned long poolFeaIndMax = poolFeaIndMin + poolUseFeaLen - 1; _feats_ixs[0] = long (poolInd[1]); poolIndMask[_feats_ixs[0]] = 0; //after selection, no longer consider this feature poolIndMask[0] = 0; // of course the first one, which corresponds to the classification variable, should not be considered. Just set the mask as 0 for safety. printf ("\n*** mRMR features *** \n"); printf ("Order \t Fea \t Name \t Score\n"); printf ("%d \t %ld \t %s \t %5.3f\n", 1, _feats_ixs[0], _names[_feats_ixs[0]].c_str(), mival[1]); //the first one, _feats_ixs[0] has been determined already for (unsigned long k = 1; k < _nfeats; k++) { double relevanceVal, redundancyVal, tmpscore, selectscore; long selectind; int b_firstSelected = 0; for (unsigned long i = poolFeaIndMin; i <= poolFeaIndMax; i++) { if (poolIndMask[long (poolInd[i])] == 0) continue; //skip this feature as it was selected already relevanceVal = calMutualInfo (_data, 0, long (poolInd[i])); //actually no necessary to re-compute it, this value can be retrieved from mival vector redundancyVal = 0; for (unsigned long j = 0; j < k; j++) redundancyVal += calMutualInfo (_data, _feats_ixs[j], long (poolInd[i])); redundancyVal /= k; switch (_method) { case MID: tmpscore = relevanceVal - redundancyVal; break; case MIQ: tmpscore = relevanceVal / (redundancyVal + 0.0001); break; default: fprintf (stderr, "Undefined selection method=%d. Use MID instead.\n", _method); tmpscore = relevanceVal - redundancyVal; } if (b_firstSelected == 0) { selectscore = tmpscore; selectind = long (poolInd[i]); b_firstSelected = 1; } else { if (tmpscore > selectscore) {//update the best feature found and the score selectscore = tmpscore; selectind = long (poolInd[i]); } } } _feats_ixs[k] = selectind; poolIndMask[selectind] = 0; printf ("%ld \t %ld \t %s \t %5.3f\n", k + 1, _feats_ixs[k], _names[_feats_ixs[k]].c_str(), selectscore); } if (mival) { delete[]mival; mival = 0; } if (poolInd) { delete[]poolInd; poolInd = 0; } if (poolIndMask) { delete[]poolIndMask; poolIndMask = 0; } return _feats_ixs; } std::vector<unsigned long> _mRMR (std::vector< std::vector<int> > _data, std::vector<string> _names, int _method, unsigned long _nfeats) { if (_data.empty()) throw std::runtime_error("Line " S__LINE__ ": _data matrix is empty"); if (_names.empty()) throw std::runtime_error("Line " S__LINE__ ": _names array is empty"); printPaperInfo(); return _select (_data, _names, _nfeats, Method (_method)); } <|endoftext|>
<commit_before>long fib(long n) { if (n < 2) { return n; } else { return fib(n - 1) + fib(n - 2); }; }; <commit_msg>remove .cc file in root directory<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <math.h> #include <string> #include <sstream> template <class T> T from_str(const std::string & str){ std::istringstream sin(str); T ret; sin >> ret; return ret; } void print(double a){ printf("%.20f, %llX\n", a, *((unsigned long long *) &a)); } int main(int argc, char **argv){ double i = from_str<double>(argv[1]); print(sqrt(-1)); print(1.0/i); print(-1.0/i); print(0.0/i); print(-0.0/i); print((1.0/i)/(-1.0/i)); print((1.0/i) + 3.0); print((-1.0/i) + 3.0); print(3.0/(1.0/i)); return 0; } <commit_msg>Remove testnan, it's annoying and can be recovered from git if needed<commit_after><|endoftext|>
<commit_before>// This file (SampleCode.cpp) was converted from SampleCode.Bas // with uCalc Transform 2.5 on 1/15/2014 4:37:12 PM using the Open Source // PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp #include <string> using namespace std; // File name: SampleCode.Bas // To convert this file to C++ make sure you have uCalc Transform on your PC // and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert // Do the following at the Command Prompt: // // C:\> PBtoCPP.Bat SampleCode.Bas const int MyEquate = 0x100; const int Other = 0x200; int ProgStatus; #if defined Other // Something #elif !defined abcd // Something else #else // Etc #endif #define MyMacroNum 12345 #define MyMacro(a, b, c) (a + b * (c)) struct point { int x; int y; }; struct MyBits { unsigned int Year : 7; unsigned int Month : 5; unsigned int DayOfMonth : 4; unsigned int DayOfWeek : 3; unsigned char Red : 1; unsigned char Blue : 1; unsigned char Green : 1; double Other; }; int MyFunc(int x) { return x * 2; } int MyFunction(int a, float& b) { int x; int y; int *Test = new int [a+25+1]; int yVar; int MyValue; // Dim q As Long // The commented line above is not translated MyFunc(a); x = MyFunc(b)+1; if (b > 5) { for (x=1; x<=10; x += 1) { for (yVar=10; yVar>=1; yVar += -1) { if (x > y) { return a+y; } while (Test[a+5] == yVar) { while (!(a+1 == 1234)) { if (y < MyEquate) { return Test[x-y]*10; } a = a + 1; do { b = a * 5 + b; } while (!(b == 300)); } } } } } delete[] Test; } void MySub(int x) { int y; float *Test; float *Number = new float [10+1]; int *Other = new int [x+1]; int z; ProgStatus = 10; y = x + 1; z = y+x; Other[x] = x+1; while (x < 10) { y = MyFunction(x, *Test); Test = &x; Number[z] = *Test + Other[5+x]; x = x+1; } delete[] Other; delete[] Number; } // ' This line is broken up using a _ (underscore) // This is a commment (even without ') // Everything after _ is a comment void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg) { // Note: comments after _ are regrouped into a different place int *MyArray = new int [10+1]; Point MyPoint; Point *pp; int n; for (x=1; x<=10; x += 1) { n = y == z // This works differently in PB than in C++ MyArray[x] = x*2; if (x == 5) { y = x+5; } else { y = 23*2; } y = x == z; MyArray[5] = MyArray[n] == MyArray[n+1]; if (x == y == z) { y = n == 2; } else { y = n == 3; } if (x == y && x != 10 || y == x && x < 25) { y = x || y == z; } if ((x == y & x != 10 | y == x & x < 25)) { y = x || y == z; } if ((x == y & x != 10) || y == x && x < 25) { y = x || y == z; } if (~(x == y | x == z)) { x = y + 10; } if (~(x == y | x == z)) { x = y + 10; } if (x != y) { MyPoint.x = y; } else { MyPoint.x = x; } pp = &p; MyPoint.x = MyPoint.y+1; n = MyPoint.x == MyPoint.y; *pp.x = *pp.y == *pp.x+1; } delete[] MyArray; } // The section below is a test for variables declared implicitely with data type // based on Def[Type] declarations or on type specifiers. float MyValue; string Label; Currency Price; double ExtVal; __int64 qNum; int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n) { Print MyValue, Label, PriceB; Label = "Missing quote at the end of this line is added by Refactor.uc"; } string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue) { string FirstName; unsigned char Age; double Total; static int Index; Print LastName, x, NewPrice, n, i, nValue, qValue; Report = FirstName + LastName; } string Hello(string& txt) { Print txt; return txt + " friend!"; } unsigned char Bye() { Print "Bye"; } // This section is a test for Subs or Functions that are called as a statement // without parentheses. The converter adds them. // #Include "Win32API.inc" extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd); extern __declspec(dllimport) int SetCursorPos(int x, int y); extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode); void DoSomething(int Arg1, string& txt, double& Number, Optional unsigned int *xyz) { SetCursorPos(10, Arg1 + 5); if (Arg1 == 15) { SetLastError(123); } } float main() { double x; double pi; DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) // Comment DoSomething(10, "abc", 5, 1); DoSomething(1, "x", 5, 0) // Etc... if (x > 1) { DoSomething(1, "x", 5, 0) // Parenthesis already here } MyFunc(5); ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal); } int; // This section tests transforms found in strings.uc string StringTest(string& MyString, string OtherString) { string MyText; int i; wstring MyWideStr; string Txt; string x; string y; wstring z; i = (MyString.find("abc", (1)-1)+1); i = (MyString.find("xyz", (i+10)-1)+1)*2; i = (MyString.find_first_of("aeiou", (1)-1)+1); // i = InStr(i+10, "This is a test") // i = InStr("This is a test", ANY "aeiou") MyText = MyString.substr(0, 3) + OtherString.substr((5)-1, 10) + x.substr(x.length()-(i+1), i+1); if (MyText.substr((3)-1, 5) == y) { MyText.replace((20)-1, MyText.length(), "Test" + to_string(i*15)); } x.replace((25)-1, stold(y) +1, y); MyString.replace((25)-1, 5, y.substr((stold(x))-1, 7)); } // This tests exported subs/functions extern "C" __declspec(dllexport) int __stdcall MyExport(int n) { StringTest("abc", "xyz"); } extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) { DoSomething(1, "xyz", 2, 3); } <commit_msg>Update SampleCode.cpp<commit_after>#include <math.h> // This file (SampleCode.cpp) was converted from SampleCode.Bas // with uCalc Transform 2.5 on 1/16/2014 12:40:12 PM using the Open Source // PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp #include <string> using namespace std; // File name: SampleCode.Bas // To convert this file to C++ make sure you have uCalc Transform on your PC // and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert // Do the following at the Command Prompt: // // C:\> PBtoCPP.Bat SampleCode.Bas const int MyEquate = 0x100; const int Other = 0x200; int ProgStatus; #if defined Other // Something #elif !defined abcd // Something else #else // Etc #endif #define MyMacroNum 12345 #define MyMacro(a, b, c) (a + b * (c)) struct point { int x; int y; }; struct MyBits { unsigned int Year : 7; unsigned int Month : 5; unsigned int DayOfMonth : 4; unsigned int DayOfWeek : 3; unsigned char Red : 1; unsigned char Blue : 1; unsigned char Green : 1; double Other; }; int MyFunc(int x) { return x * 2; } int MyFunction(int a, float& b) { int x; int y; int *Test = new int [a+25+1]; int yVar; int MyValue; // Dim q As Long // The commented line above is not translated MyFunc(a); x = MyFunc(b)+1; if (b > 5) { for (x=1; x<=10; x += 1) { for (yVar=10; yVar>=1; yVar += -1) { if (x > y) { return a+y; } while (Test[a+5] == yVar) { while (!(a+1 == 1234)) { if (y < MyEquate) { return Test[x-y]*10; } a = a + 1; do { b = a * 5 + b; } while (!(b == 300)); } } } } } delete[] Test; } void MySub(int x) { int y; float *Test; float *Number = new float [10+1]; int *Other = new int [x+1]; int z; ProgStatus = 10; y = x + 1; z = y+x; Other[x] = x+1; while (x < 10) { y = MyFunction(x, *Test); Test = &x; Number[z] = *Test + Other[5+x]; x = x+1; } delete[] Other; delete[] Number; } // ' This line is broken up using a _ (underscore) // This is a commment (even without ') // Everything after _ is a comment void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg) { // Note: comments after _ are regrouped into a different place int *MyArray = new int [10+1]; Point MyPoint; Point *pp; int n; for (x=1; x<=10; x += 1) { n = y == z // This works differently in PB than in C++ MyArray[x] = x*2; if (x == 5) { y = x+5; } else { y = 23*2; } y = x == z; MyArray[5] = MyArray[n] == MyArray[n+1]; if (x == y == z) { y = n == 2; } else { y = n == 3; } if (x == y && x != 10 || y == x && x < 25) { y = x || y == z; } if ((x == y & x != 10 | y == x & x < 25)) { y = x || y == z; } if ((x == y & x != 10) || y == x && x < 25) { y = x || y == z; } if (~(x == y | x == z)) { x = y + 10; } if (~(x == y | x == z)) { x = y + 10; } if (x != y) { MyPoint.x = y; } else { MyPoint.x = x; } pp = &p; MyPoint.x = MyPoint.y+1; n = MyPoint.x == MyPoint.y; *pp.x = *pp.y == *pp.x+1; } delete[] MyArray; } // The section below is a test for variables declared implicitely with data type // based on Def[Type] declarations or on type specifiers. float MyValue; string Label; Currency Price; double ExtVal; __int64 qNum; int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n) { Print MyValue, Label, PriceB; Label = "Missing quote at the end of this line is added by Refactor.uc"; } string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue) { string FirstName; unsigned char Age; double Total; static int Index; Print LastName, x, NewPrice, n, i, nValue, qValue; Report = FirstName + LastName; } string Hello(string& txt) { Print txt; return txt + " friend!"; } unsigned char Bye() { Print "Bye"; } // This section is a test for Subs or Functions that are called as a statement // without parentheses. The converter adds them. // #Include "Win32API.inc" extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd); extern __declspec(dllimport) int SetCursorPos(int x, int y); extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode); void DoSomething(int Arg1, string& txt, double& Number, Optional unsigned int *xyz) { SetCursorPos(10, Arg1 + 5); if (Arg1 == 15) { SetLastError(123); } } float main() { double x; double pi; DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) // Comment DoSomething(10, "abc", 5, 1); DoSomething(1, "x", 5, 0) // Etc... if (x > 1) { DoSomething(1, "x", 5, 0) // Parenthesis already here } MyFunc(5); ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal); } int; // This section tests transforms found in strings.uc string StringTest(string& MyString, string OtherString) { string MyText; int i; wstring MyWideStr; string Txt; string x; string y; wstring z; i = (MyString.find("abc", (1)-1)+1); i = (MyString.find("xyz", (i+10)-1)+1)*2; i = (MyString.find_first_of("aeiou", (1)-1)+1); // i = InStr(i+10, "This is a test") // i = InStr("This is a test", ANY "aeiou") MyText = MyString.substr(0, 3) + OtherString.substr((5)-1, 10) + x.substr(x.length()-(i+1), i+1); if (MyText.substr((3)-1, 5) == y) { MyText.replace((20)-1, MyText.length(), "Test" + to_string(i*15)); } x.replace((25)-1, stold(y) +1, y); MyString.replace((25)-1, 5, y.substr((stold(x))-1, 7)); } // This tests exported subs/functions extern "C" __declspec(dllexport) int __stdcall MyExport(int n) { StringTest("abc", "xyz"); } extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) { DoSomething(1, "xyz", 2, 3); } // Math test // If x Mod 2 > Cint(Sqr(x^2 + y^2)) Then Incr q Else Decr q double DoMath() { if (x % 2 > lround(sqrt(x^2 + y^2))) { q++; } else { q--; } n = sqrt(x) * atan(y); y = trunc(3.14159); } <|endoftext|>
<commit_before>#include <iostream> #include "unittest.h" #include "vigra/error.hxx" struct ErrorTest { void testPrecondition() { bool caughtIt = false; try { precondition(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } void testPostcondition() { bool caughtIt = false; try { postcondition(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } void testInvariant() { bool caughtIt = false; try { invariant(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } }; struct ErrorTestSuite : public TestSuite { ErrorTestSuite() : TestSuite("") { add( testCase(&ErrorTest::testPrecondition)); add( testCase(&ErrorTest::testPostcondition)); add( testCase(&ErrorTest::testInvariant)); } }; int main() { ErrorTestSuite test; int failed = test.run(); std::cout << test.report() << std::endl; return (failed != 0); } <commit_msg>changes that reflect introduction of namespace vigra<commit_after>#include <iostream> #include "unittest.h" #include "vigra/error.hxx" struct ErrorTest { void testPrecondition() { bool caughtIt = false; try { vigra_precondition(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } void testPostcondition() { bool caughtIt = false; try { vigra_postcondition(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } void testInvariant() { bool caughtIt = false; try { vigra_invariant(0, "Intentional error"); } catch(vigra::ContractViolation & c) { caughtIt = true; std::cout << "Testing error reporting: " << c.what() << std::endl; } should(caughtIt == true); } }; struct ErrorTestSuite : public TestSuite { ErrorTestSuite() : TestSuite("") { add( testCase(&ErrorTest::testPrecondition)); add( testCase(&ErrorTest::testPostcondition)); add( testCase(&ErrorTest::testInvariant)); } }; int main() { ErrorTestSuite test; int failed = test.run(); std::cout << test.report() << std::endl; return (failed != 0); } <|endoftext|>
<commit_before>#include "../include/event_queue.hh" #include "../include/file_descriptor.hh" #include <chrono> #include <cstdint> #include <fcntl.h> #include <gtest/gtest.h> #include <memory> #include <optional> #include <thread> #include <unistd.h> using std::array; using std::chrono::milliseconds; using std::chrono::system_clock; using std::chrono_literals::operator""ms; using std::function; using std::string; TEST(EventQueue, add_time_handler) { auto start = system_clock::now(); string order; EventQueue eq; eq.add_time_handler(start + 3ms, [&] { EXPECT_LE(start + 3ms, system_clock::now()); order += "3"; eq.add_time_handler(start + 6ms, [&] { EXPECT_LE(start + 6ms, system_clock::now()); order += "6"; }); }); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "2"; eq.add_time_handler(start + 4ms, [&] { EXPECT_LE(start + 4ms, system_clock::now()); order += "4"; }); }); eq.add_time_handler(start + 5ms, [&] { EXPECT_LE(start + 5ms, system_clock::now()); order += "5"; }); eq.run(); EXPECT_EQ(order, "23456"); } TEST(EventQueue, remove_time_handler) { auto start = system_clock::now(); string order; EventQueue eq; auto hid = eq.add_time_handler(start + 3ms, [&] { FAIL(); }); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "2"; eq.remove_handler(hid); eq.add_time_handler(start + 4ms, [&] { EXPECT_LE(start + 4ms, system_clock::now()); order += "4"; }); eq.add_ready_handler([&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "r"; }); }); eq.run(); EXPECT_EQ(order, "2r4"); } TEST(EventQueue, time_only_fairness) { auto start = system_clock::now(); bool stop = false; EventQueue eq; eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); uint64_t looper_iters = 0; auto looper = [&](auto&& self) { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler([&] { self(self); }); }; eq.add_ready_handler([&] { looper(looper); }); eq.run(); EXPECT_GT(looper_iters, 10); } TEST(EventQueue, file_only_fairness) { uint64_t iters_a = 0, iters_b = 0; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent) { if (iters_b + iters_b > 500) return eq.remove_handler(file_a_hid); ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent) { if (iters_b + iters_b > 500) return eq.remove_handler(file_b_hid); ++iters_b; }); eq.run(); EXPECT_EQ(iters_a, iters_b); } TEST(EventQueue, time_file_fairness) { auto start = system_clock::now(); uint64_t looper_iters = 0; bool stop = false; EventQueue eq; function<void()> looper = [&] { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); FileDescriptor fd("/dev/zero", O_RDONLY); int file_iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent) { if (stop) return eq.remove_handler(hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(hid); } ++file_iters; }); eq.run(); EXPECT_GT(looper_iters, 10); EXPECT_GT(file_iters, 4); } TEST(EventQueue, full_fairness) { auto start = system_clock::now(); uint64_t iters_a = 0, iters_b = 0; bool stop = false; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent) { if (stop) return eq.remove_handler(file_a_hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(file_a_hid); } ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent) { if (stop) return eq.remove_handler(file_b_hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(file_b_hid); } ++iters_b; }); uint looper_iters = 0; function<void()> looper = [&] { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); eq.run(); EXPECT_GT(looper_iters, 10); EXPECT_GT(iters_a, 10); EXPECT_GT(iters_b, 10); EXPECT_NEAR(iters_a, iters_b, 1); } TEST(EventQueue, file_unready_read_and_close_event) { std::array<int, 2> pfd; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK), 0); FileDescriptor rfd(pfd[0]), wfd(pfd[1]); std::string buff(10, '\0'); EventQueue eq; auto start = system_clock::now(); eq.add_time_handler(start + 2ms, [&] { write(wfd, "Test", sizeof("Test")); }); eq.add_time_handler(start + 3ms, [&] { (void)wfd.close(); }); EXPECT_EQ(read(rfd, buff.data(), buff.size()), -1); EXPECT_EQ(errno, EAGAIN); int round = 0; std::array expected_events = {FileEvent::READABLE, FileEvent::CLOSED}; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { EXPECT_EQ(events, expected_events[round++]); if (events == FileEvent::CLOSED) return eq.remove_handler(hid); int rc = read(rfd, buff.data(), buff.size()); ASSERT_EQ(rc, sizeof("Test")); buff.resize(rc - 1); ASSERT_EQ(buff, "Test"); }); eq.run(); EXPECT_EQ(round, 2); } TEST(EventQueue, file_simultaneous_read_and_close_event) { std::array<int, 2> pfd; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK), 0); FileDescriptor rfd(pfd[0]), wfd(pfd[1]); write(wfd, "Test", sizeof("Test")); (void)wfd.close(); EventQueue eq; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { EXPECT_EQ(events, FileEvent::READABLE | FileEvent::CLOSED); eq.remove_handler(hid); }); eq.run(); } TEST(EventQueueDeathTest, time_handler_removing_itself) { auto start = system_clock::now(); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_time_handler(start + 1ms, [&] { ++iters; ASSERT_DEATH({ eq.remove_handler(hid); }, ""); }); eq.run(); EXPECT_EQ(iters, 1); } TEST(EventQueue, file_handler_removing_itself) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent) { ++iters; eq.remove_handler(hid); }); eq.run(); EXPECT_EQ(iters, 1); } TEST(EventQueue, time_handler_removing_file_handler_simple) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters; auto hid = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters; }); eq.add_time_handler(system_clock::now() + 1ms, [&] { eq.remove_handler(hid); }); eq.run(); EXPECT_GT(iters, 10); } TEST(EventQueue, time_handler_removing_file_handler_while_processing_file_handlers) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters_a = 0, iters_b = 0; EventQueue::handler_id_t hid_a, hid_b; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; eq.add_ready_handler([&] { EXPECT_EQ(iters_b, 0); eq.remove_handler(hid_b); }); std::this_thread::sleep_for(1ms); eq.remove_handler(hid_a); }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; eq.remove_handler(hid_b); // In case of error }); eq.run(); EXPECT_EQ(iters_a, 1); EXPECT_EQ(iters_b, 0); } TEST(EventQueue, file_handler_removing_other_file_handler) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue::handler_id_t hid_a, hid_b, hid_c, hid_d; int iters_a = 0, iters_b = 0, iters_c = 0, iters_d = 0; EventQueue eq; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; if (iters_a == 1) eq.remove_handler(hid_b); }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; assert(iters_b < 1000); // In case of error }); hid_c = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_c; assert(iters_c < 1000); // In case of error }); hid_d = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_d; if (iters_d == 1) eq.remove_handler(hid_c); }); eq.add_time_handler(system_clock::now() + 1ms, [&] { eq.remove_handler(hid_a); eq.remove_handler(hid_d); }); eq.run(); EXPECT_GT(iters_a, 4); EXPECT_EQ(iters_b, 0); EXPECT_EQ(iters_c, 1); EXPECT_GT(iters_d, 4); } TEST(EventQueue, test_adding_new_file_handlers_after_removing_old_ones) { FileDescriptor fd("/dev/null", O_RDONLY); std::vector<EventQueue::handler_id_t> hids; std::vector<int> iters; EventQueue eq; for (int i = 0; i < 100; ++i) { constexpr auto handlers_to_add = 10; eq.add_ready_handler([&] { for (int j = 0; j < handlers_to_add; ++j) { auto hid = eq.add_file_handler(fd, FileEvent::READABLE, [&eq, &iters, &hids, idx = hids.size()] { ++iters[idx]; eq.remove_handler(hids[idx]); }); hids.emplace_back(hid); iters.emplace_back(0); } }); } eq.run(); assert(size(iters) == size(hids)); for (size_t i = 0; i < size(iters); ++i) EXPECT_EQ(iters[i], 1) << "i: " << i; } <commit_msg>test/event_queue.cc: fixed uninitialized variable<commit_after>#include "../include/event_queue.hh" #include "../include/file_descriptor.hh" #include <chrono> #include <cstdint> #include <fcntl.h> #include <gtest/gtest.h> #include <memory> #include <optional> #include <thread> #include <unistd.h> using std::array; using std::chrono::milliseconds; using std::chrono::system_clock; using std::chrono_literals::operator""ms; using std::function; using std::string; TEST(EventQueue, add_time_handler) { auto start = system_clock::now(); string order; EventQueue eq; eq.add_time_handler(start + 3ms, [&] { EXPECT_LE(start + 3ms, system_clock::now()); order += "3"; eq.add_time_handler(start + 6ms, [&] { EXPECT_LE(start + 6ms, system_clock::now()); order += "6"; }); }); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "2"; eq.add_time_handler(start + 4ms, [&] { EXPECT_LE(start + 4ms, system_clock::now()); order += "4"; }); }); eq.add_time_handler(start + 5ms, [&] { EXPECT_LE(start + 5ms, system_clock::now()); order += "5"; }); eq.run(); EXPECT_EQ(order, "23456"); } TEST(EventQueue, remove_time_handler) { auto start = system_clock::now(); string order; EventQueue eq; auto hid = eq.add_time_handler(start + 3ms, [&] { FAIL(); }); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "2"; eq.remove_handler(hid); eq.add_time_handler(start + 4ms, [&] { EXPECT_LE(start + 4ms, system_clock::now()); order += "4"; }); eq.add_ready_handler([&] { EXPECT_LE(start + 2ms, system_clock::now()); order += "r"; }); }); eq.run(); EXPECT_EQ(order, "2r4"); } TEST(EventQueue, time_only_fairness) { auto start = system_clock::now(); bool stop = false; EventQueue eq; eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); uint64_t looper_iters = 0; auto looper = [&](auto&& self) { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler([&] { self(self); }); }; eq.add_ready_handler([&] { looper(looper); }); eq.run(); EXPECT_GT(looper_iters, 10); } TEST(EventQueue, file_only_fairness) { uint64_t iters_a = 0, iters_b = 0; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent) { if (iters_b + iters_b > 500) return eq.remove_handler(file_a_hid); ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent) { if (iters_b + iters_b > 500) return eq.remove_handler(file_b_hid); ++iters_b; }); eq.run(); EXPECT_EQ(iters_a, iters_b); } TEST(EventQueue, time_file_fairness) { auto start = system_clock::now(); uint64_t looper_iters = 0; bool stop = false; EventQueue eq; function<void()> looper = [&] { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); FileDescriptor fd("/dev/zero", O_RDONLY); int file_iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent) { if (stop) return eq.remove_handler(hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(hid); } ++file_iters; }); eq.run(); EXPECT_GT(looper_iters, 10); EXPECT_GT(file_iters, 4); } TEST(EventQueue, full_fairness) { auto start = system_clock::now(); uint64_t iters_a = 0, iters_b = 0; bool stop = false; EventQueue eq; FileDescriptor fd_a("/dev/zero", O_RDONLY); EventQueue::handler_id_t file_a_hid = eq.add_file_handler(fd_a, FileEvent::READABLE, [&](FileEvent) { if (stop) return eq.remove_handler(file_a_hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(file_a_hid); } ++iters_a; }); FileDescriptor fd_b("/dev/null", O_WRONLY); EventQueue::handler_id_t file_b_hid = eq.add_file_handler(fd_b, FileEvent::WRITEABLE, [&](FileEvent) { if (stop) return eq.remove_handler(file_b_hid); if (system_clock::now() > start + 100ms) { FAIL(); return eq.remove_handler(file_b_hid); } ++iters_b; }); uint looper_iters = 0; function<void()> looper = [&] { if (stop) return; ++looper_iters; if (system_clock::now() > start + 100ms) FAIL(); eq.add_ready_handler(looper); }; eq.add_ready_handler(looper); eq.add_time_handler(start + 2ms, [&] { EXPECT_LE(start + 2ms, system_clock::now()); stop = true; }); eq.run(); EXPECT_GT(looper_iters, 10); EXPECT_GT(iters_a, 10); EXPECT_GT(iters_b, 10); EXPECT_NEAR(iters_a, iters_b, 1); } TEST(EventQueue, file_unready_read_and_close_event) { std::array<int, 2> pfd; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK), 0); FileDescriptor rfd(pfd[0]), wfd(pfd[1]); std::string buff(10, '\0'); EventQueue eq; auto start = system_clock::now(); eq.add_time_handler(start + 2ms, [&] { write(wfd, "Test", sizeof("Test")); }); eq.add_time_handler(start + 3ms, [&] { (void)wfd.close(); }); EXPECT_EQ(read(rfd, buff.data(), buff.size()), -1); EXPECT_EQ(errno, EAGAIN); int round = 0; std::array expected_events = {FileEvent::READABLE, FileEvent::CLOSED}; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { EXPECT_EQ(events, expected_events[round++]); if (events == FileEvent::CLOSED) return eq.remove_handler(hid); int rc = read(rfd, buff.data(), buff.size()); ASSERT_EQ(rc, sizeof("Test")); buff.resize(rc - 1); ASSERT_EQ(buff, "Test"); }); eq.run(); EXPECT_EQ(round, 2); } TEST(EventQueue, file_simultaneous_read_and_close_event) { std::array<int, 2> pfd; ASSERT_EQ(pipe2(pfd.data(), O_NONBLOCK), 0); FileDescriptor rfd(pfd[0]), wfd(pfd[1]); write(wfd, "Test", sizeof("Test")); (void)wfd.close(); EventQueue eq; EventQueue::handler_id_t hid = eq.add_file_handler(rfd, FileEvent::READABLE, [&](FileEvent events) { EXPECT_EQ(events, FileEvent::READABLE | FileEvent::CLOSED); eq.remove_handler(hid); }); eq.run(); } TEST(EventQueueDeathTest, time_handler_removing_itself) { auto start = system_clock::now(); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_time_handler(start + 1ms, [&] { ++iters; ASSERT_DEATH({ eq.remove_handler(hid); }, ""); }); eq.run(); EXPECT_EQ(iters, 1); } TEST(EventQueue, file_handler_removing_itself) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters = 0; EventQueue::handler_id_t hid = eq.add_file_handler(fd, FileEvent::READABLE, [&](FileEvent) { ++iters; eq.remove_handler(hid); }); eq.run(); EXPECT_EQ(iters, 1); } TEST(EventQueue, time_handler_removing_file_handler_simple) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters = 0; auto hid = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters; }); eq.add_time_handler(system_clock::now() + 1ms, [&] { eq.remove_handler(hid); }); eq.run(); EXPECT_GT(iters, 10); } TEST(EventQueue, time_handler_removing_file_handler_while_processing_file_handlers) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue eq; int iters_a = 0, iters_b = 0; EventQueue::handler_id_t hid_a, hid_b; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; eq.add_ready_handler([&] { EXPECT_EQ(iters_b, 0); eq.remove_handler(hid_b); }); std::this_thread::sleep_for(1ms); eq.remove_handler(hid_a); }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; eq.remove_handler(hid_b); // In case of error }); eq.run(); EXPECT_EQ(iters_a, 1); EXPECT_EQ(iters_b, 0); } TEST(EventQueue, file_handler_removing_other_file_handler) { FileDescriptor fd("/dev/null", O_RDONLY); EventQueue::handler_id_t hid_a, hid_b, hid_c, hid_d; int iters_a = 0, iters_b = 0, iters_c = 0, iters_d = 0; EventQueue eq; hid_a = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_a; if (iters_a == 1) eq.remove_handler(hid_b); }); hid_b = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_b; assert(iters_b < 1000); // In case of error }); hid_c = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_c; assert(iters_c < 1000); // In case of error }); hid_d = eq.add_file_handler(fd, FileEvent::READABLE, [&] { ++iters_d; if (iters_d == 1) eq.remove_handler(hid_c); }); eq.add_time_handler(system_clock::now() + 1ms, [&] { eq.remove_handler(hid_a); eq.remove_handler(hid_d); }); eq.run(); EXPECT_GT(iters_a, 4); EXPECT_EQ(iters_b, 0); EXPECT_EQ(iters_c, 1); EXPECT_GT(iters_d, 4); } TEST(EventQueue, test_adding_new_file_handlers_after_removing_old_ones) { FileDescriptor fd("/dev/null", O_RDONLY); std::vector<EventQueue::handler_id_t> hids; std::vector<int> iters; EventQueue eq; for (int i = 0; i < 100; ++i) { constexpr auto handlers_to_add = 10; eq.add_ready_handler([&] { for (int j = 0; j < handlers_to_add; ++j) { auto hid = eq.add_file_handler(fd, FileEvent::READABLE, [&eq, &iters, &hids, idx = hids.size()] { ++iters[idx]; eq.remove_handler(hids[idx]); }); hids.emplace_back(hid); iters.emplace_back(0); } }); } eq.run(); assert(size(iters) == size(hids)); for (size_t i = 0; i < size(iters); ++i) EXPECT_EQ(iters[i], 1) << "i: " << i; } <|endoftext|>
<commit_before>// Copyright 2020 Global Phasing Ltd. #include "common.h" #include "gemmi/elem.hpp" #include "gemmi/resinfo.hpp" #include "gemmi/it92.hpp" #include "gemmi/c4322.hpp" #include <pybind11/stl.h> namespace py = pybind11; using namespace gemmi; static std::vector<std::string> expand_protein_one_letter_string(const std::string& s) { std::vector<std::string> r; r.reserve(s.size()); for (char c : s) r.push_back(expand_protein_one_letter(c)); return r; } void add_elem(py::module& m) { // it92.hpp using IT92 = gemmi::IT92<double>; py::class_<IT92::Coef>(m, "IT92Coef") .def_property_readonly("a", [](IT92::Coef& c) -> std::array<double,4> { return {{ c.a(0), c.a(1), c.a(2), c.a(3) }}; }) .def_property_readonly("b", [](IT92::Coef& c) -> std::array<double,4> { return {{ c.b(0), c.b(1), c.b(2), c.b(3) }}; }) .def_property_readonly("c", &IT92::Coef::c) .def("calculate_sf", &IT92::Coef::calculate_sf, py::arg("stol2")) .def("calculate_density_iso", &IT92::Coef::calculate_density_iso, py::arg("r2"), py::arg("B")) ; // c4322.hpp using C4322 = gemmi::C4322<double>; py::class_<C4322::Coef>(m, "C4322Coef") .def_property_readonly("a", [](C4322::Coef& c) -> std::array<double,5> { return {{ c.a(0), c.a(1), c.a(2), c.a(3), c.a(4) }}; }) .def_property_readonly("b", [](C4322::Coef& c) -> std::array<double,5> { return {{ c.b(0), c.b(1), c.b(2), c.b(3), c.b(4) }}; }) .def("calculate_sf", &C4322::Coef::calculate_sf, py::arg("stol2")) .def("calculate_density_iso", &C4322::Coef::calculate_density_iso, py::arg("r2"), py::arg("B")) ; // elem.hpp py::class_<Element>(m, "Element") .def(py::init<const std::string &>()) .def(py::init<int>()) .def("__eq__", [](const Element &a, const Element &b) { return a.elem == b.elem; }, py::is_operator()) #if PY_MAJOR_VERSION < 3 // in Py3 != is inferred from == .def("__ne__", [](const Element &a, const Element &b) { return a.elem != b.elem; }, py::is_operator()) #endif .def_property_readonly("name", &Element::name) .def_property_readonly("weight", &Element::weight) .def_property_readonly("covalent_r", &Element::covalent_r) .def_property_readonly("vdw_r", &Element::vdw_r) .def_property_readonly("atomic_number", &Element::atomic_number) .def_property_readonly("is_metal", &Element::is_metal) .def_property_readonly("it92", [](const Element& self) { return IT92::get_ptr(self.elem); }, py::return_value_policy::reference_internal) .def_property_readonly("c4322", [](const Element& self) { return C4322::get_ptr(self.elem); }, py::return_value_policy::reference_internal) .def("__repr__", [](const Element& self) { return "<gemmi.Element: " + std::string(self.name()) + ">"; }); // resinfo.hpp py::class_<ResidueInfo>(m, "ResidueInfo") .def_readonly("one_letter_code", &ResidueInfo::one_letter_code) .def_readonly("hydrogen_count", &ResidueInfo::hydrogen_count) .def_readonly("weight", &ResidueInfo::weight) .def("found", &ResidueInfo::found) .def("is_standard", &ResidueInfo::is_standard) .def("is_water", &ResidueInfo::is_water) .def("is_nucleic_acid", &ResidueInfo::is_nucleic_acid) .def("is_amino_acid", &ResidueInfo::is_amino_acid); m.def("find_tabulated_residue", &find_tabulated_residue, py::arg("name"), "Find chemical component information in the internal table."); m.def("expand_protein_one_letter", &expand_protein_one_letter); m.def("expand_protein_one_letter_string", &expand_protein_one_letter_string); } <commit_msg>Add python binding for Element.is_hydrogen<commit_after>// Copyright 2020 Global Phasing Ltd. #include "common.h" #include "gemmi/elem.hpp" #include "gemmi/resinfo.hpp" #include "gemmi/it92.hpp" #include "gemmi/c4322.hpp" #include <pybind11/stl.h> namespace py = pybind11; using namespace gemmi; static std::vector<std::string> expand_protein_one_letter_string(const std::string& s) { std::vector<std::string> r; r.reserve(s.size()); for (char c : s) r.push_back(expand_protein_one_letter(c)); return r; } void add_elem(py::module& m) { // it92.hpp using IT92 = gemmi::IT92<double>; py::class_<IT92::Coef>(m, "IT92Coef") .def_property_readonly("a", [](IT92::Coef& c) -> std::array<double,4> { return {{ c.a(0), c.a(1), c.a(2), c.a(3) }}; }) .def_property_readonly("b", [](IT92::Coef& c) -> std::array<double,4> { return {{ c.b(0), c.b(1), c.b(2), c.b(3) }}; }) .def_property_readonly("c", &IT92::Coef::c) .def("calculate_sf", &IT92::Coef::calculate_sf, py::arg("stol2")) .def("calculate_density_iso", &IT92::Coef::calculate_density_iso, py::arg("r2"), py::arg("B")) ; // c4322.hpp using C4322 = gemmi::C4322<double>; py::class_<C4322::Coef>(m, "C4322Coef") .def_property_readonly("a", [](C4322::Coef& c) -> std::array<double,5> { return {{ c.a(0), c.a(1), c.a(2), c.a(3), c.a(4) }}; }) .def_property_readonly("b", [](C4322::Coef& c) -> std::array<double,5> { return {{ c.b(0), c.b(1), c.b(2), c.b(3), c.b(4) }}; }) .def("calculate_sf", &C4322::Coef::calculate_sf, py::arg("stol2")) .def("calculate_density_iso", &C4322::Coef::calculate_density_iso, py::arg("r2"), py::arg("B")) ; // elem.hpp py::class_<Element>(m, "Element") .def(py::init<const std::string &>()) .def(py::init<int>()) .def("__eq__", [](const Element &a, const Element &b) { return a.elem == b.elem; }, py::is_operator()) #if PY_MAJOR_VERSION < 3 // in Py3 != is inferred from == .def("__ne__", [](const Element &a, const Element &b) { return a.elem != b.elem; }, py::is_operator()) #endif .def_property_readonly("name", &Element::name) .def_property_readonly("weight", &Element::weight) .def_property_readonly("covalent_r", &Element::covalent_r) .def_property_readonly("vdw_r", &Element::vdw_r) .def_property_readonly("atomic_number", &Element::atomic_number) .def_property_readonly("is_hydrogen", &Element::is_hydrogen) .def_property_readonly("is_metal", &Element::is_metal) .def_property_readonly("it92", [](const Element& self) { return IT92::get_ptr(self.elem); }, py::return_value_policy::reference_internal) .def_property_readonly("c4322", [](const Element& self) { return C4322::get_ptr(self.elem); }, py::return_value_policy::reference_internal) .def("__repr__", [](const Element& self) { return "<gemmi.Element: " + std::string(self.name()) + ">"; }); // resinfo.hpp py::class_<ResidueInfo>(m, "ResidueInfo") .def_readonly("one_letter_code", &ResidueInfo::one_letter_code) .def_readonly("hydrogen_count", &ResidueInfo::hydrogen_count) .def_readonly("weight", &ResidueInfo::weight) .def("found", &ResidueInfo::found) .def("is_standard", &ResidueInfo::is_standard) .def("is_water", &ResidueInfo::is_water) .def("is_nucleic_acid", &ResidueInfo::is_nucleic_acid) .def("is_amino_acid", &ResidueInfo::is_amino_acid); m.def("find_tabulated_residue", &find_tabulated_residue, py::arg("name"), "Find chemical component information in the internal table."); m.def("expand_protein_one_letter", &expand_protein_one_letter); m.def("expand_protein_one_letter_string", &expand_protein_one_letter_string); } <|endoftext|>
<commit_before>#include <catch/catch.hpp> #include <cmath> #include <limits> #include <RaPsCallion/serializer.h> namespace rapscallion { namespace test { struct byte_view { constexpr byte_view() = default; byte_view(const Deserializer& d) : first(reinterpret_cast<const char*>(d.ptr)) , last (reinterpret_cast<const char*>(d.end)) {} template <size_t N> constexpr byte_view(const char (&arr)[N]) : first(arr) , last(&arr[N - 1]) {} constexpr const char* begin() const { return first; } constexpr const char* end() const { return last; } constexpr size_t size() const { return last - first; } constexpr bool empty() const { return first == last; } private: const char* first = nullptr; const char* last = nullptr; }; bool operator==(const byte_view& lhs, const byte_view& rhs) { return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()); } std::ostream& operator<<(std::ostream& os, const byte_view& v) { const auto oldFlags = os.setf(std::ios_base::hex, std::ios_base::basefield); const auto oldFill = os.fill('0'); os << '"'; for (const auto& c : v) { os << "\\x" << std::setw(2) << static_cast<unsigned>(static_cast<unsigned char>(c)); } os << '"'; os.setf(oldFlags); os.fill(oldFlags); return os; } void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1, const byte_view& expected_serialization = byte_view()) { GIVEN("the real number " + inStr) { WHEN("we serialize it") { Serializer s; serializer<decltype(+in)>::write(s, in); Deserializer d(s); THEN("the serialized output meets expectations") { const byte_view serialized(d); if (expected_size >= 0) CHECK(serialized.size() == expected_size); // largest encoding of IEEE754 binary64 float: // (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte // (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte // + = 10 byte CHECK(serialized.size() <= 10); if (!expected_serialization.empty()) CHECK(serialized == expected_serialization); AND_WHEN("we deserialize it again") { const auto out = serializer<decltype(+in)>::read(d); THEN("the deserialized output is equal to the original input") { if (std::isnan(in)) { CHECK(std::isnan(out)); } else { CHECK(out == in); CHECK(std::signbit(out) == std::signbit(in)); } } } } } } } void test(const std::string& inStr, const double in, const byte_view& expected_serialization) { return test(inStr, in, expected_serialization.size(), expected_serialization); } } } SCENARIO("Serializing floating point numbers", "[serialization]") { using namespace rapscallion::test; #define STRIFY1ST(num, ...) #num #define TEST(...) \ test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__) // Smallest encodings, only requiring flags TEST( std::numeric_limits<double>::infinity(), "\x02"); TEST(-std::numeric_limits<double>::infinity(), "\x03"); TEST(std::numeric_limits<double>::quiet_NaN(), "\x00"); TEST( 0.0, "\x04"); TEST(-0.0, "\x05"); TEST( 0.03125, "\x15" "\x01"); TEST(-0.03125, "\x17" "\x01"); TEST( 0.0625 , "\x11" "\x01"); TEST(-0.0625 , "\x13" "\x01"); TEST( 0.125 , "\x0d" "\x01"); TEST(-0.125 , "\x0f" "\x01"); TEST( 0.25 , "\x09" "\x01"); TEST(-0.25 , "\x0b" "\x01"); TEST( 0.5 , "\x06" "\x01"); TEST(-0.5 , "\x08" "\x01"); TEST( 1.0 , "\x0a" "\x01"); TEST(-1.0 , "\x0c" "\x01"); TEST( 2.0 , "\x0e" "\x01"); TEST(-2.0 , "\x10" "\x01"); TEST(M_PI, 9); TEST(-M_PI, 9); TEST((float)M_PI, 5); TEST(-(float)M_PI, 5); TEST(std::numeric_limits<double>::epsilon()); TEST(std::numeric_limits<double>::min()); TEST(std::numeric_limits<double>::max(), 10); TEST(std::numeric_limits<double>::denorm_min()); #undef STRIFY #undef TEST } <commit_msg>Pin small numbers' serialization sizes too<commit_after>#include <catch/catch.hpp> #include <cmath> #include <limits> #include <RaPsCallion/serializer.h> namespace rapscallion { namespace test { struct byte_view { constexpr byte_view() = default; byte_view(const Deserializer& d) : first(reinterpret_cast<const char*>(d.ptr)) , last (reinterpret_cast<const char*>(d.end)) {} template <size_t N> constexpr byte_view(const char (&arr)[N]) : first(arr) , last(&arr[N - 1]) {} constexpr const char* begin() const { return first; } constexpr const char* end() const { return last; } constexpr size_t size() const { return last - first; } constexpr bool empty() const { return first == last; } private: const char* first = nullptr; const char* last = nullptr; }; bool operator==(const byte_view& lhs, const byte_view& rhs) { return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()); } std::ostream& operator<<(std::ostream& os, const byte_view& v) { const auto oldFlags = os.setf(std::ios_base::hex, std::ios_base::basefield); const auto oldFill = os.fill('0'); os << '"'; for (const auto& c : v) { os << "\\x" << std::setw(2) << static_cast<unsigned>(static_cast<unsigned char>(c)); } os << '"'; os.setf(oldFlags); os.fill(oldFlags); return os; } void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1, const byte_view& expected_serialization = byte_view()) { GIVEN("the real number " + inStr) { WHEN("we serialize it") { Serializer s; serializer<decltype(+in)>::write(s, in); Deserializer d(s); THEN("the serialized output meets expectations") { const byte_view serialized(d); if (expected_size >= 0) CHECK(serialized.size() == expected_size); // largest encoding of IEEE754 binary64 float: // (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte // (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte // + = 10 byte CHECK(serialized.size() <= 10); if (!expected_serialization.empty()) CHECK(serialized == expected_serialization); AND_WHEN("we deserialize it again") { const auto out = serializer<decltype(+in)>::read(d); THEN("the deserialized output is equal to the original input") { if (std::isnan(in)) { CHECK(std::isnan(out)); } else { CHECK(out == in); CHECK(std::signbit(out) == std::signbit(in)); } } } } } } } void test(const std::string& inStr, const double in, const byte_view& expected_serialization) { return test(inStr, in, expected_serialization.size(), expected_serialization); } } } SCENARIO("Serializing floating point numbers", "[serialization]") { using namespace rapscallion::test; #define STRIFY1ST(num, ...) #num #define TEST(...) \ test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__) // Smallest encodings, only requiring flags TEST( std::numeric_limits<double>::infinity(), "\x02"); TEST(-std::numeric_limits<double>::infinity(), "\x03"); TEST(std::numeric_limits<double>::quiet_NaN(), "\x00"); TEST( 0.0, "\x04"); TEST(-0.0, "\x05"); TEST( 0.03125, "\x15" "\x01"); TEST(-0.03125, "\x17" "\x01"); TEST( 0.0625 , "\x11" "\x01"); TEST(-0.0625 , "\x13" "\x01"); TEST( 0.125 , "\x0d" "\x01"); TEST(-0.125 , "\x0f" "\x01"); TEST( 0.25 , "\x09" "\x01"); TEST(-0.25 , "\x0b" "\x01"); TEST( 0.5 , "\x06" "\x01"); TEST(-0.5 , "\x08" "\x01"); TEST( 1.0 , "\x0a" "\x01"); TEST(-1.0 , "\x0c" "\x01"); TEST( 2.0 , "\x0e" "\x01"); TEST(-2.0 , "\x10" "\x01"); TEST(M_PI, 9); TEST(-M_PI, 9); TEST((float)M_PI, 5); TEST(-(float)M_PI, 5); TEST(std::numeric_limits<double>::epsilon(), 3); TEST(std::numeric_limits<double>::min(), 3); TEST(std::numeric_limits<double>::max(), 10); TEST(std::numeric_limits<double>::denorm_min(), 3); #undef STRIFY #undef TEST } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include <cmath> TEMPLATE_TEST_CASE_2("saxpy/0", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = Z(2.0) * x + y; REQUIRE_EQUALS(yy[0], Z(-1.0)); REQUIRE_EQUALS(yy[1], Z(7.0)); REQUIRE_EQUALS(yy[2], Z(0.5)); REQUIRE_EQUALS(yy[3], Z(3.2)); } TEMPLATE_TEST_CASE_2("saxpy/1", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x + Z(2.0) * y; REQUIRE_EQUALS(yy[0], Z(1.0)); REQUIRE_EQUALS(yy[1], Z(8.0)); REQUIRE_EQUALS(yy[2], Z(1.0)); REQUIRE_EQUALS(yy[3], Z(3.4)); } TEMPLATE_TEST_CASE_2("saxpy/2", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x * Z(2) + y; REQUIRE_EQUALS(yy[0], Z(-1.0)); REQUIRE_EQUALS(yy[1], Z(7.0)); REQUIRE_EQUALS(yy[2], Z(0.5)); REQUIRE_EQUALS(yy[3], Z(3.2)); } TEMPLATE_TEST_CASE_2("saxpy/3", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x + y * Z(2); REQUIRE_EQUALS(yy[0], Z(1.0)); REQUIRE_EQUALS(yy[1], Z(8.0)); REQUIRE_EQUALS(yy[2], Z(1.0)); REQUIRE_EQUALS(yy[3], Z(3.4)); } TEMPLATE_TEST_CASE_2("fast_matrix/max", "fast_matrix::max", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = max(a, 1.0); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 2.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("fast_matrix/min", "fast_matrix::min", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = min(a, 1.0); REQUIRE_EQUALS(d[0], -1.0); REQUIRE_EQUALS(d[1], 1.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("pow_precise/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, -6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_precise(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(1.0)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.1, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/1", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow((a >> a) + 1.0, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(4.0)); REQUIRE_EQUALS_APPROX(d[1], Z(25.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(4.0)); } TEMPLATE_TEST_CASE_2("pow/2", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {0.1, 2.0, 0.5, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(0.25)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); } TEMPLATE_TEST_CASE_2("pow/3", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.01, 2.0, 9.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, -2.0); REQUIRE_EQUALS_APPROX(d[0], Z(10000.0)); REQUIRE_EQUALS_APPROX(d[1], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0) / Z(81.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(1.0) / Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(1.0) / Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(1.0) / Z(36.0)); } TEMPLATE_TEST_CASE_2("pow_int/0", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 0.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_int(a, 2); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 4.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); REQUIRE_EQUALS(d[4], 4.0); REQUIRE_EQUALS(d[5], 16.0); REQUIRE_EQUALS(d[6], 25.0); REQUIRE_EQUALS(d[7], 36.0); } TEMPLATE_TEST_CASE_2("pow_int/1", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow_int((a >> a) + 1.0, 2); REQUIRE_EQUALS(d[0], 4.0); REQUIRE_EQUALS(d[1], 25.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 4.0); } <commit_msg>Complete the tests for axpby<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include <cmath> TEMPLATE_TEST_CASE_2("saxpy/0", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = Z(2.0) * x + y; REQUIRE_EQUALS(yy[0], Z(-1.0)); REQUIRE_EQUALS(yy[1], Z(7.0)); REQUIRE_EQUALS(yy[2], Z(0.5)); REQUIRE_EQUALS(yy[3], Z(3.2)); } TEMPLATE_TEST_CASE_2("saxpy/1", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x + Z(2.0) * y; REQUIRE_EQUALS(yy[0], Z(1.0)); REQUIRE_EQUALS(yy[1], Z(8.0)); REQUIRE_EQUALS(yy[2], Z(1.0)); REQUIRE_EQUALS(yy[3], Z(3.4)); } TEMPLATE_TEST_CASE_2("saxpy/2", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x * Z(2) + y; REQUIRE_EQUALS(yy[0], Z(-1.0)); REQUIRE_EQUALS(yy[1], Z(7.0)); REQUIRE_EQUALS(yy[2], Z(0.5)); REQUIRE_EQUALS(yy[3], Z(3.2)); } TEMPLATE_TEST_CASE_2("saxpy/3", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x + y * Z(2); REQUIRE_EQUALS(yy[0], Z(1.0)); REQUIRE_EQUALS(yy[1], Z(8.0)); REQUIRE_EQUALS(yy[2], Z(1.0)); REQUIRE_EQUALS(yy[3], Z(3.4)); } TEMPLATE_TEST_CASE_2("saxpby/0", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = Z(2.0) * x + Z(3.0) * y; REQUIRE_EQUALS_APPROX(yy[0], Z(1.0)); REQUIRE_EQUALS_APPROX(yy[1], Z(13.0)); REQUIRE_EQUALS_APPROX(yy[2], Z(1.5)); REQUIRE_EQUALS_APPROX(yy[3], Z(5.6)); } TEMPLATE_TEST_CASE_2("saxpby/1", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x * Z(2.0) + y * Z(3.0); REQUIRE_EQUALS_APPROX(yy[0], Z(1.0)); REQUIRE_EQUALS_APPROX(yy[1], Z(13.0)); REQUIRE_EQUALS_APPROX(yy[2], Z(1.5)); REQUIRE_EQUALS_APPROX(yy[3], Z(5.6)); } TEMPLATE_TEST_CASE_2("saxpby/2", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = Z(2.0) * x + y * Z(3.0); REQUIRE_EQUALS_APPROX(yy[0], Z(1.0)); REQUIRE_EQUALS_APPROX(yy[1], Z(13.0)); REQUIRE_EQUALS_APPROX(yy[2], Z(1.5)); REQUIRE_EQUALS_APPROX(yy[3], Z(5.6)); } TEMPLATE_TEST_CASE_2("saxpby/3", "[saxpy][fast]", Z, float, double) { etl::fast_matrix<Z, 2, 2> x = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> y = {1.0, 3.0, 0.5, 1.2}; etl::fast_matrix<Z, 2, 2> yy; yy = x * Z(2.0) + Z(3.0) * y; REQUIRE_EQUALS_APPROX(yy[0], Z(1.0)); REQUIRE_EQUALS_APPROX(yy[1], Z(13.0)); REQUIRE_EQUALS_APPROX(yy[2], Z(1.5)); REQUIRE_EQUALS_APPROX(yy[3], Z(5.6)); } TEMPLATE_TEST_CASE_2("fast_matrix/max", "fast_matrix::max", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = max(a, 1.0); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 2.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("fast_matrix/min", "fast_matrix::min", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = min(a, 1.0); REQUIRE_EQUALS(d[0], -1.0); REQUIRE_EQUALS(d[1], 1.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("pow_precise/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, -6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_precise(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(1.0)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.1, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/1", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow((a >> a) + 1.0, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(4.0)); REQUIRE_EQUALS_APPROX(d[1], Z(25.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(4.0)); } TEMPLATE_TEST_CASE_2("pow/2", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {0.1, 2.0, 0.5, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(0.25)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); } TEMPLATE_TEST_CASE_2("pow/3", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.01, 2.0, 9.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, -2.0); REQUIRE_EQUALS_APPROX(d[0], Z(10000.0)); REQUIRE_EQUALS_APPROX(d[1], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0) / Z(81.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(1.0) / Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(1.0) / Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(1.0) / Z(36.0)); } TEMPLATE_TEST_CASE_2("pow_int/0", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 0.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_int(a, 2); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 4.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); REQUIRE_EQUALS(d[4], 4.0); REQUIRE_EQUALS(d[5], 16.0); REQUIRE_EQUALS(d[6], 25.0); REQUIRE_EQUALS(d[7], 36.0); } TEMPLATE_TEST_CASE_2("pow_int/1", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow_int((a >> a) + 1.0, 2); REQUIRE_EQUALS(d[0], 4.0); REQUIRE_EQUALS(d[1], 25.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 4.0); } <|endoftext|>
<commit_before>// This file is part of gltfpack; see gltfpack.h for version/license details #include "gltfpack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif static const char* kMimeTypes[][2] = { {"image/jpeg", ".jpg"}, {"image/jpeg", ".jpeg"}, {"image/png", ".png"}, }; void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images) { for (size_t i = 0; i < data->materials_count; ++i) { const cgltf_material& material = data->materials[i]; if (material.has_pbr_metallic_roughness) { const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness; if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image) images[pbr.base_color_texture.texture->image - data->images].srgb = true; } if (material.has_pbr_specular_glossiness) { const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness; if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image) images[pbr.diffuse_texture.texture->image - data->images].srgb = true; } if (material.emissive_texture.texture && material.emissive_texture.texture->image) images[material.emissive_texture.texture->image - data->images].srgb = true; if (material.normal_texture.texture && material.normal_texture.texture->image) images[material.normal_texture.texture->image - data->images].normal_map = true; } } const char* inferMimeType(const char* path) { const char* ext = strrchr(path, '.'); if (!ext) return ""; std::string extl = ext; for (size_t i = 0; i < extl.length(); ++i) extl[i] = char(tolower(extl[i])); for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (extl == kMimeTypes[i][1]) return kMimeTypes[i][0]; return ""; } static const char* mimeExtension(const char* mime_type) { for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (strcmp(kMimeTypes[i][0], mime_type) == 0) return kMimeTypes[i][1]; return ".raw"; } #ifdef __EMSCRIPTEN__ EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), { var cp = require('child_process'); var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ]; var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio }); return ret.status == null ? 256 : ret.status; }); #else static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr) { #ifdef _WIN32 std::string ignore = "nul"; #else std::string ignore = "/dev/null"; #endif std::string cmd = cmd_; if (ignore_stdout) (cmd += " >") += ignore; if (ignore_stderr) (cmd += " 2>") += ignore; return system(cmd.c_str()); } #endif bool checkBasis() { const char* basisu_path = getenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; cmd += " -version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); return rc == 0; } bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, bool uastc) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".basis"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* basisu_path = getenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; char ql[16]; sprintf(ql, "%d", (quality * 255 + 50) / 100); cmd += " -q "; cmd += ql; cmd += " -mipmap"; if (normal_map) { cmd += " -normal_map"; // for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness } else if (!srgb) { cmd += " -linear"; } if (uastc) { cmd += " -uastc"; } cmd += " -file "; cmd += temp_input.path; cmd += " -output_file "; cmd += temp_output.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false); return rc == 0 && readFile(temp_output.path.c_str(), result); } <commit_msg>gltfpack: Fix BASISU_PATH access in Emscripten<commit_after>// This file is part of gltfpack; see gltfpack.h for version/license details #include "gltfpack.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif static const char* kMimeTypes[][2] = { {"image/jpeg", ".jpg"}, {"image/jpeg", ".jpeg"}, {"image/png", ".png"}, }; void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images) { for (size_t i = 0; i < data->materials_count; ++i) { const cgltf_material& material = data->materials[i]; if (material.has_pbr_metallic_roughness) { const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness; if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image) images[pbr.base_color_texture.texture->image - data->images].srgb = true; } if (material.has_pbr_specular_glossiness) { const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness; if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image) images[pbr.diffuse_texture.texture->image - data->images].srgb = true; } if (material.emissive_texture.texture && material.emissive_texture.texture->image) images[material.emissive_texture.texture->image - data->images].srgb = true; if (material.normal_texture.texture && material.normal_texture.texture->image) images[material.normal_texture.texture->image - data->images].normal_map = true; } } const char* inferMimeType(const char* path) { const char* ext = strrchr(path, '.'); if (!ext) return ""; std::string extl = ext; for (size_t i = 0; i < extl.length(); ++i) extl[i] = char(tolower(extl[i])); for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (extl == kMimeTypes[i][1]) return kMimeTypes[i][0]; return ""; } static const char* mimeExtension(const char* mime_type) { for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i) if (strcmp(kMimeTypes[i][0], mime_type) == 0) return kMimeTypes[i][1]; return ".raw"; } #ifdef __EMSCRIPTEN__ EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), { var cp = require('child_process'); var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ]; var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio }); return ret.status == null ? 256 : ret.status; }); EM_JS(const char*, readenv, (const char* name), { var val = process.env[UTF8ToString(name)]; if (!val) return 0; var ret = _malloc(lengthBytesUTF8(val) + 1); stringToUTF8(val, ret, lengthBytesUTF8(val) + 1); return ret; }); #else static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr) { #ifdef _WIN32 std::string ignore = "nul"; #else std::string ignore = "/dev/null"; #endif std::string cmd = cmd_; if (ignore_stdout) (cmd += " >") += ignore; if (ignore_stderr) (cmd += " 2>") += ignore; return system(cmd.c_str()); } static const char* readenv(const char* name) { return getenv(name); } #endif bool checkBasis() { const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; cmd += " -version"; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true); return rc == 0; } bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, bool uastc) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".basis"); if (!writeFile(temp_input.path.c_str(), data)) return false; const char* basisu_path = readenv("BASISU_PATH"); std::string cmd = basisu_path ? basisu_path : "basisu"; char ql[16]; sprintf(ql, "%d", (quality * 255 + 50) / 100); cmd += " -q "; cmd += ql; cmd += " -mipmap"; if (normal_map) { cmd += " -normal_map"; // for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness } else if (!srgb) { cmd += " -linear"; } if (uastc) { cmd += " -uastc"; } cmd += " -file "; cmd += temp_input.path; cmd += " -output_file "; cmd += temp_output.path; int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false); return rc == 0 && readFile(temp_output.path.c_str(), result); } <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2110 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1267316 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/05/11 03:01:23<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2111 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2239 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1324475 by johtaylo@johtaylo-jtincrementor-increment on 2016/10/10 03:00:04<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2240 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2349 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1367013 by johtaylo@johtaylo-jtincrementor-increment on 2017/01/29 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2350 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pages.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-03-11 10:49: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 _PAGES_HXX_ #define _PAGES_HXX_ #include <vcl/tabpage.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/scrbar.hxx> #include <svtools/wizardmachine.hxx> #include <svtools/svmedit.hxx> #include <svtools/lstner.hxx> #include <svtools/xtextedt.hxx> namespace desktop { class WelcomePage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; svt::OWizardMachine *m_pParent; enum OEMType { OEM_NONE, OEM_NORMAL, OEM_EXTENDED }; OEMType checkOEM(); public: WelcomePage( svt::OWizardMachine* parent, const ResId& resid); protected: virtual void ActivatePage(); }; class LicenseView : public MultiLineEdit, public SfxListener { BOOL mbEndReached; Link maEndReachedHdl; Link maScrolledHdl; public: LicenseView( Window* pParent, const ResId& rResId ); ~LicenseView(); void ScrollDown( ScrollType eScroll ); BOOL IsEndReached() const; BOOL EndReached() const { return mbEndReached; } void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; } void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; } const Link& GetAutocompleteHdl() const { return maEndReachedHdl; } void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; } const Link& GetScrolledHdl() const { return maScrolledHdl; } virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); }; class LicensePage : public svt::OWizardPage { private: svt::OWizardMachine *m_pParent; FixedText m_ftHead; FixedText m_ftBody1; FixedText m_ftBody1Txt; FixedText m_ftBody2; FixedText m_ftBody2Txt; LicenseView m_mlLicense; PushButton m_pbDown; sal_Bool m_bLicenseRead; public: LicensePage( svt::OWizardMachine* parent, const ResId& resid); private: DECL_LINK(PageDownHdl, PushButton*); DECL_LINK(EndReachedHdl, LicenseView*); DECL_LINK(ScrolledHdl, LicenseView*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; class MigrationPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbMigration; sal_Bool m_bMigrationDone; public: MigrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UserPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; FixedText m_ftFirst; Edit m_edFirst; FixedText m_ftLast; Edit m_edLast; FixedText m_ftInitials; Edit m_edInitials; FixedText m_ftFather; Edit m_edFather; LanguageType m_lang; public: UserPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class RegistrationPage : public svt::OWizardPage { private: FixedText m_ftHeader; FixedText m_ftBody; FixedImage m_fiImage; RadioButton m_rbNow; RadioButton m_rbLater; RadioButton m_rbNever; RadioButton m_rbReg; FixedLine m_flSeparator; FixedText m_ftEnd; public: RegistrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; } #endif <commit_msg>INTEGRATION: CWS licensing1 (1.2.20); FILE MERGED 2005/03/10 13:06:02 lo 1.2.20.1: #119700# tab action<commit_after>/************************************************************************* * * $RCSfile: pages.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-03-29 15:42: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): _______________________________________ * * ************************************************************************/ #ifndef _PAGES_HXX_ #define _PAGES_HXX_ #include <vcl/tabpage.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/scrbar.hxx> #include <svtools/wizardmachine.hxx> #include <svtools/svmedit.hxx> #include <svtools/lstner.hxx> #include <svtools/xtextedt.hxx> namespace desktop { class WelcomePage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; svt::OWizardMachine *m_pParent; enum OEMType { OEM_NONE, OEM_NORMAL, OEM_EXTENDED }; OEMType checkOEM(); bool checkEval(); public: WelcomePage( svt::OWizardMachine* parent, const ResId& resid); protected: virtual void ActivatePage(); }; class LicenseView : public MultiLineEdit, public SfxListener { BOOL mbEndReached; Link maEndReachedHdl; Link maScrolledHdl; public: LicenseView( Window* pParent, const ResId& rResId ); ~LicenseView(); void ScrollDown( ScrollType eScroll ); BOOL IsEndReached() const; BOOL EndReached() const { return mbEndReached; } void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; } void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; } const Link& GetAutocompleteHdl() const { return maEndReachedHdl; } void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; } const Link& GetScrolledHdl() const { return maScrolledHdl; } virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); }; class LicensePage : public svt::OWizardPage { private: svt::OWizardMachine *m_pParent; FixedText m_ftHead; FixedText m_ftBody1; FixedText m_ftBody1Txt; FixedText m_ftBody2; FixedText m_ftBody2Txt; LicenseView m_mlLicense; PushButton m_pbDown; sal_Bool m_bLicenseRead; public: LicensePage( svt::OWizardMachine* parent, const ResId& resid); private: DECL_LINK(PageDownHdl, PushButton*); DECL_LINK(EndReachedHdl, LicenseView*); DECL_LINK(ScrolledHdl, LicenseView*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; class MigrationPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; CheckBox m_cbMigration; sal_Bool m_bMigrationDone; public: MigrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class UserPage : public svt::OWizardPage { private: FixedText m_ftHead; FixedText m_ftBody; FixedText m_ftFirst; Edit m_edFirst; FixedText m_ftLast; Edit m_edLast; FixedText m_ftInitials; Edit m_edInitials; FixedText m_ftFather; Edit m_edFather; LanguageType m_lang; public: UserPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual void ActivatePage(); }; class RegistrationPage : public svt::OWizardPage { private: FixedText m_ftHeader; FixedText m_ftBody; FixedImage m_fiImage; RadioButton m_rbNow; RadioButton m_rbLater; RadioButton m_rbNever; RadioButton m_rbReg; FixedLine m_flSeparator; FixedText m_ftEnd; public: RegistrationPage( svt::OWizardMachine* parent, const ResId& resid); virtual sal_Bool commitPage(COMMIT_REASON _eReason); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); }; } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2563 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1497670 by johtaylo@johtaylo-jtincrementor2-increment on 2017/12/22 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2564 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2581 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1509763 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/30 03:00:06<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2582 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2580 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1508957 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/27 03:00:06<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2581 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2015 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1230704 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/01/25 03:00:14<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2016 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1867 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1179013 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/08/11 03:00:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1868 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#include <exp/datapump.h> #include <coap/encoder.h> #include <coap/decoder/netbuf.h> #include <coap/decoder/subject.h> namespace moducom { namespace coap { template <class TMessageObserver, class TNetBuf> void process_messageobserver_helper(DecoderSubjectBase<TMessageObserver>& ds, TNetBuf& netbuf, typename TMessageObserver::context_t& context) { //typedef pipeline::MemoryChunk::readonly_t chunk_t; typedef estd::experimental::const_buffer chunk_t; typedef typename TMessageObserver::context_t request_context_t; netbuf.first(); // TODO: Need to assign addr_incoming to the observer, preferably through incoming context // Seems like it might be prudent either for DecoderSubjectBase itself to be more tightly coupled // to that context *OR* to initiate it/control it explicitly from these helper functions // until this happens, we can't actually queue any output messages. Note also we probably // want a pointer to datapump itself in the context // NOTE: Don't do this just yet, even though it's basically correct, our consuming unit test // is counting on this context remaining in scope //ds.get_observer().context(request_context); // FIX: Need to revise end/next to be more tristate because // dispatch() wants to know if this is the last chunk, but // next() potentially invalidates the *current* buffer, yet // we don't know by our internal netbuf standards whether the // *current* chunk is the last one until after calling next() //while(!netbuf.end()) { chunk_t chunk(netbuf.processed(), netbuf.length_processed()); // FIX: above comment is why this is true here ds.dispatch(chunk, true); netbuf.next(); } } template <class TMessageObserver, class TNetBuf, class TAddr> void process_messageobserver_netbuf(DecoderSubjectBase<TMessageObserver>& ds, TNetBuf& netbuf, TAddr& addr_incoming) { typedef typename TMessageObserver::context_t incoming_context_t; typedef typename TMessageObserver::context_traits_t request_context_traits; incoming_context_t request_context; request_context_traits::set_address(request_context, addr_incoming); process_messageobserver_helper(ds, netbuf, request_context); } template <class TDataPump, class TDecoderSubject> void process_messageobserver(TDataPump& datapump, TDecoderSubject& ds) { typedef TDataPump datapump_t; typedef typename datapump_t::netbuf_t netbuf_t; typedef typename datapump_t::addr_t addr_t; addr_t addr_incoming; netbuf_t* netbuf; netbuf = datapump.dequeue_in(&addr_incoming); if(netbuf != NULLPTR) { //cout << " ip=" << ipaddr.sin_addr.s_addr << endl; process_messageobserver_netbuf(ds, *netbuf, addr_incoming); #ifdef FEATURE_MCCOAP_DATAPUMP_INLINE netbuf_t temporary; // in this scenario, netbuf gets copied around. Ideally we'd actually do an emplace // but code isn't quite there yet netbuf = &temporary; #else // FIX: Need a much more cohesive way of doing this delete netbuf; netbuf = new netbuf_t; #endif datapump.dequeue_pop(); } } }} <commit_msg>Adding unused and experimental upgraded notify-helper for datapump<commit_after>#include <exp/datapump.h> #include <coap/encoder.h> #include <coap/decoder/netbuf.h> #include <coap/decoder/subject.h> namespace moducom { namespace coap { template <class TMessageObserver, class TNetBuf> void process_messageobserver_helper(DecoderSubjectBase<TMessageObserver>& ds, TNetBuf& netbuf, typename TMessageObserver::context_t& context) { //typedef pipeline::MemoryChunk::readonly_t chunk_t; typedef estd::experimental::const_buffer chunk_t; typedef typename TMessageObserver::context_t request_context_t; netbuf.first(); // TODO: Need to assign addr_incoming to the observer, preferably through incoming context // Seems like it might be prudent either for DecoderSubjectBase itself to be more tightly coupled // to that context *OR* to initiate it/control it explicitly from these helper functions // until this happens, we can't actually queue any output messages. Note also we probably // want a pointer to datapump itself in the context // NOTE: Don't do this just yet, even though it's basically correct, our consuming unit test // is counting on this context remaining in scope //ds.get_observer().context(request_context); // FIX: Need to revise end/next to be more tristate because // dispatch() wants to know if this is the last chunk, but // next() potentially invalidates the *current* buffer, yet // we don't know by our internal netbuf standards whether the // *current* chunk is the last one until after calling next() //while(!netbuf.end()) { chunk_t chunk(netbuf.processed(), netbuf.length_processed()); // FIX: above comment is why this is true here ds.dispatch(chunk, true); netbuf.next(); } } template <class TMessageObserver, class TNetBuf, class TAddr> void process_messageobserver_netbuf(DecoderSubjectBase<TMessageObserver>& ds, TNetBuf& netbuf, TAddr& addr_incoming) { typedef typename TMessageObserver::context_t incoming_context_t; typedef typename TMessageObserver::context_traits_t request_context_traits; incoming_context_t request_context; request_context_traits::set_address(request_context, addr_incoming); process_messageobserver_helper(ds, netbuf, request_context); } template <class TDataPump, class TDecoderSubject> void process_messageobserver(TDataPump& datapump, TDecoderSubject& ds) { typedef TDataPump datapump_t; typedef typename datapump_t::netbuf_t netbuf_t; typedef typename datapump_t::addr_t addr_t; addr_t addr_incoming; netbuf_t* netbuf; netbuf = datapump.dequeue_in(&addr_incoming); if(netbuf != NULLPTR) { //cout << " ip=" << ipaddr.sin_addr.s_addr << endl; process_messageobserver_netbuf(ds, *netbuf, addr_incoming); #ifdef FEATURE_MCCOAP_DATAPUMP_INLINE netbuf_t temporary; // in this scenario, netbuf gets copied around. Ideally we'd actually do an emplace // but code isn't quite there yet netbuf = &temporary; #else // FIX: Need a much more cohesive way of doing this delete netbuf; netbuf = new netbuf_t; #endif datapump.dequeue_pop(); } } // 2nd-generation subject/observer code designed for use with estd::experimental::subject code // merely evaluates presence of incoming-from-transport data, and if present, fires off // notification to subject // FIX: Obviously needs better name template <class TDataPump, class TSubject> void process_messageobserver2(TDataPump& datapump, TSubject& subject) { typedef TDataPump datapump_t; typedef typename datapump_t::Item item_t; typedef typename datapump_t::netbuf_t netbuf_t; typedef typename datapump_t::addr_t addr_t; if(!datapump.dequeue_empty()) { item_t& item = datapump.dequeue_front(); addr_t addr_incoming = item.addr(); netbuf_t* netbuf = item.netbuf(); subject.notify(item); #ifdef FEATURE_MCCOAP_DATAPUMP_INLINE #else // FIX: Need a much more cohesive way of doing this delete netbuf; #endif datapump.dequeue_pop(); } } }} <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2357 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1369504 by johtaylo@johtaylo-jtincrementor-increment on 2017/02/06 03:00:04<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2358 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // 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 2012 Anton Chernov <chernov.anton.mail@gmail.com> // Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com> // Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org> // #include "DeclarativeDataPlugin.h" #include "DeclarativeDataPluginModel.h" #include "MarbleDeclarativeWidget.h" #include "DeclarativeDataPluginItem.h" #include "MarbleDebug.h" #include "MarbleWidget.h" #include "MarbleModel.h" #include <QMetaObject> #include <QMetaProperty> #include <QScriptValue> #include <QScriptValueIterator> #if QT_VERSION < 0x050000 typedef QDeclarativeComponent QQmlComponent; #endif using namespace Marble; class DeclarativeDataPluginPrivate { public: DeclarativeDataPlugin* q; QString m_planet; QString m_name; QString m_nameId; QString m_version; QString m_guiString; QString m_copyrightYears; QString m_description; QList<Marble::PluginAuthor> m_authors; QString m_aboutText; bool m_isInitialized; QList<AbstractDataPluginItem *> m_items; QList<DeclarativeDataPluginModel*> m_modelInstances; QQmlComponent* m_delegate; QVariant m_model; static int m_global_counter; int m_counter; DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q ); static void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value ); void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates ); void parseListModel( QAbstractListModel* listModel ); void parseObject( QObject* object ); }; int DeclarativeDataPluginPrivate::m_global_counter = 0; DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) : q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 ), m_counter( m_global_counter ) { ++m_global_counter; } void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value ) { if( key == "lat" || key == "latitude" ) { coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree ); } else if( key == "lon" || key == "longitude" ) { coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree ); } else if( key == "alt" || key == "altitude" ) { coordinates.setAltitude( value.toDouble() ); } else { item->setProperty( key.toLatin1(), value ); } } void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates ) { if ( coordinates.isValid() ) { item->setCoordinate( coordinates ); QVariant const idValue = item->property( "identifier" ); if ( idValue.isValid() && !idValue.toString().isEmpty() ) { item->setId( idValue.toString() ); } else { item->setId( coordinates.toString() ) ; } m_items.append( item ); } else { delete item; } } void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel ) { QHash< int, QByteArray > roles = listModel->roleNames(); for( int i = 0; i < listModel->rowCount(); ++i ) { GeoDataCoordinates coordinates; QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) ); QHash< int, QByteArray >::const_iterator it = roles.constBegin(); DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q ); for ( ; it != roles.constEnd(); ++it ) { parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) ); } addItem( item, coordinates ); } } void DeclarativeDataPluginPrivate::parseObject( QObject *object ) { int count = 0; QMetaObject const * meta = object->metaObject(); for( int i = 0; i < meta->propertyCount(); ++i ) { if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) { count = meta->property(i).read( object ).toInt(); } } for( int i = 0; i < meta->methodCount(); ++i ) { #if QT_VERSION < 0x050000 if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) { #else if( meta->method(i).methodSignature() == "get(int)" ) { #endif for( int j=0; j < count; ++j ) { QScriptValue value; meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) ); QObject * propertyObject = value.toQObject(); GeoDataCoordinates coordinates; DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q ); if ( propertyObject ) { for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) { QString const propertyName = propertyObject->metaObject()->property( k ).name(); QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject ); parseChunk( item, coordinates, propertyName, value ); } } else { QScriptValueIterator it( value ); while ( it.hasNext() ) { it.next(); parseChunk( item, coordinates, it.name(), it.value().toVariant() ); } } addItem( item, coordinates ); } } } } Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const { DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel ); instance->d->m_planet = d->m_planet; instance->d->m_name = d->m_name; instance->d->m_nameId = d->m_nameId; instance->d->m_version = d->m_version; instance->d->m_guiString = d->m_guiString; instance->d->m_copyrightYears = d->m_copyrightYears; instance->d->m_description = d->m_description; instance->d->m_authors = d->m_authors; instance->d->m_aboutText = d->m_aboutText; instance->d->m_isInitialized = d->m_isInitialized; instance->d->m_items = d->m_items; instance->d->m_delegate = d->m_delegate; instance->d->m_model = d->m_model; instance->d->m_counter = d->m_counter; instance->setNumberOfItems( numberOfItems() ); instance->setFavoriteItemsOnly( isFavoriteItemsOnly() ); DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel ); dataModel->addItemsToList( d->m_items ); instance->setModel( dataModel ); connect( dataModel, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)), this, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)) ); d->m_modelInstances << dataModel; return instance; } DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel ) : AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) ) { setEnabled( true ); setVisible( true ); } DeclarativeDataPlugin::~DeclarativeDataPlugin() { delete d; } QString DeclarativeDataPlugin::planet() const { return d->m_planet; } void DeclarativeDataPlugin::setPlanet( const QString &planet ) { if ( d->m_planet != planet ) { d->m_planet = planet; emit planetChanged(); } } QString DeclarativeDataPlugin::name() const { return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name; } QString DeclarativeDataPlugin::guiString() const { return d->m_guiString.isEmpty() ? name() : d->m_guiString; } QString DeclarativeDataPlugin::nameId() const { return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId; } QString DeclarativeDataPlugin::version() const { return d->m_version.isEmpty() ? "1.0" : d->m_version; } QString DeclarativeDataPlugin::description() const { return d->m_description; } QString DeclarativeDataPlugin::copyrightYears() const { return d->m_copyrightYears; } QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const { return d->m_authors; } QStringList DeclarativeDataPlugin::authors() const { QStringList authors; foreach( const PluginAuthor& author, d->m_authors ) { authors<< author.name << author.email; } return authors; } QString DeclarativeDataPlugin::aboutDataText() const { return d->m_aboutText; } QIcon DeclarativeDataPlugin::icon() const { return QIcon(); } void DeclarativeDataPlugin::setName( const QString & name ) { if( d->m_name != name ) { d->m_name = name; emit nameChanged(); } } void DeclarativeDataPlugin::setGuiString( const QString & guiString ) { if( d->m_guiString != guiString ) { d->m_guiString = guiString; emit guiStringChanged(); } } void DeclarativeDataPlugin::setNameId( const QString & nameId ) { if( d->m_nameId != nameId ) { d->m_nameId = nameId; emit nameIdChanged(); } } void DeclarativeDataPlugin::setVersion( const QString & version ) { if( d->m_version != version ) { d->m_version = version; emit versionChanged(); } } void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears ) { if( d->m_copyrightYears != copyrightYears ) { d->m_copyrightYears = copyrightYears; emit copyrightYearsChanged(); } } void DeclarativeDataPlugin::setDescription( const QString description ) { if( d->m_description != description ) { d->m_description = description; emit descriptionChanged(); } } void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors ) { if( pluginAuthors.size() % 2 == 0 ) { QStringList::const_iterator it = pluginAuthors.constBegin(); while ( it != pluginAuthors.constEnd() ) { QString name = *(++it); QString email = *(++it);; d->m_authors.append( PluginAuthor( name, email) ); } emit authorsChanged(); } } void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText ) { if( d->m_aboutText != aboutDataText ) { d->m_aboutText = aboutDataText; emit aboutDataTextChanged(); } } QQmlComponent *DeclarativeDataPlugin::delegate() { return d->m_delegate; } void DeclarativeDataPlugin::setDelegate( QQmlComponent *delegate ) { if ( delegate != d->m_delegate ) { d->m_delegate = delegate; emit delegateChanged(); } } void DeclarativeDataPlugin::initialize() { if( !model() ) { setModel( new DeclarativeDataPluginModel( marbleModel(), this ) ); } d->m_isInitialized = true; } bool DeclarativeDataPlugin::isInitialized() const { return d->m_isInitialized; } RenderState DeclarativeDataPlugin::renderState() const { return RenderState( "Declarative Data" ); } void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model ) { d->m_model = model; d->m_items.clear(); QObject* object = model.value<QObject*>(); if( qobject_cast< QAbstractListModel* >( object ) ) { d->parseListModel( qobject_cast< QAbstractListModel *>( object ) ); } else { d->parseObject( object ); } /** @todo: Listen for and reflect changes to the items in the model */ foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) { model->addItemsToList( d->m_items ); } emit declarativeModelChanged(); } QVariant DeclarativeDataPlugin::declarativeModel() { return d->m_model; } #include "DeclarativeDataPlugin.moc" <commit_msg>minimize includes<commit_after>// // 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 2012 Anton Chernov <chernov.anton.mail@gmail.com> // Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com> // Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org> // #include "DeclarativeDataPlugin.h" #include "DeclarativeDataPluginModel.h" #include "DeclarativeDataPluginItem.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include <QAbstractListModel> #include <QMetaObject> #include <QMetaProperty> #include <QScriptValue> #include <QScriptValueIterator> #if QT_VERSION < 0x050000 typedef QDeclarativeComponent QQmlComponent; #endif using namespace Marble; class DeclarativeDataPluginPrivate { public: DeclarativeDataPlugin* q; QString m_planet; QString m_name; QString m_nameId; QString m_version; QString m_guiString; QString m_copyrightYears; QString m_description; QList<Marble::PluginAuthor> m_authors; QString m_aboutText; bool m_isInitialized; QList<AbstractDataPluginItem *> m_items; QList<DeclarativeDataPluginModel*> m_modelInstances; QQmlComponent* m_delegate; QVariant m_model; static int m_global_counter; int m_counter; DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q ); static void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value ); void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates ); void parseListModel( QAbstractListModel* listModel ); void parseObject( QObject* object ); }; int DeclarativeDataPluginPrivate::m_global_counter = 0; DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) : q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 ), m_counter( m_global_counter ) { ++m_global_counter; } void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value ) { if( key == "lat" || key == "latitude" ) { coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree ); } else if( key == "lon" || key == "longitude" ) { coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree ); } else if( key == "alt" || key == "altitude" ) { coordinates.setAltitude( value.toDouble() ); } else { item->setProperty( key.toLatin1(), value ); } } void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates ) { if ( coordinates.isValid() ) { item->setCoordinate( coordinates ); QVariant const idValue = item->property( "identifier" ); if ( idValue.isValid() && !idValue.toString().isEmpty() ) { item->setId( idValue.toString() ); } else { item->setId( coordinates.toString() ) ; } m_items.append( item ); } else { delete item; } } void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel ) { QHash< int, QByteArray > roles = listModel->roleNames(); for( int i = 0; i < listModel->rowCount(); ++i ) { GeoDataCoordinates coordinates; QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) ); QHash< int, QByteArray >::const_iterator it = roles.constBegin(); DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q ); for ( ; it != roles.constEnd(); ++it ) { parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) ); } addItem( item, coordinates ); } } void DeclarativeDataPluginPrivate::parseObject( QObject *object ) { int count = 0; QMetaObject const * meta = object->metaObject(); for( int i = 0; i < meta->propertyCount(); ++i ) { if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) { count = meta->property(i).read( object ).toInt(); } } for( int i = 0; i < meta->methodCount(); ++i ) { #if QT_VERSION < 0x050000 if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) { #else if( meta->method(i).methodSignature() == "get(int)" ) { #endif for( int j=0; j < count; ++j ) { QScriptValue value; meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) ); QObject * propertyObject = value.toQObject(); GeoDataCoordinates coordinates; DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q ); if ( propertyObject ) { for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) { QString const propertyName = propertyObject->metaObject()->property( k ).name(); QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject ); parseChunk( item, coordinates, propertyName, value ); } } else { QScriptValueIterator it( value ); while ( it.hasNext() ) { it.next(); parseChunk( item, coordinates, it.name(), it.value().toVariant() ); } } addItem( item, coordinates ); } } } } Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const { DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel ); instance->d->m_planet = d->m_planet; instance->d->m_name = d->m_name; instance->d->m_nameId = d->m_nameId; instance->d->m_version = d->m_version; instance->d->m_guiString = d->m_guiString; instance->d->m_copyrightYears = d->m_copyrightYears; instance->d->m_description = d->m_description; instance->d->m_authors = d->m_authors; instance->d->m_aboutText = d->m_aboutText; instance->d->m_isInitialized = d->m_isInitialized; instance->d->m_items = d->m_items; instance->d->m_delegate = d->m_delegate; instance->d->m_model = d->m_model; instance->d->m_counter = d->m_counter; instance->setNumberOfItems( numberOfItems() ); instance->setFavoriteItemsOnly( isFavoriteItemsOnly() ); DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel ); dataModel->addItemsToList( d->m_items ); instance->setModel( dataModel ); connect( dataModel, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)), this, SIGNAL(dataRequest(qreal,qreal,qreal,qreal)) ); d->m_modelInstances << dataModel; return instance; } DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel ) : AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) ) { setEnabled( true ); setVisible( true ); } DeclarativeDataPlugin::~DeclarativeDataPlugin() { delete d; } QString DeclarativeDataPlugin::planet() const { return d->m_planet; } void DeclarativeDataPlugin::setPlanet( const QString &planet ) { if ( d->m_planet != planet ) { d->m_planet = planet; emit planetChanged(); } } QString DeclarativeDataPlugin::name() const { return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name; } QString DeclarativeDataPlugin::guiString() const { return d->m_guiString.isEmpty() ? name() : d->m_guiString; } QString DeclarativeDataPlugin::nameId() const { return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId; } QString DeclarativeDataPlugin::version() const { return d->m_version.isEmpty() ? "1.0" : d->m_version; } QString DeclarativeDataPlugin::description() const { return d->m_description; } QString DeclarativeDataPlugin::copyrightYears() const { return d->m_copyrightYears; } QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const { return d->m_authors; } QStringList DeclarativeDataPlugin::authors() const { QStringList authors; foreach( const PluginAuthor& author, d->m_authors ) { authors<< author.name << author.email; } return authors; } QString DeclarativeDataPlugin::aboutDataText() const { return d->m_aboutText; } QIcon DeclarativeDataPlugin::icon() const { return QIcon(); } void DeclarativeDataPlugin::setName( const QString & name ) { if( d->m_name != name ) { d->m_name = name; emit nameChanged(); } } void DeclarativeDataPlugin::setGuiString( const QString & guiString ) { if( d->m_guiString != guiString ) { d->m_guiString = guiString; emit guiStringChanged(); } } void DeclarativeDataPlugin::setNameId( const QString & nameId ) { if( d->m_nameId != nameId ) { d->m_nameId = nameId; emit nameIdChanged(); } } void DeclarativeDataPlugin::setVersion( const QString & version ) { if( d->m_version != version ) { d->m_version = version; emit versionChanged(); } } void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears ) { if( d->m_copyrightYears != copyrightYears ) { d->m_copyrightYears = copyrightYears; emit copyrightYearsChanged(); } } void DeclarativeDataPlugin::setDescription( const QString description ) { if( d->m_description != description ) { d->m_description = description; emit descriptionChanged(); } } void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors ) { if( pluginAuthors.size() % 2 == 0 ) { QStringList::const_iterator it = pluginAuthors.constBegin(); while ( it != pluginAuthors.constEnd() ) { QString name = *(++it); QString email = *(++it);; d->m_authors.append( PluginAuthor( name, email) ); } emit authorsChanged(); } } void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText ) { if( d->m_aboutText != aboutDataText ) { d->m_aboutText = aboutDataText; emit aboutDataTextChanged(); } } QQmlComponent *DeclarativeDataPlugin::delegate() { return d->m_delegate; } void DeclarativeDataPlugin::setDelegate( QQmlComponent *delegate ) { if ( delegate != d->m_delegate ) { d->m_delegate = delegate; emit delegateChanged(); } } void DeclarativeDataPlugin::initialize() { if( !model() ) { setModel( new DeclarativeDataPluginModel( marbleModel(), this ) ); } d->m_isInitialized = true; } bool DeclarativeDataPlugin::isInitialized() const { return d->m_isInitialized; } RenderState DeclarativeDataPlugin::renderState() const { return RenderState( "Declarative Data" ); } void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model ) { d->m_model = model; d->m_items.clear(); QObject* object = model.value<QObject*>(); if( qobject_cast< QAbstractListModel* >( object ) ) { d->parseListModel( qobject_cast< QAbstractListModel *>( object ) ); } else { d->parseObject( object ); } /** @todo: Listen for and reflect changes to the items in the model */ foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) { model->addItemsToList( d->m_items ); } emit declarativeModelChanged(); } QVariant DeclarativeDataPlugin::declarativeModel() { return d->m_model; } #include "DeclarativeDataPlugin.moc" <|endoftext|>
<commit_before>#include "writer/verilog/axi/master_controller.h" #include "iroha/i_design.h" #include "writer/verilog/axi/master_port.h" #include "writer/verilog/module.h" #include "writer/verilog/ports.h" #include "writer/verilog/table.h" namespace iroha { namespace writer { namespace verilog { namespace axi { MasterController::MasterController(const IResource &res, bool reset_polarity) : AxiController(res, reset_polarity) { MasterPort::GetReadWrite(res_, &r_, &w_); } MasterController::~MasterController() { } void MasterController::Write(ostream &os) { AddSramPorts(); ports_->AddPort("addr", Port::INPUT, 32); ports_->AddPort("len", Port::INPUT, sram_addr_width_); ports_->AddPort("start", Port::INPUT, sram_addr_width_); ports_->AddPort("wen", Port::INPUT, 0); ports_->AddPort("req", Port::INPUT, 0); ports_->AddPort("ack", Port::OUTPUT, 0); string initials; GenReadChannel(cfg_, true, nullptr, ports_.get(), &initials); GenWriteChannel(cfg_, true, nullptr, ports_.get(), &initials); string name = MasterPort::ControllerName(res_, reset_polarity_); os << "module " << name << "("; ports_->Output(Ports::PORT_NAME, os); os << ");\n"; ports_->Output(Ports::PORT_TYPE, os); os << "\n" << " `define S_IDLE 0\n" << " `define S_ADDR_WAIT 1\n"; if (r_) { os << " `define S_READ_DATA 2\n" << " `define S_READ_DATA_WAIT 3\n"; } if (w_) { os << " `define S_WRITE_WAIT 4\n"; } os << " reg [2:0] st;\n\n"; if (w_) { os << " `define WS_IDLE 0\n" << " `define WS_WRITE 1\n" << " `define WS_WAIT 2\n" << " reg [1:0] wst;\n" << " reg [" << sram_addr_width_ << ":0] wmax;\n\n"; } if (r_) { os << " reg [" << sram_addr_width_ << ":0] ridx;\n" << " reg read_last;\n\n"; } if (r_) { os << " reg [" << sram_addr_width_ << ":0] widx;\n\n"; } os << " always @(posedge clk) begin\n" << " if (" << (reset_polarity_ ? "" : "!") << ResetName(reset_polarity_) << ") begin\n" << " ack <= 0;\n" << " sram_req <= 0;\n" << " sram_wen <= 0;\n" << " st <= `S_IDLE;\n"; if (w_) { os << " wst <= `WS_IDLE;\n" << " wmax <= 0;\n"; } os << initials << " end else begin\n"; OutputMainFsm(os); if (w_) { OutputWriterFsm(os); } os << " end\n" << " end\n" << "endmodule\n"; } void MasterController::AddPorts(const PortConfig &cfg, Module *mod, bool r, bool w, string *s) { Ports *ports = mod->GetPorts(); if (r) { GenReadChannel(cfg, true, mod, ports, s); } if (w) { GenWriteChannel(cfg, true, mod, ports, s); } } void MasterController::OutputMainFsm(ostream &os) { if (r_) { os << " if (sram_EXCLUSIVE) begin\n" << " sram_wen <= (st == `S_READ_DATA && RVALID);\n" << " end\n"; } else { os << " sram_wen <= 0;\n"; } os << " case (st)\n" << " `S_IDLE: begin\n"; if (r_ || w_) { os << " if (req) begin\n"; if (r_) { os << " ridx <= 0;\n"; } os << " st <= `S_ADDR_WAIT;\n"; if (r_ && !w_) { os << " ARVALID <= 1;\n" << " ARADDR <= addr;\n" << " ARLEN <= len;\n"; } if (!r_ && w_) { os << " AWVALID <= 1;\n" << " AWADDR <= addr;\n" << " AWLEN <= len;\n"; } if (r_ && w_) { os << " if (wen) begin\n" << " ARVALID <= 1;\n" << " ARADDR <= addr;\n" << " ARLEN <= len;\n" << " end else begin\n" << " AWVALID <= 1;\n" << " AWADDR <= addr;\n" << " AWLEN <= len;\n" << " wmax <= len;\n" << " end\n"; } os << " end\n"; } os << " end\n"; if (r_ || w_) { os << " `S_ADDR_WAIT: begin\n"; if (r_ && !w_) { os << " if (ARREADY) begin\n" << " st <= `S_READ_DATA;\n" << " ARVALID <= 0;\n" << " RREADY <= 1;\n" << " end\n"; } if (!r_ && w_) { os << " if (AWREADY) begin\n" << " st <= `S_WRITE_WAIT;\n" << " AWVALID <= 0;\n" << " end\n"; } if (r_ && w_) { os << " if (wen) begin\n" << " if (AWREADY) begin\n" << " st <= `S_WRITE_WAIT;\n" << " AWVALID <= 0;\n" << " sram_addr <= ridx;\n" << " end\n" << " end else begin\n" << " if (ARREADY) begin\n" << " st <= `S_READ_DATA;\n" << " RREADY <= 1;\n" << " end\n" << " end\n"; } os << " end\n"; } if (r_) { ReadState(os); } if (w_) { os << " `S_WRITE_WAIT: begin\n" << " if (BVALID) begin\n" << " st <= `S_IDLE;\n" << " end\n" << " if (wst == `WS_IDLE && req && wen) begin\n" << " sram_addr <= start;\n" << " if (!sram_EXCLUSIVE) begin\n" << " sram_req <= 1;\n" << " end\n" << " end\n" << " if (wst == `WS_WRITE) begin\n" << " if (WREADY && WVALID) begin\n" << " sram_addr <= sram_addr + 1;\n" << " if (!sram_EXCLUSIVE) begin\n" << " sram_req <= 1;\n" << " end\n" << " end else if (sram_ack && !sram_EXCLUSIVE) begin\n" << " sram_req <= 0;\n" << " end\n" << " end\n" << " end\n"; } os << " endcase\n"; } void MasterController::ReadState(ostream &os) { os << " `S_READ_DATA: begin\n" << " if (RVALID) begin\n" << " sram_addr <= start + ridx;\n" << " sram_wdata <= RDATA;\n" << " ridx <= ridx + 1;\n" << " if (sram_EXCLUSIVE) begin\n" << " if (RLAST) begin\n" << " RREADY <= 0;\n" << " st <= `S_IDLE;\n" << " end\n" << " end else begin\n" << " st <= `S_READ_DATA_WAIT;\n" << " sram_req <= 1;\n" << " sram_wen <= 1;\n" << " RREADY <= 0;\n" << " read_last <= RLAST;\n" << " end\n" << " end\n" << " end\n" << " `S_READ_DATA_WAIT: begin\n" // !sram_EXCLUSIVE << " if (sram_ack) begin\n" << " sram_req <= 0;\n" << " sram_wen <= 0;\n" << " if (read_last) begin\n" << " st <= `S_IDLE;\n" << " end else begin\n" << " st <= `S_READ_DATA;\n" << " RREADY <= 1;\n" << " end\n" << " end\n" << " end\n"; } void MasterController::OutputWriterFsm(ostream &os) { os << " case (wst)\n" << " `WS_IDLE: begin\n" << " if (req && wen) begin\n" << " wst <= `WS_WRITE;\n" << " widx <= 0;\n" << " end\n" << " end\n" << " `WS_WRITE: begin\n" << " if (widx <= wmax) begin\n" << " if (sram_EXCLUSIVE || sram_ack) begin\n" << " WVALID <= 1;\n" << " WDATA <= sram_rdata;\n" << " if (widx == wmax) begin\n" << " WLAST <= 1;\n" << " end\n" << " end\n" << " if (WREADY && WVALID) begin\n" << " widx <= widx + 1;\n" << " if (!sram_EXCLUSIVE) begin\n" << " WVALID <= 0;\n" << " end\n" << " end\n" << " end else begin\n" << " WVALID <= 0;\n" << " WLAST <= 0;\n" << " wst <= `WS_WAIT;\n" << " BREADY <= 1;\n" << " end\n" << " end\n" << " `WS_WAIT: begin\n" << " if (BVALID) begin\n" << " BREADY <= 0;\n" << " st <= `WS_IDLE;\n" << " end\n" << " end\n" << " endcase\n"; } } // namespace axi } // namespace verilog } // namespace writer } // namespace iroha <commit_msg>Fix to generate ack.<commit_after>#include "writer/verilog/axi/master_controller.h" #include "iroha/i_design.h" #include "writer/verilog/axi/master_port.h" #include "writer/verilog/module.h" #include "writer/verilog/ports.h" #include "writer/verilog/table.h" namespace iroha { namespace writer { namespace verilog { namespace axi { MasterController::MasterController(const IResource &res, bool reset_polarity) : AxiController(res, reset_polarity) { MasterPort::GetReadWrite(res_, &r_, &w_); } MasterController::~MasterController() { } void MasterController::Write(ostream &os) { AddSramPorts(); ports_->AddPort("addr", Port::INPUT, 32); ports_->AddPort("len", Port::INPUT, sram_addr_width_); ports_->AddPort("start", Port::INPUT, sram_addr_width_); ports_->AddPort("wen", Port::INPUT, 0); ports_->AddPort("req", Port::INPUT, 0); ports_->AddPort("ack", Port::OUTPUT, 0); string initials; GenReadChannel(cfg_, true, nullptr, ports_.get(), &initials); GenWriteChannel(cfg_, true, nullptr, ports_.get(), &initials); string name = MasterPort::ControllerName(res_, reset_polarity_); os << "module " << name << "("; ports_->Output(Ports::PORT_NAME, os); os << ");\n"; ports_->Output(Ports::PORT_TYPE, os); os << "\n" << " `define S_IDLE 0\n" << " `define S_ADDR_WAIT 1\n"; if (r_) { os << " `define S_READ_DATA 2\n" << " `define S_READ_DATA_WAIT 3\n"; } if (w_) { os << " `define S_WRITE_WAIT 4\n"; } os << " reg [2:0] st;\n\n"; if (w_) { os << " `define WS_IDLE 0\n" << " `define WS_WRITE 1\n" << " `define WS_WAIT 2\n" << " reg [1:0] wst;\n" << " reg [" << sram_addr_width_ << ":0] wmax;\n\n"; } if (r_) { os << " reg [" << sram_addr_width_ << ":0] ridx;\n" << " reg read_last;\n\n"; } if (r_) { os << " reg [" << sram_addr_width_ << ":0] widx;\n\n"; } os << " always @(posedge clk) begin\n" << " if (" << (reset_polarity_ ? "" : "!") << ResetName(reset_polarity_) << ") begin\n" << " ack <= 0;\n" << " sram_req <= 0;\n" << " sram_wen <= 0;\n" << " st <= `S_IDLE;\n"; if (w_) { os << " wst <= `WS_IDLE;\n" << " wmax <= 0;\n"; } os << initials << " end else begin\n"; OutputMainFsm(os); if (w_) { OutputWriterFsm(os); } os << " end\n" << " end\n" << "endmodule\n"; } void MasterController::AddPorts(const PortConfig &cfg, Module *mod, bool r, bool w, string *s) { Ports *ports = mod->GetPorts(); if (r) { GenReadChannel(cfg, true, mod, ports, s); } if (w) { GenWriteChannel(cfg, true, mod, ports, s); } } void MasterController::OutputMainFsm(ostream &os) { if (r_) { os << " if (sram_EXCLUSIVE) begin\n" << " sram_wen <= (st == `S_READ_DATA && RVALID);\n" << " end\n"; } else { os << " sram_wen <= 0;\n"; } os << " case (st)\n" << " `S_IDLE: begin\n"; if (r_ || w_) { os << " if (req) begin\n" << " ack <= 1;\n"; if (r_) { os << " ridx <= 0;\n"; } os << " st <= `S_ADDR_WAIT;\n"; if (r_ && !w_) { os << " ARVALID <= 1;\n" << " ARADDR <= addr;\n" << " ARLEN <= len;\n"; } if (!r_ && w_) { os << " AWVALID <= 1;\n" << " AWADDR <= addr;\n" << " AWLEN <= len;\n"; } if (r_ && w_) { os << " if (wen) begin\n" << " ARVALID <= 1;\n" << " ARADDR <= addr;\n" << " ARLEN <= len;\n" << " end else begin\n" << " AWVALID <= 1;\n" << " AWADDR <= addr;\n" << " AWLEN <= len;\n" << " wmax <= len;\n" << " end\n"; } os << " end\n"; } os << " end\n"; if (r_ || w_) { os << " `S_ADDR_WAIT: begin\n" << " ack <= 0;\n"; if (r_ && !w_) { os << " if (ARREADY) begin\n" << " st <= `S_READ_DATA;\n" << " ARVALID <= 0;\n" << " RREADY <= 1;\n" << " end\n"; } if (!r_ && w_) { os << " if (AWREADY) begin\n" << " st <= `S_WRITE_WAIT;\n" << " AWVALID <= 0;\n" << " end\n"; } if (r_ && w_) { os << " if (wen) begin\n" << " if (AWREADY) begin\n" << " st <= `S_WRITE_WAIT;\n" << " AWVALID <= 0;\n" << " sram_addr <= ridx;\n" << " end\n" << " end else begin\n" << " if (ARREADY) begin\n" << " st <= `S_READ_DATA;\n" << " RREADY <= 1;\n" << " end\n" << " end\n"; } os << " end\n"; } if (r_) { ReadState(os); } if (w_) { os << " `S_WRITE_WAIT: begin\n" << " if (BVALID) begin\n" << " st <= `S_IDLE;\n" << " end\n" << " if (wst == `WS_IDLE && req && wen) begin\n" << " sram_addr <= start;\n" << " if (!sram_EXCLUSIVE) begin\n" << " sram_req <= 1;\n" << " end\n" << " end\n" << " if (wst == `WS_WRITE) begin\n" << " if (WREADY && WVALID) begin\n" << " sram_addr <= sram_addr + 1;\n" << " if (!sram_EXCLUSIVE) begin\n" << " sram_req <= 1;\n" << " end\n" << " end else if (sram_ack && !sram_EXCLUSIVE) begin\n" << " sram_req <= 0;\n" << " end\n" << " end\n" << " end\n"; } os << " endcase\n"; } void MasterController::ReadState(ostream &os) { os << " `S_READ_DATA: begin\n" << " if (RVALID) begin\n" << " sram_addr <= start + ridx;\n" << " sram_wdata <= RDATA;\n" << " ridx <= ridx + 1;\n" << " if (sram_EXCLUSIVE) begin\n" << " if (RLAST) begin\n" << " RREADY <= 0;\n" << " st <= `S_IDLE;\n" << " end\n" << " end else begin\n" << " st <= `S_READ_DATA_WAIT;\n" << " sram_req <= 1;\n" << " sram_wen <= 1;\n" << " RREADY <= 0;\n" << " read_last <= RLAST;\n" << " end\n" << " end\n" << " end\n" << " `S_READ_DATA_WAIT: begin\n" // !sram_EXCLUSIVE << " if (sram_ack) begin\n" << " sram_req <= 0;\n" << " sram_wen <= 0;\n" << " if (read_last) begin\n" << " st <= `S_IDLE;\n" << " end else begin\n" << " st <= `S_READ_DATA;\n" << " RREADY <= 1;\n" << " end\n" << " end\n" << " end\n"; } void MasterController::OutputWriterFsm(ostream &os) { os << " case (wst)\n" << " `WS_IDLE: begin\n" << " if (req && wen) begin\n" << " wst <= `WS_WRITE;\n" << " widx <= 0;\n" << " end\n" << " end\n" << " `WS_WRITE: begin\n" << " if (widx <= wmax) begin\n" << " if (sram_EXCLUSIVE || sram_ack) begin\n" << " WVALID <= 1;\n" << " WDATA <= sram_rdata;\n" << " if (widx == wmax) begin\n" << " WLAST <= 1;\n" << " end\n" << " end\n" << " if (WREADY && WVALID) begin\n" << " widx <= widx + 1;\n" << " if (!sram_EXCLUSIVE) begin\n" << " WVALID <= 0;\n" << " end\n" << " end\n" << " end else begin\n" << " WVALID <= 0;\n" << " WLAST <= 0;\n" << " wst <= `WS_WAIT;\n" << " BREADY <= 1;\n" << " end\n" << " end\n" << " `WS_WAIT: begin\n" << " if (BVALID) begin\n" << " BREADY <= 0;\n" << " st <= `WS_IDLE;\n" << " end\n" << " end\n" << " endcase\n"; } } // namespace axi } // namespace verilog } // namespace writer } // namespace iroha <|endoftext|>
<commit_before>//============================================================================== // CellML file class //============================================================================== //---GRY--- NOTE THAT OUR CURRENT USE OF THE CellML API IS *WRONG*. INDEED, WE // ARE ASSUMING THAT THE BINARIES IMPLEMENT A CLEANED UP C++ INTERFACE // (SEE https://tracker.physiomeproject.org/show_bug.cgi?id=3108) WHILE // THIS IS NOT (YET) THE CASE. STILL, WE PREFER TO HAVE MEMORY LEAKS, // ETC. AND BE READY FOR WHEN BINARIES ARE UPDATED RATHER THAN HAVE // UGLY CODE, ETC. THIS BEING SAID, THERE IS STILL THE ISSUE OF // DECLARE_QUERY_INTERFACE_OBJREF WHICH CAN'T BE MIMICKED AT THIS POINT // (SEE https://tracker.physiomeproject.org/show_bug.cgi?id=3165) //============================================================================== #include "cellmlfile.h" //============================================================================== #include <QTime> #include <QUrl> //============================================================================== #include "IfaceVACSS.hxx" #include "CellMLBootstrap.hpp" #include "VACSSBootstrap.hpp" //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== CellmlFile::CellmlFile(const QString &pFileName) : mFileName(pFileName) { // Instantiate our runtime object mRuntime = new CellmlFileRuntime(); // Reset ourselves reset(); } //============================================================================== CellmlFile::~CellmlFile() { // Delete some internal objects delete mRuntime; } //============================================================================== void CellmlFile::reset() { // Reset all of the file's properties /*delete mModel;*/ mModel = 0; //---GRY--- WE CANNOT delete mModel AT THIS STAGE. FOR THIS, WE WOULD NEED // TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN COMMENT AT THE // BEGINNING OF THIS FILE) mIssues.clear(); mLoadingNeeded = true; mIsValidNeeded = true; mRuntimeUpdateNeeded = true; } //============================================================================== bool CellmlFile::load() { if (!mLoadingNeeded) // The file is already loaded, so... return true; // Reset any issues that we may have found before mIssues.clear(); // Get a bootstrap object ObjRef<iface::cellml_api::CellMLBootstrap> cellmlBootstrap = CreateCellMLBootstrap(); // Get its model loader ObjRef<iface::cellml_api::DOMModelLoader> modelLoader = cellmlBootstrap->modelLoader(); // Try to load the model try { QTime time; time.start(); mModel = modelLoader->loadFromURL(QUrl::fromLocalFile(mFileName).toString().toStdWString().c_str()); qDebug(" - CellML file - Loading time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); } catch (iface::cellml_api::CellMLException &) { // Something went wrong with the loading of the model, so... mIssues.append(CellmlFileIssue(CellmlFileIssue::Error, tr("the model could not be loaded (%1)").arg(QString::fromStdWString(modelLoader->lastErrorMessage())))); return false; } // In the case of a non CellML 1.0 model, we want all imports to be fully // instantiated if (QString::fromStdWString(mModel->cellmlVersion()).compare(Cellml_1_0)) try { QTime time; time.start(); mModel->fullyInstantiateImports(); qDebug(" - CellML full instantiation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); } catch (...) { // Something went wrong with the full instantiation of the imports, // so... reset(); mIssues.append(CellmlFileIssue(CellmlFileIssue::Error, tr("the model's imports could not be fully instantiated"))); return false; } // All done, so... mLoadingNeeded = false; return true; } //============================================================================== bool CellmlFile::reload() { // We want to reload the file, so we must first reset it reset(); // Now, we can try to (re)load the file return load(); } //============================================================================== bool CellmlFile::isValid() { if (!mIsValidNeeded) // The file has already been validated, so... return mIsValid; // Load (but not reload!) the file, if needed if (load()) { // The file was properly loaded (or was already loaded), so check // whether it is CellML valid // Note: validateModel() is somewhat slow, but there is (unfortunately) // nothing we can do about it. Then, there is getPositionInXML() // which is painfully slow, but unlike for validateModel() its use // is not essential (even though it would be nice from an // end-user's perspective). So, rather than retrieve the // line/column of every single warning/error, we only keep track // of the various warnings/errors and only retrieve their // corresponding line/column when requested (definitely not neat // from an end-user's perspective, but we just can't afford the // time it takes to fully validate a model that has many // warnings/errors)... QTime time; time.start(); ObjRef<iface::cellml_services::VACSService> vacssService = CreateVACSService(); ObjRef<iface::cellml_services::CellMLValidityErrorSet> cellmlValidityErrorSet = vacssService->validateModel(mModel); qDebug(" - CellML validation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); // Determine the number of errors and warnings // Note: CellMLValidityErrorSet::nValidityErrors() returns any type of // validation issue, be it an error or a warning, so we need to // determine the number of true errors uint32_t cellmlErrorsCount = 0; time.restart(); for (uint32_t i = 0, iMax = cellmlValidityErrorSet->nValidityErrors(); i < iMax; ++i) { ObjRef<iface::cellml_services::CellMLValidityError> cellmlValidityIssue = cellmlValidityErrorSet->getValidityError(i); DECLARE_QUERY_INTERFACE_OBJREF(cellmlRepresentationValidityError, cellmlValidityIssue, cellml_services::CellMLRepresentationValidityError); // Determine the issue's location uint32_t line = 0; uint32_t column = 0; QString importedFile = QString(); if (cellmlRepresentationValidityError) { // We are dealing with a CellML representation issue, so // determine its line and column ObjRef<iface::dom::Node> errorNode = cellmlRepresentationValidityError->errorNode(); line = vacssService->getPositionInXML(errorNode, cellmlRepresentationValidityError->errorNodalOffset(), &column); } else { // We are not dealing with a CellML representation issue, so // check whether we are dealing with a semantic one DECLARE_QUERY_INTERFACE_OBJREF(cellmlSemanticValidityError, cellmlValidityIssue, cellml_services::CellMLSemanticValidityError); if (cellmlSemanticValidityError) { // We are dealing with a CellML semantic issue, so determine // its line and column ObjRef<iface::cellml_api::CellMLElement> cellmlElement = cellmlSemanticValidityError->errorElement(); DECLARE_QUERY_INTERFACE_OBJREF(cellmlDomElement, cellmlElement, cellml_api::CellMLDOMElement); ObjRef<iface::dom::Element> domElement = cellmlDomElement->domElement(); line = vacssService->getPositionInXML(domElement, 0, &column); // Also determine its imported file, if any while (true) { // Retrieve the CellML element's parent iface::cellml_api::CellMLElement *cellmlElementParent = already_AddRefd<iface::cellml_api::CellMLElement>(cellmlElement->parentElement()); if (!cellmlElementParent) // There is no parent, so... break; // Check whether the parent is an imported file DECLARE_QUERY_INTERFACE_OBJREF(importedCellmlFile, cellmlElementParent, cellml_api::Model); if (!importedCellmlFile) // This is not an imported file, so... continue; // Retrieve the imported CellML element ObjRef<iface::cellml_api::CellMLElement> importedCellmlElement = importedCellmlFile->parentElement(); if (!importedCellmlElement) // This is not an imported CellML element, so... break; // Check whether the imported CellML element is an // import CellML element DECLARE_QUERY_INTERFACE(importCellmlElement, importedCellmlElement, cellml_api::CellMLImport); if (!importCellmlElement) // This is not an import CellML element, so... break; ObjRef<iface::cellml_api::URI> href = importCellmlElement->xlinkHref(); importedFile = QString::fromStdWString(href->asText()); break; } } } // Determine the issue's type CellmlFileIssue::Type issueType; if (cellmlValidityIssue->isWarningOnly()) { // We are dealing with a warning issueType = CellmlFileIssue::Warning; } else { // We are dealing with an error ++cellmlErrorsCount; issueType = CellmlFileIssue::Error; } // Append the issue to our list mIssues.append(CellmlFileIssue(issueType, QString::fromStdWString(cellmlValidityIssue->description()), line, column, importedFile)); } qDebug(" - CellML warnings vs. errors time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); if (cellmlErrorsCount) // There are CellML errors, so... mIsValid = false; else // Everything went as expected, so... mIsValid = true; mIsValidNeeded = false; return mIsValid; } else { // Something went wrong with the loading of the file, so... return false; } } //============================================================================== CellmlFileIssues CellmlFile::issues() { // Return the file's issue(s) return mIssues; } //============================================================================== CellmlFileRuntime * CellmlFile::runtime() { if (!mRuntimeUpdateNeeded) // There is no need for the runtime to be updated, so... return mRuntime; // Check whether the file is valid if (isValid()) { // The file is valid, so return an updated version of its runtime mRuntimeUpdateNeeded = false; return mRuntime->update(mModel); } else { // The file isn't valid, so reset its runtime return mRuntime->update(); } } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor editing.<commit_after>//============================================================================== // CellML file class //============================================================================== //---GRY--- NOTE THAT OUR CURRENT USE OF THE CellML API IS *WRONG*. INDEED, WE // ARE ASSUMING THAT THE BINARIES IMPLEMENT A CLEANED UP C++ INTERFACE // (SEE https://tracker.physiomeproject.org/show_bug.cgi?id=3108) WHILE // THIS IS NOT (YET) THE CASE. STILL, WE PREFER TO HAVE MEMORY LEAKS, // ETC. AND BE READY FOR WHEN BINARIES ARE UPDATED RATHER THAN HAVE // UGLY CODE, ETC. THIS BEING SAID, THERE IS STILL THE ISSUE OF // DECLARE_QUERY_INTERFACE_OBJREF WHICH CAN'T BE MIMICKED AT THIS POINT // (SEE https://tracker.physiomeproject.org/show_bug.cgi?id=3165) //============================================================================== #include "cellmlfile.h" //============================================================================== #include <QTime> #include <QUrl> //============================================================================== #include "IfaceVACSS.hxx" #include "CellMLBootstrap.hpp" #include "VACSSBootstrap.hpp" //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== CellmlFile::CellmlFile(const QString &pFileName) : mFileName(pFileName) { // Instantiate our runtime object mRuntime = new CellmlFileRuntime(); // Reset ourselves reset(); } //============================================================================== CellmlFile::~CellmlFile() { // Delete some internal objects delete mRuntime; } //============================================================================== void CellmlFile::reset() { // Reset all of the file's properties /*delete mModel;*/ mModel = 0; //---GRY--- WE CANNOT delete mModel AT THIS STAGE. FOR THIS, WE WOULD NEED // TO USE THE CLEANED UP C++ INTERFACE (SEE THE MAIN COMMENT AT THE // BEGINNING OF THIS FILE) mIssues.clear(); mLoadingNeeded = true; mIsValidNeeded = true; mRuntimeUpdateNeeded = true; } //============================================================================== bool CellmlFile::load() { if (!mLoadingNeeded) // The file is already loaded, so... return true; // Reset any issues that we may have found before mIssues.clear(); // Get a bootstrap object ObjRef<iface::cellml_api::CellMLBootstrap> cellmlBootstrap = CreateCellMLBootstrap(); // Get its model loader ObjRef<iface::cellml_api::DOMModelLoader> modelLoader = cellmlBootstrap->modelLoader(); // Try to load the model try { QTime time; time.start(); mModel = modelLoader->loadFromURL(QUrl::fromLocalFile(mFileName).toString().toStdWString().c_str()); qDebug(" - CellML Loading time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); } catch (iface::cellml_api::CellMLException &) { // Something went wrong with the loading of the model, so... mIssues.append(CellmlFileIssue(CellmlFileIssue::Error, tr("the model could not be loaded (%1)").arg(QString::fromStdWString(modelLoader->lastErrorMessage())))); return false; } // In the case of a non CellML 1.0 model, we want all imports to be fully // instantiated if (QString::fromStdWString(mModel->cellmlVersion()).compare(Cellml_1_0)) try { QTime time; time.start(); mModel->fullyInstantiateImports(); qDebug(" - CellML full instantiation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); } catch (...) { // Something went wrong with the full instantiation of the imports, // so... reset(); mIssues.append(CellmlFileIssue(CellmlFileIssue::Error, tr("the model's imports could not be fully instantiated"))); return false; } // All done, so... mLoadingNeeded = false; return true; } //============================================================================== bool CellmlFile::reload() { // We want to reload the file, so we must first reset it reset(); // Now, we can try to (re)load the file return load(); } //============================================================================== bool CellmlFile::isValid() { if (!mIsValidNeeded) // The file has already been validated, so... return mIsValid; // Load (but not reload!) the file, if needed if (load()) { // The file was properly loaded (or was already loaded), so check // whether it is CellML valid // Note: validateModel() is somewhat slow, but there is (unfortunately) // nothing we can do about it. Then, there is getPositionInXML() // which is painfully slow, but unlike for validateModel() its use // is not essential (even though it would be nice from an // end-user's perspective). So, rather than retrieve the // line/column of every single warning/error, we only keep track // of the various warnings/errors and only retrieve their // corresponding line/column when requested (definitely not neat // from an end-user's perspective, but we just can't afford the // time it takes to fully validate a model that has many // warnings/errors)... QTime time; time.start(); ObjRef<iface::cellml_services::VACSService> vacssService = CreateVACSService(); ObjRef<iface::cellml_services::CellMLValidityErrorSet> cellmlValidityErrorSet = vacssService->validateModel(mModel); qDebug(" - CellML validation time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); // Determine the number of errors and warnings // Note: CellMLValidityErrorSet::nValidityErrors() returns any type of // validation issue, be it an error or a warning, so we need to // determine the number of true errors uint32_t cellmlErrorsCount = 0; time.restart(); for (uint32_t i = 0, iMax = cellmlValidityErrorSet->nValidityErrors(); i < iMax; ++i) { ObjRef<iface::cellml_services::CellMLValidityError> cellmlValidityIssue = cellmlValidityErrorSet->getValidityError(i); DECLARE_QUERY_INTERFACE_OBJREF(cellmlRepresentationValidityError, cellmlValidityIssue, cellml_services::CellMLRepresentationValidityError); // Determine the issue's location uint32_t line = 0; uint32_t column = 0; QString importedFile = QString(); if (cellmlRepresentationValidityError) { // We are dealing with a CellML representation issue, so // determine its line and column ObjRef<iface::dom::Node> errorNode = cellmlRepresentationValidityError->errorNode(); line = vacssService->getPositionInXML(errorNode, cellmlRepresentationValidityError->errorNodalOffset(), &column); } else { // We are not dealing with a CellML representation issue, so // check whether we are dealing with a semantic one DECLARE_QUERY_INTERFACE_OBJREF(cellmlSemanticValidityError, cellmlValidityIssue, cellml_services::CellMLSemanticValidityError); if (cellmlSemanticValidityError) { // We are dealing with a CellML semantic issue, so determine // its line and column ObjRef<iface::cellml_api::CellMLElement> cellmlElement = cellmlSemanticValidityError->errorElement(); DECLARE_QUERY_INTERFACE_OBJREF(cellmlDomElement, cellmlElement, cellml_api::CellMLDOMElement); ObjRef<iface::dom::Element> domElement = cellmlDomElement->domElement(); line = vacssService->getPositionInXML(domElement, 0, &column); // Also determine its imported file, if any while (true) { // Retrieve the CellML element's parent iface::cellml_api::CellMLElement *cellmlElementParent = already_AddRefd<iface::cellml_api::CellMLElement>(cellmlElement->parentElement()); if (!cellmlElementParent) // There is no parent, so... break; // Check whether the parent is an imported file DECLARE_QUERY_INTERFACE_OBJREF(importedCellmlFile, cellmlElementParent, cellml_api::Model); if (!importedCellmlFile) // This is not an imported file, so... continue; // Retrieve the imported CellML element ObjRef<iface::cellml_api::CellMLElement> importedCellmlElement = importedCellmlFile->parentElement(); if (!importedCellmlElement) // This is not an imported CellML element, so... break; // Check whether the imported CellML element is an // import CellML element DECLARE_QUERY_INTERFACE(importCellmlElement, importedCellmlElement, cellml_api::CellMLImport); if (!importCellmlElement) // This is not an import CellML element, so... break; ObjRef<iface::cellml_api::URI> href = importCellmlElement->xlinkHref(); importedFile = QString::fromStdWString(href->asText()); break; } } } // Determine the issue's type CellmlFileIssue::Type issueType; if (cellmlValidityIssue->isWarningOnly()) { // We are dealing with a warning issueType = CellmlFileIssue::Warning; } else { // We are dealing with an error ++cellmlErrorsCount; issueType = CellmlFileIssue::Error; } // Append the issue to our list mIssues.append(CellmlFileIssue(issueType, QString::fromStdWString(cellmlValidityIssue->description()), line, column, importedFile)); } qDebug(" - CellML warnings vs. errors time: %s s", qPrintable(QString::number(0.001*time.elapsed(), 'g', 3))); if (cellmlErrorsCount) // There are CellML errors, so... mIsValid = false; else // Everything went as expected, so... mIsValid = true; mIsValidNeeded = false; return mIsValid; } else { // Something went wrong with the loading of the file, so... return false; } } //============================================================================== CellmlFileIssues CellmlFile::issues() { // Return the file's issue(s) return mIssues; } //============================================================================== CellmlFileRuntime * CellmlFile::runtime() { if (!mRuntimeUpdateNeeded) // There is no need for the runtime to be updated, so... return mRuntime; // Check whether the file is valid if (isValid()) { // The file is valid, so return an updated version of its runtime mRuntimeUpdateNeeded = false; return mRuntime->update(mModel); } else { // The file isn't valid, so reset its runtime return mRuntime->update(); } } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "include/dart_api.h" #include "platform/assert.h" #include "vm/globals.h" #include "vm/isolate.h" #include "vm/lockers.h" #include "vm/thread_pool.h" #include "vm/unit_test.h" namespace dart { UNIT_TEST_CASE(IsolateCurrent) { Dart_Isolate isolate = Dart_CreateIsolate( NULL, NULL, bin::isolate_snapshot_buffer, NULL, NULL, NULL); EXPECT_EQ(isolate, Dart_CurrentIsolate()); Dart_ShutdownIsolate(); EXPECT_EQ(reinterpret_cast<Dart_Isolate>(NULL), Dart_CurrentIsolate()); } // Test to ensure that an exception is thrown if no isolate creation // callback has been set by the embedder when an isolate is spawned. TEST_CASE(IsolateSpawn) { const char* kScriptChars = "import 'dart:isolate';\n" // Ignores printed lines. "var _nullPrintClosure = (String line) {};\n" "void entry(message) {}\n" "int testMain() {\n" " Isolate.spawn(entry, null);\n" // TODO(floitsch): the following code is only to bump the event loop // so it executes asynchronous microtasks. " var rp = new RawReceivePort();\n" " rp.sendPort.send(null);\n" " rp.handler = (_) { rp.close(); };\n" "}\n"; Dart_Handle test_lib = TestCase::LoadTestScript(kScriptChars, NULL); // Setup the internal library's 'internalPrint' function. // Necessary because asynchronous errors use "print" to print their // stack trace. Dart_Handle url = NewString("dart:_internal"); DART_CHECK_VALID(url); Dart_Handle internal_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(internal_lib); Dart_Handle print = Dart_GetField(test_lib, NewString("_nullPrintClosure")); Dart_Handle result = Dart_SetField(internal_lib, NewString("_printClosure"), print); DART_CHECK_VALID(result); // Setup the 'scheduleImmediate' closure. url = NewString("dart:isolate"); DART_CHECK_VALID(url); Dart_Handle isolate_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(isolate_lib); Dart_Handle schedule_immediate_closure = Dart_Invoke(isolate_lib, NewString("_getIsolateScheduleImmediateClosure"), 0, NULL); Dart_Handle args[1]; args[0] = schedule_immediate_closure; url = NewString("dart:async"); DART_CHECK_VALID(url); Dart_Handle async_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(async_lib); DART_CHECK_VALID(Dart_Invoke( async_lib, NewString("_setScheduleImmediateClosure"), 1, args)); result = Dart_Invoke(test_lib, NewString("testMain"), 0, NULL); EXPECT(!Dart_IsError(result)); // Run until all ports to isolate are closed. result = Dart_RunLoop(); EXPECT_ERROR(result, "Null callback specified for isolate creation"); EXPECT(Dart_ErrorHasException(result)); Dart_Handle exception_result = Dart_ErrorGetException(result); EXPECT_VALID(exception_result); } class InterruptChecker : public ThreadPool::Task { public: static const intptr_t kTaskCount; static const intptr_t kIterations; InterruptChecker(Isolate* isolate, Monitor* awake_monitor, bool* awake, Monitor* round_monitor, const intptr_t* round) : isolate_(isolate), awake_monitor_(awake_monitor), awake_(awake), round_monitor_(round_monitor), round_(round) { } virtual void Run() { Thread::EnterIsolateAsHelper(isolate_); // Tell main thread that we are ready. { MonitorLocker ml(awake_monitor_); ASSERT(!*awake_); *awake_ = true; ml.Notify(); } for (intptr_t i = 0; i < kIterations; ++i) { // Busy wait for interrupts. while (!isolate_->HasInterruptsScheduled(Isolate::kVMInterrupt)) { // Do nothing. } // Tell main thread that we observed the interrupt. { MonitorLocker ml(awake_monitor_); ASSERT(!*awake_); *awake_ = true; ml.Notify(); } // Wait for main thread to let us resume, i.e., until all tasks are here. { MonitorLocker ml(round_monitor_); EXPECT(*round_ == i || *round_ == (i + 1)); while (*round_ == i) { ml.Wait(); } EXPECT(*round_ == i + 1); } } Thread::ExitIsolateAsHelper(); // Use awake also to signal exit. { MonitorLocker ml(awake_monitor_); *awake_ = true; ml.Notify(); } } private: Isolate* isolate_; Monitor* awake_monitor_; bool* awake_; Monitor* round_monitor_; const intptr_t* round_; }; const intptr_t InterruptChecker::kTaskCount = 50; const intptr_t InterruptChecker::kIterations = 1000; // Waits for all tasks to set their individual flag, then clears them all. static void WaitForAllTasks(bool* flags, Monitor* monitor) { MonitorLocker ml(monitor); while (true) { intptr_t count = 0; for (intptr_t task = 0; task < InterruptChecker::kTaskCount; ++task) { if (flags[task]) { ++count; } } if (count == InterruptChecker::kTaskCount) { memset(flags, 0, sizeof(*flags) * count); break; } else { ml.Wait(); } } } // Test and document usage of Isolate::HasInterruptsScheduled. // // Go through a number of rounds of scheduling interrupts and waiting until all // unsynchronized busy-waiting tasks observe it (in the current implementation, // the exact latency depends on cache coherence). Synchronization is then used // to ensure that the response to the interrupt, i.e., starting a new round, // happens *after* the interrupt is observed. Without this synchronization, the // compiler and/or CPU could reorder operations to make the tasks observe the // round update *before* the interrupt is set. TEST_CASE(StackLimitInterrupts) { Monitor awake_monitor; // Synchronizes the 'awake' flags. bool awake[InterruptChecker::kTaskCount]; memset(awake, 0, sizeof(awake)); Monitor round_monitor; // Synchronizes the 'round' counter. intptr_t round = 0; Isolate* isolate = Thread::Current()->isolate(); // Start all tasks. They will busy-wait until interrupted in the first round. for (intptr_t task = 0; task < InterruptChecker::kTaskCount; task++) { Dart::thread_pool()->Run(new InterruptChecker( isolate, &awake_monitor, &awake[task], &round_monitor, &round)); } // Wait for all tasks to get ready for the first round. WaitForAllTasks(awake, &awake_monitor); for (intptr_t i = 0; i < InterruptChecker::kIterations; ++i) { isolate->ScheduleInterrupts(Isolate::kVMInterrupt); // Wait for all tasks to observe the interrupt. WaitForAllTasks(awake, &awake_monitor); // Continue with next round. uword interrupts = isolate->GetAndClearInterrupts(); EXPECT((interrupts & Isolate::kVMInterrupt) != 0); { MonitorLocker ml(&round_monitor); ++round; ml.NotifyAll(); } } // Wait for tasks to exit cleanly. WaitForAllTasks(awake, &awake_monitor); } } // namespace dart <commit_msg>Reduce size of test StackLimitInterrupts to avoid Win timeouts.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "include/dart_api.h" #include "platform/assert.h" #include "vm/globals.h" #include "vm/isolate.h" #include "vm/lockers.h" #include "vm/thread_pool.h" #include "vm/unit_test.h" namespace dart { UNIT_TEST_CASE(IsolateCurrent) { Dart_Isolate isolate = Dart_CreateIsolate( NULL, NULL, bin::isolate_snapshot_buffer, NULL, NULL, NULL); EXPECT_EQ(isolate, Dart_CurrentIsolate()); Dart_ShutdownIsolate(); EXPECT_EQ(reinterpret_cast<Dart_Isolate>(NULL), Dart_CurrentIsolate()); } // Test to ensure that an exception is thrown if no isolate creation // callback has been set by the embedder when an isolate is spawned. TEST_CASE(IsolateSpawn) { const char* kScriptChars = "import 'dart:isolate';\n" // Ignores printed lines. "var _nullPrintClosure = (String line) {};\n" "void entry(message) {}\n" "int testMain() {\n" " Isolate.spawn(entry, null);\n" // TODO(floitsch): the following code is only to bump the event loop // so it executes asynchronous microtasks. " var rp = new RawReceivePort();\n" " rp.sendPort.send(null);\n" " rp.handler = (_) { rp.close(); };\n" "}\n"; Dart_Handle test_lib = TestCase::LoadTestScript(kScriptChars, NULL); // Setup the internal library's 'internalPrint' function. // Necessary because asynchronous errors use "print" to print their // stack trace. Dart_Handle url = NewString("dart:_internal"); DART_CHECK_VALID(url); Dart_Handle internal_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(internal_lib); Dart_Handle print = Dart_GetField(test_lib, NewString("_nullPrintClosure")); Dart_Handle result = Dart_SetField(internal_lib, NewString("_printClosure"), print); DART_CHECK_VALID(result); // Setup the 'scheduleImmediate' closure. url = NewString("dart:isolate"); DART_CHECK_VALID(url); Dart_Handle isolate_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(isolate_lib); Dart_Handle schedule_immediate_closure = Dart_Invoke(isolate_lib, NewString("_getIsolateScheduleImmediateClosure"), 0, NULL); Dart_Handle args[1]; args[0] = schedule_immediate_closure; url = NewString("dart:async"); DART_CHECK_VALID(url); Dart_Handle async_lib = Dart_LookupLibrary(url); DART_CHECK_VALID(async_lib); DART_CHECK_VALID(Dart_Invoke( async_lib, NewString("_setScheduleImmediateClosure"), 1, args)); result = Dart_Invoke(test_lib, NewString("testMain"), 0, NULL); EXPECT(!Dart_IsError(result)); // Run until all ports to isolate are closed. result = Dart_RunLoop(); EXPECT_ERROR(result, "Null callback specified for isolate creation"); EXPECT(Dart_ErrorHasException(result)); Dart_Handle exception_result = Dart_ErrorGetException(result); EXPECT_VALID(exception_result); } class InterruptChecker : public ThreadPool::Task { public: static const intptr_t kTaskCount; static const intptr_t kIterations; InterruptChecker(Isolate* isolate, Monitor* awake_monitor, bool* awake, Monitor* round_monitor, const intptr_t* round) : isolate_(isolate), awake_monitor_(awake_monitor), awake_(awake), round_monitor_(round_monitor), round_(round) { } virtual void Run() { Thread::EnterIsolateAsHelper(isolate_); // Tell main thread that we are ready. { MonitorLocker ml(awake_monitor_); ASSERT(!*awake_); *awake_ = true; ml.Notify(); } for (intptr_t i = 0; i < kIterations; ++i) { // Busy wait for interrupts. while (!isolate_->HasInterruptsScheduled(Isolate::kVMInterrupt)) { // Do nothing. } // Tell main thread that we observed the interrupt. { MonitorLocker ml(awake_monitor_); ASSERT(!*awake_); *awake_ = true; ml.Notify(); } // Wait for main thread to let us resume, i.e., until all tasks are here. { MonitorLocker ml(round_monitor_); EXPECT(*round_ == i || *round_ == (i + 1)); while (*round_ == i) { ml.Wait(); } EXPECT(*round_ == i + 1); } } Thread::ExitIsolateAsHelper(); // Use awake also to signal exit. { MonitorLocker ml(awake_monitor_); *awake_ = true; ml.Notify(); } } private: Isolate* isolate_; Monitor* awake_monitor_; bool* awake_; Monitor* round_monitor_; const intptr_t* round_; }; const intptr_t InterruptChecker::kTaskCount = 5; const intptr_t InterruptChecker::kIterations = 10; // Waits for all tasks to set their individual flag, then clears them all. static void WaitForAllTasks(bool* flags, Monitor* monitor) { MonitorLocker ml(monitor); while (true) { intptr_t count = 0; for (intptr_t task = 0; task < InterruptChecker::kTaskCount; ++task) { if (flags[task]) { ++count; } } if (count == InterruptChecker::kTaskCount) { memset(flags, 0, sizeof(*flags) * count); break; } else { ml.Wait(); } } } // Test and document usage of Isolate::HasInterruptsScheduled. // // Go through a number of rounds of scheduling interrupts and waiting until all // unsynchronized busy-waiting tasks observe it (in the current implementation, // the exact latency depends on cache coherence). Synchronization is then used // to ensure that the response to the interrupt, i.e., starting a new round, // happens *after* the interrupt is observed. Without this synchronization, the // compiler and/or CPU could reorder operations to make the tasks observe the // round update *before* the interrupt is set. TEST_CASE(StackLimitInterrupts) { Monitor awake_monitor; // Synchronizes the 'awake' flags. bool awake[InterruptChecker::kTaskCount]; memset(awake, 0, sizeof(awake)); Monitor round_monitor; // Synchronizes the 'round' counter. intptr_t round = 0; Isolate* isolate = Thread::Current()->isolate(); // Start all tasks. They will busy-wait until interrupted in the first round. for (intptr_t task = 0; task < InterruptChecker::kTaskCount; task++) { Dart::thread_pool()->Run(new InterruptChecker( isolate, &awake_monitor, &awake[task], &round_monitor, &round)); } // Wait for all tasks to get ready for the first round. WaitForAllTasks(awake, &awake_monitor); for (intptr_t i = 0; i < InterruptChecker::kIterations; ++i) { isolate->ScheduleInterrupts(Isolate::kVMInterrupt); // Wait for all tasks to observe the interrupt. WaitForAllTasks(awake, &awake_monitor); // Continue with next round. uword interrupts = isolate->GetAndClearInterrupts(); EXPECT((interrupts & Isolate::kVMInterrupt) != 0); { MonitorLocker ml(&round_monitor); ++round; ml.NotifyAll(); } } // Wait for tasks to exit cleanly. WaitForAllTasks(awake, &awake_monitor); } } // namespace dart <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cmdargs.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: mhu $ $Date: 2002-07-23 12:41:07 $ * * 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 <osl/mutex.hxx> #include <rtl/process.h> #include <rtl/ustring.hxx> #include "macro.hxx" rtl_uString ** g_ppCommandArgs = 0; sal_uInt32 g_nCommandArgCount = 0; struct rtl_CmdArgs_ArgHolder { ~rtl_CmdArgs_ArgHolder(); }; rtl_CmdArgs_ArgHolder::~rtl_CmdArgs_ArgHolder() { while (g_nCommandArgCount > 0) rtl_uString_release (g_ppCommandArgs[--g_nCommandArgCount]); rtl_freeMemory (g_ppCommandArgs); g_ppCommandArgs = 0; } static rtl_CmdArgs_ArgHolder MyHolder; static void impl_rtl_initCommandArgs() { osl::MutexGuard guard( osl::Mutex::getGlobalMutex() ); if (!g_ppCommandArgs) { sal_Int32 i, n = osl_getCommandArgCount(); g_ppCommandArgs = (rtl_uString**)rtl_allocateZeroMemory (n * sizeof(rtl_uString*)); for (i = 0; i < n; i++) { rtl_uString * pArg = 0; osl_getCommandArg (i, &pArg); if (('-' == pArg->buffer[0] || '/' == pArg->buffer[0]) && 'e' == pArg->buffer[1] && 'n' == pArg->buffer[2] && 'v' == pArg->buffer[3] && ':' == pArg->buffer[4] && rtl_ustr_indexOfChar (&(pArg->buffer[5]), '=') >= 0 ) { // ignore. rtl_uString_release (pArg); } else { // assign. g_ppCommandArgs[g_nCommandArgCount++] = pArg; } } } } oslProcessError SAL_CALL rtl_getAppCommandArg ( sal_uInt32 nArg, rtl_uString **ppCommandArg) { if (!g_ppCommandArgs) impl_rtl_initCommandArgs(); oslProcessError result = osl_Process_E_NotFound; if( nArg < g_nCommandArgCount ) { rtl::OUString expandedArg (expandMacros(NULL, g_ppCommandArgs[nArg])); rtl_uString_assign( ppCommandArg, expandedArg.pData ); result = osl_Process_E_None; } return (result); } sal_uInt32 SAL_CALL rtl_getAppCommandArgCount (void) { if (!g_ppCommandArgs) impl_rtl_initCommandArgs(); return g_nCommandArgCount; } <commit_msg>INTEGRATION: CWS tune04 (1.5.274); FILE MERGED 2004/06/14 09:56:25 cmc 1.5.274.1: #i29636# turn global objects into local static data<commit_after>/************************************************************************* * * $RCSfile: cmdargs.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hjs $ $Date: 2004-06-25 17:14:59 $ * * 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 <osl/mutex.hxx> #include <rtl/process.h> #include <rtl/ustring.hxx> #include "macro.hxx" rtl_uString ** g_ppCommandArgs = 0; sal_uInt32 g_nCommandArgCount = 0; struct rtl_CmdArgs_ArgHolder { ~rtl_CmdArgs_ArgHolder(); }; rtl_CmdArgs_ArgHolder::~rtl_CmdArgs_ArgHolder() { while (g_nCommandArgCount > 0) rtl_uString_release (g_ppCommandArgs[--g_nCommandArgCount]); rtl_freeMemory (g_ppCommandArgs); g_ppCommandArgs = 0; } static void impl_rtl_initCommandArgs() { osl::MutexGuard guard( osl::Mutex::getGlobalMutex() ); static rtl_CmdArgs_ArgHolder MyHolder; if (!g_ppCommandArgs) { sal_Int32 i, n = osl_getCommandArgCount(); g_ppCommandArgs = (rtl_uString**)rtl_allocateZeroMemory (n * sizeof(rtl_uString*)); for (i = 0; i < n; i++) { rtl_uString * pArg = 0; osl_getCommandArg (i, &pArg); if (('-' == pArg->buffer[0] || '/' == pArg->buffer[0]) && 'e' == pArg->buffer[1] && 'n' == pArg->buffer[2] && 'v' == pArg->buffer[3] && ':' == pArg->buffer[4] && rtl_ustr_indexOfChar (&(pArg->buffer[5]), '=') >= 0 ) { // ignore. rtl_uString_release (pArg); } else { // assign. g_ppCommandArgs[g_nCommandArgCount++] = pArg; } } } } oslProcessError SAL_CALL rtl_getAppCommandArg ( sal_uInt32 nArg, rtl_uString **ppCommandArg) { if (!g_ppCommandArgs) impl_rtl_initCommandArgs(); oslProcessError result = osl_Process_E_NotFound; if( nArg < g_nCommandArgCount ) { rtl::OUString expandedArg (expandMacros(NULL, g_ppCommandArgs[nArg])); rtl_uString_assign( ppCommandArg, expandedArg.pData ); result = osl_Process_E_None; } return (result); } sal_uInt32 SAL_CALL rtl_getAppCommandArgCount (void) { if (!g_ppCommandArgs) impl_rtl_initCommandArgs(); return g_nCommandArgCount; } <|endoftext|>
<commit_before>#include "microflo.h" Packet::Packet() : buf('0') , boolean(false) , msg(MsgInvalid) {} Packet::Packet(char c) : buf(c) , boolean(false) , msg(MsgCharacter) {} Packet::Packet(bool b) : buf('0') , boolean(b) , msg(MsgBoolean) {} Packet::Packet(Msg _msg) : buf('0') , boolean(false) , msg(_msg) {} GraphStreamer::GraphStreamer() : network(0) , currentByte(0) , state(ParseHeader) {} void GraphStreamer::parseByte(char b) { buffer[currentByte++] = b; // printf("%s: state=%d, currentByte=%d, input=%d\n", __PRETTY_FUNCTION__, state, currentByte, b); if (state == ParseHeader) { if (currentByte == GRAPH_MAGIC_SIZE) { // FIXME: duplication of magic definition if (buffer[0] == 'u' && buffer[1] == 'C' && buffer[2] == '/', buffer[3] == 'F', buffer[4] == 'l', buffer[5] == 'o') { state = ParseCmd; } else { state = Invalid; } currentByte = 0; } } else if (state == ParseCmd) { if (currentByte == GRAPH_CMD_SIZE) { GraphCmd cmd = (GraphCmd)buffer[0]; if (cmd >= GraphCmdInvalid) { state = Invalid; // XXX: or maybe just ignore? } else { if (cmd == GraphCmdReset) { // TODO: implement } else if (cmd == GraphCmdCreateComponent) { ComponentId id = (ComponentId)buffer[1]; // FIXME: validate network->addNode(Component::create(id)); } else if (cmd == GraphCmdConnectNodes) { // FIXME: validate int src = (unsigned int)buffer[1]; int target = (unsigned int)buffer[2]; network->connectTo(src, target); } } currentByte = 0; } } else if (state == Invalid) { currentByte = 0; // avoid overflow } else { } } void Component::send(Packet out) { network->sendMessage(connection.target, out, this); } #ifdef ARDUINO void Debugger::setup(Network *network) { Serial.begin(9600); network->setNotifications(&Debugger::printSend, &Debugger::printDeliver); } // FIXME: print async, currently output gets truncated on networks with > 3 edges void Debugger::printPacket(Packet *p) { Serial.print("Packet("); Serial.print("type="); Serial.print(p->msg); Serial.print(","); Serial.print(")"); } void Debugger::printSend(int index, Message m, Component *sender) { Serial.print("SEND: "); Serial.print("index="); Serial.print(index); Serial.print(","); Serial.print("from="); Serial.print((unsigned long)sender); Serial.print(","); Serial.print("to="); Serial.print((unsigned long)m.target); Serial.print(" "); printPacket(&m.pkg); Serial.println(); } void Debugger::printDeliver(int index, Message m) { Serial.print("DELIVER: "); Serial.print("index="); Serial.print(index); Serial.print(","); Serial.print("to="); Serial.print((unsigned long)m.target); Serial.print(" "); printPacket(&m.pkg); Serial.println(); } #endif Network::Network() : lastAddedNodeIndex(0) , messageWriteIndex(0) , messageReadIndex(0) , messageSentNotify(0) , messageDeliveredNotify(0) { for (int i=0; i<MAX_NODES; i++) { nodes[i] = 0; } } void Network::setNotifications(MessageSendNotification send, MessageDeliveryNotification deliver) { messageSentNotify = send; messageDeliveredNotify = deliver; } void Network::deliverMessages(int firstIndex, int lastIndex) { if (firstIndex > lastIndex || lastIndex > MAX_MESSAGES-1 || firstIndex < 0) { return; } for (int i=firstIndex; i<=lastIndex; i++) { messages[i].target->process(messages[i].pkg); if (messageDeliveredNotify) { messageDeliveredNotify(i, messages[i]); } } } void Network::processMessages() { if (messageReadIndex > messageWriteIndex) { deliverMessages(messageReadIndex, MAX_MESSAGES-1); deliverMessages(0, messageWriteIndex); } else if (messageReadIndex < messageWriteIndex) { deliverMessages(messageReadIndex, messageWriteIndex); } else { // no messages } messageReadIndex = messageWriteIndex; } void Network::sendMessage(Component *target, Packet &pkg, Component *sender) { if (messageWriteIndex > MAX_MESSAGES-1) { messageWriteIndex = 0; } Message &msg = messages[messageWriteIndex++]; msg.target = target; msg.pkg = pkg; if (messageSentNotify) { messageSentNotify(messageWriteIndex-1, msg, sender); } } void Network::runSetup() { for (int i=0; i<MAX_NODES; i++) { if (nodes[i]) { nodes[i]->process(Packet(MsgSetup)); } } } void Network::runTick() { // TODO: consider the balance between scheduling and messaging (bounded-buffer problem) // Deliver messages processMessages(); // Schedule for (int i=0; i<MAX_NODES; i++) { Component *t = nodes[i]; if (t) { t->process(Packet(MsgTick)); } } } void Network::connectTo(int srcId, int targetId) { if (srcId < 0 || srcId > lastAddedNodeIndex || targetId < 0 || targetId > lastAddedNodeIndex) { return; } connectTo(nodes[srcId], nodes[targetId]); } void Network::connectTo(Component *src, Component *target) { src->connectTo(target); } int Network::addNode(Component *node) { nodes[lastAddedNodeIndex++] = node; node->setNetwork(this); return lastAddedNodeIndex; } <commit_msg>Fix message delivery bug if component sent messages during delivery<commit_after>#include "microflo.h" Packet::Packet() : buf('0') , boolean(false) , msg(MsgInvalid) {} Packet::Packet(char c) : buf(c) , boolean(false) , msg(MsgCharacter) {} Packet::Packet(bool b) : buf('0') , boolean(b) , msg(MsgBoolean) {} Packet::Packet(Msg _msg) : buf('0') , boolean(false) , msg(_msg) {} GraphStreamer::GraphStreamer() : network(0) , currentByte(0) , state(ParseHeader) {} void GraphStreamer::parseByte(char b) { buffer[currentByte++] = b; // printf("%s: state=%d, currentByte=%d, input=%d\n", __PRETTY_FUNCTION__, state, currentByte, b); if (state == ParseHeader) { if (currentByte == GRAPH_MAGIC_SIZE) { // FIXME: duplication of magic definition if (buffer[0] == 'u' && buffer[1] == 'C' && buffer[2] == '/', buffer[3] == 'F', buffer[4] == 'l', buffer[5] == 'o') { state = ParseCmd; } else { state = Invalid; } currentByte = 0; } } else if (state == ParseCmd) { if (currentByte == GRAPH_CMD_SIZE) { GraphCmd cmd = (GraphCmd)buffer[0]; if (cmd >= GraphCmdInvalid) { state = Invalid; // XXX: or maybe just ignore? } else { if (cmd == GraphCmdReset) { // TODO: implement } else if (cmd == GraphCmdCreateComponent) { ComponentId id = (ComponentId)buffer[1]; // FIXME: validate network->addNode(Component::create(id)); } else if (cmd == GraphCmdConnectNodes) { // FIXME: validate int src = (unsigned int)buffer[1]; int target = (unsigned int)buffer[2]; network->connectTo(src, target); } } currentByte = 0; } } else if (state == Invalid) { currentByte = 0; // avoid overflow } else { } } void Component::send(Packet out) { network->sendMessage(connection.target, out, this); } #ifdef ARDUINO void Debugger::setup(Network *network) { Serial.begin(9600); network->setNotifications(&Debugger::printSend, &Debugger::printDeliver); } // FIXME: print async, currently output gets truncated on networks with > 3 edges void Debugger::printPacket(Packet *p) { Serial.print("Packet("); Serial.print("type="); Serial.print(p->msg); Serial.print(","); Serial.print(")"); } void Debugger::printSend(int index, Message m, Component *sender) { Serial.print("SEND: "); Serial.print("index="); Serial.print(index); Serial.print(","); Serial.print("from="); Serial.print((unsigned long)sender); Serial.print(","); Serial.print("to="); Serial.print((unsigned long)m.target); Serial.print(" "); printPacket(&m.pkg); Serial.println(); } void Debugger::printDeliver(int index, Message m) { Serial.print("DELIVER: "); Serial.print("index="); Serial.print(index); Serial.print(","); Serial.print("to="); Serial.print((unsigned long)m.target); Serial.print(" "); printPacket(&m.pkg); Serial.println(); } #endif Network::Network() : lastAddedNodeIndex(0) , messageWriteIndex(0) , messageReadIndex(0) , messageSentNotify(0) , messageDeliveredNotify(0) { for (int i=0; i<MAX_NODES; i++) { nodes[i] = 0; } } void Network::setNotifications(MessageSendNotification send, MessageDeliveryNotification deliver) { messageSentNotify = send; messageDeliveredNotify = deliver; } void Network::deliverMessages(int firstIndex, int lastIndex) { if (firstIndex > lastIndex || lastIndex > MAX_MESSAGES-1 || firstIndex < 0) { return; } for (int i=firstIndex; i<=lastIndex; i++) { messages[i].target->process(messages[i].pkg); if (messageDeliveredNotify) { messageDeliveredNotify(i, messages[i]); } } } void Network::processMessages() { // Messages may be emitted during delivery, so copy the range we intend to deliver const int readIndex = messageReadIndex; const int writeIndex = messageWriteIndex; if (readIndex > writeIndex) { deliverMessages(readIndex, MAX_MESSAGES-1); deliverMessages(0, writeIndex); } else if (readIndex < writeIndex) { deliverMessages(readIndex, writeIndex); } else { // no messages } messageReadIndex = writeIndex; } void Network::sendMessage(Component *target, Packet &pkg, Component *sender) { if (messageWriteIndex > MAX_MESSAGES-1) { messageWriteIndex = 0; } Message &msg = messages[messageWriteIndex++]; msg.target = target; msg.pkg = pkg; if (messageSentNotify) { messageSentNotify(messageWriteIndex-1, msg, sender); } } void Network::runSetup() { for (int i=0; i<MAX_NODES; i++) { if (nodes[i]) { nodes[i]->process(Packet(MsgSetup)); } } } void Network::runTick() { // TODO: consider the balance between scheduling and messaging (bounded-buffer problem) // Deliver messages processMessages(); // Schedule for (int i=0; i<MAX_NODES; i++) { Component *t = nodes[i]; if (t) { t->process(Packet(MsgTick)); } } } void Network::connectTo(int srcId, int targetId) { if (srcId < 0 || srcId > lastAddedNodeIndex || targetId < 0 || targetId > lastAddedNodeIndex) { return; } connectTo(nodes[srcId], nodes[targetId]); } void Network::connectTo(Component *src, Component *target) { src->connectTo(target); } int Network::addNode(Component *node) { nodes[lastAddedNodeIndex++] = node; node->setNetwork(this); return lastAddedNodeIndex; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "perfetto/base/build_config.h" #include "src/base/test/test_task_runner.h" #include "test/test_helper.h" #include "src/profiling/memory/heapprofd_producer.h" #include "src/tracing/ipc/default_socket.h" #include <sys/system_properties.h> // This test only works when run on Android using an Android Q version of // Bionic. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #error "This test can only be used on Android." #endif // If we're building on Android and starting the daemons ourselves, // create the sockets in a world-writable location. #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) #define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer" #else #define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket() #endif namespace perfetto { namespace profiling { namespace { void WaitForHeapprofd(uint64_t timeout_ms) { constexpr uint64_t kSleepMs = 10; std::vector<std::string> cmdlines{"heapprofd"}; std::set<pid_t> pids; for (size_t i = 0; i < timeout_ms / kSleepMs && pids.empty(); ++i) { FindPidsForCmdlines(cmdlines, &pids); usleep(kSleepMs * 1000); } } class HeapprofdDelegate : public ThreadDelegate { public: HeapprofdDelegate(const std::string& producer_socket) : producer_socket_(producer_socket) {} ~HeapprofdDelegate() override = default; void Initialize(base::TaskRunner* task_runner) override { producer_.reset( new HeapprofdProducer(HeapprofdMode::kCentral, task_runner)); producer_->ConnectWithRetries(producer_socket_.c_str()); } private: std::string producer_socket_; std::unique_ptr<HeapprofdProducer> producer_; }; constexpr const char* kEnableHeapprofdProperty = "persist.heapprofd.enable"; int __attribute__((unused)) SetProperty(std::string* value) { if (value) { __system_property_set(kEnableHeapprofdProperty, value->c_str()); delete value; } return 0; } base::ScopedResource<std::string*, SetProperty, nullptr> StartSystemHeapprofdIfRequired() { base::ignore_result(TEST_PRODUCER_SOCK_NAME); std::string prev_property_value = "0"; const prop_info* pi = __system_property_find(kEnableHeapprofdProperty); if (pi) { __system_property_read_callback( pi, [](void* cookie, const char*, const char* value, uint32_t) { *reinterpret_cast<std::string*>(cookie) = value; }, &prev_property_value); } __system_property_set(kEnableHeapprofdProperty, "1"); WaitForHeapprofd(5000); return base::ScopedResource<std::string*, SetProperty, nullptr>( new std::string(prev_property_value)); } pid_t ForkContinousMalloc(size_t bytes) { pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: for (;;) { // This volatile is needed to prevent the compiler from trying to be // helpful and compiling a "useless" malloc + free into a noop. volatile char* x = static_cast<char*>(malloc(bytes)); if (x) { x[1] = 'x'; free(const_cast<char*>(x)); } } default: break; } return pid; } class HeapprofdEndToEnd : public ::testing::Test { public: HeapprofdEndToEnd() { // This is not needed for correctness, but works around a init behavior that // makes this test take much longer. If persist.heapprofd.enable is set to 0 // and then set to 1 again too quickly, init decides that the service is // "restarting" and waits before restarting it. usleep(50000); helper.StartServiceIfRequired(); unset_property = StartSystemHeapprofdIfRequired(); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); } protected: base::TestTaskRunner task_runner; TestHelper helper{&task_runner}; #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) TaskRunnerThread producer_thread("perfetto.prd"); producer_thread.Start(std::unique_ptr<HeapprofdDelegate>( new HeapprofdDelegate(TEST_PRODUCER_SOCK_NAME))); #else base::ScopedResource<std::string*, SetProperty, nullptr> unset_property; #endif }; TEST_F(HeapprofdEndToEnd, Smoke) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); heapprofd_config->mutable_continuous_dump_config()->set_dump_phase_ms(0); heapprofd_config->mutable_continuous_dump_config()->set_dump_interval_ms(100); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.cumulative_allocated() % kAllocSize, 0); EXPECT_EQ(sample.cumulative_freed() % kAllocSize, 0); last_allocated = sample.cumulative_allocated(); last_freed = sample.cumulative_freed(); } profile_packets++; } } EXPECT_GT(profile_packets, 0); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } TEST_F(HeapprofdEndToEnd, FinalFlush) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.cumulative_allocated() % kAllocSize, 0); EXPECT_EQ(sample.cumulative_freed() % kAllocSize, 0); last_allocated = sample.cumulative_allocated(); last_freed = sample.cumulative_freed(); } profile_packets++; } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } TEST_F(HeapprofdEndToEnd, NativeStartup) { TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(5000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_process_cmdline() = "find"; heapprofd_config->set_all(false); helper.StartTracing(trace_config); // Wait to guarantee that the process forked below is hooked by the profiler // by virtue of the startup check, and not by virtue of being seen as a // runnning process. This sleep is here to prevent that, accidentally, the // test gets to the fork()+exec() too soon, before the heap profiling daemon // has received the trace config. sleep(1); pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: { int null = open("/dev/null", O_RDWR); dup2(null, STDIN_FILENO); dup2(null, STDOUT_FILENO); dup2(null, STDERR_FILENO); // TODO(fmayer): Use a dedicated test binary rather than relying on find // doing allocations. PERFETTO_CHECK(execl("/system/bin/find", "find", "/", nullptr) == 0); break; } default: break; } helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t total_allocated = 0; uint64_t total_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); profile_packets++; for (const auto& sample : dump.samples()) { samples++; total_allocated += sample.cumulative_allocated(); total_freed += sample.cumulative_freed(); } } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(total_allocated, 0); EXPECT_GT(total_freed, 0); } } // namespace } // namespace profiling } // namespace perfetto <commit_msg>Disable heap profiling e2e tests am: e2f79261ed<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "perfetto/base/build_config.h" #include "src/base/test/test_task_runner.h" #include "test/test_helper.h" #include "src/profiling/memory/heapprofd_producer.h" #include "src/tracing/ipc/default_socket.h" #include <sys/system_properties.h> // This test only works when run on Android using an Android Q version of // Bionic. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #error "This test can only be used on Android." #endif // If we're building on Android and starting the daemons ourselves, // create the sockets in a world-writable location. #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) #define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer" #else #define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket() #endif namespace perfetto { namespace profiling { namespace { void WaitForHeapprofd(uint64_t timeout_ms) { constexpr uint64_t kSleepMs = 10; std::vector<std::string> cmdlines{"heapprofd"}; std::set<pid_t> pids; for (size_t i = 0; i < timeout_ms / kSleepMs && pids.empty(); ++i) { FindPidsForCmdlines(cmdlines, &pids); usleep(kSleepMs * 1000); } } class HeapprofdDelegate : public ThreadDelegate { public: HeapprofdDelegate(const std::string& producer_socket) : producer_socket_(producer_socket) {} ~HeapprofdDelegate() override = default; void Initialize(base::TaskRunner* task_runner) override { producer_.reset( new HeapprofdProducer(HeapprofdMode::kCentral, task_runner)); producer_->ConnectWithRetries(producer_socket_.c_str()); } private: std::string producer_socket_; std::unique_ptr<HeapprofdProducer> producer_; }; constexpr const char* kEnableHeapprofdProperty = "persist.heapprofd.enable"; int __attribute__((unused)) SetProperty(std::string* value) { if (value) { __system_property_set(kEnableHeapprofdProperty, value->c_str()); delete value; } return 0; } base::ScopedResource<std::string*, SetProperty, nullptr> StartSystemHeapprofdIfRequired() { base::ignore_result(TEST_PRODUCER_SOCK_NAME); std::string prev_property_value = "0"; const prop_info* pi = __system_property_find(kEnableHeapprofdProperty); if (pi) { __system_property_read_callback( pi, [](void* cookie, const char*, const char* value, uint32_t) { *reinterpret_cast<std::string*>(cookie) = value; }, &prev_property_value); } __system_property_set(kEnableHeapprofdProperty, "1"); WaitForHeapprofd(5000); return base::ScopedResource<std::string*, SetProperty, nullptr>( new std::string(prev_property_value)); } pid_t ForkContinousMalloc(size_t bytes) { pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: for (;;) { // This volatile is needed to prevent the compiler from trying to be // helpful and compiling a "useless" malloc + free into a noop. volatile char* x = static_cast<char*>(malloc(bytes)); if (x) { x[1] = 'x'; free(const_cast<char*>(x)); } } default: break; } return pid; } class HeapprofdEndToEnd : public ::testing::Test { public: HeapprofdEndToEnd() { // This is not needed for correctness, but works around a init behavior that // makes this test take much longer. If persist.heapprofd.enable is set to 0 // and then set to 1 again too quickly, init decides that the service is // "restarting" and waits before restarting it. usleep(50000); helper.StartServiceIfRequired(); unset_property = StartSystemHeapprofdIfRequired(); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); } protected: base::TestTaskRunner task_runner; TestHelper helper{&task_runner}; #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) TaskRunnerThread producer_thread("perfetto.prd"); producer_thread.Start(std::unique_ptr<HeapprofdDelegate>( new HeapprofdDelegate(TEST_PRODUCER_SOCK_NAME))); #else base::ScopedResource<std::string*, SetProperty, nullptr> unset_property; #endif }; // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_Smoke) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); heapprofd_config->mutable_continuous_dump_config()->set_dump_phase_ms(0); heapprofd_config->mutable_continuous_dump_config()->set_dump_interval_ms(100); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.cumulative_allocated() % kAllocSize, 0); EXPECT_EQ(sample.cumulative_freed() % kAllocSize, 0); last_allocated = sample.cumulative_allocated(); last_freed = sample.cumulative_freed(); } profile_packets++; } } EXPECT_GT(profile_packets, 0); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_FinalFlush) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.cumulative_allocated() % kAllocSize, 0); EXPECT_EQ(sample.cumulative_freed() % kAllocSize, 0); last_allocated = sample.cumulative_allocated(); last_freed = sample.cumulative_freed(); } profile_packets++; } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_NativeStartup) { TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(5000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_process_cmdline() = "find"; heapprofd_config->set_all(false); helper.StartTracing(trace_config); // Wait to guarantee that the process forked below is hooked by the profiler // by virtue of the startup check, and not by virtue of being seen as a // runnning process. This sleep is here to prevent that, accidentally, the // test gets to the fork()+exec() too soon, before the heap profiling daemon // has received the trace config. sleep(1); pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: { int null = open("/dev/null", O_RDWR); dup2(null, STDIN_FILENO); dup2(null, STDOUT_FILENO); dup2(null, STDERR_FILENO); // TODO(fmayer): Use a dedicated test binary rather than relying on find // doing allocations. PERFETTO_CHECK(execl("/system/bin/find", "find", "/", nullptr) == 0); break; } default: break; } helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t total_allocated = 0; uint64_t total_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); profile_packets++; for (const auto& sample : dump.samples()) { samples++; total_allocated += sample.cumulative_allocated(); total_freed += sample.cumulative_freed(); } } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(total_allocated, 0); EXPECT_GT(total_freed, 0); } } // namespace } // namespace profiling } // namespace perfetto <|endoftext|>
<commit_before>// Copyright (C) 2016 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/MaterialPipeline.hpp> #ifndef NAZARA_RENDERER_OPENGL #define NAZARA_RENDERER_OPENGL // Mandatory to include the OpenGL headers #endif #include <Nazara/Renderer/OpenGL.hpp> #include <Nazara/Renderer/UberShaderPreprocessor.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { namespace { const UInt8 r_basicFragmentShader[] = { #include <Nazara/Graphics/Resources/Shaders/Basic/core.frag.h> }; const UInt8 r_basicVertexShader[] = { #include <Nazara/Graphics/Resources/Shaders/Basic/core.vert.h> }; const UInt8 r_phongLightingFragmentShader[] = { #include <Nazara/Graphics/Resources/Shaders/PhongLighting/core.frag.h> }; const UInt8 r_phongLightingVertexShader[] = { #include <Nazara/Graphics/Resources/Shaders/PhongLighting/core.vert.h> }; } /*! * \ingroup graphics * \class Nz::MaterialPipeline * * \brief Graphics class used to contains all rendering states that are not allowed to change individually on rendering devices */ /*! * \brief Returns a reference to a MaterialPipeline built with MaterialPipelineInfo * * This function is using a cache, calling it multiples times with the same MaterialPipelineInfo will returns references to a single MaterialPipeline * * \param pipelineInfo Pipeline informations used to build/retrieve a MaterialPipeline object */ MaterialPipelineRef MaterialPipeline::GetPipeline(const MaterialPipelineInfo& pipelineInfo) { auto it = s_pipelineCache.find(pipelineInfo); if (it == s_pipelineCache.end()) it = s_pipelineCache.insert(it, PipelineCache::value_type(pipelineInfo, New(pipelineInfo))); return it->second; } void MaterialPipeline::GenerateRenderPipeline(UInt32 flags) const { ParameterList list; list.SetParameter("ALPHA_MAPPING", m_pipelineInfo.hasAlphaMap); list.SetParameter("ALPHA_TEST", m_pipelineInfo.alphaTest); list.SetParameter("COMPUTE_TBNMATRIX", m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap); list.SetParameter("DIFFUSE_MAPPING", m_pipelineInfo.hasDiffuseMap); list.SetParameter("EMISSIVE_MAPPING", m_pipelineInfo.hasEmissiveMap); list.SetParameter("NORMAL_MAPPING", m_pipelineInfo.hasNormalMap); list.SetParameter("PARALLAX_MAPPING", m_pipelineInfo.hasHeightMap); list.SetParameter("SHADOW_MAPPING", m_pipelineInfo.shadowReceive); list.SetParameter("SPECULAR_MAPPING", m_pipelineInfo.hasSpecularMap); list.SetParameter("TEXTURE_MAPPING", m_pipelineInfo.hasAlphaMap || m_pipelineInfo.hasDiffuseMap || m_pipelineInfo.hasEmissiveMap || m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap || m_pipelineInfo.hasSpecularMap || flags & ShaderFlags_TextureOverlay); list.SetParameter("TRANSFORM", true); list.SetParameter("FLAG_BILLBOARD", static_cast<bool>((flags & ShaderFlags_Billboard) != 0)); list.SetParameter("FLAG_DEFERRED", static_cast<bool>((flags & ShaderFlags_Deferred) != 0)); list.SetParameter("FLAG_INSTANCING", static_cast<bool>((flags & ShaderFlags_Instancing) != 0)); list.SetParameter("FLAG_TEXTUREOVERLAY", static_cast<bool>((flags & ShaderFlags_TextureOverlay) != 0)); list.SetParameter("FLAG_VERTEXCOLOR", static_cast<bool>((flags & ShaderFlags_VertexColor) != 0)); Instance& instance = m_instances[flags]; instance.uberInstance = m_pipelineInfo.uberShader->Get(list); RenderPipelineInfo renderPipelineInfo; static_cast<RenderStates&>(renderPipelineInfo).operator=(m_pipelineInfo); // Not my proudest line renderPipelineInfo.shader = instance.uberInstance->GetShader(); instance.renderPipeline.Create(renderPipelineInfo); #define CacheUniform(name) instance.uniforms[MaterialUniform_##name] = renderPipelineInfo.shader->GetUniformLocation("Material" #name) CacheUniform(AlphaMap); CacheUniform(AlphaThreshold); CacheUniform(Ambient); CacheUniform(Diffuse); CacheUniform(DiffuseMap); CacheUniform(EmissiveMap); CacheUniform(HeightMap); CacheUniform(NormalMap); CacheUniform(Shininess); CacheUniform(Specular); CacheUniform(SpecularMap); #undef CacheUniform } bool MaterialPipeline::Initialize() { // Basic shader { UberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New(); String fragmentShader(reinterpret_cast<const char*>(r_basicFragmentShader), sizeof(r_basicFragmentShader)); String vertexShader(reinterpret_cast<const char*>(r_basicVertexShader), sizeof(r_basicVertexShader)); uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING"); uberShader->SetShader(ShaderStageType_Vertex, vertexShader, "FLAG_BILLBOARD FLAG_INSTANCING FLAG_VERTEXCOLOR TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH"); UberShaderLibrary::Register("Basic", uberShader); } // PhongLighting shader { UberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New(); String fragmentShader(reinterpret_cast<const char*>(r_phongLightingFragmentShader), sizeof(r_phongLightingFragmentShader)); String vertexShader(reinterpret_cast<const char*>(r_phongLightingVertexShader), sizeof(r_phongLightingVertexShader)); uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_DEFERRED FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING EMISSIVE_MAPPING NORMAL_MAPPING PARALLAX_MAPPING SHADOW_MAPPING SPECULAR_MAPPING"); uberShader->SetShader(ShaderStageType_Vertex, vertexShader, "FLAG_BILLBOARD FLAG_DEFERRED FLAG_INSTANCING FLAG_VERTEXCOLOR COMPUTE_TBNMATRIX PARALLAX_MAPPING SHADOW_MAPPING TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH"); UberShaderLibrary::Register("PhongLighting", uberShader); } // Once the base shaders are registered, we can now set some default materials MaterialPipelineInfo pipelineInfo; // Basic 2D - No depth write/face culling pipelineInfo.depthWrite = false; pipelineInfo.faceCulling = false; MaterialPipelineLibrary::Register("Basic2D", GetPipeline(pipelineInfo)); // Translucent 2D - Alpha blending with no depth write/face culling pipelineInfo.blending = false; pipelineInfo.depthWrite = false; pipelineInfo.faceCulling = false; pipelineInfo.dstBlend = BlendFunc_InvSrcAlpha; pipelineInfo.srcBlend = BlendFunc_SrcAlpha; MaterialPipelineLibrary::Register("Translucent2D", GetPipeline(pipelineInfo)); return true; } void MaterialPipeline::Uninitialize() { s_pipelineCache.clear(); UberShaderLibrary::Unregister("PhongLighting"); UberShaderLibrary::Unregister("Basic"); MaterialPipelineLibrary::Uninitialize(); } MaterialPipelineLibrary::LibraryMap MaterialPipeline::s_library; MaterialPipeline::PipelineCache MaterialPipeline::s_pipelineCache; }<commit_msg>Graphics/MaterialPipeline: Fix default pipeline not having an ubershader<commit_after>// Copyright (C) 2016 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/MaterialPipeline.hpp> #ifndef NAZARA_RENDERER_OPENGL #define NAZARA_RENDERER_OPENGL // Mandatory to include the OpenGL headers #endif #include <Nazara/Renderer/OpenGL.hpp> #include <Nazara/Renderer/UberShaderPreprocessor.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { namespace { const UInt8 r_basicFragmentShader[] = { #include <Nazara/Graphics/Resources/Shaders/Basic/core.frag.h> }; const UInt8 r_basicVertexShader[] = { #include <Nazara/Graphics/Resources/Shaders/Basic/core.vert.h> }; const UInt8 r_phongLightingFragmentShader[] = { #include <Nazara/Graphics/Resources/Shaders/PhongLighting/core.frag.h> }; const UInt8 r_phongLightingVertexShader[] = { #include <Nazara/Graphics/Resources/Shaders/PhongLighting/core.vert.h> }; } /*! * \ingroup graphics * \class Nz::MaterialPipeline * * \brief Graphics class used to contains all rendering states that are not allowed to change individually on rendering devices */ /*! * \brief Returns a reference to a MaterialPipeline built with MaterialPipelineInfo * * This function is using a cache, calling it multiples times with the same MaterialPipelineInfo will returns references to a single MaterialPipeline * * \param pipelineInfo Pipeline informations used to build/retrieve a MaterialPipeline object */ MaterialPipelineRef MaterialPipeline::GetPipeline(const MaterialPipelineInfo& pipelineInfo) { auto it = s_pipelineCache.find(pipelineInfo); if (it == s_pipelineCache.end()) it = s_pipelineCache.insert(it, PipelineCache::value_type(pipelineInfo, New(pipelineInfo))); return it->second; } void MaterialPipeline::GenerateRenderPipeline(UInt32 flags) const { NazaraAssert(m_pipelineInfo.uberShader, "Material pipeline has no uber shader"); ParameterList list; list.SetParameter("ALPHA_MAPPING", m_pipelineInfo.hasAlphaMap); list.SetParameter("ALPHA_TEST", m_pipelineInfo.alphaTest); list.SetParameter("COMPUTE_TBNMATRIX", m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap); list.SetParameter("DIFFUSE_MAPPING", m_pipelineInfo.hasDiffuseMap); list.SetParameter("EMISSIVE_MAPPING", m_pipelineInfo.hasEmissiveMap); list.SetParameter("NORMAL_MAPPING", m_pipelineInfo.hasNormalMap); list.SetParameter("PARALLAX_MAPPING", m_pipelineInfo.hasHeightMap); list.SetParameter("SHADOW_MAPPING", m_pipelineInfo.shadowReceive); list.SetParameter("SPECULAR_MAPPING", m_pipelineInfo.hasSpecularMap); list.SetParameter("TEXTURE_MAPPING", m_pipelineInfo.hasAlphaMap || m_pipelineInfo.hasDiffuseMap || m_pipelineInfo.hasEmissiveMap || m_pipelineInfo.hasNormalMap || m_pipelineInfo.hasHeightMap || m_pipelineInfo.hasSpecularMap || flags & ShaderFlags_TextureOverlay); list.SetParameter("TRANSFORM", true); list.SetParameter("FLAG_BILLBOARD", static_cast<bool>((flags & ShaderFlags_Billboard) != 0)); list.SetParameter("FLAG_DEFERRED", static_cast<bool>((flags & ShaderFlags_Deferred) != 0)); list.SetParameter("FLAG_INSTANCING", static_cast<bool>((flags & ShaderFlags_Instancing) != 0)); list.SetParameter("FLAG_TEXTUREOVERLAY", static_cast<bool>((flags & ShaderFlags_TextureOverlay) != 0)); list.SetParameter("FLAG_VERTEXCOLOR", static_cast<bool>((flags & ShaderFlags_VertexColor) != 0)); Instance& instance = m_instances[flags]; instance.uberInstance = m_pipelineInfo.uberShader->Get(list); RenderPipelineInfo renderPipelineInfo; static_cast<RenderStates&>(renderPipelineInfo).operator=(m_pipelineInfo); // Not my proudest line renderPipelineInfo.shader = instance.uberInstance->GetShader(); instance.renderPipeline.Create(renderPipelineInfo); #define CacheUniform(name) instance.uniforms[MaterialUniform_##name] = renderPipelineInfo.shader->GetUniformLocation("Material" #name) CacheUniform(AlphaMap); CacheUniform(AlphaThreshold); CacheUniform(Ambient); CacheUniform(Diffuse); CacheUniform(DiffuseMap); CacheUniform(EmissiveMap); CacheUniform(HeightMap); CacheUniform(NormalMap); CacheUniform(Shininess); CacheUniform(Specular); CacheUniform(SpecularMap); #undef CacheUniform } bool MaterialPipeline::Initialize() { // Basic shader { UberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New(); String fragmentShader(reinterpret_cast<const char*>(r_basicFragmentShader), sizeof(r_basicFragmentShader)); String vertexShader(reinterpret_cast<const char*>(r_basicVertexShader), sizeof(r_basicVertexShader)); uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING"); uberShader->SetShader(ShaderStageType_Vertex, vertexShader, "FLAG_BILLBOARD FLAG_INSTANCING FLAG_VERTEXCOLOR TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH"); UberShaderLibrary::Register("Basic", uberShader); } // PhongLighting shader { UberShaderPreprocessorRef uberShader = UberShaderPreprocessor::New(); String fragmentShader(reinterpret_cast<const char*>(r_phongLightingFragmentShader), sizeof(r_phongLightingFragmentShader)); String vertexShader(reinterpret_cast<const char*>(r_phongLightingVertexShader), sizeof(r_phongLightingVertexShader)); uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_DEFERRED FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING EMISSIVE_MAPPING NORMAL_MAPPING PARALLAX_MAPPING SHADOW_MAPPING SPECULAR_MAPPING"); uberShader->SetShader(ShaderStageType_Vertex, vertexShader, "FLAG_BILLBOARD FLAG_DEFERRED FLAG_INSTANCING FLAG_VERTEXCOLOR COMPUTE_TBNMATRIX PARALLAX_MAPPING SHADOW_MAPPING TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH"); UberShaderLibrary::Register("PhongLighting", uberShader); } // Once the base shaders are registered, we can now set some default materials MaterialPipelineInfo pipelineInfo; pipelineInfo.uberShader = UberShaderLibrary::Get("Basic"); // Basic 2D - No depth write/face culling pipelineInfo.depthWrite = false; pipelineInfo.faceCulling = false; MaterialPipelineLibrary::Register("Basic2D", GetPipeline(pipelineInfo)); // Translucent 2D - Alpha blending with no depth write/face culling pipelineInfo.blending = false; pipelineInfo.depthWrite = false; pipelineInfo.faceCulling = false; pipelineInfo.dstBlend = BlendFunc_InvSrcAlpha; pipelineInfo.srcBlend = BlendFunc_SrcAlpha; MaterialPipelineLibrary::Register("Translucent2D", GetPipeline(pipelineInfo)); return true; } void MaterialPipeline::Uninitialize() { s_pipelineCache.clear(); UberShaderLibrary::Unregister("PhongLighting"); UberShaderLibrary::Unregister("Basic"); MaterialPipelineLibrary::Uninitialize(); } MaterialPipelineLibrary::LibraryMap MaterialPipeline::s_library; MaterialPipeline::PipelineCache MaterialPipeline::s_pipelineCache; }<|endoftext|>
<commit_before>#include <vector> #include "caffe/layers/affinity_loss_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void AffinityLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; diff_.ReshapeLike(*bottom[0]); } template <typename Dtype> void AffinityLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int count = bottom[0]->count(); Dtype sum = 0.0; Dtype scale = this->layer_param_.affinity_loss_param().scale(); Dtype gap = this->layer_param_.affinity_loss_param().gap()/2.0; const Dtype *labels = bottom[1]->cpu_data(); const Dtype *preds = bottom[0]->cpu_data(); Dtype *d = diff_.mutable_cpu_data(); for(unsigned i = 0; i < count; i++) { Dtype label = labels[i]; Dtype pred = preds[i]; if(label > 0) { //normal euclidean Dtype diff = std::fabs(pred-label); diff -= gap; if(diff < 0) diff = 0; d[i] = scale*diff; sum += diff*diff; } else if(label < 0 && pred > -label) { //hinge like Dtype diff = pred+label; diff -= gap; if(diff < 0) diff = 0; d[i] = scale*diff; sum += diff*diff; } else { //ignore d[i] = 0; } } Dtype loss = sum / bottom[0]->num() / Dtype(2); top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void AffinityLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? 1 : -1; const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num(); caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } /*LOG(INFO) << "AFFGRADS"; for(unsigned i = 0, n = bottom[0]->num(); i < n; i++) { LOG(INFO) << bottom[0]->cpu_diff()[i]; }*/ } INSTANTIATE_CLASS(AffinityLossLayer); REGISTER_LAYER_CLASS(AffinityLoss); } // namespace caffe <commit_msg>fig bug with gapped affinity<commit_after>#include <vector> #include "caffe/layers/affinity_loss_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void AffinityLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; diff_.ReshapeLike(*bottom[0]); } template <typename Dtype> void AffinityLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int count = bottom[0]->count(); Dtype sum = 0.0; Dtype scale = this->layer_param_.affinity_loss_param().scale(); Dtype gap = this->layer_param_.affinity_loss_param().gap()/2.0; const Dtype *labels = bottom[1]->cpu_data(); const Dtype *preds = bottom[0]->cpu_data(); Dtype *d = diff_.mutable_cpu_data(); for(unsigned i = 0; i < count; i++) { Dtype label = labels[i]; Dtype pred = preds[i]; if(label > 0) { //normal euclidean Dtype diff = pred-label; if(diff < 0) { diff = std::min(diff+gap,Dtype(0)); } else { diff = std::max(diff-gap,Dtype(0)); } d[i] = scale*diff; sum += diff*diff; } else if(label < 0 && pred > -label) { //hinge like Dtype diff = pred+label; if(diff < 0) { diff = std::min(diff+gap,Dtype(0)); } else { diff = std::max(diff-gap,Dtype(0)); } d[i] = scale*diff; sum += diff*diff; } else { //ignore d[i] = 0; } } Dtype loss = sum / bottom[0]->num() / Dtype(2); top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void AffinityLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? 1 : -1; const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num(); caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } /*LOG(INFO) << "AFFGRADS"; for(unsigned i = 0, n = bottom[0]->num(); i < n; i++) { LOG(INFO) << bottom[0]->cpu_diff()[i]; }*/ } INSTANTIATE_CLASS(AffinityLossLayer); REGISTER_LAYER_CLASS(AffinityLoss); } // namespace caffe <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: setnodeaccess.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:24:44 $ * * 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 CONFIGMGR_SETNODEACCESS_HXX #define CONFIGMGR_SETNODEACCESS_HXX #ifndef CONFIGMGR_NODEACCESS_HXX #include "nodeaccess.hxx" #endif #ifndef INCLUDED_SHARABLE_TREEFRAGMENT_HXX #include "treefragment.hxx" #endif #include "treeaccessor.hxx" namespace configmgr { // ----------------------------------------------------------------------------- namespace data { // ------------------------------------------------------------------------- class TreeAccessor; // ------------------------------------------------------------------------- /** class that mediates access to the data of a Set node <p>Is a handle class with reference copy semantics.</p> */ class SetNodeAccess { public: typedef TreeAddress ElementAddress; typedef TreeAccessor ElementAccess; SetNodeAccess(const sharable::SetNode *_pNodeRef) : m_pData((SetNodeAddress)_pNodeRef) {} SetNodeAccess(const sharable::Node *_pNodeRef) : m_pData(check(_pNodeRef)) {} explicit SetNodeAccess(NodeAccess const & _aNode) : m_pData(check(_aNode)) {} static bool isInstance(NodeAccess const & _aNode) { return check(_aNode) != NULL; } bool isValid() const { return m_pData != NULL; } configuration::Name getName() const; node::Attributes getAttributes() const; bool isDefault() const; bool isLocalizedValueSetNode() const; configuration::Name getElementTemplateName() const; configuration::Name getElementTemplateModule() const; bool hasElement (configuration::Name const& _aName) const { return SetNodeAccess::implGetElement(_aName) != NULL; } ElementAccess getElementTree (configuration::Name const& _aName) const { return TreeAccessor(implGetElement(_aName)); } operator NodeAccess() const { return NodeAccess(NodeAddress(m_pData)); } sharable::SetNode & data() const { return *m_pData; } operator SetNodeAddress () const { return (SetNodeAddress)m_pData; } operator NodeAddress () const { return (NodeAddress)m_pData; } static void addElement(SetNodeAddress _aSetAddress, ElementAddress _aNewElement); static ElementAddress removeElement(SetNodeAddress _aSetAddress, configuration::Name const & _aName); private: static SetNodeAddress check(sharable::Node *pNode) { return pNode ? const_cast<SetNodeAddress>(pNode->setData()) : NULL; } static SetNodeAddress check(NodeAccess const&aRef) { return check(static_cast<sharable::Node *>(aRef)); } ElementAddress implGetElement(configuration::Name const& _aName) const; SetNodeAddress m_pData; }; SetNodeAddress toSetNodeAddress(NodeAddress const & _aNodeAddr); // ------------------------------------------------------------------------- inline configuration::Name SetNodeAccess::getName() const { return NodeAccess::wrapName( data().info.getName() ); } inline configuration::Name SetNodeAccess::getElementTemplateName() const { return NodeAccess::wrapName( data().getElementTemplateName() ); } inline configuration::Name SetNodeAccess::getElementTemplateModule() const { return NodeAccess::wrapName( data().getElementTemplateModule() ); } inline node::Attributes SetNodeAccess::getAttributes() const { return sharable::node(data()).getAttributes(); } inline bool SetNodeAccess::isDefault() const { return data().info.isDefault(); } inline bool SetNodeAccess::isLocalizedValueSetNode() const { return data().isLocalizedValue(); } // ------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- } // namespace configmgr #endif // CONFIGMGR_SETNODEACCESS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.16); FILE MERGED 2008/04/01 12:27:25 thb 1.6.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:45 rt 1.6.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: setnodeaccess.hxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ #ifndef CONFIGMGR_SETNODEACCESS_HXX #define CONFIGMGR_SETNODEACCESS_HXX #include "nodeaccess.hxx" #include "treefragment.hxx" #include "treeaccessor.hxx" namespace configmgr { // ----------------------------------------------------------------------------- namespace data { // ------------------------------------------------------------------------- class TreeAccessor; // ------------------------------------------------------------------------- /** class that mediates access to the data of a Set node <p>Is a handle class with reference copy semantics.</p> */ class SetNodeAccess { public: typedef TreeAddress ElementAddress; typedef TreeAccessor ElementAccess; SetNodeAccess(const sharable::SetNode *_pNodeRef) : m_pData((SetNodeAddress)_pNodeRef) {} SetNodeAccess(const sharable::Node *_pNodeRef) : m_pData(check(_pNodeRef)) {} explicit SetNodeAccess(NodeAccess const & _aNode) : m_pData(check(_aNode)) {} static bool isInstance(NodeAccess const & _aNode) { return check(_aNode) != NULL; } bool isValid() const { return m_pData != NULL; } configuration::Name getName() const; node::Attributes getAttributes() const; bool isDefault() const; bool isLocalizedValueSetNode() const; configuration::Name getElementTemplateName() const; configuration::Name getElementTemplateModule() const; bool hasElement (configuration::Name const& _aName) const { return SetNodeAccess::implGetElement(_aName) != NULL; } ElementAccess getElementTree (configuration::Name const& _aName) const { return TreeAccessor(implGetElement(_aName)); } operator NodeAccess() const { return NodeAccess(NodeAddress(m_pData)); } sharable::SetNode & data() const { return *m_pData; } operator SetNodeAddress () const { return (SetNodeAddress)m_pData; } operator NodeAddress () const { return (NodeAddress)m_pData; } static void addElement(SetNodeAddress _aSetAddress, ElementAddress _aNewElement); static ElementAddress removeElement(SetNodeAddress _aSetAddress, configuration::Name const & _aName); private: static SetNodeAddress check(sharable::Node *pNode) { return pNode ? const_cast<SetNodeAddress>(pNode->setData()) : NULL; } static SetNodeAddress check(NodeAccess const&aRef) { return check(static_cast<sharable::Node *>(aRef)); } ElementAddress implGetElement(configuration::Name const& _aName) const; SetNodeAddress m_pData; }; SetNodeAddress toSetNodeAddress(NodeAddress const & _aNodeAddr); // ------------------------------------------------------------------------- inline configuration::Name SetNodeAccess::getName() const { return NodeAccess::wrapName( data().info.getName() ); } inline configuration::Name SetNodeAccess::getElementTemplateName() const { return NodeAccess::wrapName( data().getElementTemplateName() ); } inline configuration::Name SetNodeAccess::getElementTemplateModule() const { return NodeAccess::wrapName( data().getElementTemplateModule() ); } inline node::Attributes SetNodeAccess::getAttributes() const { return sharable::node(data()).getAttributes(); } inline bool SetNodeAccess::isDefault() const { return data().info.isDefault(); } inline bool SetNodeAccess::isLocalizedValueSetNode() const { return data().isLocalizedValue(); } // ------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- } // namespace configmgr #endif // CONFIGMGR_SETNODEACCESS_HXX <|endoftext|>
<commit_before>#include "Connection.h" #include "MySqlBase.h" #include "Statement.h" #include <vector> #include <boost/scoped_array.hpp> Core::Db::Connection::Connection( MySqlBase * pBase, const std::string& hostName, const std::string& userName, const std::string& password ) : m_pBase( pBase ), m_bConnected( false ) { m_pRawCon = mysql_init( nullptr ); if( mysql_real_connect( m_pRawCon, hostName.c_str(), userName.c_str(), password.c_str(), nullptr, 3306, nullptr, 0) == nullptr ) { throw std::runtime_error( mysql_error( m_pRawCon ) ); } m_bConnected = true; } Core::Db::Connection::Connection( MySqlBase * pBase, const std::string& hostName, const std::string& userName, const std::string& password, const optionMap& options ) : m_pBase( pBase ) { m_pRawCon = mysql_init( nullptr ); // Different mysql versions support different options, for now whatever was unsupporter here was commented out // but left there. for( auto entry : options ) { switch( entry.first ) { // integer based options case MYSQL_OPT_CONNECT_TIMEOUT: case MYSQL_OPT_PROTOCOL: case MYSQL_OPT_READ_TIMEOUT: // case MYSQL_OPT_SSL_MODE: // case MYSQL_OPT_RETRY_COUNT: case MYSQL_OPT_WRITE_TIMEOUT: // case MYSQL_OPT_MAX_ALLOWED_PACKET: // case MYSQL_OPT_NET_BUFFER_LENGTH: { uint32_t optVal = std::stoi( entry.second, nullptr, 10 ); setOption( entry.first, optVal ); } break; // bool based options // case MYSQL_ENABLE_CLEARTEXT_PLUGIN: // case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS: case MYSQL_OPT_COMPRESS: case MYSQL_OPT_GUESS_CONNECTION: case MYSQL_OPT_LOCAL_INFILE: case MYSQL_OPT_RECONNECT: // case MYSQL_OPT_SSL_ENFORCE: // case MYSQL_OPT_SSL_VERIFY_SERVER_CERT: case MYSQL_OPT_USE_EMBEDDED_CONNECTION: case MYSQL_OPT_USE_REMOTE_CONNECTION: case MYSQL_REPORT_DATA_TRUNCATION: case MYSQL_SECURE_AUTH: { my_bool optVal = entry.second == "0" ? 0 : 1; setOption( entry.first, &optVal ); } break; // string based options // case MYSQL_DEFAULT_AUTH: // case MYSQL_OPT_BIND: // case MYSQL_OPT_SSL_CA: // case MYSQL_OPT_SSL_CAPATH: // case MYSQL_OPT_SSL_CERT: // case MYSQL_OPT_SSL_CIPHER: // case MYSQL_OPT_SSL_CRL: // case MYSQL_OPT_SSL_CRLPATH: // case MYSQL_OPT_SSL_KEY: // case MYSQL_OPT_TLS_VERSION: // case MYSQL_PLUGIN_DIR: case MYSQL_READ_DEFAULT_FILE: case MYSQL_READ_DEFAULT_GROUP: // case MYSQL_SERVER_PUBLIC_KEY: case MYSQL_SET_CHARSET_DIR: case MYSQL_SET_CHARSET_NAME: case MYSQL_SET_CLIENT_IP: case MYSQL_SHARED_MEMORY_BASE_NAME: { setOption( entry.first, entry.second.c_str() ); } break; default: throw std::runtime_error( "Unknown option: " + std::to_string( entry.first ) ); } } if( mysql_real_connect( m_pRawCon, hostName.c_str(), userName.c_str(), password.c_str(), nullptr, 3306, nullptr, 0) == nullptr ) { throw std::runtime_error( mysql_error( m_pRawCon ) ); } } Core::Db::Connection::~Connection() { } void Core::Db::Connection::setOption( enum mysql_option option, const void *arg ) { if( mysql_options( m_pRawCon, option, arg ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::setOption( enum mysql_option option, uint32_t arg ) { if( mysql_options( m_pRawCon, option, &arg ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::setOption( enum mysql_option option, const std::string& arg ) { if( mysql_options( m_pRawCon, option, arg.c_str() ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::close() { mysql_close( m_pRawCon ); m_bConnected = false; } bool Core::Db::Connection::isClosed() const { return !m_bConnected; } Core::Db::MySqlBase* Core::Db::Connection::getMySqlBase() const { return m_pBase; } void Core::Db::Connection::setAutoCommit( bool autoCommit ) { auto b = static_cast< my_bool >( autoCommit == true ? 1 : 0 ); if( mysql_autocommit( m_pRawCon, b ) != 0 ) throw std::runtime_error( "Connection::setAutoCommit failed!" ); } bool Core::Db::Connection::getAutoCommit() { // TODO: should be replaced with wrapped sql query function once available std::string query("SELECT @@autocommit"); auto res = mysql_real_query( m_pRawCon, query.c_str(), query.length() ); if( res != 0 ) throw std::runtime_error( "Query failed!" ); auto pRes = mysql_store_result( m_pRawCon ); auto row = mysql_fetch_row( pRes ); uint32_t ac = atoi( row[0] ); return ac != 0; } void Core::Db::Connection::beginTransaction() { } void Core::Db::Connection::commitTransaction() { } void Core::Db::Connection::rollbackTransaction() { } std::string Core::Db::Connection::escapeString( const std::string &inData ) { boost::scoped_array< char > buffer( new char[inData.length() * 2 + 1] ); if( !buffer.get() ) return ""; unsigned long return_len = mysql_real_escape_string( m_pRawCon, buffer.get(), inData.c_str(), static_cast< unsigned long > ( inData.length() ) ); return std::string( buffer.get(), return_len ); } void Core::Db::Connection::setSchema( const std::string &schema ) { if( mysql_select_db( m_pRawCon, schema.c_str() ) != 0 ) throw std::runtime_error( "Current database could not be changed to " + schema ); } Core::Db::Statement *Core::Db::Connection::createStatement() { return new Statement( this ); } MYSQL *Core::Db::Connection::getRawCon() { return m_pRawCon; } std::string Core::Db::Connection::getError() { auto mysqlError = mysql_error( m_pRawCon ); if( mysqlError ) return std::string( mysqlError ); return ""; } <commit_msg>Added transactions<commit_after>#include "Connection.h" #include "MySqlBase.h" #include "Statement.h" #include <vector> #include <boost/scoped_array.hpp> Core::Db::Connection::Connection( MySqlBase * pBase, const std::string& hostName, const std::string& userName, const std::string& password ) : m_pBase( pBase ), m_bConnected( false ) { m_pRawCon = mysql_init( nullptr ); if( mysql_real_connect( m_pRawCon, hostName.c_str(), userName.c_str(), password.c_str(), nullptr, 3306, nullptr, 0) == nullptr ) throw std::runtime_error( mysql_error( m_pRawCon ) ); m_bConnected = true; } Core::Db::Connection::Connection( MySqlBase * pBase, const std::string& hostName, const std::string& userName, const std::string& password, const optionMap& options ) : m_pBase( pBase ) { m_pRawCon = mysql_init( nullptr ); // Different mysql versions support different options, for now whatever was unsupporter here was commented out // but left there. for( auto entry : options ) { switch( entry.first ) { // integer based options case MYSQL_OPT_CONNECT_TIMEOUT: case MYSQL_OPT_PROTOCOL: case MYSQL_OPT_READ_TIMEOUT: // case MYSQL_OPT_SSL_MODE: // case MYSQL_OPT_RETRY_COUNT: case MYSQL_OPT_WRITE_TIMEOUT: // case MYSQL_OPT_MAX_ALLOWED_PACKET: // case MYSQL_OPT_NET_BUFFER_LENGTH: { uint32_t optVal = std::stoi( entry.second, nullptr, 10 ); setOption( entry.first, optVal ); } break; // bool based options // case MYSQL_ENABLE_CLEARTEXT_PLUGIN: // case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS: case MYSQL_OPT_COMPRESS: case MYSQL_OPT_GUESS_CONNECTION: case MYSQL_OPT_LOCAL_INFILE: case MYSQL_OPT_RECONNECT: // case MYSQL_OPT_SSL_ENFORCE: // case MYSQL_OPT_SSL_VERIFY_SERVER_CERT: case MYSQL_OPT_USE_EMBEDDED_CONNECTION: case MYSQL_OPT_USE_REMOTE_CONNECTION: case MYSQL_REPORT_DATA_TRUNCATION: case MYSQL_SECURE_AUTH: { my_bool optVal = entry.second == "0" ? 0 : 1; setOption( entry.first, &optVal ); } break; // string based options // case MYSQL_DEFAULT_AUTH: // case MYSQL_OPT_BIND: // case MYSQL_OPT_SSL_CA: // case MYSQL_OPT_SSL_CAPATH: // case MYSQL_OPT_SSL_CERT: // case MYSQL_OPT_SSL_CIPHER: // case MYSQL_OPT_SSL_CRL: // case MYSQL_OPT_SSL_CRLPATH: // case MYSQL_OPT_SSL_KEY: // case MYSQL_OPT_TLS_VERSION: // case MYSQL_PLUGIN_DIR: case MYSQL_READ_DEFAULT_FILE: case MYSQL_READ_DEFAULT_GROUP: // case MYSQL_SERVER_PUBLIC_KEY: case MYSQL_SET_CHARSET_DIR: case MYSQL_SET_CHARSET_NAME: case MYSQL_SET_CLIENT_IP: case MYSQL_SHARED_MEMORY_BASE_NAME: { setOption( entry.first, entry.second.c_str() ); } break; default: throw std::runtime_error( "Unknown option: " + std::to_string( entry.first ) ); } } if( mysql_real_connect( m_pRawCon, hostName.c_str(), userName.c_str(), password.c_str(), nullptr, 3306, nullptr, 0) == nullptr ) throw std::runtime_error( mysql_error( m_pRawCon ) ); } Core::Db::Connection::~Connection() { } void Core::Db::Connection::setOption( enum mysql_option option, const void *arg ) { if( mysql_options( m_pRawCon, option, arg ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::setOption( enum mysql_option option, uint32_t arg ) { if( mysql_options( m_pRawCon, option, &arg ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::setOption( enum mysql_option option, const std::string& arg ) { if( mysql_options( m_pRawCon, option, arg.c_str() ) != 0 ) throw std::runtime_error( "Connection::setOption failed!" ); } void Core::Db::Connection::close() { mysql_close( m_pRawCon ); m_bConnected = false; } bool Core::Db::Connection::isClosed() const { return !m_bConnected; } Core::Db::MySqlBase* Core::Db::Connection::getMySqlBase() const { return m_pBase; } void Core::Db::Connection::setAutoCommit( bool autoCommit ) { auto b = static_cast< my_bool >( autoCommit == true ? 1 : 0 ); if( mysql_autocommit( m_pRawCon, b ) != 0 ) throw std::runtime_error( "Connection::setAutoCommit failed!" ); } bool Core::Db::Connection::getAutoCommit() { // TODO: should be replaced with wrapped sql query function once available std::string query("SELECT @@autocommit"); auto res = mysql_real_query( m_pRawCon, query.c_str(), query.length() ); if( res != 0 ) throw std::runtime_error( "Query failed!" ); auto pRes = mysql_store_result( m_pRawCon ); auto row = mysql_fetch_row( pRes ); uint32_t ac = atoi( row[0] ); return ac != 0; } void Core::Db::Connection::beginTransaction() { boost::scoped_ptr< Statement > stmt( createStatement() ); stmt->execute( "START TRANSACTION;" ); } void Core::Db::Connection::commitTransaction() { boost::scoped_ptr< Statement > stmt( createStatement() ); stmt->execute( "COMMIT" ); } void Core::Db::Connection::rollbackTransaction() { boost::scoped_ptr< Statement > stmt( createStatement() ); stmt->execute( "ROLLBACK" ); } std::string Core::Db::Connection::escapeString( const std::string &inData ) { boost::scoped_array< char > buffer( new char[inData.length() * 2 + 1] ); if( !buffer.get() ) return ""; unsigned long return_len = mysql_real_escape_string( m_pRawCon, buffer.get(), inData.c_str(), static_cast< unsigned long > ( inData.length() ) ); return std::string( buffer.get(), return_len ); } void Core::Db::Connection::setSchema( const std::string &schema ) { if( mysql_select_db( m_pRawCon, schema.c_str() ) != 0 ) throw std::runtime_error( "Current database could not be changed to " + schema ); } Core::Db::Statement *Core::Db::Connection::createStatement() { return new Statement( this ); } MYSQL *Core::Db::Connection::getRawCon() { return m_pRawCon; } std::string Core::Db::Connection::getError() { auto mysqlError = mysql_error( m_pRawCon ); if( mysqlError ) return std::string( mysqlError ); return ""; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: idlcproduce.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: vg $ $Date: 2007-09-20 15:01:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_idlc.hxx" #ifndef _IDLC_IDLC_HXX_ #include <idlc/idlc.hxx> #endif #ifndef _IDLC_ASTMODULE_HXX_ #include <idlc/astmodule.hxx> #endif #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #if defined(SAL_W32) || defined(SAL_OS2) #include <io.h> #include <direct.h> #include <errno.h> #endif #ifdef SAL_UNX #include <unistd.h> #include <sys/stat.h> #include <errno.h> #endif using namespace ::rtl; using namespace ::osl; StringList* pCreatedDirectories = NULL; static sal_Bool checkOutputPath(const OString& completeName) { OString sysPathName = convertToAbsoluteSystemPath(completeName); OStringBuffer buffer(sysPathName.getLength()); if ( sysPathName.indexOf( SEPARATOR ) == -1 ) return sal_True; sal_Int32 nIndex = 0; OString token(sysPathName.getToken(0, SEPARATOR, nIndex)); const sal_Char* p = token.getStr(); if (strcmp(p, "..") == 0 || *(p+1) == ':' || strcmp(p, ".") == 0) { buffer.append(token); buffer.append(SEPARATOR); } else nIndex = 0; do { buffer.append(sysPathName.getToken(0, SEPARATOR, nIndex)); if ( buffer.getLength() > 0 && nIndex != -1 ) { #if defined(SAL_UNX) || defined(SAL_OS2) if (mkdir((char*)buffer.getStr(), 0777) == -1) #else if (mkdir((char*)buffer.getStr()) == -1) #endif { if (errno == ENOENT) { fprintf(stderr, "%s: cannot create directory '%s'\n", idlc()->getOptions()->getProgramName().getStr(), buffer.getStr()); return sal_False; } } else { if ( !pCreatedDirectories ) pCreatedDirectories = new StringList(); pCreatedDirectories->push_front(buffer.getStr()); } } buffer.append(SEPARATOR); } while( nIndex != -1 ); return sal_True; } static sal_Bool cleanPath() { if ( pCreatedDirectories ) { StringList::iterator iter = pCreatedDirectories->begin(); StringList::iterator end = pCreatedDirectories->end(); while ( iter != end ) { //#ifdef SAL_UNX // if (rmdir((char*)(*iter).getStr(), 0777) == -1) //#else if (rmdir((char*)(*iter).getStr()) == -1) //#endif { fprintf(stderr, "%s: cannot remove directory '%s'\n", idlc()->getOptions()->getProgramName().getStr(), (*iter).getStr()); return sal_False; } ++iter; } delete pCreatedDirectories; } return sal_True; } void removeIfExists(const OString& pathname) { unlink(pathname.getStr()); } sal_Int32 SAL_CALL produceFile(const OString& regFileName) { Options* pOptions = idlc()->getOptions(); OString regTmpName = regFileName.replaceAt(regFileName.getLength() -3, 3, "_idlc_"); if ( !checkOutputPath(regFileName) ) { fprintf(stderr, "%s: could not create path of registry file '%s'.\n", pOptions->getProgramName().getStr(), regFileName.getStr()); return 1; } RegistryLoader regLoader; if ( !regLoader.isLoaded() ) { fprintf(stderr, "%s: could not load registry dll.\n", pOptions->getProgramName().getStr()); removeIfExists(regFileName); cleanPath(); return 1; } Registry regFile(regLoader); removeIfExists(regTmpName); OString urlRegTmpName = convertToFileUrl(regTmpName); if ( regFile.create(OStringToOUString(urlRegTmpName, RTL_TEXTENCODING_UTF8)) ) { fprintf(stderr, "%s: could not create registry file '%s'\n", pOptions->getProgramName().getStr(), regTmpName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } RegistryKey rootKey; if ( regFile.openRootKey(rootKey) ) { fprintf(stderr, "%s: could not open root of registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } // produce registry file if ( !idlc()->getRoot()->dump(rootKey) ) { rootKey.closeKey(); regFile.close(); regFile.destroy(OStringToOUString(regFileName, RTL_TEXTENCODING_UTF8)); removeIfExists(regFileName); cleanPath(); return 1; } if ( rootKey.closeKey() ) { fprintf(stderr, "%s: could not close root of registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } if ( regFile.close() ) { fprintf(stderr, "%s: could not close registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } removeIfExists(regFileName); if ( File::move(OStringToOUString(regTmpName, osl_getThreadTextEncoding()), OStringToOUString(regFileName, osl_getThreadTextEncoding())) != FileBase::E_None ) { fprintf(stderr, "%s: cannot rename temporary registry '%s' to '%s'\n", idlc()->getOptions()->getProgramName().getStr(), regTmpName.getStr(), regFileName.getStr()); removeIfExists(regTmpName); cleanPath(); return 1; } removeIfExists(regTmpName); return 0; } <commit_msg>INTEGRATION: CWS sb71 (1.13.26); FILE MERGED 2007/10/02 09:48:49 sb 1.13.26.2: RESYNC: (1.13-1.14); FILE MERGED 2007/06/22 09:34:45 sb 1.13.26.1: #i75466# Support for dynamic loading of the reg shared library has been dropped.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: idlcproduce.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2007-10-15 12:44:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_idlc.hxx" #ifndef _IDLC_IDLC_HXX_ #include <idlc/idlc.hxx> #endif #ifndef _IDLC_ASTMODULE_HXX_ #include <idlc/astmodule.hxx> #endif #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #if defined(SAL_W32) || defined(SAL_OS2) #include <io.h> #include <direct.h> #include <errno.h> #endif #ifdef SAL_UNX #include <unistd.h> #include <sys/stat.h> #include <errno.h> #endif using namespace ::rtl; using namespace ::osl; StringList* pCreatedDirectories = NULL; static sal_Bool checkOutputPath(const OString& completeName) { OString sysPathName = convertToAbsoluteSystemPath(completeName); OStringBuffer buffer(sysPathName.getLength()); if ( sysPathName.indexOf( SEPARATOR ) == -1 ) return sal_True; sal_Int32 nIndex = 0; OString token(sysPathName.getToken(0, SEPARATOR, nIndex)); const sal_Char* p = token.getStr(); if (strcmp(p, "..") == 0 || *(p+1) == ':' || strcmp(p, ".") == 0) { buffer.append(token); buffer.append(SEPARATOR); } else nIndex = 0; do { buffer.append(sysPathName.getToken(0, SEPARATOR, nIndex)); if ( buffer.getLength() > 0 && nIndex != -1 ) { #if defined(SAL_UNX) || defined(SAL_OS2) if (mkdir((char*)buffer.getStr(), 0777) == -1) #else if (mkdir((char*)buffer.getStr()) == -1) #endif { if (errno == ENOENT) { fprintf(stderr, "%s: cannot create directory '%s'\n", idlc()->getOptions()->getProgramName().getStr(), buffer.getStr()); return sal_False; } } else { if ( !pCreatedDirectories ) pCreatedDirectories = new StringList(); pCreatedDirectories->push_front(buffer.getStr()); } } buffer.append(SEPARATOR); } while( nIndex != -1 ); return sal_True; } static sal_Bool cleanPath() { if ( pCreatedDirectories ) { StringList::iterator iter = pCreatedDirectories->begin(); StringList::iterator end = pCreatedDirectories->end(); while ( iter != end ) { //#ifdef SAL_UNX // if (rmdir((char*)(*iter).getStr(), 0777) == -1) //#else if (rmdir((char*)(*iter).getStr()) == -1) //#endif { fprintf(stderr, "%s: cannot remove directory '%s'\n", idlc()->getOptions()->getProgramName().getStr(), (*iter).getStr()); return sal_False; } ++iter; } delete pCreatedDirectories; } return sal_True; } void removeIfExists(const OString& pathname) { unlink(pathname.getStr()); } sal_Int32 SAL_CALL produceFile(const OString& regFileName) { Options* pOptions = idlc()->getOptions(); OString regTmpName = regFileName.replaceAt(regFileName.getLength() -3, 3, "_idlc_"); if ( !checkOutputPath(regFileName) ) { fprintf(stderr, "%s: could not create path of registry file '%s'.\n", pOptions->getProgramName().getStr(), regFileName.getStr()); return 1; } Registry regFile; removeIfExists(regTmpName); OString urlRegTmpName = convertToFileUrl(regTmpName); if ( regFile.create(OStringToOUString(urlRegTmpName, RTL_TEXTENCODING_UTF8)) ) { fprintf(stderr, "%s: could not create registry file '%s'\n", pOptions->getProgramName().getStr(), regTmpName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } RegistryKey rootKey; if ( regFile.openRootKey(rootKey) ) { fprintf(stderr, "%s: could not open root of registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } // produce registry file if ( !idlc()->getRoot()->dump(rootKey) ) { rootKey.closeKey(); regFile.close(); regFile.destroy(OStringToOUString(regFileName, RTL_TEXTENCODING_UTF8)); removeIfExists(regFileName); cleanPath(); return 1; } if ( rootKey.closeKey() ) { fprintf(stderr, "%s: could not close root of registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } if ( regFile.close() ) { fprintf(stderr, "%s: could not close registry file '%s'\n", pOptions->getProgramName().getStr(), regFileName.getStr()); removeIfExists(regTmpName); removeIfExists(regFileName); cleanPath(); return 1; } removeIfExists(regFileName); if ( File::move(OStringToOUString(regTmpName, osl_getThreadTextEncoding()), OStringToOUString(regFileName, osl_getThreadTextEncoding())) != FileBase::E_None ) { fprintf(stderr, "%s: cannot rename temporary registry '%s' to '%s'\n", idlc()->getOptions()->getProgramName().getStr(), regTmpName.getStr(), regFileName.getStr()); removeIfExists(regTmpName); cleanPath(); return 1; } removeIfExists(regTmpName); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <string> using std::string; using std::cout; using std::endl; int main() { string str("a simple string"); // while int i = 0; while (i < str.size()) str[i++] = 'X'; cout << str << endl; // for for (i = 0; i<str.size(); ++i) str[i] = 'Y'; cout << str << endl; // I like range for. return 0; } <commit_msg>Update ex3_8.cpp<commit_after>#include <iostream> #include <string> using std::string; using std::cout; using std::endl; int main() { string str("a simple string"); // while int i = 0; while (i < str.size()) str[i++] = 'X'; cout << str << endl; // for for (i = 0; i<str.size(); ++i) str[i] = 'Y'; cout << str << endl; // I like range for. return 0; } <|endoftext|>
<commit_before>#include <catch.hpp> #include <map> #include <string> #include <boost/variant/get.hpp> #include "../../src/HTMLParser/HTMLParser.hpp" #include "../../src/HTMLParser/tokens/StartToken.hpp" #include "../../src/HTMLParser/tokens/DoctypeToken.hpp" #include "../../src/HTMLParser/tokens/EndToken.hpp" TEST_CASE("HTML tokenization") { std::map<std::wstring, std::wstring> empty_map; SECTION("Manually creating tokens") { SECTION("Manually creating doctype token") { DoctypeToken doctype_token = DoctypeToken(); CHECK_FALSE(doctype_token.quirks_required()); CHECK_FALSE(doctype_token.is_name_set()); CHECK_FALSE(doctype_token.is_public_identifier_set()); CHECK_FALSE(doctype_token.is_system_identifier_set()); } SECTION("Manually creating HTML root token") { StartToken html_token = StartToken(); CHECK_FALSE(html_token.is_self_closing()); CHECK(html_token.get_attributes() == empty_map); CHECK(html_token.get_tag_name() == L""); } } SECTION("Creating tokens with parser") { HTMLParser parser; SECTION("Creating doctype tokens with parser") { SECTION("Normal doctype token") { auto token = parser.create_token_from_string(L"<!DOCTYPE html>"); DoctypeToken *doctype_token = dynamic_cast<DoctypeToken*>(token.get()); REQUIRE(token->is_doctype_token()); CHECK_FALSE(doctype_token->quirks_required()); CHECK(doctype_token->is_name_set()); CHECK(doctype_token->get_tag_name() == L"html"); } SECTION("Doctype name not set") { // std::unique_ptr<HTMLToken> token = auto token = parser.create_token_from_string(L"<!DOCTYPE>"); DoctypeToken *doctype_token = dynamic_cast<DoctypeToken*>(token.get()); REQUIRE(token->is_doctype_token()); CHECK(doctype_token->quirks_required()); CHECK_FALSE(doctype_token->is_name_set()); } SECTION("Correctly handles extra identifiers") { std::wstring long_doctype = L"<!DOCTYPE HTML PUBLIC " L"\"-//W3C//DTD HTML 4.01 Transitional//EN\" " L"\"http://www.w3.org/TR/html4/loose.dtd\">"; std::unique_ptr<HTMLToken> token = parser.create_token_from_string(long_doctype); DoctypeToken *doctype_token = dynamic_cast<DoctypeToken*>(token.get()); REQUIRE(token->is_doctype_token()); CHECK(doctype_token->quirks_required()); CHECK(doctype_token->get_tag_name() == L"html"); CHECK(doctype_token->is_name_set()); } } SECTION("Creating start tokens with parser") { std::map<std::wstring, std::wstring> lang_map = {{L"lang", L"en"}}; SECTION("Creating html root token with parser") { // std::unique_ptr<HTMLToken> token = auto token = parser.create_token_from_string(L"<HtMl lang=\"en\">"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); std::map<std::wstring, std::wstring> attributes_map = start_token->get_attributes(); CHECK_FALSE(start_token->is_self_closing()); CHECK(start_token->contains_attribute(L"lang")); CHECK(start_token->get_attribute_value(L"lang") == L"en"); CHECK(start_token->get_tag_name() == L"html"); } SECTION("Creating self-closing tag with parser") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<br/>"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); CHECK(start_token->is_self_closing()); CHECK(start_token->get_tag_name() == L"br"); } SECTION("Tag with multiple attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<img src=\"example.png\" width='10' height='20'>"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); std::map<std::wstring, std::wstring> attributes_map = start_token->get_attributes(); CHECK(start_token->get_tag_name() == L"img"); CHECK_FALSE(start_token->is_self_closing()); CHECK(start_token->contains_attribute(L"src")); CHECK(start_token->contains_attribute(L"width")); CHECK(start_token->contains_attribute(L"height")); CHECK(start_token->get_attribute_value(L"src") == L"example.png"); CHECK(start_token->get_attribute_value(L"width") == L"10"); CHECK(start_token->get_attribute_value(L"height") == L"20"); } SECTION("Tag with repeated attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<html lang='en' lang='br'>"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); CHECK(start_token->get_tag_name() == L"html"); CHECK(start_token->contains_attribute(L"lang")); CHECK(start_token->get_attribute_value(L"lang") == L"en"); CHECK_FALSE(start_token->get_attribute_value(L"lang") == L"br"); CHECK_FALSE(start_token->is_self_closing()); } SECTION("Capitalization in attribute name/value") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<html lAnG='eN'>"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); CHECK(start_token->get_tag_name() == L"html"); CHECK(start_token->contains_attribute(L"lang")); CHECK(start_token->get_attribute_value(L"lang") == L"en"); CHECK_FALSE(start_token->contains_attribute(L"lAnG")); CHECK_FALSE(start_token->is_self_closing()); } SECTION("Self-closing tag with attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<area shape=\"circle\"/>"); StartToken *start_token = dynamic_cast<StartToken*>(token.get()); CHECK(start_token->get_tag_name() == L"area"); CHECK(start_token->is_self_closing()); CHECK(start_token->contains_attribute(L"shape")); CHECK(start_token->get_attribute_value(L"shape") == L"circle"); } } SECTION("Creating end tags with parser") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"</p>"); EndToken *end_token = dynamic_cast<EndToken*>(token.get()); CHECK(end_token->get_tag_name() == L"p"); CHECK_FALSE(end_token->is_self_closing()); } } } <commit_msg>Remove needless dynamic casts from tests<commit_after>#include <catch.hpp> #include <map> #include <string> #include <boost/variant/get.hpp> #include "../../src/HTMLParser/HTMLParser.hpp" #include "../../src/HTMLParser/tokens/StartToken.hpp" #include "../../src/HTMLParser/tokens/DoctypeToken.hpp" #include "../../src/HTMLParser/tokens/EndToken.hpp" #include "../../src/HTMLParser/tokens/CommentToken.hpp" TEST_CASE("HTML tokenization") { std::map<std::wstring, std::wstring> empty_map; SECTION("Manually creating tokens") { SECTION("Manually creating doctype token") { DoctypeToken doctype_token = DoctypeToken(); CHECK_FALSE(doctype_token.quirks_required()); CHECK_FALSE(doctype_token.is_name_set()); CHECK_FALSE(doctype_token.is_public_identifier_set()); CHECK_FALSE(doctype_token.is_system_identifier_set()); } SECTION("Manually creating HTML root token") { StartToken html_token = StartToken(); CHECK_FALSE(html_token.is_self_closing()); CHECK(html_token.get_attributes() == empty_map); CHECK(html_token.get_tag_name() == L""); } } SECTION("Creating tokens with parser") { HTMLParser parser; SECTION("Creating doctype tokens with parser") { SECTION("Normal doctype token") { auto doctype_token = parser.create_token_from_string(L"<!DOCTYPE html>"); REQUIRE(doctype_token->is_doctype_token()); CHECK_FALSE(doctype_token->quirks_required()); CHECK(doctype_token->is_name_set()); CHECK(doctype_token->get_tag_name() == L"html"); } SECTION("Doctype name not set") { auto doctype_token = parser.create_token_from_string(L"<!DOCTYPE>"); REQUIRE(doctype_token->is_doctype_token()); CHECK(doctype_token->quirks_required()); CHECK_FALSE(doctype_token->is_name_set()); } SECTION("Correctly handles extra identifiers") { std::wstring long_doctype = L"<!DOCTYPE HTML PUBLIC " L"\"-//W3C//DTD HTML 4.01 Transitional//EN\" " L"\"http://www.w3.org/TR/html4/loose.dtd\">"; std::unique_ptr<HTMLToken> doctype_token = parser.create_token_from_string(long_doctype); REQUIRE(doctype_token->is_doctype_token()); CHECK(doctype_token->quirks_required()); CHECK(doctype_token->get_tag_name() == L"html"); CHECK(doctype_token->is_name_set()); } } SECTION("Creating start tokens with parser") { std::map<std::wstring, std::wstring> lang_map = {{L"lang", L"en"}}; SECTION("Creating html root token with parser") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<HtMl lang=\"en\">"); std::map<std::wstring, std::wstring> attributes_map = token->get_attributes(); REQUIRE(token->is_start_token()); CHECK_FALSE(token->is_self_closing()); CHECK(token->contains_attribute(L"lang")); CHECK(token->get_attribute_value(L"lang") == L"en"); CHECK(token->get_tag_name() == L"html"); } SECTION("Creating self-closing tag with parser") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<br/>"); REQUIRE(token->is_start_token()); CHECK(token->is_self_closing()); CHECK(token->get_tag_name() == L"br"); } SECTION("Tag with multiple attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<img src=\"example.png\" width='10' height='20'>"); std::map<std::wstring, std::wstring> attributes_map = token->get_attributes(); REQUIRE(token->is_start_token()); CHECK(token->get_tag_name() == L"img"); CHECK_FALSE(token->is_self_closing()); CHECK(token->contains_attribute(L"src")); CHECK(token->contains_attribute(L"width")); CHECK(token->contains_attribute(L"height")); CHECK(token->get_attribute_value(L"src") == L"example.png"); CHECK(token->get_attribute_value(L"width") == L"10"); CHECK(token->get_attribute_value(L"height") == L"20"); } SECTION("Tag with repeated attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<html lang='en' lang='br'>"); REQUIRE(token->is_start_token()); CHECK(token->get_tag_name() == L"html"); CHECK(token->contains_attribute(L"lang")); CHECK(token->get_attribute_value(L"lang") == L"en"); CHECK_FALSE(token->get_attribute_value(L"lang") == L"br"); CHECK_FALSE(token->is_self_closing()); } SECTION("Capitalization in attribute name/value") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<html lAnG='eN'>"); REQUIRE(token->is_start_token()); CHECK(token->get_tag_name() == L"html"); CHECK(token->contains_attribute(L"lang")); CHECK(token->get_attribute_value(L"lang") == L"en"); CHECK_FALSE(token->contains_attribute(L"lAnG")); CHECK_FALSE(token->is_self_closing()); } SECTION("Self-closing tag with attributes") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<area shape=\"circle\"/>"); REQUIRE(token->is_start_token()); CHECK(token->get_tag_name() == L"area"); CHECK(token->is_self_closing()); CHECK(token->contains_attribute(L"shape")); CHECK(token->get_attribute_value(L"shape") == L"circle"); } } SECTION("Creating end tags with parser") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"</p>"); REQUIRE(token->is_end_token()); CHECK(token->get_tag_name() == L"p"); CHECK_FALSE(token->is_self_closing()); } SECTION("Creating comment tags with parser") { SECTION("Normal comment") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string( L"<!--This is a comment-->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L"This is a comment"); } SECTION("Comment with no data") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<!---->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L""); } SECTION("Comment with hyphen in data") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<!--Test-string-->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L"Test-string"); } SECTION("Comment with hyphen before data") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<!---Test string-->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L"-Test string"); } SECTION("Comment with two hyphens in the middle") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<!--Test--string->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L"-Test--string"); } SECTION("Comment with exclamation mark and hyphens in the middle") { std::unique_ptr<HTMLToken> token = parser.create_token_from_string(L"<!--Test--!string->"); REQUIRE(token->is_comment_token()); CHECK(token->get_data() == L"-Test--!string"); } } } } <|endoftext|>
<commit_before>#include <list> #include <string> #include "uvpp_tcp.hpp" int main() { uvpp::Loop uvloop; uvpp::Signal sigtrap(uvloop); sigtrap.set_callback([&uvloop](){ uvloop.stop(); }); sigtrap.start(SIGINT); uvpp::Tcp server(uvloop); std::list<uvpp::Tcp> clients; struct sockaddr_in saddr; uv_ip4_addr("127.0.0.1", 12345, &saddr); server.bind(saddr); server.listen([&](uvpp::Tcp conn){ struct sockaddr_in saddr; conn.getpeername(saddr); char buffer[64]; uv_ip4_name(&saddr, buffer, sizeof(buffer)); printf("connection from %s:%d\n", buffer, ntohs(saddr.sin_port)); clients.emplace_back(std::move(conn)); auto connit = --clients.end(); connit->set_callback([&clients, connit](char *buf, int len){ if (len < 0) { uvpp::print_error(len); clients.erase(connit); return; } auto str = std::string(buf, len); std::cout << str << std::endl; connit->write(buf, len); }); connit->read_start(); }); uvloop.run(); } <commit_msg>use std::prev to get last element<commit_after>#include <list> #include <string> #include "uvpp_tcp.hpp" int main() { uvpp::Loop uvloop; uvpp::Signal sigtrap(uvloop); sigtrap.set_callback([&uvloop](){ uvloop.stop(); }); sigtrap.start(SIGINT); uvpp::Tcp server(uvloop); std::list<uvpp::Tcp> clients; struct sockaddr_in saddr; uv_ip4_addr("127.0.0.1", 12345, &saddr); server.bind(saddr); server.listen([&](uvpp::Tcp conn){ struct sockaddr_in saddr; conn.getpeername(saddr); char buffer[64]; uv_ip4_name(&saddr, buffer, sizeof(buffer)); printf("connection from %s:%d\n", buffer, ntohs(saddr.sin_port)); clients.emplace_back(std::move(conn)); auto connit = std::prev(clients.end()); connit->set_callback([&clients, connit](char *buf, int len){ if (len < 0) { uvpp::print_error(len); clients.erase(connit); return; } auto str = std::string(buf, len); std::cout << str << std::endl; connit->write(buf, len); }); connit->read_start(); }); uvloop.run(); } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EGLSurfacelessContextTest.cpp: // Tests for the EGL_KHR_surfaceless_context and GL_OES_surfaceless_context #include <gtest/gtest.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_configs.h" #include "test_utils/gl_raii.h" using namespace angle; namespace { class EGLSurfacelessContextTest : public ANGLETest { public: EGLSurfacelessContextTest() : mDisplay(0) {} void SetUp() override { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>( eglGetProcAddress("eglGetPlatformDisplayEXT")); ASSERT_TRUE(eglGetPlatformDisplayEXT != nullptr); EGLint dispattrs[] = {EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(), EGL_NONE}; mDisplay = eglGetPlatformDisplayEXT( EGL_PLATFORM_ANGLE_ANGLE, reinterpret_cast<void *>(EGL_DEFAULT_DISPLAY), dispattrs); ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY); ASSERT_EGL_TRUE(eglInitialize(mDisplay, nullptr, nullptr)); int nConfigs = 0; ASSERT_EGL_TRUE(eglGetConfigs(mDisplay, nullptr, 0, &nConfigs)); ASSERT_TRUE(nConfigs != 0); int nReturnedConfigs = 0; std::vector<EGLConfig> configs(nConfigs); ASSERT_EGL_TRUE(eglGetConfigs(mDisplay, configs.data(), nConfigs, &nReturnedConfigs)); ASSERT_TRUE(nConfigs == nReturnedConfigs); for (auto config : configs) { EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); if (surfaceType & EGL_PBUFFER_BIT) { mConfig = config; break; } } ASSERT_NE(nullptr, mConfig); } void TearDown() override { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (mContext != EGL_NO_CONTEXT) { eglDestroyContext(mDisplay, mContext); } if (mContext != EGL_NO_SURFACE) { eglDestroySurface(mDisplay, mPbuffer); } eglTerminate(mDisplay); } protected: EGLContext createContext() { const EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; EGLContext mContext = eglCreateContext(mDisplay, mConfig, EGL_NO_CONTEXT, contextAttribs); EXPECT_TRUE(mContext != EGL_NO_CONTEXT); return mContext; } EGLSurface createPbuffer(int width, int height) { const EGLint pbufferAttribs[] = { EGL_WIDTH, 500, EGL_HEIGHT, 500, EGL_NONE, }; EGLSurface mPbuffer = eglCreatePbufferSurface(mDisplay, mConfig, pbufferAttribs); EXPECT_TRUE(mPbuffer != EGL_NO_SURFACE); return mPbuffer; } void createFramebuffer(GLFramebuffer *fbo, GLTexture *tex) const { glBindFramebuffer(GL_FRAMEBUFFER, fbo->get()); glBindTexture(GL_TEXTURE_2D, tex->get()); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 500, 500, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex->get(), 0); EXPECT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER)); } bool checkExtension(bool verbose = true) const { if (!ANGLETest::eglDisplayExtensionEnabled(mDisplay, "EGL_KHR_surfaceless_context")) { if (verbose) { std::cout << "Test skipped because EGL_KHR_surfaceless_context is not available." << std::endl; } return false; } return true; } EGLContext mContext = EGL_NO_CONTEXT; EGLSurface mPbuffer = EGL_NO_SURFACE; EGLConfig mConfig = 0; EGLDisplay mDisplay = EGL_NO_DISPLAY; }; // Test surfaceless MakeCurrent returns the correct value. TEST_P(EGLSurfacelessContextTest, MakeCurrentSurfaceless) { EGLContext context = createContext(); if (eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) { ASSERT_TRUE(checkExtension(false)); } else { // The extension allows EGL_BAD_MATCH with the extension too, but ANGLE // shouldn't do that. ASSERT_FALSE(checkExtension(false)); } } // Test that the scissor and viewport are set correctly TEST_P(EGLSurfacelessContextTest, DefaultScissorAndViewport) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLint scissor[4] = {1, 2, 3, 4}; glGetIntegerv(GL_SCISSOR_BOX, scissor); ASSERT_GL_NO_ERROR(); ASSERT_EQ(0, scissor[0]); ASSERT_EQ(0, scissor[1]); ASSERT_EQ(0, scissor[2]); ASSERT_EQ(0, scissor[3]); GLint viewport[4] = {1, 2, 3, 4}; glGetIntegerv(GL_VIEWPORT, viewport); ASSERT_GL_NO_ERROR(); ASSERT_EQ(0, viewport[0]); ASSERT_EQ(0, viewport[1]); ASSERT_EQ(0, viewport[2]); ASSERT_EQ(0, viewport[3]); } // Test the CheckFramebufferStatus returns the correct value. TEST_P(EGLSurfacelessContextTest, CheckFramebufferStatus) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_UNDEFINED_OES, glCheckFramebufferStatus(GL_FRAMEBUFFER)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER)); } // Test that clearing and readpixels work when done in an FBO. TEST_P(EGLSurfacelessContextTest, ClearReadPixelsInFBO) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::red); ASSERT_GL_NO_ERROR(); } // Test clear+readpixels in an FBO in surfaceless and in the default FBO in a pbuffer TEST_P(EGLSurfacelessContextTest, Switcheroo) { if (!checkExtension()) { return; } EGLContext context = createContext(); EGLSurface pbuffer = createPbuffer(500, 500); // We need to make the context current to do the one time setup of the FBO ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); for (int i = 0; i < 4; ++i) { // Clear to red in the FBO in surfaceless mode ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::red); ASSERT_GL_NO_ERROR(); // Clear to green in the pbuffer ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, pbuffer, pbuffer, context)); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::green); ASSERT_GL_NO_ERROR(); } } } // anonymous namespace ANGLE_INSTANTIATE_TEST(EGLSurfacelessContextTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL()); <commit_msg>Fix member variable masking in EGLSurfacelessContextTest<commit_after>// // Copyright (c) 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EGLSurfacelessContextTest.cpp: // Tests for the EGL_KHR_surfaceless_context and GL_OES_surfaceless_context #include <gtest/gtest.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_configs.h" #include "test_utils/gl_raii.h" using namespace angle; namespace { class EGLSurfacelessContextTest : public ANGLETest { public: EGLSurfacelessContextTest() : mDisplay(0) {} void SetUp() override { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>( eglGetProcAddress("eglGetPlatformDisplayEXT")); ASSERT_TRUE(eglGetPlatformDisplayEXT != nullptr); EGLint dispattrs[] = {EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(), EGL_NONE}; mDisplay = eglGetPlatformDisplayEXT( EGL_PLATFORM_ANGLE_ANGLE, reinterpret_cast<void *>(EGL_DEFAULT_DISPLAY), dispattrs); ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY); ASSERT_EGL_TRUE(eglInitialize(mDisplay, nullptr, nullptr)); int nConfigs = 0; ASSERT_EGL_TRUE(eglGetConfigs(mDisplay, nullptr, 0, &nConfigs)); ASSERT_TRUE(nConfigs != 0); int nReturnedConfigs = 0; std::vector<EGLConfig> configs(nConfigs); ASSERT_EGL_TRUE(eglGetConfigs(mDisplay, configs.data(), nConfigs, &nReturnedConfigs)); ASSERT_TRUE(nConfigs == nReturnedConfigs); for (auto config : configs) { EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); if (surfaceType & EGL_PBUFFER_BIT) { mConfig = config; break; } } ASSERT_NE(nullptr, mConfig); } void TearDown() override { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (mContext != EGL_NO_CONTEXT) { eglDestroyContext(mDisplay, mContext); } if (mContext != EGL_NO_SURFACE) { eglDestroySurface(mDisplay, mPbuffer); } eglTerminate(mDisplay); } protected: EGLContext createContext() { const EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; mContext = eglCreateContext(mDisplay, mConfig, EGL_NO_CONTEXT, contextAttribs); EXPECT_TRUE(mContext != EGL_NO_CONTEXT); return mContext; } EGLSurface createPbuffer(int width, int height) { const EGLint pbufferAttribs[] = { EGL_WIDTH, 500, EGL_HEIGHT, 500, EGL_NONE, }; mPbuffer = eglCreatePbufferSurface(mDisplay, mConfig, pbufferAttribs); EXPECT_TRUE(mPbuffer != EGL_NO_SURFACE); return mPbuffer; } void createFramebuffer(GLFramebuffer *fbo, GLTexture *tex) const { glBindFramebuffer(GL_FRAMEBUFFER, fbo->get()); glBindTexture(GL_TEXTURE_2D, tex->get()); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 500, 500, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex->get(), 0); EXPECT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER)); } bool checkExtension(bool verbose = true) const { if (!ANGLETest::eglDisplayExtensionEnabled(mDisplay, "EGL_KHR_surfaceless_context")) { if (verbose) { std::cout << "Test skipped because EGL_KHR_surfaceless_context is not available." << std::endl; } return false; } return true; } EGLContext mContext = EGL_NO_CONTEXT; EGLSurface mPbuffer = EGL_NO_SURFACE; EGLConfig mConfig = 0; EGLDisplay mDisplay = EGL_NO_DISPLAY; }; // Test surfaceless MakeCurrent returns the correct value. TEST_P(EGLSurfacelessContextTest, MakeCurrentSurfaceless) { EGLContext context = createContext(); if (eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) { ASSERT_TRUE(checkExtension(false)); } else { // The extension allows EGL_BAD_MATCH with the extension too, but ANGLE // shouldn't do that. ASSERT_FALSE(checkExtension(false)); } } // Test that the scissor and viewport are set correctly TEST_P(EGLSurfacelessContextTest, DefaultScissorAndViewport) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLint scissor[4] = {1, 2, 3, 4}; glGetIntegerv(GL_SCISSOR_BOX, scissor); ASSERT_GL_NO_ERROR(); ASSERT_EQ(0, scissor[0]); ASSERT_EQ(0, scissor[1]); ASSERT_EQ(0, scissor[2]); ASSERT_EQ(0, scissor[3]); GLint viewport[4] = {1, 2, 3, 4}; glGetIntegerv(GL_VIEWPORT, viewport); ASSERT_GL_NO_ERROR(); ASSERT_EQ(0, viewport[0]); ASSERT_EQ(0, viewport[1]); ASSERT_EQ(0, viewport[2]); ASSERT_EQ(0, viewport[3]); } // Test the CheckFramebufferStatus returns the correct value. TEST_P(EGLSurfacelessContextTest, CheckFramebufferStatus) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_UNDEFINED_OES, glCheckFramebufferStatus(GL_FRAMEBUFFER)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER)); } // Test that clearing and readpixels work when done in an FBO. TEST_P(EGLSurfacelessContextTest, ClearReadPixelsInFBO) { if (!checkExtension()) { return; } EGLContext context = createContext(); ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::red); ASSERT_GL_NO_ERROR(); } // Test clear+readpixels in an FBO in surfaceless and in the default FBO in a pbuffer TEST_P(EGLSurfacelessContextTest, Switcheroo) { if (!checkExtension()) { return; } EGLContext context = createContext(); EGLSurface pbuffer = createPbuffer(500, 500); // We need to make the context current to do the one time setup of the FBO ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); GLFramebuffer fbo; GLTexture tex; createFramebuffer(&fbo, &tex); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); for (int i = 0; i < 4; ++i) { // Clear to red in the FBO in surfaceless mode ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context)); glBindFramebuffer(GL_FRAMEBUFFER, fbo.get()); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::red); ASSERT_GL_NO_ERROR(); // Clear to green in the pbuffer ASSERT_EGL_TRUE(eglMakeCurrent(mDisplay, pbuffer, pbuffer, context)); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_COLOR_EQ(250, 250, GLColor::green); ASSERT_GL_NO_ERROR(); } } } // anonymous namespace ANGLE_INSTANTIATE_TEST(EGLSurfacelessContextTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL()); <|endoftext|>
<commit_before>/* This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Given a set of persistence diagrams, the tool calculates a histogram glyph. The glyph uses persistence indicator functions, a summarizing function of a persistence diagram. This tool follows the publication: Clique Community Persistence: A Topological Visual Analysis Approach for Complex Networks Bastian Rieck, Ulderico Fugacci, Jonas Lukasczyk, Heike Leitte Submitted to IEEE Vis 2017 TODO: Link to documentation */ #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> #include <cmath> #include <getopt.h> #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistenceDiagrams/PersistenceIndicatorFunction.hh> #include <aleph/persistenceDiagrams/io/Raw.hh> using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using StepFunction = aleph::math::StepFunction<double>; /* Prints a vector in a simple matrix-like format. Given a row index, all of the entries are considered to be the columns of the matrix: Input: {4,5,6}, row = 23 Output: 23 0 4 23 1 5 23 2 6 <empty line> This output format is flexible and permits direct usage in other tools such as TikZ or pgfplots. */ template <class Map> void print( std::ostream& o, const Map& m, unsigned row ) { unsigned column = 0; for( auto it = m.begin(); it != m.end(); ++it ) o << column++ << "\t" << row << "\t" << *it << "\n"; o << "\n"; } void usage() { std::cerr << "Usage: persistence_indicator_function_glyph [--max-k=K] BINS FILES\n" << "\n" << "Calculates persistence indicator function glyphs based on a set\n" << "of persistence diagrams. The function uses BINS many bins. More\n" << "than one file may be processed.\n" << "\n" << "Optional arguments:\n" << "\n" << " --max-k: Always use the specified number of glyphs. This makes\n" << " sure that even if a group of persistence diagrams has\n" << " an insufficient number of members, its glyph shall be\n" << " extended. This is useful for group comparison.\n" << "\n\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "max-k", required_argument, nullptr, 'K' }, { nullptr, 0 , nullptr, 0 } }; int option = 0; unsigned maxK = 0; while( ( option = getopt_long( argc, argv, "K:", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'K': maxK = unsigned( std::stoul( optarg ) ); break; default: break; } } if( argc - optind < 2 ) { usage(); return -1; } unsigned n = static_cast<unsigned>( std::stoul( argv[optind++] ) ); std::vector<std::string> filenames; std::vector<PersistenceDiagram> persistenceDiagrams; std::vector<StepFunction> persistenceIndicatorFunctions; std::set<DataType> domain; for( int i = optind; i < argc; i++ ) { filenames.push_back( argv[i] ); std::cerr << "* Processing '" << argv[i] << "'..."; PersistenceDiagram persistenceDiagram = aleph::io::load<DataType>( filenames.back() ); persistenceDiagram.removeDiagonal(); persistenceDiagram.removeUnpaired(); persistenceDiagrams.push_back( persistenceDiagram ); persistenceIndicatorFunctions.push_back( aleph::persistenceIndicatorFunction( persistenceDiagram ) ); persistenceIndicatorFunctions.back().domain( std::inserter( domain, domain.begin() ) ); std::cerr << "finished\n"; } if( domain.empty() ) return -1; auto min = *domain.begin(); auto max = std::nextafter( *domain.rbegin(), std::numeric_limits<DataType>::max() ); std::cerr << "* Domain: [" << min << "," << max << "]\n"; // Prepare bins ------------------------------------------------------ std::vector<DataType> linbins; std::vector<DataType> logbins; linbins.reserve( n ); logbins.reserve( n ); for( unsigned i = 0; i < n; i++ ) { auto offset = ( max - min ) / n; auto value = min + i * offset; linbins.push_back( value ); } std::cerr << "* Linear-spaced bins: "; for( auto&& linbin : linbins ) std::cerr << linbin << " "; std::cerr << "\n"; for( unsigned i = 0; i < n; i++ ) { auto offset = ( std::log10( max ) - std::log10( min ) ) / (n-1); auto value = std::log10( min ) + i * offset; logbins.push_back( value ); } std::transform( logbins.begin(), logbins.end(), logbins.begin(), [] ( const DataType x ) { return std::pow( DataType(10), x ); } ); std::cerr << "* Log-spaced bins: "; for( auto&& logbin : logbins ) std::cerr << logbin << " "; std::cerr << "\n"; for( auto it = linbins.begin(); it != linbins.end(); ++it ) { if( it != linbins.begin() ) { auto prev = std::prev( it ); domain.insert( ( *prev + *it ) / 2.0 ); } } for( auto it = logbins.begin(); it != logbins.end(); ++it ) { if( it != logbins.begin() && std::isfinite( *it ) ) { auto prev = std::prev( it ); domain.insert( ( *prev + *it ) / 2.0 ); } } // Replace domain --------------------------------------------------- { std::set<DataType> newDomain; for( auto&& x : domain ) { if( x != *domain.rbegin() ) newDomain.insert( std::nextafter( x, std::numeric_limits<DataType>::max() ) ); if( x != *domain.begin() ) newDomain.insert( std::nextafter( x, -std::numeric_limits<DataType>::max() ) ); } domain.swap( newDomain ); } // Prepare histogram calculation ------------------------------------- auto valueToLinIndex = [&min, &max, &linbins, &n] ( DataType value ) { auto offset = ( max - min ) / n; return static_cast<std::size_t>( ( value - min ) / offset ); }; auto valueToLogIndex = [&min, &max, &logbins, &n] ( DataType value ) { auto offset = ( std::log10( max ) - std::log10( min ) ) / n; return static_cast<std::size_t>( ( std::log10( value ) - std::log10( min ) ) / offset ); }; std::ofstream linout( "/tmp/Persistence_indicator_function_glyph_" + std::to_string( n ) + "_lin.txt" ); std::ofstream logout( "/tmp/Persistence_indicator_function_glyph_" + std::to_string( n ) + "_log.txt" ); unsigned index = 0; for( auto&& pif : persistenceIndicatorFunctions ) { std::vector<DataType> linhist(n); std::vector<DataType> loghist(n); for( auto&& x : domain ) { auto value = pif(x); auto linbin = valueToLinIndex(x); auto logbin = valueToLogIndex(x); linhist.at(linbin) = std::max( linhist.at(linbin), value ); if( logbin < loghist.size() ) loghist.at(logbin) = std::max( loghist.at(logbin), value ); } print( linout, linhist, index ); print( logout, loghist, index ); ++index; } // Extend the output with sufficiently many empty histograms. This // ensures that the output has the same dimensions. for( unsigned i = unsigned( persistenceIndicatorFunctions.size() ); i < maxK; i++ ) { std::vector<DataType> hist(n); print( linout, hist, i ); print( logout, hist, i ); } } <commit_msg>Added link to documentation & removed "uncaptured" variables<commit_after>/* This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Given a set of persistence diagrams, the tool calculates a histogram glyph. The glyph uses persistence indicator functions, a summarizing function of a persistence diagram. This tool follows the publication: Clique Community Persistence: A Topological Visual Analysis Approach for Complex Networks Bastian Rieck, Ulderico Fugacci, Jonas Lukasczyk, Heike Leitte Submitted to IEEE Vis 2017 Please see https://submanifold.github.io/Aleph/Rieck17d.html for more usage details. */ #include <algorithm> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> #include <cmath> #include <getopt.h> #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistenceDiagrams/PersistenceIndicatorFunction.hh> #include <aleph/persistenceDiagrams/io/Raw.hh> using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using StepFunction = aleph::math::StepFunction<double>; /* Prints a vector in a simple matrix-like format. Given a row index, all of the entries are considered to be the columns of the matrix: Input: {4,5,6}, row = 23 Output: 23 0 4 23 1 5 23 2 6 <empty line> This output format is flexible and permits direct usage in other tools such as TikZ or pgfplots. */ template <class Map> void print( std::ostream& o, const Map& m, unsigned row ) { unsigned column = 0; for( auto it = m.begin(); it != m.end(); ++it ) o << column++ << "\t" << row << "\t" << *it << "\n"; o << "\n"; } void usage() { std::cerr << "Usage: persistence_indicator_function_glyph [--max-k=K] BINS FILES\n" << "\n" << "Calculates persistence indicator function glyphs based on a set\n" << "of persistence diagrams. The function uses BINS many bins. More\n" << "than one file may be processed.\n" << "\n" << "Optional arguments:\n" << "\n" << " --max-k: Always use the specified number of glyphs. This makes\n" << " sure that even if a group of persistence diagrams has\n" << " an insufficient number of members, its glyph shall be\n" << " extended. This is useful for group comparison.\n" << "\n\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "max-k", required_argument, nullptr, 'K' }, { nullptr, 0 , nullptr, 0 } }; int option = 0; unsigned maxK = 0; while( ( option = getopt_long( argc, argv, "K:", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'K': maxK = unsigned( std::stoul( optarg ) ); break; default: break; } } if( argc - optind < 2 ) { usage(); return -1; } unsigned n = static_cast<unsigned>( std::stoul( argv[optind++] ) ); std::vector<std::string> filenames; std::vector<PersistenceDiagram> persistenceDiagrams; std::vector<StepFunction> persistenceIndicatorFunctions; std::set<DataType> domain; for( int i = optind; i < argc; i++ ) { filenames.push_back( argv[i] ); std::cerr << "* Processing '" << argv[i] << "'..."; PersistenceDiagram persistenceDiagram = aleph::io::load<DataType>( filenames.back() ); persistenceDiagram.removeDiagonal(); persistenceDiagram.removeUnpaired(); persistenceDiagrams.push_back( persistenceDiagram ); persistenceIndicatorFunctions.push_back( aleph::persistenceIndicatorFunction( persistenceDiagram ) ); persistenceIndicatorFunctions.back().domain( std::inserter( domain, domain.begin() ) ); std::cerr << "finished\n"; } if( domain.empty() ) return -1; auto min = *domain.begin(); auto max = std::nextafter( *domain.rbegin(), std::numeric_limits<DataType>::max() ); std::cerr << "* Domain: [" << min << "," << max << "]\n"; // Prepare bins ------------------------------------------------------ std::vector<DataType> linbins; std::vector<DataType> logbins; linbins.reserve( n ); logbins.reserve( n ); for( unsigned i = 0; i < n; i++ ) { auto offset = ( max - min ) / n; auto value = min + i * offset; linbins.push_back( value ); } std::cerr << "* Linear-spaced bins: "; for( auto&& linbin : linbins ) std::cerr << linbin << " "; std::cerr << "\n"; for( unsigned i = 0; i < n; i++ ) { auto offset = ( std::log10( max ) - std::log10( min ) ) / (n-1); auto value = std::log10( min ) + i * offset; logbins.push_back( value ); } std::transform( logbins.begin(), logbins.end(), logbins.begin(), [] ( const DataType x ) { return std::pow( DataType(10), x ); } ); std::cerr << "* Log-spaced bins: "; for( auto&& logbin : logbins ) std::cerr << logbin << " "; std::cerr << "\n"; for( auto it = linbins.begin(); it != linbins.end(); ++it ) { if( it != linbins.begin() ) { auto prev = std::prev( it ); domain.insert( ( *prev + *it ) / 2.0 ); } } for( auto it = logbins.begin(); it != logbins.end(); ++it ) { if( it != logbins.begin() && std::isfinite( *it ) ) { auto prev = std::prev( it ); domain.insert( ( *prev + *it ) / 2.0 ); } } // Replace domain --------------------------------------------------- { std::set<DataType> newDomain; for( auto&& x : domain ) { if( x != *domain.rbegin() ) newDomain.insert( std::nextafter( x, std::numeric_limits<DataType>::max() ) ); if( x != *domain.begin() ) newDomain.insert( std::nextafter( x, -std::numeric_limits<DataType>::max() ) ); } domain.swap( newDomain ); } // Prepare histogram calculation ------------------------------------- auto valueToLinIndex = [&min, &max, &n] ( DataType value ) { auto offset = ( max - min ) / n; return static_cast<std::size_t>( ( value - min ) / offset ); }; auto valueToLogIndex = [&min, &max, &n] ( DataType value ) { auto offset = ( std::log10( max ) - std::log10( min ) ) / n; return static_cast<std::size_t>( ( std::log10( value ) - std::log10( min ) ) / offset ); }; std::ofstream linout( "/tmp/Persistence_indicator_function_glyph_" + std::to_string( n ) + "_lin.txt" ); std::ofstream logout( "/tmp/Persistence_indicator_function_glyph_" + std::to_string( n ) + "_log.txt" ); unsigned index = 0; for( auto&& pif : persistenceIndicatorFunctions ) { std::vector<DataType> linhist(n); std::vector<DataType> loghist(n); for( auto&& x : domain ) { auto value = pif(x); auto linbin = valueToLinIndex(x); auto logbin = valueToLogIndex(x); linhist.at(linbin) = std::max( linhist.at(linbin), value ); if( logbin < loghist.size() ) loghist.at(logbin) = std::max( loghist.at(logbin), value ); } print( linout, linhist, index ); print( logout, loghist, index ); ++index; } // Extend the output with sufficiently many empty histograms. This // ensures that the output has the same dimensions. for( unsigned i = unsigned( persistenceIndicatorFunctions.size() ); i < maxK; i++ ) { std::vector<DataType> hist(n); print( linout, hist, i ); print( logout, hist, i ); } } <|endoftext|>
<commit_before>#include "P3dSprBuilder.h" #include "IPackNode.h" #include "PackNodeFactory.h" #include <ee/std_functor.h> #include <ee/Visitor.h> #include <easyparticle3d.h> #include <algorithm> namespace erespacker { P3dSprBuilder::P3dSprBuilder(ExportNameSet& export_set) : m_export_set(export_set) { } P3dSprBuilder::~P3dSprBuilder() { for_each(m_nodes.begin(), m_nodes.end(), ee::DeletePointerFunctor<IPackNode>()); } void P3dSprBuilder::Traverse(ee::Visitor& visitor) const { for (int i = 0, n = m_nodes.size(); i < n; ++i) { bool has_next; visitor.Visit(m_nodes[i], has_next); if (!has_next) { break; } } } const IPackNode* P3dSprBuilder::Create(const eparticle3d::Sprite* spr) { PackP3dSpr* node = new PackP3dSpr; node->p3d = PackNodeFactory::Instance()->Create(&spr->GetSymbol()); node->loop = spr->IsLoop(); node->local = spr->IsLocalModeDraw(); node->alone = spr->IsAlone(); node->reuse = spr->IsReuse(); m_nodes.push_back(node); return node; } void P3dSprBuilder::Create(const eparticle3d::Symbol* sym, const IPackNode* p3d) { PackP3dSpr* node = new PackP3dSpr; node->p3d = p3d; node->loop = true; node->local = false; node->alone = false; node->reuse = true; m_nodes.push_back(node); m_export_set.LoadExport(sym, node); } }<commit_msg>[FIXED] p3d spr pack<commit_after>#include "P3dSprBuilder.h" #include "IPackNode.h" #include "PackNodeFactory.h" #include <ee/std_functor.h> #include <ee/Visitor.h> #include <easyparticle3d.h> #include <algorithm> namespace erespacker { P3dSprBuilder::P3dSprBuilder(ExportNameSet& export_set) : m_export_set(export_set) { } P3dSprBuilder::~P3dSprBuilder() { for_each(m_nodes.begin(), m_nodes.end(), ee::DeletePointerFunctor<IPackNode>()); } void P3dSprBuilder::Traverse(ee::Visitor& visitor) const { for (int i = 0, n = m_nodes.size(); i < n; ++i) { bool has_next; visitor.Visit(m_nodes[i], has_next); if (!has_next) { break; } } } const IPackNode* P3dSprBuilder::Create(const eparticle3d::Sprite* spr) { PackP3dSpr* node = new PackP3dSpr; node->p3d = PackNodeFactory::Instance()->Create(&spr->GetSymbol()); node->loop = spr->IsLoop(); node->local = spr->IsLocalModeDraw(); node->alone = spr->IsAlone(); node->reuse = spr->IsReuse(); m_nodes.push_back(node); return node; } void P3dSprBuilder::Create(const eparticle3d::Symbol* sym, const IPackNode* p3d) { PackP3dSpr* node = new PackP3dSpr; node->p3d = p3d; node->loop = sym->IsLoop(); node->local = sym->IsLocal(); node->alone = false; node->reuse = false; m_nodes.push_back(node); m_export_set.LoadExport(sym, node); } }<|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/pldm/responses/pldm_fru_data_responders.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* @file pldm_fru_data_responders.C * * @brief Implementation of the PLDM FRU Data responder functions. */ // PLDM #include <pldm/pldm_errl.H> #include <pldm/pldm_const.H> #include <pldm/pldm_reasoncodes.H> #include <pldm/pldm_response.H> #include <pldm/extended/pldm_fru.H> #include <pldm/extended/pdr_manager.H> #include <pldm/extended/hb_pdrs.H> #include <pldm/responses/pldm_fru_data_responders.H> #include "../common/pldmtrace.H" // libpldm #include "../extern/platform.h" #include "../extern/base.h" #include "../extern/fru.h" // Targeting #include <targeting/common/utilFilter.H> #include <targeting/targplatutil.H> // Device FW, VPD constants #include <devicefw/driverif.H> #include <vpd/mvpdenums.H> #include <vpd/spdenums.H> // Standard library #include <map> #include <assert.h> using namespace TARGETING; using namespace ERRORLOG; using namespace PLDM; namespace { // Used by the metadata request handler for the value of FRUTableMaximumSize; 0 // means SetFRURecordTable command is not supported (see DSP 0257 v1.0.0 Table // 9) const int FRU_TABLE_MAX_SIZE_UNSUPPORTED = 0; // This is a list of types for which we need to send a location code to the BMC const fru_inventory_class host_location_code_frus[] = { { CLASS_CHIP, TYPE_PROC, ENTITY_TYPE_PROCESSOR_MODULE }, { CLASS_LOGICAL_CARD, TYPE_DIMM, ENTITY_TYPE_DIMM } }; /* @brief Encode a GetFRURecordTable response * * @param[in] i_instance_id Forwarded to encode_get_fru_record_table_resp * @param[in] i_completion_code Forwarded * @param[in] i_next_data_transfer_handle Forwarded * @param[in] i_transfer_flag Forwarded * @param[in] i_fru_record_table_bytes FRU record table to send * @param[in] i_fru_record_table_size Size of FRU record table in bytes * @param[out] o_msg PLDM message to encode * @return int PLDM result code * @note The libpldm encoder for responses to GetFRURecordTable requests has an * aberrant signature and will not work nicely with send_pldm_response, so * we have to make our own here. */ int encode_get_fru_record_table_resp_hb(const uint8_t i_instance_id, const uint8_t i_completion_code, const uint32_t i_next_data_transfer_handle, const uint8_t i_transfer_flag, const uint8_t* const i_fru_record_table_bytes, const size_t i_fru_record_table_size, pldm_msg* const o_msg) { const int rc = encode_get_fru_record_table_resp(i_instance_id, i_completion_code, i_next_data_transfer_handle, i_transfer_flag, o_msg); if (rc == PLDM_SUCCESS) { const auto response = reinterpret_cast<pldm_get_fru_record_table_resp*>(o_msg->payload); memcpy(response->fru_record_table_data, i_fru_record_table_bytes, i_fru_record_table_size); } return rc; } // @brief A class to manage creating a FRU record table class FruRecordTable { public: /* @brief Returns the size of the record table data in bytes */ uint32_t recordDataByteSize() const; /* @brief Returns pointer to the record data bytes */ const uint8_t* recordData() const; /* @brief Returns the number of records in this table */ uint16_t recordCount() const; /* @brief Returns the number of record sets in this table */ uint16_t recordSetCount() const; /* @brief Load all the FRU records from VPD into the table. */ void loadAllFruRecords(); private: /* @brief Load all the FRU records for a particular target. * * @note Right now this only loads the location code. * * @param[in] i_target The Target to read VPD from * @param[in] i_entityType The entity type of the target */ void loadFruRecords(TARGETING::Target* const i_target, const entity_type i_entityType); std::vector<uint8_t> iv_fru_record_table_bytes; uint16_t iv_num_records = 0; std::map<fru_record_set_id_t, bool> iv_record_sets; }; uint32_t FruRecordTable::recordDataByteSize() const { return iv_fru_record_table_bytes.size(); } const uint8_t* FruRecordTable::recordData() const { return iv_fru_record_table_bytes.data(); } uint16_t FruRecordTable::recordCount() const { return iv_num_records; } uint16_t FruRecordTable::recordSetCount() const { return iv_record_sets.size(); } void FruRecordTable::loadAllFruRecords() { PLDM_INF("Loading all FRU records..."); /* Iterate the relevant targets and serialize each location code */ for (const auto& info : host_location_code_frus) { TargetHandleList targets; getClassResources(targets, info.targetClass, info.targetType, UTIL_FILTER_PRESENT); for (const auto target : targets) { loadFruRecords(target, info.entityType); } } PLDM_INF("Done loading all FRU records (%d records, %d record sets, %d bytes)", recordCount(), recordSetCount(), recordDataByteSize()); PLDM_DBG_BIN("Encoded FRU record table", iv_fru_record_table_bytes.data(), iv_fru_record_table_bytes.size()); } /* @brief Encode a FRU Record key/value pair and append it to a buffer. * * @param[in] i_type The type of the value * @param[in] i_length The length of the value * @param[in] i_value The value * @param[in/out] io_data The buffer to append to */ void encodeTlv(const uint8_t i_type, const size_t i_length, const void* const i_value, std::vector<uint8_t>& io_data) { assert(i_length <= UINT8_MAX, "Length of FRU record field value is too large to encode in TLV"); io_data.push_back(i_type); io_data.push_back(i_length); io_data.insert(end(io_data), static_cast<const uint8_t*>(i_value), static_cast<const uint8_t*>(i_value) + i_length); } using fru_data_t = std::vector<uint8_t>; /* @brief Reads the location code from a target and encodes it as in TLV format. * * @param[in] i_target The target to read VPD from * @param[out] o_fru_data The vector to fill with FRU TLVs */ void read_location_code_tlv(Target* const i_target, fru_data_t& o_fru_data) { o_fru_data.clear(); /* The location code attribute only contains the "local" location code, so * we have to prefix the chassis location code to root it properly. */ std::vector<char> full_location_code; /* Read the chassis location code */ { /* @TODO RTC 250663: Uncomment this block when the CHASSIS_LOCATION_CODE attribute is defined. Target* const sys = UTIL::assertGetToplevelTarget(); ATTR_CHASSIS_LOCATION_CODE_type location_code { }; static_assert(sizeof(location_code) <= UINT8_MAX, "Location code too large to encode in a FRU TLV"); assert(sys->tryGetAttr<ATTR_CHASSIS_LOCATION_CODE>(location_code), "Cannot get ATTR_CHASSIS_LOCATION_CODE from toplevel target"); full_location_code.insert(end(full_location_code), location_code, location_code + strlen(location_code)); */ } /* Append separator */ full_location_code.push_back('-'); /* Append the target location code */ { ATTR_LOCATION_CODE_type location_code { }; static_assert(sizeof(location_code) <= UINT8_MAX, "Location code too large to encode in a FRU TLV"); assert(i_target->tryGetAttr<ATTR_LOCATION_CODE>(location_code), "Cannot get ATTR_LOCATION_CODE from HUID = 0x%08x", get_huid(i_target)); full_location_code.insert(end(full_location_code), location_code, location_code + strlen(location_code)); } /* Encode the TLV */ const int location_code_key = 254; encodeTlv(location_code_key, full_location_code.size(), full_location_code.data(), o_fru_data); } void FruRecordTable::loadFruRecords(Target* const i_target, const entity_type i_entityType) { PLDM_INF("Loading FRU records for %s (0x%08x)", attrToString<ATTR_TYPE>(i_target->getAttr<ATTR_TYPE>()), get_huid(i_target)); const fru_record_set_id_t rsid = getTargetFruRecordSetID(i_target); /* Read the target's location code, encoded as a TLV */ fru_data_t fru_tlvs; read_location_code_tlv(i_target, fru_tlvs); /* Reserve space in the record table */ size_t fru_record_table_used_bytes = iv_fru_record_table_bytes.size(); const size_t record_hdr_size = (sizeof(struct pldm_fru_record_data_format) - sizeof(struct pldm_fru_record_tlv)); iv_fru_record_table_bytes.resize(iv_fru_record_table_bytes.size() + record_hdr_size + fru_tlvs.size()); /* Encode the record in the table */ const int num_tlvs = 1; const int encode_rc = encode_fru_record(iv_fru_record_table_bytes.data(), iv_fru_record_table_bytes.size(), &fru_record_table_used_bytes, rsid, PLDM_FRU_RECORD_TYPE_OEM, num_tlvs, PLDM_FRU_ENCODING_ASCII, fru_tlvs.data(), fru_tlvs.size()); assert(encode_rc == PLDM_SUCCESS, "encode_fru_record failed with rc = %d", encode_rc); /* Adjust bookkeeping numbers */ ++iv_num_records; iv_record_sets[rsid] = true; } } // anonymous namespace namespace PLDM { errlHndl_t handleGetFruRecordTableMetadataRequest(const msg_q_t i_msgQ, const pldm_msg* const i_msg, const size_t i_payload_len) { PLDM_ENTER("handleGetFruRecordTableMetadataRequest"); // getFruRecordTableMetadata requests don't have any payload, so no need to // decode them. FruRecordTable table; table.loadAllFruRecords(); const errlHndl_t errl = send_pldm_response<PLDM_GET_FRU_RECORD_TABLE_METADATA_RESP_BYTES> (i_msgQ, encode_get_fru_record_table_metadata_resp, PLDM_RESPONSE_EMPTY_PAYLOAD_SIZE, i_msg->hdr.instance_id, PLDM_SUCCESS, SUPPORTED_FRU_VERSION_MAJOR, SUPPORTED_FRU_VERSION_MINOR, FRU_TABLE_MAX_SIZE_UNSUPPORTED, table.recordDataByteSize(), table.recordSetCount(), table.recordCount(), 0); // checksum, not calculated if (errl) { PLDM_ERR("handleGetFruRecordTableMetadataRequest: send_pldm_response failed"); } PLDM_EXIT("handleGetFruRecordTableMetadataRequest"); return errl; } errlHndl_t handleGetFruRecordTableRequest(const msg_q_t i_msgQ, const pldm_msg* const i_msg, const size_t i_payload_len) { PLDM_ENTER("handleGetFruRecordTableRequest"); // The getFruRecordTable requests do have request data, but it's only // related to multi-part transfers which we don't support and which the BMC // will not send us. FruRecordTable table; table.loadAllFruRecords(); const errlHndl_t errl = send_pldm_response<PLDM_GET_FRU_RECORD_TABLE_MIN_RESP_BYTES> (i_msgQ, encode_get_fru_record_table_resp_hb, table.recordDataByteSize(), i_msg->hdr.instance_id, PLDM_SUCCESS, 0, // No next transfer handle PLDM_START_AND_END, table.recordData(), payload_length_placeholder_t{}); if (errl) { PLDM_ERR("handleGetFruRecordTableRequest: send_pldm_response failed"); } PLDM_EXIT("handleGetFruRecordTableRequest"); return errl; } } <commit_msg>Prefix location code PDR fields with the chassis location code<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/pldm/responses/pldm_fru_data_responders.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /* @file pldm_fru_data_responders.C * * @brief Implementation of the PLDM FRU Data responder functions. */ // PLDM #include <pldm/pldm_errl.H> #include <pldm/pldm_const.H> #include <pldm/pldm_reasoncodes.H> #include <pldm/pldm_response.H> #include <pldm/extended/pldm_fru.H> #include <pldm/extended/pdr_manager.H> #include <pldm/extended/hb_pdrs.H> #include <pldm/responses/pldm_fru_data_responders.H> #include "../common/pldmtrace.H" // libpldm #include "../extern/platform.h" #include "../extern/base.h" #include "../extern/fru.h" // Targeting #include <targeting/common/utilFilter.H> #include <targeting/targplatutil.H> // Device FW, VPD constants #include <devicefw/driverif.H> #include <vpd/mvpdenums.H> #include <vpd/spdenums.H> // Standard library #include <map> #include <assert.h> using namespace TARGETING; using namespace ERRORLOG; using namespace PLDM; namespace { // Used by the metadata request handler for the value of FRUTableMaximumSize; 0 // means SetFRURecordTable command is not supported (see DSP 0257 v1.0.0 Table // 9) const int FRU_TABLE_MAX_SIZE_UNSUPPORTED = 0; // This is a list of types for which we need to send a location code to the BMC const fru_inventory_class host_location_code_frus[] = { { CLASS_CHIP, TYPE_PROC, ENTITY_TYPE_PROCESSOR_MODULE }, { CLASS_LOGICAL_CARD, TYPE_DIMM, ENTITY_TYPE_DIMM } }; /* @brief Encode a GetFRURecordTable response * * @param[in] i_instance_id Forwarded to encode_get_fru_record_table_resp * @param[in] i_completion_code Forwarded * @param[in] i_next_data_transfer_handle Forwarded * @param[in] i_transfer_flag Forwarded * @param[in] i_fru_record_table_bytes FRU record table to send * @param[in] i_fru_record_table_size Size of FRU record table in bytes * @param[out] o_msg PLDM message to encode * @return int PLDM result code * @note The libpldm encoder for responses to GetFRURecordTable requests has an * aberrant signature and will not work nicely with send_pldm_response, so * we have to make our own here. */ int encode_get_fru_record_table_resp_hb(const uint8_t i_instance_id, const uint8_t i_completion_code, const uint32_t i_next_data_transfer_handle, const uint8_t i_transfer_flag, const uint8_t* const i_fru_record_table_bytes, const size_t i_fru_record_table_size, pldm_msg* const o_msg) { const int rc = encode_get_fru_record_table_resp(i_instance_id, i_completion_code, i_next_data_transfer_handle, i_transfer_flag, o_msg); if (rc == PLDM_SUCCESS) { const auto response = reinterpret_cast<pldm_get_fru_record_table_resp*>(o_msg->payload); memcpy(response->fru_record_table_data, i_fru_record_table_bytes, i_fru_record_table_size); } return rc; } // @brief A class to manage creating a FRU record table class FruRecordTable { public: /* @brief Returns the size of the record table data in bytes */ uint32_t recordDataByteSize() const; /* @brief Returns pointer to the record data bytes */ const uint8_t* recordData() const; /* @brief Returns the number of records in this table */ uint16_t recordCount() const; /* @brief Returns the number of record sets in this table */ uint16_t recordSetCount() const; /* @brief Load all the FRU records from VPD into the table. */ void loadAllFruRecords(); private: /* @brief Load all the FRU records for a particular target. * * @note Right now this only loads the location code. * * @param[in] i_target The Target to read VPD from * @param[in] i_entityType The entity type of the target */ void loadFruRecords(TARGETING::Target* const i_target, const entity_type i_entityType); std::vector<uint8_t> iv_fru_record_table_bytes; uint16_t iv_num_records = 0; std::map<fru_record_set_id_t, bool> iv_record_sets; }; uint32_t FruRecordTable::recordDataByteSize() const { return iv_fru_record_table_bytes.size(); } const uint8_t* FruRecordTable::recordData() const { return iv_fru_record_table_bytes.data(); } uint16_t FruRecordTable::recordCount() const { return iv_num_records; } uint16_t FruRecordTable::recordSetCount() const { return iv_record_sets.size(); } void FruRecordTable::loadAllFruRecords() { PLDM_INF("Loading all FRU records..."); /* Iterate the relevant targets and serialize each location code */ for (const auto& info : host_location_code_frus) { TargetHandleList targets; getClassResources(targets, info.targetClass, info.targetType, UTIL_FILTER_PRESENT); for (const auto target : targets) { loadFruRecords(target, info.entityType); } } PLDM_INF("Done loading all FRU records (%d records, %d record sets, %d bytes)", recordCount(), recordSetCount(), recordDataByteSize()); PLDM_DBG_BIN("Encoded FRU record table", iv_fru_record_table_bytes.data(), iv_fru_record_table_bytes.size()); } /* @brief Encode a FRU Record key/value pair and append it to a buffer. * * @param[in] i_type The type of the value * @param[in] i_length The length of the value * @param[in] i_value The value * @param[in/out] io_data The buffer to append to */ void encodeTlv(const uint8_t i_type, const size_t i_length, const void* const i_value, std::vector<uint8_t>& io_data) { assert(i_length <= UINT8_MAX, "Length of FRU record field value is too large to encode in TLV"); io_data.push_back(i_type); io_data.push_back(i_length); io_data.insert(end(io_data), static_cast<const uint8_t*>(i_value), static_cast<const uint8_t*>(i_value) + i_length); } using fru_data_t = std::vector<uint8_t>; /* @brief Reads the location code from a target and encodes it as in TLV format. * * @param[in] i_target The target to read VPD from * @param[out] o_fru_data The vector to fill with FRU TLVs */ void read_location_code_tlv(Target* const i_target, fru_data_t& o_fru_data) { o_fru_data.clear(); /* The location code attribute only contains the "local" location code, so * we have to prefix the chassis location code to root it properly. */ std::vector<char> full_location_code; /* Read the chassis location code */ { Target* const sys = UTIL::assertGetToplevelTarget(); ATTR_CHASSIS_LOCATION_CODE_type location_code { }; static_assert(sizeof(location_code) <= UINT8_MAX, "Location code too large to encode in a FRU TLV"); assert(sys->tryGetAttr<ATTR_CHASSIS_LOCATION_CODE>(location_code), "Cannot get ATTR_CHASSIS_LOCATION_CODE from toplevel target"); full_location_code.insert(end(full_location_code), location_code, location_code + strlen(location_code)); } /* Append separator */ full_location_code.push_back('-'); /* Append the target location code */ { ATTR_LOCATION_CODE_type location_code { }; static_assert(sizeof(location_code) <= UINT8_MAX, "Location code too large to encode in a FRU TLV"); assert(i_target->tryGetAttr<ATTR_LOCATION_CODE>(location_code), "Cannot get ATTR_LOCATION_CODE from HUID = 0x%08x", get_huid(i_target)); full_location_code.insert(end(full_location_code), location_code, location_code + strlen(location_code)); } /* Encode the TLV */ const int location_code_key = 254; encodeTlv(location_code_key, full_location_code.size(), full_location_code.data(), o_fru_data); } void FruRecordTable::loadFruRecords(Target* const i_target, const entity_type i_entityType) { PLDM_INF("Loading FRU records for %s (0x%08x)", attrToString<ATTR_TYPE>(i_target->getAttr<ATTR_TYPE>()), get_huid(i_target)); const fru_record_set_id_t rsid = getTargetFruRecordSetID(i_target); /* Read the target's location code, encoded as a TLV */ fru_data_t fru_tlvs; read_location_code_tlv(i_target, fru_tlvs); /* Reserve space in the record table */ size_t fru_record_table_used_bytes = iv_fru_record_table_bytes.size(); const size_t record_hdr_size = (sizeof(struct pldm_fru_record_data_format) - sizeof(struct pldm_fru_record_tlv)); iv_fru_record_table_bytes.resize(iv_fru_record_table_bytes.size() + record_hdr_size + fru_tlvs.size()); /* Encode the record in the table */ const int num_tlvs = 1; const int encode_rc = encode_fru_record(iv_fru_record_table_bytes.data(), iv_fru_record_table_bytes.size(), &fru_record_table_used_bytes, rsid, PLDM_FRU_RECORD_TYPE_OEM, num_tlvs, PLDM_FRU_ENCODING_ASCII, fru_tlvs.data(), fru_tlvs.size()); assert(encode_rc == PLDM_SUCCESS, "encode_fru_record failed with rc = %d", encode_rc); /* Adjust bookkeeping numbers */ ++iv_num_records; iv_record_sets[rsid] = true; } } // anonymous namespace namespace PLDM { errlHndl_t handleGetFruRecordTableMetadataRequest(const msg_q_t i_msgQ, const pldm_msg* const i_msg, const size_t i_payload_len) { PLDM_ENTER("handleGetFruRecordTableMetadataRequest"); // getFruRecordTableMetadata requests don't have any payload, so no need to // decode them. FruRecordTable table; table.loadAllFruRecords(); const errlHndl_t errl = send_pldm_response<PLDM_GET_FRU_RECORD_TABLE_METADATA_RESP_BYTES> (i_msgQ, encode_get_fru_record_table_metadata_resp, PLDM_RESPONSE_EMPTY_PAYLOAD_SIZE, i_msg->hdr.instance_id, PLDM_SUCCESS, SUPPORTED_FRU_VERSION_MAJOR, SUPPORTED_FRU_VERSION_MINOR, FRU_TABLE_MAX_SIZE_UNSUPPORTED, table.recordDataByteSize(), table.recordSetCount(), table.recordCount(), 0); // checksum, not calculated if (errl) { PLDM_ERR("handleGetFruRecordTableMetadataRequest: send_pldm_response failed"); } PLDM_EXIT("handleGetFruRecordTableMetadataRequest"); return errl; } errlHndl_t handleGetFruRecordTableRequest(const msg_q_t i_msgQ, const pldm_msg* const i_msg, const size_t i_payload_len) { PLDM_ENTER("handleGetFruRecordTableRequest"); // The getFruRecordTable requests do have request data, but it's only // related to multi-part transfers which we don't support and which the BMC // will not send us. FruRecordTable table; table.loadAllFruRecords(); const errlHndl_t errl = send_pldm_response<PLDM_GET_FRU_RECORD_TABLE_MIN_RESP_BYTES> (i_msgQ, encode_get_fru_record_table_resp_hb, table.recordDataByteSize(), i_msg->hdr.instance_id, PLDM_SUCCESS, 0, // No next transfer handle PLDM_START_AND_END, table.recordData(), payload_length_placeholder_t{}); if (errl) { PLDM_ERR("handleGetFruRecordTableRequest: send_pldm_response failed"); } PLDM_EXIT("handleGetFruRecordTableRequest"); return errl; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/p2p/port_allocator.h" #include "base/bind.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "content/renderer/p2p/host_address_request.h" #include "jingle/glue/utils.h" #include "net/base/ip_endpoint.h" #include "ppapi/c/dev/ppb_transport_dev.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLError.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLLoader.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" using WebKit::WebString; using WebKit::WebURL; using WebKit::WebURLLoader; using WebKit::WebURLLoaderOptions; using WebKit::WebURLRequest; using WebKit::WebURLResponse; namespace content { namespace { // URL used to create a relay session. const char kCreateRelaySessionURL[] = "/create_session"; // Number of times we will try to request relay session. const int kRelaySessionRetries = 3; // Manimum relay server size we would try to parse. const int kMaximumRelayResponseSize = 102400; bool ParsePortNumber( const std::string& string, int* value) { if (!base::StringToInt(string, value) || *value <= 0 || *value >= 65536) { LOG(ERROR) << "Received invalid port number from relay server: " << string; return false; } return true; } } // namespace P2PPortAllocator::P2PPortAllocator( WebKit::WebFrame* web_frame, P2PSocketDispatcher* socket_dispatcher, talk_base::NetworkManager* network_manager, talk_base::PacketSocketFactory* socket_factory, const webkit_glue::P2PTransport::Config& config) : cricket::BasicPortAllocator(network_manager, socket_factory), web_frame_(web_frame), socket_dispatcher_(socket_dispatcher), config_(config) { uint32 flags = 0; if (config_.disable_tcp_transport) flags |= cricket::PORTALLOCATOR_DISABLE_TCP; set_flags(flags); } P2PPortAllocator::~P2PPortAllocator() { } cricket::PortAllocatorSession* P2PPortAllocator::CreateSession( const std::string& name, const std::string& session_type) { return new P2PPortAllocatorSession(this, name, session_type); } P2PPortAllocatorSession::P2PPortAllocatorSession( P2PPortAllocator* allocator, const std::string& name, const std::string& session_type) : cricket::BasicPortAllocatorSession(allocator, name, session_type), allocator_(allocator), relay_session_attempts_(0), relay_udp_port_(0), relay_tcp_port_(0), relay_ssltcp_port_(0) { } P2PPortAllocatorSession::~P2PPortAllocatorSession() { if (stun_address_request_) stun_address_request_->Cancel(); } void P2PPortAllocatorSession::didReceiveData( WebURLLoader* loader, const char* data, int data_length, int encoded_data_length) { DCHECK_EQ(loader, relay_session_request_.get()); if (static_cast<int>(relay_session_response_.size()) + data_length > kMaximumRelayResponseSize) { LOG(ERROR) << "Response received from the server is too big."; loader->cancel(); return; } relay_session_response_.append(data, data + data_length); } void P2PPortAllocatorSession::didFinishLoading(WebURLLoader* loader, double finish_time) { ParseRelayResponse(); } void P2PPortAllocatorSession::didFail(WebKit::WebURLLoader* loader, const WebKit::WebURLError& error) { DCHECK_EQ(loader, relay_session_request_.get()); DCHECK_NE(error.reason, 0); LOG(ERROR) << "Relay session request failed."; // Retry the request. AllocateRelaySession(); } void P2PPortAllocatorSession::GetPortConfigurations() { // Add an empty configuration synchronously, so a local connection // can be started immediately. ConfigReady(new cricket::PortConfiguration( talk_base::SocketAddress(), "", "", "")); ResolveStunServerAddress(); AllocateRelaySession(); } void P2PPortAllocatorSession::ResolveStunServerAddress() { if (allocator_->config_.stun_server.empty()) return; DCHECK(!stun_address_request_); stun_address_request_ = new P2PHostAddressRequest(allocator_->socket_dispatcher_); stun_address_request_->Request(allocator_->config_.stun_server, base::Bind( &P2PPortAllocatorSession::OnStunServerAddress, base::Unretained(this))); } void P2PPortAllocatorSession::OnStunServerAddress( const net::IPAddressNumber& address) { if (address.empty()) { LOG(ERROR) << "Failed to resolve STUN server address " << allocator_->config_.stun_server; return; } if (!jingle_glue::IPEndPointToSocketAddress( net::IPEndPoint(address, allocator_->config_.stun_server_port), &stun_server_address_)) { return; } AddConfig(); } void P2PPortAllocatorSession::AllocateRelaySession() { if (allocator_->config_.relay_server.empty()) return; if (!allocator_->config_.legacy_relay) { NOTIMPLEMENTED() << " TURN support is not implemented yet."; return; } if (relay_session_attempts_ > kRelaySessionRetries) return; relay_session_attempts_++; relay_session_response_.clear(); WebURLLoaderOptions options; options.allowCredentials = false; // TODO(sergeyu): Set to CrossOriginRequestPolicyUseAccessControl // when this code can be used by untrusted plugins. // See http://crbug.com/104195 . options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyAllow; relay_session_request_.reset( allocator_->web_frame_->createAssociatedURLLoader(options)); if (!relay_session_request_.get()) { LOG(ERROR) << "Failed to create URL loader."; return; } WebURLRequest request; request.initialize(); request.setURL(WebURL(GURL( "https://" + allocator_->config_.relay_server + kCreateRelaySessionURL))); request.setAllowStoredCredentials(false); request.setCachePolicy(WebURLRequest::ReloadIgnoringCacheData); request.setHTTPMethod("GET"); request.addHTTPHeaderField( WebString::fromUTF8("X-Talk-Google-Relay-Auth"), WebString::fromUTF8(allocator_->config_.relay_password)); request.addHTTPHeaderField( WebString::fromUTF8("X-Google-Relay-Auth"), WebString::fromUTF8(allocator_->config_.relay_password)); request.addHTTPHeaderField(WebString::fromUTF8("X-Session-Type"), WebString::fromUTF8(session_type())); request.addHTTPHeaderField(WebString::fromUTF8("X-Stream-Type"), WebString::fromUTF8(name())); relay_session_request_->loadAsynchronously(request, this); } void P2PPortAllocatorSession::ParseRelayResponse() { std::vector<std::pair<std::string, std::string> > value_pairs; if (!base::SplitStringIntoKeyValuePairs(relay_session_response_, '=', '\n', &value_pairs)) { LOG(ERROR) << "Received invalid response from relay server"; return; } relay_username_.clear(); relay_password_.clear(); relay_ip_.Clear(); relay_udp_port_ = 0; relay_tcp_port_ = 0; relay_ssltcp_port_ = 0; for (std::vector<std::pair<std::string, std::string> >::iterator it = value_pairs.begin(); it != value_pairs.end(); ++it) { std::string key; std::string value; TrimWhitespaceASCII(it->first, TRIM_ALL, &key); TrimWhitespaceASCII(it->second, TRIM_ALL, &value); if (key == "username") { relay_username_ = value; } else if (key == "password") { relay_password_ = value; } else if (key == "relay.ip") { relay_ip_.SetIP(value); if (relay_ip_.ip() == 0) { LOG(ERROR) << "Received unresolved relay server address: " << value; return; } } else if (key == "relay.udp_port") { if (!ParsePortNumber(value, &relay_udp_port_)) return; } else if (key == "relay.tcp_port") { if (!ParsePortNumber(value, &relay_tcp_port_)) return; } else if (key == "relay.ssltcp_port") { if (!ParsePortNumber(value, &relay_ssltcp_port_)) return; } } AddConfig(); } void P2PPortAllocatorSession::AddConfig() { cricket::PortConfiguration* config = new cricket::PortConfiguration(stun_server_address_, relay_username_, relay_password_, ""); cricket::PortConfiguration::PortList ports; if (relay_ip_.ip() != 0) { if (relay_udp_port_ > 0) { talk_base::SocketAddress address(relay_ip_.ip(), relay_udp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_UDP)); } if (relay_tcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) { talk_base::SocketAddress address(relay_ip_.ip(), relay_tcp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_TCP)); } if (relay_ssltcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) { talk_base::SocketAddress address(relay_ip_.ip(), relay_ssltcp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_SSLTCP)); } } config->AddRelay(ports, 0.0f); ConfigReady(config); } } // namespace content <commit_msg>Fix relay support in P2P Transport API.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/p2p/port_allocator.h" #include "base/bind.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "content/renderer/p2p/host_address_request.h" #include "jingle/glue/utils.h" #include "net/base/ip_endpoint.h" #include "ppapi/c/dev/ppb_transport_dev.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLError.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLLoader.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" using WebKit::WebString; using WebKit::WebURL; using WebKit::WebURLLoader; using WebKit::WebURLLoaderOptions; using WebKit::WebURLRequest; using WebKit::WebURLResponse; namespace content { namespace { // URL used to create a relay session. const char kCreateRelaySessionURL[] = "/create_session"; // Number of times we will try to request relay session. const int kRelaySessionRetries = 3; // Manimum relay server size we would try to parse. const int kMaximumRelayResponseSize = 102400; bool ParsePortNumber( const std::string& string, int* value) { if (!base::StringToInt(string, value) || *value <= 0 || *value >= 65536) { LOG(ERROR) << "Received invalid port number from relay server: " << string; return false; } return true; } } // namespace P2PPortAllocator::P2PPortAllocator( WebKit::WebFrame* web_frame, P2PSocketDispatcher* socket_dispatcher, talk_base::NetworkManager* network_manager, talk_base::PacketSocketFactory* socket_factory, const webkit_glue::P2PTransport::Config& config) : cricket::BasicPortAllocator(network_manager, socket_factory), web_frame_(web_frame), socket_dispatcher_(socket_dispatcher), config_(config) { uint32 flags = 0; if (config_.disable_tcp_transport) flags |= cricket::PORTALLOCATOR_DISABLE_TCP; set_flags(flags); } P2PPortAllocator::~P2PPortAllocator() { } cricket::PortAllocatorSession* P2PPortAllocator::CreateSession( const std::string& name, const std::string& session_type) { return new P2PPortAllocatorSession(this, name, session_type); } P2PPortAllocatorSession::P2PPortAllocatorSession( P2PPortAllocator* allocator, const std::string& name, const std::string& session_type) : cricket::BasicPortAllocatorSession(allocator, name, session_type), allocator_(allocator), relay_session_attempts_(0), relay_udp_port_(0), relay_tcp_port_(0), relay_ssltcp_port_(0) { } P2PPortAllocatorSession::~P2PPortAllocatorSession() { if (stun_address_request_) stun_address_request_->Cancel(); } void P2PPortAllocatorSession::didReceiveData( WebURLLoader* loader, const char* data, int data_length, int encoded_data_length) { DCHECK_EQ(loader, relay_session_request_.get()); if (static_cast<int>(relay_session_response_.size()) + data_length > kMaximumRelayResponseSize) { LOG(ERROR) << "Response received from the server is too big."; loader->cancel(); return; } relay_session_response_.append(data, data + data_length); } void P2PPortAllocatorSession::didFinishLoading(WebURLLoader* loader, double finish_time) { ParseRelayResponse(); } void P2PPortAllocatorSession::didFail(WebKit::WebURLLoader* loader, const WebKit::WebURLError& error) { DCHECK_EQ(loader, relay_session_request_.get()); DCHECK_NE(error.reason, 0); LOG(ERROR) << "Relay session request failed."; // Retry the request. AllocateRelaySession(); } void P2PPortAllocatorSession::GetPortConfigurations() { // Add an empty configuration synchronously, so a local connection // can be started immediately. ConfigReady(new cricket::PortConfiguration( talk_base::SocketAddress(), "", "", "")); ResolveStunServerAddress(); AllocateRelaySession(); } void P2PPortAllocatorSession::ResolveStunServerAddress() { if (allocator_->config_.stun_server.empty()) return; DCHECK(!stun_address_request_); stun_address_request_ = new P2PHostAddressRequest(allocator_->socket_dispatcher_); stun_address_request_->Request(allocator_->config_.stun_server, base::Bind( &P2PPortAllocatorSession::OnStunServerAddress, base::Unretained(this))); } void P2PPortAllocatorSession::OnStunServerAddress( const net::IPAddressNumber& address) { if (address.empty()) { LOG(ERROR) << "Failed to resolve STUN server address " << allocator_->config_.stun_server; return; } if (!jingle_glue::IPEndPointToSocketAddress( net::IPEndPoint(address, allocator_->config_.stun_server_port), &stun_server_address_)) { return; } AddConfig(); } void P2PPortAllocatorSession::AllocateRelaySession() { if (allocator_->config_.relay_server.empty()) return; if (!allocator_->config_.legacy_relay) { NOTIMPLEMENTED() << " TURN support is not implemented yet."; return; } if (relay_session_attempts_ > kRelaySessionRetries) return; relay_session_attempts_++; relay_session_response_.clear(); WebURLLoaderOptions options; options.allowCredentials = false; // TODO(sergeyu): Set to CrossOriginRequestPolicyUseAccessControl // when this code can be used by untrusted plugins. // See http://crbug.com/104195 . options.crossOriginRequestPolicy = WebURLLoaderOptions::CrossOriginRequestPolicyAllow; relay_session_request_.reset( allocator_->web_frame_->createAssociatedURLLoader(options)); if (!relay_session_request_.get()) { LOG(ERROR) << "Failed to create URL loader."; return; } WebURLRequest request; request.initialize(); request.setURL(WebURL(GURL( "https://" + allocator_->config_.relay_server + kCreateRelaySessionURL))); request.setAllowStoredCredentials(false); request.setCachePolicy(WebURLRequest::ReloadIgnoringCacheData); request.setHTTPMethod("GET"); request.addHTTPHeaderField( WebString::fromUTF8("X-Talk-Google-Relay-Auth"), WebString::fromUTF8(allocator_->config_.relay_password)); request.addHTTPHeaderField( WebString::fromUTF8("X-Google-Relay-Auth"), WebString::fromUTF8(allocator_->config_.relay_password)); request.addHTTPHeaderField(WebString::fromUTF8("X-Session-Type"), WebString::fromUTF8(session_type())); request.addHTTPHeaderField(WebString::fromUTF8("X-Stream-Type"), WebString::fromUTF8(name())); relay_session_request_->loadAsynchronously(request, this); } void P2PPortAllocatorSession::ParseRelayResponse() { std::vector<std::pair<std::string, std::string> > value_pairs; if (!base::SplitStringIntoKeyValuePairs(relay_session_response_, '=', '\n', &value_pairs)) { LOG(ERROR) << "Received invalid response from relay server"; return; } relay_username_.clear(); relay_password_.clear(); relay_ip_.Clear(); relay_udp_port_ = 0; relay_tcp_port_ = 0; relay_ssltcp_port_ = 0; for (std::vector<std::pair<std::string, std::string> >::iterator it = value_pairs.begin(); it != value_pairs.end(); ++it) { std::string key; std::string value; TrimWhitespaceASCII(it->first, TRIM_ALL, &key); TrimWhitespaceASCII(it->second, TRIM_ALL, &value); if (key == "username") { relay_username_ = value; } else if (key == "password") { relay_password_ = value; } else if (key == "relay.ip") { relay_ip_.SetIP(value); if (relay_ip_.ip() == 0) { LOG(ERROR) << "Received unresolved relay server address: " << value; return; } } else if (key == "relay.udp_port") { if (!ParsePortNumber(value, &relay_udp_port_)) return; } else if (key == "relay.tcp_port") { if (!ParsePortNumber(value, &relay_tcp_port_)) return; } else if (key == "relay.ssltcp_port") { if (!ParsePortNumber(value, &relay_ssltcp_port_)) return; } } AddConfig(); } void P2PPortAllocatorSession::AddConfig() { cricket::PortConfiguration* config = new cricket::PortConfiguration(stun_server_address_, relay_username_, relay_password_, ""); if (relay_ip_.ip() != 0) { cricket::PortConfiguration::PortList ports; if (relay_udp_port_ > 0) { talk_base::SocketAddress address(relay_ip_.ip(), relay_udp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_UDP)); } if (relay_tcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) { talk_base::SocketAddress address(relay_ip_.ip(), relay_tcp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_TCP)); } if (relay_ssltcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) { talk_base::SocketAddress address(relay_ip_.ip(), relay_ssltcp_port_); ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_SSLTCP)); } if (!ports.empty()) config->AddRelay(ports, 0.0f); } ConfigReady(config); } } // namespace content <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "addr_to_symbol.h" #include <vespa/vespalib/util/classname.h> #include <dlfcn.h> #include <llvm/Object/ObjectFile.h> using vespalib::demangle; using llvm::object::ObjectFile; namespace vespalib::eval { namespace { void my_local_test_symbol() {} } // <unnamed> vespalib::string addr_to_symbol(const void *addr) { if (addr == nullptr) { return {"<nullptr>"}; } Dl_info info; memset(&info, 0, sizeof(info)); if (dladdr(addr, &info) == 0) { // address not in any shared object return {"<invalid>"}; } if (info.dli_sname != nullptr) { // address of global symbol return demangle(info.dli_sname); } // find addr offset into shared object uint64_t offset = ((const char *)addr) - ((const char *)info.dli_fbase); // use llvm to look up local symbols... auto file = ObjectFile::createObjectFile(info.dli_fname); if (!file) { return {"<object_error>"}; } auto symbols = file.get().getBinary()->symbols(); for (const auto &symbol: symbols) { auto sym_name = symbol.getName(); auto sym_addr = symbol.getAddress(); if (sym_name && sym_addr && (*sym_addr == offset)) { return demangle(sym_name->str().c_str()); } } // could not resolve symbol return {"<unknown>"}; } const void *get_addr_of_local_test_symbol() { return (const void *) my_local_test_symbol; } } <commit_msg>Check symbol type when mapping from address to symbol.<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "addr_to_symbol.h" #include <vespa/vespalib/util/classname.h> #include <dlfcn.h> #include <llvm/Object/ObjectFile.h> using vespalib::demangle; using llvm::object::ObjectFile; using SymbolType = llvm::object::SymbolRef::Type; namespace vespalib::eval { namespace { void my_local_test_symbol() {} bool symbol_is_data_or_function(SymbolType type) { return ((type == SymbolType::ST_Data) || (type == SymbolType::ST_Function)); } } // <unnamed> vespalib::string addr_to_symbol(const void *addr) { if (addr == nullptr) { return {"<nullptr>"}; } Dl_info info; memset(&info, 0, sizeof(info)); if (dladdr(addr, &info) == 0) { // address not in any shared object return {"<invalid>"}; } if (info.dli_sname != nullptr) { // address of global symbol return demangle(info.dli_sname); } // find addr offset into shared object uint64_t offset = ((const char *)addr) - ((const char *)info.dli_fbase); // use llvm to look up local symbols... auto file = ObjectFile::createObjectFile(info.dli_fname); if (!file) { return {"<object_error>"}; } auto symbols = file.get().getBinary()->symbols(); for (const auto &symbol: symbols) { auto sym_name = symbol.getName(); auto sym_addr = symbol.getAddress(); auto sym_type = symbol.getType(); if (sym_name && sym_addr && sym_type && symbol_is_data_or_function(*sym_type) && (*sym_addr == offset)) { return demangle(sym_name->str().c_str()); } } // could not resolve symbol return {"<unknown>"}; } const void *get_addr_of_local_test_symbol() { return (const void *) my_local_test_symbol; } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class GrammarResolver { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver(); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param nameSpaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const nameSpaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param nameSpaceKey Key to associate with Grammar abstraction * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(const XMLCh* const nameSpaceKey, Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarRegistry to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); //@} private: // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // // fGrammarRegistry The parsed Grammar Pool, if no caching option. // // fCachedGrammarRegistry The cached Grammar Pool. It represents a // mapping between Namespace and a Grammar // // fDataTypeReg DatatypeValidatorFactory registery // // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; XMLStringPool fStringPool; RefHashTableOf<Grammar>* fGrammarRegistry; RefHashTableOf<Grammar>* fCachedGrammarRegistry; DatatypeValidatorFactory* fDataTypeReg; }; inline XMLStringPool* GrammarResolver::getStringPool() { return &fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline Grammar* GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) { if (fCacheGrammar) return fCachedGrammarRegistry->orphanKey(nameSpaceKey); return fGrammarRegistry->orphanKey(nameSpaceKey); } XERCES_CPP_NAMESPACE_END #endif <commit_msg>[Bug 9697] Make GrammarResolver to be exportable<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver(); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param nameSpaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const nameSpaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param nameSpaceKey Key to associate with Grammar abstraction * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(const XMLCh* const nameSpaceKey, Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarRegistry to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); //@} private: // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // // fGrammarRegistry The parsed Grammar Pool, if no caching option. // // fCachedGrammarRegistry The cached Grammar Pool. It represents a // mapping between Namespace and a Grammar // // fDataTypeReg DatatypeValidatorFactory registery // // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; XMLStringPool fStringPool; RefHashTableOf<Grammar>* fGrammarRegistry; RefHashTableOf<Grammar>* fCachedGrammarRegistry; DatatypeValidatorFactory* fDataTypeReg; }; inline XMLStringPool* GrammarResolver::getStringPool() { return &fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline Grammar* GrammarResolver::orphanGrammar(const XMLCh* const nameSpaceKey) { if (fCacheGrammar) return fCachedGrammarRegistry->orphanKey(nameSpaceKey); return fGrammarRegistry->orphanKey(nameSpaceKey); } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_1D_HPP #define STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_1D_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/scal/fun/to_var.hpp> #include <stan/math/rev/mat/fun/to_var.hpp> #include <stan/math/rev/arr/fun/to_var.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/meta/OperandsAndPartials.hpp> #include <boost/bind.hpp> #include <cmath> #include <ostream> #include <vector> #include <stan/math/prim/arr/functor/DEIntegrator.hpp> namespace stan { namespace math { template <typename T> struct return_type_of_value_of { typedef double type; }; template <typename T> struct return_type_of_value_of <std::vector<T> > { typedef std::vector<double> type; }; template <typename T, int R, int C> struct return_type_of_value_of <Eigen::Matrix<T, R, C> > { typedef Eigen::Matrix<double, R, C> type; }; template <typename T> struct return_type_of_to_var { typedef var type; }; template <typename T> struct return_type_of_to_var <std::vector<T> > { typedef std::vector<var> type; }; template <typename T, int R, int C> struct return_type_of_to_var <Eigen::Matrix<T, R, C> > { typedef Eigen::Matrix<var, R, C> type; }; /** * Wrap around function to call static method Integrate from * class DEIntegrator. * * @tparam T Type of f. * @param f a functor with signature double (double). * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param tae target absolute error. * @return numeric integral of function f. */ template <typename F> inline double call_DEIntegrator(const F& f, const double a, const double b, const double tae) { return DEIntegrator<F>::Integrate(f, a, b, tae); } /** * Return the numeric integral of a function f given its gradient g. * * @tparam T Type of f. * @tparam G Type of g. * @param f a functor with signature * double (double, std::vector<T_beta>) or with signature * double (double, T_beta) where the first argument is one being * integrated and the second one is either an extra scalar or vector * being passed to f. * @param g a functor with signature * double (double, std::vector<T_beta>, int, std::ostream*) or with * signature double (double, T_beta, int, std::ostream*) where the * first argument is onebeing integrated and the second one is * either an extra scalar or vector being passed to f and the * third one selects which component of the gradient vector * is to be returned. * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param msgs stream. * @return numeric integral of function f. */ template <typename F, typename G, typename T_beta> inline typename scalar_type<T_beta>::type integrate_1d_grad(const F& f, const G& g, const double a, const double b, const T_beta& beta, std::ostream* msgs) { check_finite("integrate_1d", "lower limit", a); check_finite("integrate_1d", "upper limit", b); //hard case, we want a normalizing factor if (!is_constant_struct<T_beta>::value) { size_t N = length(beta); std::vector<double> grad(N); typename return_type_of_value_of<T_beta>::type value_of_beta = value_of(beta); for (size_t n = 0; n < N; n++) grad[n] = call_DEIntegrator( boost::bind<double>(g, _1, value_of_beta, static_cast<int>(n+1), msgs), a, b, 1e-6); double val_ = call_DEIntegrator(boost::bind<double>(f, _1, value_of_beta, msgs), a, b, 1e-6); OperandsAndPartials<T_beta> operands_and_partials(beta); for (size_t n = 0; n < N; n++) operands_and_partials.d_x1[n] += grad[n]; return operands_and_partials.value(val_); //easy case, here we are calculating a normalizing constant, //not a normalizing factor, so g doesn't matter at all } else { return call_DEIntegrator( boost::bind<double>(f, _1, value_of(beta), msgs), a, b, 1e-6); } } /** * Calculate gradient of f(x, param, std::ostream*) * with respect to param_n (which must be an element of param) */ template <typename F, typename T_param> inline double gradient_of_f(const F& f, const double x, const T_param& param, const var& param_n, std::ostream* msgs) { set_zero_all_adjoints_nested(); f(x, param, msgs).grad(); return param_n.adj(); } /** * Return the numeric integral of a function f with its * gradients being infered automatically (but slowly). * * @tparam T Type of f. * @param f a functor with signature * double (double, std::vector<T_beta>, std::ostream*) or with * signature double (double, T_beta, std::ostream*) where the first * argument is one being integrated and the second one is either * an extra scalar or vector being passed to f. * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param msgs stream. * @return numeric integral of function f. */ template <typename F, typename T_param> inline typename scalar_type<T_param>::type integrate_1d(const F& f, const double a, const double b, const T_param& param, std::ostream* msgs) { stan::math::check_finite("integrate_1d", "lower limit", a); stan::math::check_finite("integrate_1d", "upper limit", b); double val_ = call_DEIntegrator( boost::bind<double>(f, _1, value_of(param), msgs), a, b, 1e-6); if (!is_constant_struct<T_param>::value) { size_t N = stan::length(param); std::vector<double> results(N); try { start_nested(); typedef typename return_type_of_to_var<T_param>::type clean_T_param; clean_T_param clean_param = to_var(value_of(param)); VectorView<const clean_T_param> clean_param_vec(clean_param); for (size_t n = 0; n < N; n++) results[n] = call_DEIntegrator(boost::bind<double>(gradient_of_f<F, clean_T_param>, f, _1, clean_param, clean_param_vec[n], msgs), a, b, 1e-6); } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); OperandsAndPartials<T_param> operands_and_partials(param); for (size_t n = 0; n < N; n++) operands_and_partials.d_x1[n] += results[n]; return operands_and_partials.value(val_); } else { return val_; } } } } #endif <commit_msg>update integrator to work with new operands and partials<commit_after>#ifndef STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_1D_HPP #define STAN_MATH_PRIM_ARR_FUNCTOR_INTEGRATE_1D_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/scal/fun/to_var.hpp> #include <stan/math/rev/mat/fun/to_var.hpp> #include <stan/math/rev/arr/fun/to_var.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <boost/bind.hpp> #include <cmath> #include <ostream> #include <vector> #include <stan/math/prim/arr/functor/DEIntegrator.hpp> namespace stan { namespace math { template <typename T> struct return_type_of_value_of { typedef double type; }; template <typename T> struct return_type_of_value_of <std::vector<T> > { typedef std::vector<double> type; }; template <typename T, int R, int C> struct return_type_of_value_of <Eigen::Matrix<T, R, C> > { typedef Eigen::Matrix<double, R, C> type; }; template <typename T> struct return_type_of_to_var { typedef var type; }; template <typename T> struct return_type_of_to_var <std::vector<T> > { typedef std::vector<var> type; }; template <typename T, int R, int C> struct return_type_of_to_var <Eigen::Matrix<T, R, C> > { typedef Eigen::Matrix<var, R, C> type; }; /** * Wrap around function to call static method Integrate from * class DEIntegrator. * * @tparam T Type of f. * @param f a functor with signature double (double). * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param tae target absolute error. * @return numeric integral of function f. */ template <typename F> inline double call_DEIntegrator(const F& f, const double a, const double b, const double tae) { return DEIntegrator<F>::Integrate(f, a, b, tae); } /** * Return the numeric integral of a function f given its gradient g. * * @tparam T Type of f. * @tparam G Type of g. * @param f a functor with signature * double (double, std::vector<T_beta>) or with signature * double (double, T_beta) where the first argument is one being * integrated and the second one is either an extra scalar or vector * being passed to f. * @param g a functor with signature * double (double, std::vector<T_beta>, int, std::ostream*) or with * signature double (double, T_beta, int, std::ostream*) where the * first argument is onebeing integrated and the second one is * either an extra scalar or vector being passed to f and the * third one selects which component of the gradient vector * is to be returned. * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param msgs stream. * @return numeric integral of function f. */ template <typename F, typename G, typename T_beta> inline typename scalar_type<T_beta>::type integrate_1d_grad(const F& f, const G& g, const double a, const double b, const T_beta& beta, std::ostream* msgs) { check_finite("integrate_1d", "lower limit", a); check_finite("integrate_1d", "upper limit", b); //hard case, we want a normalizing factor if (!is_constant_struct<T_beta>::value) { size_t N = length(beta); std::vector<double> grad(N); typename return_type_of_value_of<T_beta>::type value_of_beta = value_of(beta); for (size_t n = 0; n < N; n++) grad[n] = call_DEIntegrator( boost::bind<double>(g, _1, value_of_beta, static_cast<int>(n+1), msgs), a, b, 1e-6); double val_ = call_DEIntegrator(boost::bind<double>(f, _1, value_of_beta, msgs), a, b, 1e-6); operands_and_partials<T_beta> ops_partials(beta); for (size_t n = 0; n < N; n++) ops_partials.edge1_.partials_[n] += grad[n]; return ops_partials.build(val_); //easy case, here we are calculating a normalizing constant, //not a normalizing factor, so g doesn't matter at all } else { return call_DEIntegrator( boost::bind<double>(f, _1, value_of(beta), msgs), a, b, 1e-6); } } /** * Calculate gradient of f(x, param, std::ostream*) * with respect to param_n (which must be an element of param) */ template <typename F, typename T_param> inline double gradient_of_f(const F& f, const double x, const T_param& param, const var& param_n, std::ostream* msgs) { set_zero_all_adjoints_nested(); f(x, param, msgs).grad(); return param_n.adj(); } /** * Return the numeric integral of a function f with its * gradients being infered automatically (but slowly). * * @tparam T Type of f. * @param f a functor with signature * double (double, std::vector<T_beta>, std::ostream*) or with * signature double (double, T_beta, std::ostream*) where the first * argument is one being integrated and the second one is either * an extra scalar or vector being passed to f. * @param a lower limit of integration, must be double type. * @param b upper limit of integration, must be double type. * @param msgs stream. * @return numeric integral of function f. */ template <typename F, typename T_param> inline typename scalar_type<T_param>::type integrate_1d(const F& f, const double a, const double b, const T_param& param, std::ostream* msgs) { stan::math::check_finite("integrate_1d", "lower limit", a); stan::math::check_finite("integrate_1d", "upper limit", b); double val_ = call_DEIntegrator( boost::bind<double>(f, _1, value_of(param), msgs), a, b, 1e-6); if (!is_constant_struct<T_param>::value) { size_t N = stan::length(param); std::vector<double> results(N); try { start_nested(); typedef typename return_type_of_to_var<T_param>::type clean_T_param; clean_T_param clean_param = to_var(value_of(param)); scalar_seq_view<const clean_T_param> clean_param_vec(clean_param); for (size_t n = 0; n < N; n++) results[n] = call_DEIntegrator(boost::bind<double>(gradient_of_f<F, clean_T_param>, f, _1, clean_param, clean_param_vec[n], msgs), a, b, 1e-6); } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); operands_and_partials<T_param> ops_partials(param); for (size_t n = 0; n < N; n++) ops_partials.edge1_.partials_[n] += results[n]; return ops_partials.build(val_); } else { return val_; } } } } #endif <|endoftext|>
<commit_before>#include "halley/tools/assets/import_assets_database.h" #include "halley/file/byte_serializer.h" #include "halley/resources/resource_data.h" #include "halley/tools/file/filesystem.h" using namespace Halley; void ImportAssetsDatabaseEntry::serialize(Serializer& s) const { s << assetId; s << srcDir; s << inputFiles; s << outputFiles; int t = int(assetType); s << t; } void ImportAssetsDatabaseEntry::deserialize(Deserializer& s) { s >> assetId; s >> srcDir; s >> inputFiles; s >> outputFiles; int t; s >> t; assetType = AssetType(t); } void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const { s << asset; } void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s) { s >> asset; } ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile) : directory(directory) , dbFile(dbFile) { load(); } void ImportAssetsDatabase::load() { std::lock_guard<std::mutex> lock(mutex); auto data = FileSystem::readFile(dbFile); if (data.size() > 0) { auto s = Deserializer(data); deserialize(s); } } void ImportAssetsDatabase::save() const { std::lock_guard<std::mutex> lock(mutex); FileSystem::writeFile(dbFile, Serializer::toBytes(*this)); } bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const { std::lock_guard<std::mutex> lock(mutex); // Check if it failed loading last time auto iter = assetsFailed.find(asset.assetId); bool failed = iter != assetsFailed.end(); if (!failed) { // No failures, check if this was imported before iter = assetsImported.find(asset.assetId); if (iter == assetsImported.end()) { // Asset didn't even exist before return true; } } // At this point, iter points to the failed one if it failed, or the the old successful one if it didn't. auto& oldAsset = iter->second.asset; // Input directory changed? if (asset.srcDir != oldAsset.srcDir) { return true; } // Total count of input files changed? if (asset.inputFiles.size() != oldAsset.inputFiles.size()) { return true; } // Any of the input files changed? // Note: We don't have to check old files on new input, because the size matches and all entries matched. for (auto& i: asset.inputFiles) { auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const ImportAssetsDatabaseEntry::InputFile& entry) { return entry.first == i.first; }); if (result == oldAsset.inputFiles.end()) { // File wasn't there before return true; } else if (result->second != i.second) { // Timestamp changed return true; } } // Have any of the output files gone missing? if (!failed) { for (auto& o: oldAsset.outputFiles) { if (!FileSystem::exists(directory / o)) { return true; } } } return false; } void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsImported[asset.assetId] = entry; auto failIter = assetsFailed.find(asset.assetId); if (failIter != assetsFailed.end()) { assetsFailed.erase(failIter); } } void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); assetsImported.erase(asset.assetId); } void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsFailed[asset.assetId] = entry; } void ImportAssetsDatabase::markAllInputsAsMissing() { std::lock_guard<std::mutex> lock(mutex); for (auto& e: assetsImported) { e.second.present = false; } } void ImportAssetsDatabase::markInputAsPresent(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); auto iter = assetsImported.find(asset.assetId); if (iter != assetsImported.end()) { iter->second.present = true; } } std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const { std::lock_guard<std::mutex> lock(mutex); std::vector<ImportAssetsDatabaseEntry> result; for (auto& e : assetsImported) { if (!e.second.present) { result.push_back(e.second.asset); } } return result; } std::vector<Path> ImportAssetsDatabase::getOutFiles(String assetId) const { auto iter = assetsImported.find(assetId); if (iter != assetsImported.end()) { return iter->second.asset.outputFiles; } else { return {}; } } constexpr static int currentAssetVersion = 6; void ImportAssetsDatabase::serialize(Serializer& s) const { int version = currentAssetVersion; s << version; s << assetsImported; } void ImportAssetsDatabase::deserialize(Deserializer& s) { int version; s >> version; if (version == currentAssetVersion) { s >> assetsImported; } } <commit_msg>Bump import asset database.<commit_after>#include "halley/tools/assets/import_assets_database.h" #include "halley/file/byte_serializer.h" #include "halley/resources/resource_data.h" #include "halley/tools/file/filesystem.h" using namespace Halley; void ImportAssetsDatabaseEntry::serialize(Serializer& s) const { s << assetId; s << srcDir; s << inputFiles; s << outputFiles; int t = int(assetType); s << t; } void ImportAssetsDatabaseEntry::deserialize(Deserializer& s) { s >> assetId; s >> srcDir; s >> inputFiles; s >> outputFiles; int t; s >> t; assetType = AssetType(t); } void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const { s << asset; } void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s) { s >> asset; } ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile) : directory(directory) , dbFile(dbFile) { load(); } void ImportAssetsDatabase::load() { std::lock_guard<std::mutex> lock(mutex); auto data = FileSystem::readFile(dbFile); if (data.size() > 0) { auto s = Deserializer(data); deserialize(s); } } void ImportAssetsDatabase::save() const { std::lock_guard<std::mutex> lock(mutex); FileSystem::writeFile(dbFile, Serializer::toBytes(*this)); } bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const { std::lock_guard<std::mutex> lock(mutex); // Check if it failed loading last time auto iter = assetsFailed.find(asset.assetId); bool failed = iter != assetsFailed.end(); if (!failed) { // No failures, check if this was imported before iter = assetsImported.find(asset.assetId); if (iter == assetsImported.end()) { // Asset didn't even exist before return true; } } // At this point, iter points to the failed one if it failed, or the the old successful one if it didn't. auto& oldAsset = iter->second.asset; // Input directory changed? if (asset.srcDir != oldAsset.srcDir) { return true; } // Total count of input files changed? if (asset.inputFiles.size() != oldAsset.inputFiles.size()) { return true; } // Any of the input files changed? // Note: We don't have to check old files on new input, because the size matches and all entries matched. for (auto& i: asset.inputFiles) { auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const ImportAssetsDatabaseEntry::InputFile& entry) { return entry.first == i.first; }); if (result == oldAsset.inputFiles.end()) { // File wasn't there before return true; } else if (result->second != i.second) { // Timestamp changed return true; } } // Have any of the output files gone missing? if (!failed) { for (auto& o: oldAsset.outputFiles) { if (!FileSystem::exists(directory / o)) { return true; } } } return false; } void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsImported[asset.assetId] = entry; auto failIter = assetsFailed.find(asset.assetId); if (failIter != assetsFailed.end()) { assetsFailed.erase(failIter); } } void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); assetsImported.erase(asset.assetId); } void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsFailed[asset.assetId] = entry; } void ImportAssetsDatabase::markAllInputsAsMissing() { std::lock_guard<std::mutex> lock(mutex); for (auto& e: assetsImported) { e.second.present = false; } } void ImportAssetsDatabase::markInputAsPresent(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); auto iter = assetsImported.find(asset.assetId); if (iter != assetsImported.end()) { iter->second.present = true; } } std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const { std::lock_guard<std::mutex> lock(mutex); std::vector<ImportAssetsDatabaseEntry> result; for (auto& e : assetsImported) { if (!e.second.present) { result.push_back(e.second.asset); } } return result; } std::vector<Path> ImportAssetsDatabase::getOutFiles(String assetId) const { auto iter = assetsImported.find(assetId); if (iter != assetsImported.end()) { return iter->second.asset.outputFiles; } else { return {}; } } constexpr static int currentAssetVersion = 7; void ImportAssetsDatabase::serialize(Serializer& s) const { int version = currentAssetVersion; s << version; s << assetsImported; } void ImportAssetsDatabase::deserialize(Deserializer& s) { int version; s >> version; if (version == currentAssetVersion) { s >> assetsImported; } } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/sbml-testsuite/wrapper.cpp,v $ // $Revision: 1.5 $ // $Name: $ // $Author: shoops $ // $Date: 2009/07/23 19:53:48 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #define COPASI_MAIN #include <iostream> #include <fstream> #include <string> #include <list> #include <sstream> #include <stdlib.h> #include "copasi/copasi.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/report/CCopasiContainer.h" #include "copasi/model/CMetab.h" #include "copasi/report/CCopasiObjectName.h" #include "copasi/utilities/CCopasiVector.h" #include "copasi/model/CModel.h" #include "copasi/utilities/CCopasiException.h" #include "copasi/commandline/COptionParser.h" #include "copasi/commandline/COptions.h" #include "copasi/trajectory/CTrajectoryTask.h" #include "copasi/trajectory/CTrajectoryMethod.h" #include "copasi/trajectory/CTrajectoryProblem.h" #include "copasi/report/CReportDefinitionVector.h" #include "copasi/report/CReportDefinition.h" #include "copasi/report/CCopasiStaticString.h" void parse_items(const std::string& text, std::list<std::string>& itemList) { // parse the items //std::cout << "parsing: " << text << std::endl; std::istringstream iss(text); std::string token; std::string delimiter = " \t\r\n"; std::size_t begin, end; while (getline(iss, token, ',')) { // strip whitespaces begin = token.find_first_not_of(delimiter); end = token.find_last_not_of(delimiter); if (begin != std::string::npos) { //std::cout << token.substr(begin,end-begin+1) << std::endl; itemList.push_back(token.substr(begin, end - begin + 1)); } } } int main(int argc, char** argv) { std::string in_dir; std::string out_dir; std::string test_name; unsigned int level = 0; unsigned int version = 0; double start_time = 0.0; double duration = 0.0; unsigned int steps = 0; std::list<std::string> variables; std::set<std::string> amounts; std::set<std::string> concentrations; double absolute_error = 0.0; double relative_error = 0.0; try { // Parse the commandline options COptions::init(argc, argv); } catch (copasi::autoexcept &e) {} catch (copasi::option_error &e) {} if (argc != 6) { std::cerr << "Usage: sbml-testsuite INPUT_DIRECTORY TESTNAME OUTPUTDIRECTORY SBMLLEVEL SBMLVERSION" << std::endl; exit(1); } in_dir = argv[1]; test_name = argv[2]; out_dir = argv[3]; level = strtol(argv[4], NULL, 10); version = strtol(argv[5], NULL, 10); if (level != 1 && level != 2) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } if (level == 1 && (version < 1 || version > 2)) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } else if (version < 1 || version > 3) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } std::ostringstream os; os << in_dir << "/" << test_name << "/" << test_name << "-settings.txt"; // open the settings file and parse it std::cout << "parsing file: " << os.str() << std::endl; std::ifstream f; f.open(os.str().c_str()); if (f.is_open()) { std::string line; while (! f.eof()) { getline(f, line); size_t pos = line.find(':'); if (pos != std::string::npos) { std::string tag = line.substr(0, pos); std::string value = line.substr(pos + 1); if (tag == "start") { start_time = strToDouble(value.c_str(), NULL); } else if (tag == "duration") { duration = strToDouble(value.c_str(), NULL); } else if (tag == "steps") { steps = strtol(value.c_str(), NULL, 10); } else if (tag == "variables") { // parse the variables parse_items(value, variables); } else if (tag == "amount") { // parse the variables std::list<std::string> tmp; parse_items(value, tmp); amounts.insert(tmp.begin(), tmp.end()); } else if (tag == "concentration") { // parse the variables std::list<std::string> tmp; parse_items(value, tmp); concentrations.insert(tmp.begin(), tmp.end()); } else if (tag == "absolute") { absolute_error = strToDouble(value.c_str(), NULL); } else if (tag == "relative") { relative_error = strToDouble(value.c_str(), NULL); } else { std::cerr << "Warning. Unknown tag \"" << tag << "\"." << std::endl; } } } f.close(); } else { std::cerr << "Error. Unable to open file \"" << os.str() << "\"." << std::endl; exit(1); } if (duration <= 0.0) { std::cerr << "Error. Duration < 0.0." << std::endl; exit(1); } if (steps == 0) { std::cerr << "Error. Number of steps set to 0." << std::endl; exit(1); } if (variables.empty()) { std::cerr << "Error. No variables specified." << std::endl; exit(1); } if (start_time < 0.0) { std::cerr << "Error. Start time < 0.0." << std::endl; exit(1); } if (absolute_error < 0.0) { std::cerr << "Error. Absolute error < 0.0." << std::endl; exit(1); } if (relative_error < 0.0) { std::cerr << "Error. Relative error < 0.0." << std::endl; exit(1); } /* std::cout << "Simulating " << in_dir << "/" << test_name << "/" << test_name << "-sbml-l" << level << "v" << version << ".xml" << std::endl; std::cout << "Start time: " << start_time << std::endl; std::cout << "Duration: " << duration << std::endl; std::cout << "Absolute error: " << absolute_error << std::endl; std::cout << "Relative error: " << relative_error << std::endl; std::list<std::string>::const_iterator it=variables.begin(),endit=variables.end(); std::cout << "Outputting variables: "; while(it!=endit) { std::cout << *it << ", "; ++it; } std::cout << std::endl; */ os.str(""); os << in_dir << "/" << test_name << "/" << test_name << "-sbml-l" << level << "v" << version << ".xml"; std::string sbml_filename = os.str(); double end_time = start_time + duration; os.str(""); os << out_dir << "/" << test_name << ".csv"; std::string output_filename = os.str(); CTrajectoryTask* pTrajectoryTask = NULL; std::string CWD = COptions::getPWD(); if (end_time == 0.0) { std::cerr << "Error. Invalid endtime " << end_time << std::endl; exit(1); } try { // Create the root container. CCopasiRootContainer::init(false, 0, NULL); } catch (copasi::autoexcept &e) {} catch (copasi::option_error &e) {} try { // Create the global data model. CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); // Import the SBML File pDataModel->importSBML(sbml_filename.c_str()); // create a report with the correct filename and all the species against // time. CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList(); CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run"); pReport->setSeparator(CCopasiReportSeparator(",")); pReport->setTaskType(CCopasiTask::timeCourse); pReport->setIsTable(true); std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr(); pTable->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time")); // create a map of all posible variables std::map<std::string, const CModelEntity*> variableMap; const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites(); unsigned int i, iMax = metabolites.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(metabolites[i]->getSBMLId(), metabolites[i])); } const CCopasiVector<CCompartment>& compartments = pDataModel->getModel()->getCompartments(); iMax = compartments.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(compartments[i]->getSBMLId(), compartments[i])); } const CCopasiVector<CModelValue>& modelValues = pDataModel->getModel()->getModelValues(); iMax = modelValues.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(modelValues[i]->getSBMLId(), modelValues[i])); } std::list<std::string>::const_iterator it = variables.begin(), endit = variables.end(); std::map<std::string, const CModelEntity*>::const_iterator pos; unsigned int dummyCount = 1; while (it != endit) { pos = variableMap.find(*it); if (pos == variableMap.end()) { std::cerr << "Could not find a model entity for the SBML id " << *it << std::endl; exit(1); } if (dynamic_cast<const CMetab*>(pos->second) != NULL) { if (amounts.find(*it) != amounts.end()) { // create a new global value with an assignment std::stringstream ss; ss << "dummy_modelvalue_" << dummyCount; CModelValue* pTmpMV = pDataModel->getModel()->createModelValue(ss.str()); ++dummyCount; ss.str(""); assert(pTmpMV); // create an assignment that takes the concentration of the // metabolite and multiplies it by the compartment ss << "<" << pos->second->getObject(CCopasiObjectName("Reference=Concentration"))->getCN() << "> * <" << dynamic_cast<const CMetab*>(pos->second)->getCompartment()->getObject(CCopasiObjectName("Reference=Volume"))->getCN() << ">"; pTmpMV->setStatus(CModelEntity::ASSIGNMENT); assert(pTmpMV->setExpression(ss.str())); pTable->push_back(pTmpMV->getObject(CCopasiObjectName("Reference=Value"))->getCN()); } else if (concentrations.find(*it) != concentrations.end()) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Concentration"))->getCN()); } else { std::cerr << "Species \"" << *it << "\" neither given in the amounts or the conentration section." << std::endl; exit(1); } } else if (dynamic_cast<const CCompartment*>(pos->second) != NULL) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Volume"))->getCN()); } else if (dynamic_cast<const CModelValue*>(pos->second) != NULL) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Value"))->getCN()); } ++it; } // create a trajectory task pTrajectoryTask = new CTrajectoryTask(); pTrajectoryTask->getProblem()->setModel(pDataModel->getModel()); pTrajectoryTask->setScheduled(true); pTrajectoryTask->getReport().setReportDefinition(pReport); pTrajectoryTask->getReport().setTarget(output_filename); pTrajectoryTask->getReport().setAppend(false); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem()); pProblem->setStepNumber((const unsigned C_INT32)steps); pProblem->setDuration((const C_FLOAT64)end_time); pProblem->setTimeSeriesRequested(true); CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod()); pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-12); CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList(); TaskList.remove("Time-Course"); TaskList.add(pTrajectoryTask, true); // save the file for control purposes //std::string saveFilename = pSBMLFilename; //saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps"; //pDataModel->saveModel(saveFilename, NULL, true); // Run the trajectory task pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, pDataModel, NULL); pTrajectoryTask->process(true); pTrajectoryTask->restore(); // create another report that will write to the directory where the input file came from // this can be used for debugging // create a trajectory task //pTrajectoryTask->getReport().setTarget(pOutputFilename); //pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, pDataModel, NULL); //pTrajectoryTask->process(true); //pTrajectoryTask->restore(); } catch (CCopasiException Exception) { std::cerr << Exception.getMessage().getText() << std::endl; } CCopasiRootContainer::destroy(); return 0; } <commit_msg>Enabled write of COPASI file into the test suite directory to ease debugging.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/sbml-testsuite/wrapper.cpp,v $ // $Revision: 1.6 $ // $Name: $ // $Author: shoops $ // $Date: 2009/07/28 13:54:16 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #define COPASI_MAIN #include <iostream> #include <fstream> #include <string> #include <list> #include <sstream> #include <stdlib.h> #include "copasi/copasi.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/report/CCopasiContainer.h" #include "copasi/model/CMetab.h" #include "copasi/report/CCopasiObjectName.h" #include "copasi/utilities/CCopasiVector.h" #include "copasi/model/CModel.h" #include "copasi/utilities/CCopasiException.h" #include "copasi/commandline/COptionParser.h" #include "copasi/commandline/COptions.h" #include "copasi/trajectory/CTrajectoryTask.h" #include "copasi/trajectory/CTrajectoryMethod.h" #include "copasi/trajectory/CTrajectoryProblem.h" #include "copasi/report/CReportDefinitionVector.h" #include "copasi/report/CReportDefinition.h" #include "copasi/report/CCopasiStaticString.h" void parse_items(const std::string& text, std::list<std::string>& itemList) { // parse the items //std::cout << "parsing: " << text << std::endl; std::istringstream iss(text); std::string token; std::string delimiter = " \t\r\n"; std::size_t begin, end; while (getline(iss, token, ',')) { // strip whitespaces begin = token.find_first_not_of(delimiter); end = token.find_last_not_of(delimiter); if (begin != std::string::npos) { //std::cout << token.substr(begin,end-begin+1) << std::endl; itemList.push_back(token.substr(begin, end - begin + 1)); } } } int main(int argc, char** argv) { std::string in_dir; std::string out_dir; std::string test_name; unsigned int level = 0; unsigned int version = 0; double start_time = 0.0; double duration = 0.0; unsigned int steps = 0; std::list<std::string> variables; std::set<std::string> amounts; std::set<std::string> concentrations; double absolute_error = 0.0; double relative_error = 0.0; if (argc != 6) { std::cerr << "Usage: sbml-testsuite INPUT_DIRECTORY TESTNAME OUTPUTDIRECTORY SBMLLEVEL SBMLVERSION" << std::endl; exit(1); } try { // Create the root container. CCopasiRootContainer::init(argc, argv, false); } catch (copasi::autoexcept &e) {} catch (copasi::option_error &e) {} in_dir = argv[1]; test_name = argv[2]; out_dir = argv[3]; level = strtol(argv[4], NULL, 10); version = strtol(argv[5], NULL, 10); if (level != 1 && level != 2) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } if (level == 1 && (version < 1 || version > 2)) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } else if (version < 1 || version > 3) { std::cerr << "SBML Level " << level << " Version " << version << " not supported." << std::endl; exit(1); } std::ostringstream os; os << in_dir << "/" << test_name << "/" << test_name << "-settings.txt"; // open the settings file and parse it std::cout << "parsing file: " << os.str() << std::endl; std::ifstream f; f.open(os.str().c_str()); if (f.is_open()) { std::string line; while (! f.eof()) { getline(f, line); size_t pos = line.find(':'); if (pos != std::string::npos) { std::string tag = line.substr(0, pos); std::string value = line.substr(pos + 1); if (tag == "start") { start_time = strToDouble(value.c_str(), NULL); } else if (tag == "duration") { duration = strToDouble(value.c_str(), NULL); } else if (tag == "steps") { steps = strtol(value.c_str(), NULL, 10); } else if (tag == "variables") { // parse the variables parse_items(value, variables); } else if (tag == "amount") { // parse the variables std::list<std::string> tmp; parse_items(value, tmp); amounts.insert(tmp.begin(), tmp.end()); } else if (tag == "concentration") { // parse the variables std::list<std::string> tmp; parse_items(value, tmp); concentrations.insert(tmp.begin(), tmp.end()); } else if (tag == "absolute") { absolute_error = strToDouble(value.c_str(), NULL); } else if (tag == "relative") { relative_error = strToDouble(value.c_str(), NULL); } else { std::cerr << "Warning. Unknown tag \"" << tag << "\"." << std::endl; } } } f.close(); } else { std::cerr << "Error. Unable to open file \"" << os.str() << "\"." << std::endl; exit(1); } if (duration <= 0.0) { std::cerr << "Error. Duration < 0.0." << std::endl; exit(1); } if (steps == 0) { std::cerr << "Error. Number of steps set to 0." << std::endl; exit(1); } if (variables.empty()) { std::cerr << "Error. No variables specified." << std::endl; exit(1); } if (start_time < 0.0) { std::cerr << "Error. Start time < 0.0." << std::endl; exit(1); } if (absolute_error < 0.0) { std::cerr << "Error. Absolute error < 0.0." << std::endl; exit(1); } if (relative_error < 0.0) { std::cerr << "Error. Relative error < 0.0." << std::endl; exit(1); } /* std::cout << "Simulating " << in_dir << "/" << test_name << "/" << test_name << "-sbml-l" << level << "v" << version << ".xml" << std::endl; std::cout << "Start time: " << start_time << std::endl; std::cout << "Duration: " << duration << std::endl; std::cout << "Absolute error: " << absolute_error << std::endl; std::cout << "Relative error: " << relative_error << std::endl; std::list<std::string>::const_iterator it=variables.begin(),endit=variables.end(); std::cout << "Outputting variables: "; while(it!=endit) { std::cout << *it << ", "; ++it; } std::cout << std::endl; */ os.str(""); os << in_dir << "/" << test_name << "/" << test_name << "-sbml-l" << level << "v" << version << ".xml"; std::string sbml_filename = os.str(); double end_time = start_time + duration; os.str(""); os << out_dir << "/" << test_name << ".csv"; std::string output_filename = os.str(); CTrajectoryTask* pTrajectoryTask = NULL; std::string CWD = COptions::getPWD(); if (end_time == 0.0) { std::cerr << "Error. Invalid endtime " << end_time << std::endl; exit(1); } try { // Create the global data model. CCopasiDataModel* pDataModel = CCopasiRootContainer::addDatamodel(); // Import the SBML File pDataModel->importSBML(sbml_filename.c_str()); // create a report with the correct filename and all the species against // time. CReportDefinitionVector* pReports = pDataModel->getReportDefinitionList(); CReportDefinition* pReport = pReports->createReportDefinition("Report", "Output for SBML testsuite run"); pReport->setSeparator(CCopasiReportSeparator(",")); pReport->setTaskType(CCopasiTask::timeCourse); pReport->setIsTable(true); std::vector<CRegisteredObjectName>* pTable = pReport->getTableAddr(); pTable->push_back(CCopasiObjectName(pDataModel->getModel()->getCN() + ",Reference=Time")); // create a map of all posible variables std::map<std::string, const CModelEntity*> variableMap; const CCopasiVector<CMetab>& metabolites = pDataModel->getModel()->getMetabolites(); unsigned int i, iMax = metabolites.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(metabolites[i]->getSBMLId(), metabolites[i])); } const CCopasiVector<CCompartment>& compartments = pDataModel->getModel()->getCompartments(); iMax = compartments.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(compartments[i]->getSBMLId(), compartments[i])); } const CCopasiVector<CModelValue>& modelValues = pDataModel->getModel()->getModelValues(); iMax = modelValues.size(); for (i = 0; i < iMax; ++i) { variableMap.insert(std::pair<std::string, const CModelEntity*>(modelValues[i]->getSBMLId(), modelValues[i])); } std::list<std::string>::const_iterator it = variables.begin(), endit = variables.end(); std::map<std::string, const CModelEntity*>::const_iterator pos; unsigned int dummyCount = 1; while (it != endit) { pos = variableMap.find(*it); if (pos == variableMap.end()) { std::cerr << "Could not find a model entity for the SBML id " << *it << std::endl; exit(1); } if (dynamic_cast<const CMetab*>(pos->second) != NULL) { if (amounts.find(*it) != amounts.end()) { // create a new global value with an assignment std::stringstream ss; ss << "dummy_modelvalue_" << dummyCount; CModelValue* pTmpMV = pDataModel->getModel()->createModelValue(ss.str()); ++dummyCount; ss.str(""); assert(pTmpMV); // create an assignment that takes the concentration of the // metabolite and multiplies it by the compartment ss << "<" << pos->second->getObject(CCopasiObjectName("Reference=Concentration"))->getCN() << "> * <" << dynamic_cast<const CMetab*>(pos->second)->getCompartment()->getObject(CCopasiObjectName("Reference=Volume"))->getCN() << ">"; pTmpMV->setStatus(CModelEntity::ASSIGNMENT); assert(pTmpMV->setExpression(ss.str())); pTable->push_back(pTmpMV->getObject(CCopasiObjectName("Reference=Value"))->getCN()); } else if (concentrations.find(*it) != concentrations.end()) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Concentration"))->getCN()); } else { std::cerr << "Species \"" << *it << "\" neither given in the amounts or the conentration section." << std::endl; exit(1); } } else if (dynamic_cast<const CCompartment*>(pos->second) != NULL) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Volume"))->getCN()); } else if (dynamic_cast<const CModelValue*>(pos->second) != NULL) { pTable->push_back(pos->second->getObject(CCopasiObjectName("Reference=Value"))->getCN()); } ++it; } // create a trajectory task pTrajectoryTask = new CTrajectoryTask(); pTrajectoryTask->getProblem()->setModel(pDataModel->getModel()); pTrajectoryTask->setScheduled(true); pTrajectoryTask->getReport().setReportDefinition(pReport); pTrajectoryTask->getReport().setTarget(output_filename); pTrajectoryTask->getReport().setAppend(false); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem*>(pTrajectoryTask->getProblem()); pProblem->setStepNumber((const unsigned C_INT32)steps); pProblem->setDuration((const C_FLOAT64)end_time); pProblem->setTimeSeriesRequested(true); CTrajectoryMethod* pMethod = dynamic_cast<CTrajectoryMethod*>(pTrajectoryTask->getMethod()); pMethod->getParameter("Absolute Tolerance")->setValue(1.0e-12); CCopasiVectorN< CCopasiTask > & TaskList = * pDataModel->getTaskList(); TaskList.remove("Time-Course"); TaskList.add(pTrajectoryTask, true); // save the file for control purposes std::string saveFilename = sbml_filename; saveFilename = saveFilename.substr(0, saveFilename.length() - 4) + ".cps"; pDataModel->saveModel(saveFilename, NULL, true, false); // Run the trajectory task pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, pDataModel, NULL); pTrajectoryTask->process(true); pTrajectoryTask->restore(); // create another report that will write to the directory where the input file came from // this can be used for debugging // create a trajectory task //pTrajectoryTask->getReport().setTarget(pOutputFilename); //pTrajectoryTask->initialize(CCopasiTask::OUTPUT_COMPLETE, pDataModel, NULL); //pTrajectoryTask->process(true); //pTrajectoryTask->restore(); } catch (CCopasiException Exception) { std::cerr << Exception.getMessage().getText() << std::endl; } CCopasiRootContainer::destroy(); return 0; } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : support/application.hpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ #if !defined(UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP) #define UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP // includes, system #include <boost/noncopyable.hpp> // boost::noncopyable #include <boost/program_options.hpp> // boost::program_options::options_description, // boost::program_options::positional_options_description, // boost::program_options::variables_map // includes, project #include <support/printable.hpp> namespace support { namespace application { // types, exported (class, enum, struct, union, typedef) class base : private boost::noncopyable, public support::printable { public: virtual signed run() =0; virtual void print_on(std::ostream&) const; protected: boost::program_options::options_description cmdline_options_; boost::program_options::positional_options_description cmdline_positionals_; unsigned verbose_level_; explicit base(int /* argc */, char* /* argv */[]); virtual ~base() =0; virtual void cmdline_eval (boost::program_options::variables_map&); virtual void cmdline_process(int /* argc */, char* /* argv */[]); }; class multi_instance : private base { public: explicit multi_instance(int /* argc */, char* /* argv */[]); virtual ~multi_instance(); }; class single_instance : private base { public: explicit single_instance(int /* argc */, char* /* argv */[]); virtual ~single_instance(); virtual void print_on(std::ostream&) const; private: static single_instance* instance_; }; template <typename T> class executor : private boost::noncopyable { public: explicit executor(int, char* []); ~executor(); signed run(); private: std::unique_ptr<T> instance_; }; // variables, exported (extern) // functions, inlined (inline) // functions, exported (extern) template <typename T> signed execute(int, char* []); template <typename T> signed execute(int, char* [], std::nothrow_t const&); } // namespace application { } // namespace support { #include <support/application.inl> #endif // #if !defined(UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP) <commit_msg>update: access specifiers<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : support/application.hpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ #if !defined(UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP) #define UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP // includes, system #include <boost/noncopyable.hpp> // boost::noncopyable #include <boost/program_options.hpp> // boost::program_options::options_description, // boost::program_options::positional_options_description, // boost::program_options::variables_map // includes, project #include <support/printable.hpp> namespace support { namespace application { // types, exported (class, enum, struct, union, typedef) class base : private boost::noncopyable, public support::printable { public: virtual signed run() =0; virtual void print_on(std::ostream&) const; protected: boost::program_options::options_description cmdline_options_; boost::program_options::positional_options_description cmdline_positionals_; unsigned verbose_level_; explicit base(int /* argc */, char* /* argv */[]); virtual ~base() =0; virtual void cmdline_eval (boost::program_options::variables_map&); virtual void cmdline_process(int /* argc */, char* /* argv */[]); }; class multi_instance : private base { protected: explicit multi_instance(int /* argc */, char* /* argv */[]); virtual ~multi_instance(); }; class single_instance : private base { protected: explicit single_instance(int /* argc */, char* /* argv */[]); virtual ~single_instance(); virtual void print_on(std::ostream&) const; private: static single_instance* instance_; }; template <typename T> class executor : private boost::noncopyable { public: explicit executor(int, char* []); ~executor(); signed run(); private: std::unique_ptr<T> instance_; }; // variables, exported (extern) // functions, inlined (inline) // functions, exported (extern) template <typename T> signed execute(int, char* []); template <typename T> signed execute(int, char* [], std::nothrow_t const&); } // namespace application { } // namespace support { #include <support/application.inl> #endif // #if !defined(UKACHULLDCS_08961_SUPPORT_APPLICATION_HPP) <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery 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 University of Wisconsin - Madison 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 DTK_TopologyTools.cpp * \author Stuart R. Slattery * \brief TopologyTools definition. */ //---------------------------------------------------------------------------// #include <vector> #include "DTK_CellTopologyFactory.hpp" #include "DTK_TopologyTools.hpp" #include <DTK_Exception.hpp> #include <Teuchos_ENull.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_Tuple.hpp> #include <Shards_CellTopology.hpp> #include <Intrepid_FieldContainer.hpp> #include <Intrepid_CellTools.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! * \brief Get the number of linear nodes for a particular iMesh topology. */ int TopologyTools::numLinearNodes( const moab::EntityType element_topology ) { int num_nodes = 0; switch( element_topology ) { case moab::MBVERTEX: num_nodes = 1; break; case moab::MBEDGE: num_nodes = 2; break; case moab::MBTRI: num_nodes = 3; break; case moab::MBQUAD: num_nodes = 4; break; case moab::MBTET: num_nodes = 4; break; case moab::MBHEX: num_nodes = 8; break; case moab::MBPYRAMID: num_nodes = 5; break; default: testPrecondition( moab::MBEDGE == element_topology || moab::MBTRI == element_topology || moab::MBQUAD == element_topology || moab::MBTET == element_topology || moab::MBHEX == element_topology || moab::MBPYRAMID == element_topology, "Invalid mesh topology" ); } return num_nodes; } //---------------------------------------------------------------------------// /*! * \brief Point in element query. */ bool TopologyTools::pointInElement( Teuchos::Array<double>& coords, const moab::EntityHandle element, const Teuchos::RCP<moab::Interface>& moab ) { moab::ErrorCode error; // Get the element topology. moab::EntityType element_topology = moab->type_from_handle( element ); // Wrap the point in a field container. int node_dim = coords.size(); Teuchos::Tuple<int,2> point_dimensions; point_dimensions[0] = 1; point_dimensions[1] = node_dim; Teuchos::ArrayRCP<double> coords_view = Teuchos::arcpFromArray( coords ); Intrepid::FieldContainer<double> point( Teuchos::Array<int>(point_dimensions), coords_view ); // Typical topology case. if ( moab::MBPYRAMID != element_topology ) { // Get the element nodes. std::vector<moab::EntityHandle> element_nodes; error = moab->get_adjacencies( &element, 1, 0, false, element_nodes ); testInvariant( moab::MB_SUCCESS == error, "Failure getting element nodes" ); // Create the Shards topology for the element type. int num_element_nodes = element_nodes.size(); Teuchos::RCP<shards::CellTopology> cell_topo = CellTopologyFactory::create( element_topology, num_element_nodes ); // Extract the node coordinates. Teuchos::Array<double> cell_node_coords( 3 * num_element_nodes ); error = moab->get_coords( &element_nodes[0], element_nodes.size(), &cell_node_coords[0] ); testInvariant( moab::MB_SUCCESS == error, "Failure getting node coordinates" ); // Reduce the dimension of the coordinates if necessary and wrap in a // field container. This means (for now at least) that 2D meshes must be // constructed from 2D nodes (this obviously won't work for 2D meshes that // have curvature). Teuchos::Tuple<int,3> cell_node_dimensions; cell_node_dimensions[0] = 1; cell_node_dimensions[1] = num_element_nodes; cell_node_dimensions[2] = node_dim; for ( int i = 2; i != node_dim-1 ; --i ) { for ( int n = element_nodes.size() - 1; n > -1; --n ) { cell_node_coords.erase( cell_node_coords.begin() + 3*n + i ); } } Intrepid::FieldContainer<double> cell_nodes( Teuchos::Array<int>(cell_node_dimensions), Teuchos::arcpFromArray( cell_node_coords ) ); // Map the point to the reference frame of the cell. Intrepid::FieldContainer<double> reference_point( 1, node_dim ); Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in the reference cell. return Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); } // We have to handle pyramids differently because Intrepid doesn't support // them with basis functions. Instead we'll resolve them with two linear // tetrahedrons and check for point inclusion in that set instead. else { // Get the element nodes. std::vector<moab::EntityHandle> element_nodes; error = moab->get_adjacencies( &element, 1, 0, false, element_nodes ); testInvariant( moab::MB_SUCCESS == error, "Failure getting element nodes" ); // Create the Shards topology for the linear tetrahedrons. Teuchos::RCP<shards::CellTopology> cell_topo = CellTopologyFactory::create( moab::MBTET, 4 ); // Extract the node coordinates. int num_element_nodes = element_nodes.size(); Teuchos::Array<double> cell_node_coords( 3 * num_element_nodes ); error = moab->get_coords( &element_nodes[0], element_nodes.size(), &cell_node_coords[0] ); testInvariant( moab::MB_SUCCESS == error, "Failure getting node coordinates" ); // Build 2 tetrahedrons from the 1 pyramid. testInvariant( node_dim == 3, "Pyramid elements must be 3D." ); Intrepid::FieldContainer<double> cell_nodes( 1, 4, node_dim ); // Tetrahederon 1. cell_nodes( 0, 0, 0 ) = cell_node_coords[0]; cell_nodes( 0, 0, 1 ) = cell_node_coords[1]; cell_nodes( 0, 0, 2 ) = cell_node_coords[2]; cell_nodes( 0, 1, 0 ) = cell_node_coords[3]; cell_nodes( 0, 1, 1 ) = cell_node_coords[4]; cell_nodes( 0, 1, 2 ) = cell_node_coords[5]; cell_nodes( 0, 2, 0 ) = cell_node_coords[6]; cell_nodes( 0, 2, 1 ) = cell_node_coords[7]; cell_nodes( 0, 2, 2 ) = cell_node_coords[8]; cell_nodes( 0, 3, 0 ) = cell_node_coords[12]; cell_nodes( 0, 3, 1 ) = cell_node_coords[13]; cell_nodes( 0, 3, 2 ) = cell_node_coords[14]; // Map the point to the reference frame of the first linear // tetrahedron. Intrepid::FieldContainer<double> reference_point( 1, node_dim ); Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in tetrahedron 1. bool in_tet_1 = Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); // Tetrahederon 2. cell_nodes( 0, 0, 0 ) = cell_node_coords[0]; cell_nodes( 0, 0, 1 ) = cell_node_coords[1]; cell_nodes( 0, 0, 2 ) = cell_node_coords[2]; cell_nodes( 0, 1, 0 ) = cell_node_coords[6]; cell_nodes( 0, 1, 1 ) = cell_node_coords[7]; cell_nodes( 0, 1, 2 ) = cell_node_coords[8]; cell_nodes( 0, 2, 0 ) = cell_node_coords[9]; cell_nodes( 0, 2, 1 ) = cell_node_coords[10]; cell_nodes( 0, 2, 2 ) = cell_node_coords[11]; cell_nodes( 0, 3, 0 ) = cell_node_coords[12]; cell_nodes( 0, 3, 1 ) = cell_node_coords[13]; cell_nodes( 0, 3, 2 ) = cell_node_coords[14]; // Map the point to the reference frame of the first linear // tetrahedron. Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in tetrahedron 2. bool in_tet_2 = Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); // If the point is in either tetrahedron, it is in the pyramid. if ( in_tet_1 || in_tet_2 ) { return true; } else { return false; } } } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// // end DTK_TopologyTools.cpp //---------------------------------------------------------------------------// <commit_msg>Cleaning up topology tools.<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery 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 University of Wisconsin - Madison 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 DTK_TopologyTools.cpp * \author Stuart R. Slattery * \brief TopologyTools definition. */ //---------------------------------------------------------------------------// #include <vector> #include "DTK_CellTopologyFactory.hpp" #include "DTK_TopologyTools.hpp" #include <DTK_Exception.hpp> #include <Teuchos_ENull.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_Tuple.hpp> #include <Shards_CellTopology.hpp> #include <Intrepid_FieldContainer.hpp> #include <Intrepid_CellTools.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! * \brief Get the number of linear nodes for a particular iMesh topology. */ int TopologyTools::numLinearNodes( const moab::EntityType element_topology ) { int num_nodes = 0; switch( element_topology ) { case moab::MBVERTEX: num_nodes = 1; break; case moab::MBEDGE: num_nodes = 2; break; case moab::MBTRI: num_nodes = 3; break; case moab::MBQUAD: num_nodes = 4; break; case moab::MBTET: num_nodes = 4; break; case moab::MBHEX: num_nodes = 8; break; case moab::MBPYRAMID: num_nodes = 5; break; default: testPrecondition( moab::MBEDGE == element_topology || moab::MBTRI == element_topology || moab::MBQUAD == element_topology || moab::MBTET == element_topology || moab::MBHEX == element_topology || moab::MBPYRAMID == element_topology, "Invalid mesh topology" ); } return num_nodes; } //---------------------------------------------------------------------------// /*! * \brief Point in element query. */ bool TopologyTools::pointInElement( Teuchos::Array<double>& coords, const moab::EntityHandle element, const Teuchos::RCP<moab::Interface>& moab ) { moab::ErrorCode error; // Wrap the point in a field container. int node_dim = coords.size(); Teuchos::Tuple<int,2> point_dimensions; point_dimensions[0] = 1; point_dimensions[1] = node_dim; Teuchos::ArrayRCP<double> coords_view = Teuchos::arcpFromArray( coords ); Intrepid::FieldContainer<double> point( Teuchos::Array<int>(point_dimensions), coords_view ); // Get the element nodes. std::vector<moab::EntityHandle> element_nodes; error = moab->get_adjacencies( &element, 1, 0, false, element_nodes ); testInvariant( moab::MB_SUCCESS == error, "Failure getting element nodes" ); // Extract the node coordinates. int num_element_nodes = element_nodes.size(); Teuchos::Array<double> cell_node_coords( 3 * num_element_nodes ); error = moab->get_coords( &element_nodes[0], element_nodes.size(), &cell_node_coords[0] ); testInvariant( moab::MB_SUCCESS == error, "Failure getting node coordinates" ); // Get the element topology. moab::EntityType element_topology = moab->type_from_handle( element ); // Typical topology case. if ( moab::MBPYRAMID != element_topology ) { // Create the Shards topology for the element type. Teuchos::RCP<shards::CellTopology> cell_topo = CellTopologyFactory::create( element_topology, num_element_nodes ); // Reduce the dimension of the coordinates if necessary and wrap in a // field container. This means (for now at least) that 2D meshes must be // constructed from 2D nodes (this obviously won't work for 2D meshes that // have curvature). Teuchos::Tuple<int,3> cell_node_dimensions; cell_node_dimensions[0] = 1; cell_node_dimensions[1] = num_element_nodes; cell_node_dimensions[2] = node_dim; for ( int i = 2; i != node_dim-1 ; --i ) { for ( int n = element_nodes.size() - 1; n > -1; --n ) { cell_node_coords.erase( cell_node_coords.begin() + 3*n + i ); } } Intrepid::FieldContainer<double> cell_nodes( Teuchos::Array<int>(cell_node_dimensions), Teuchos::arcpFromArray( cell_node_coords ) ); // Map the point to the reference frame of the cell. Intrepid::FieldContainer<double> reference_point( 1, node_dim ); Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in the reference cell. return Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); } // We have to handle pyramids differently because Intrepid doesn't // currently support them with basis functions. Instead we'll resolve them // with two linear tetrahedrons and check for point inclusion in that set // instead. else { // Create the Shards topology for the linear tetrahedrons. Teuchos::RCP<shards::CellTopology> cell_topo = CellTopologyFactory::create( moab::MBTET, 4 ); // Build 2 tetrahedrons from the 1 pyramid. testInvariant( node_dim == 3, "Pyramid elements must be 3D." ); Intrepid::FieldContainer<double> cell_nodes( 1, 4, node_dim ); // Tetrahederon 1. cell_nodes( 0, 0, 0 ) = cell_node_coords[0]; cell_nodes( 0, 0, 1 ) = cell_node_coords[1]; cell_nodes( 0, 0, 2 ) = cell_node_coords[2]; cell_nodes( 0, 1, 0 ) = cell_node_coords[3]; cell_nodes( 0, 1, 1 ) = cell_node_coords[4]; cell_nodes( 0, 1, 2 ) = cell_node_coords[5]; cell_nodes( 0, 2, 0 ) = cell_node_coords[6]; cell_nodes( 0, 2, 1 ) = cell_node_coords[7]; cell_nodes( 0, 2, 2 ) = cell_node_coords[8]; cell_nodes( 0, 3, 0 ) = cell_node_coords[12]; cell_nodes( 0, 3, 1 ) = cell_node_coords[13]; cell_nodes( 0, 3, 2 ) = cell_node_coords[14]; // Map the point to the reference frame of the first linear // tetrahedron. Intrepid::FieldContainer<double> reference_point( 1, node_dim ); Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in tetrahedron 1. bool in_tet_1 = Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); // Tetrahederon 2. cell_nodes( 0, 0, 0 ) = cell_node_coords[0]; cell_nodes( 0, 0, 1 ) = cell_node_coords[1]; cell_nodes( 0, 0, 2 ) = cell_node_coords[2]; cell_nodes( 0, 1, 0 ) = cell_node_coords[6]; cell_nodes( 0, 1, 1 ) = cell_node_coords[7]; cell_nodes( 0, 1, 2 ) = cell_node_coords[8]; cell_nodes( 0, 2, 0 ) = cell_node_coords[9]; cell_nodes( 0, 2, 1 ) = cell_node_coords[10]; cell_nodes( 0, 2, 2 ) = cell_node_coords[11]; cell_nodes( 0, 3, 0 ) = cell_node_coords[12]; cell_nodes( 0, 3, 1 ) = cell_node_coords[13]; cell_nodes( 0, 3, 2 ) = cell_node_coords[14]; // Map the point to the reference frame of the first linear // tetrahedron. Intrepid::CellTools<double>::mapToReferenceFrame( reference_point, point, cell_nodes, *cell_topo, 0 ); // Check for reference point inclusion in tetrahedron 2. bool in_tet_2 = Intrepid::CellTools<double>::checkPointsetInclusion( reference_point, *cell_topo); // If the point is in either tetrahedron, it is in the pyramid. if ( in_tet_1 || in_tet_2 ) { return true; } else { return false; } } } //---------------------------------------------------------------------------// } // end namespace DataTransferKit //---------------------------------------------------------------------------// // end DTK_TopologyTools.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is added by mcw. */ #include <sal/config.h> #include <unotest/filters-test.hxx> #include <test/bootstrapfixture.hxx> #include <rtl/strbuf.hxx> #include <osl/file.hxx> #include "scdll.hxx" #include <sfx2/app.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/sfxmodelfactory.hxx> #include <svl/stritem.hxx> #define TEST_BUG_FILES 0 #include "helper/qahelper.hxx" #include "calcconfig.hxx" #include "interpre.hxx" #include "docsh.hxx" #include "postit.hxx" #include "patattr.hxx" #include "scitems.hxx" #include "document.hxx" #include "cellform.hxx" #include "drwlayer.hxx" #include "userdat.hxx" #include "formulacell.hxx" #include <svx/svdpage.hxx> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; /* Implementation of Filters test */ class ScOpenclTest : public test::FiltersTest , public ScBootstrapFixture { public: ScOpenclTest(); void enableOpenCL(ScDocShell* pShell); void SetEnv(); virtual void setUp(); virtual void tearDown(); virtual bool load( const OUString &rFilter, const OUString &rURL, const OUString &rUserData, unsigned int nFilterFlags, unsigned int nClipboardID, unsigned int nFilterVersion); void testSharedFormulaXLS(); void testSharedFormulaXLSGroundWater(); void testSharedFormulaXLSStockHistory(); void testFinacialFormula(); CPPUNIT_TEST_SUITE(ScOpenclTest); CPPUNIT_TEST(testSharedFormulaXLS); CPPUNIT_TEST(testSharedFormulaXLSGroundWater); CPPUNIT_TEST(testSharedFormulaXLSStockHistory); CPPUNIT_TEST(testFinacialFormula); CPPUNIT_TEST_SUITE_END(); private: uno::Reference<uno::XInterface> m_xCalcComponent; }; bool ScOpenclTest::load(const OUString &rFilter, const OUString &rURL, const OUString &rUserData, unsigned int nFilterFlags, unsigned int nClipboardID, unsigned int nFilterVersion) { ScDocShellRef xDocShRef = ScBootstrapFixture::load(rURL, rFilter, rUserData, OUString(), nFilterFlags, nClipboardID, nFilterVersion ); bool bLoaded = xDocShRef.Is(); //reference counting of ScDocShellRef is very confused. if (bLoaded) xDocShRef->DoClose(); return bLoaded; } void ScOpenclTest::SetEnv() { #ifdef WIN32 char *newpathfull = (char *)malloc(1024); newpathfull= "PATH=;C:\\Program Files (x86)\\AMD APP\\bin\\x86_64;"; putenv(newpathfull); #else return; #endif } void ScOpenclTest::enableOpenCL(ScDocShell* pShell) { ScModule* pScMod = SC_MOD(); ScFormulaOptions rOpt = pScMod->GetFormulaOptions(); ScCalcConfig maSavedConfig = rOpt.GetCalcConfig(); maSavedConfig.mbOpenCLEnabled = true; rOpt.SetCalcConfig(maSavedConfig); pShell->SetFormulaOptions(rOpt); } void ScOpenclTest::testSharedFormulaXLSStockHistory() { #if 1 ScDocShellRef xDocSh = loadDoc("stock-history.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("stock-history.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 33; i < 44; ++i) { // Cell H34:H44 in S&P 500 (tab 1) double fLibre = pDoc->GetValue(ScAddress(7, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(7, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel); } for (SCROW i = 33; i < 44; ++i) { // Cell J34:J44 in S&P 500 (tab 1) double fLibre = pDoc->GetValue(ScAddress(9, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(9, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel); } xDocSh->DoClose(); xDocShRes->DoClose(); #endif } void ScOpenclTest::testSharedFormulaXLSGroundWater() { ScDocShellRef xDocSh = loadDoc("ground-water-daily.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("ground-water-daily.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 5; i <= 77; ++i) { double fLibre = pDoc->GetValue(ScAddress(11,i,1)); double fExcel = pDocRes->GetValue(ScAddress(11,i,1)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } xDocSh->DoClose(); xDocShRes->DoClose(); } void ScOpenclTest::testSharedFormulaXLS() { ScDocShellRef xDocSh = loadDoc("sum_ex.", XLS); enableOpenCL(xDocSh); ScDocument *pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("sum_ex.", XLS); ScDocument *pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. // AMLOEXT-5 for (SCROW i = 0; i < 5; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-6 for (SCROW i = 6; i < 14; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-8 for (SCROW i = 15; i < 18; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-10 for (SCROW i = 19; i < 22; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-9 for (SCROW i = 23; i < 25; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); //double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); // There seems to be a bug in LibreOffice beta CPPUNIT_ASSERT_EQUAL(/*fExcel*/ 60.0, fLibre); } // AMLOEXT-9 for (SCROW i = 25; i < 27; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-11 for (SCROW i = 28; i < 35; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-11; workaround for a Calc beta bug CPPUNIT_ASSERT_EQUAL(25.0, pDoc->GetValue(ScAddress(2, 35, 0))); CPPUNIT_ASSERT_EQUAL(24.0, pDoc->GetValue(ScAddress(2, 36, 0))); // AMLOEXT-12 for (SCROW i = 38; i < 43; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-14 for (SCROW i = 5; i < 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(5, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(5, i, 1)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-15, AMLOEXT-16, and AMLOEXT-17 for (SCROW i = 5; i < 10; ++i) { for (SCCOL j = 6; j < 11; ++j) { double fLibre = pDoc->GetValue(ScAddress(j, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(j, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(fExcel*0.0001)); } } xDocSh->DoClose(); xDocShRes->DoClose(); } void ScOpenclTest::testFinacialFormula() { ScDocShellRef xDocSh = loadDoc("FinancialFormulaTest.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("FinancialFormulaTest.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(2,i,0)); double fExcel = pDocRes->GetValue(ScAddress(2,i,0)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } // AMLOEXT-22 for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(6,i,1)); double fExcel = pDocRes->GetValue(ScAddress(6,i,1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-23] for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(2,i,2)); double fExcel = pDocRes->GetValue(ScAddress(2,i,2)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-24] for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(6,i,3)); double fExcel = pDocRes->GetValue(ScAddress(6,i,3)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-25] for (SCROW i = 0; i <= 9; ++i) { double fLibre = pDoc->GetValue(ScAddress(3,i,4)); double fExcel = pDocRes->GetValue(ScAddress(3,i,4)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } xDocSh->DoClose(); xDocShRes->DoClose(); } ScOpenclTest::ScOpenclTest() : ScBootstrapFixture( "/sc/qa/unit/data" ) { } void ScOpenclTest::setUp() { test::BootstrapFixture::setUp(); SetEnv(); // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure, // which is a private symbol to us, gets called m_xCalcComponent = getMultiServiceFactory()-> createInstance("com.sun.star.comp.Calc.SpreadsheetDocument"); CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is()); } void ScOpenclTest::tearDown() { uno::Reference< lang::XComponent > ( m_xCalcComponent, UNO_QUERY_THROW )->dispose(); test::BootstrapFixture::tearDown(); } CPPUNIT_TEST_SUITE_REGISTRATION(ScOpenclTest); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Testcase for PRICEMAT<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is added by mcw. */ #include <sal/config.h> #include <unotest/filters-test.hxx> #include <test/bootstrapfixture.hxx> #include <rtl/strbuf.hxx> #include <osl/file.hxx> #include "scdll.hxx" #include <sfx2/app.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/sfxmodelfactory.hxx> #include <svl/stritem.hxx> #define TEST_BUG_FILES 0 #include "helper/qahelper.hxx" #include "calcconfig.hxx" #include "interpre.hxx" #include "docsh.hxx" #include "postit.hxx" #include "patattr.hxx" #include "scitems.hxx" #include "document.hxx" #include "cellform.hxx" #include "drwlayer.hxx" #include "userdat.hxx" #include "formulacell.hxx" #include <svx/svdpage.hxx> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; /* Implementation of Filters test */ class ScOpenclTest : public test::FiltersTest , public ScBootstrapFixture { public: ScOpenclTest(); void enableOpenCL(ScDocShell* pShell); void SetEnv(); virtual void setUp(); virtual void tearDown(); virtual bool load( const OUString &rFilter, const OUString &rURL, const OUString &rUserData, unsigned int nFilterFlags, unsigned int nClipboardID, unsigned int nFilterVersion); void testSharedFormulaXLS(); void testSharedFormulaXLSGroundWater(); void testSharedFormulaXLSStockHistory(); void testFinacialFormula(); CPPUNIT_TEST_SUITE(ScOpenclTest); CPPUNIT_TEST(testSharedFormulaXLS); CPPUNIT_TEST(testSharedFormulaXLSGroundWater); CPPUNIT_TEST(testSharedFormulaXLSStockHistory); CPPUNIT_TEST(testFinacialFormula); CPPUNIT_TEST_SUITE_END(); private: uno::Reference<uno::XInterface> m_xCalcComponent; }; bool ScOpenclTest::load(const OUString &rFilter, const OUString &rURL, const OUString &rUserData, unsigned int nFilterFlags, unsigned int nClipboardID, unsigned int nFilterVersion) { ScDocShellRef xDocShRef = ScBootstrapFixture::load(rURL, rFilter, rUserData, OUString(), nFilterFlags, nClipboardID, nFilterVersion ); bool bLoaded = xDocShRef.Is(); //reference counting of ScDocShellRef is very confused. if (bLoaded) xDocShRef->DoClose(); return bLoaded; } void ScOpenclTest::SetEnv() { #ifdef WIN32 char *newpathfull = (char *)malloc(1024); newpathfull= "PATH=;C:\\Program Files (x86)\\AMD APP\\bin\\x86_64;"; putenv(newpathfull); #else return; #endif } void ScOpenclTest::enableOpenCL(ScDocShell* pShell) { ScModule* pScMod = SC_MOD(); ScFormulaOptions rOpt = pScMod->GetFormulaOptions(); ScCalcConfig maSavedConfig = rOpt.GetCalcConfig(); maSavedConfig.mbOpenCLEnabled = true; rOpt.SetCalcConfig(maSavedConfig); pShell->SetFormulaOptions(rOpt); } void ScOpenclTest::testSharedFormulaXLSStockHistory() { #if 1 ScDocShellRef xDocSh = loadDoc("stock-history.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("stock-history.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 33; i < 44; ++i) { // Cell H34:H44 in S&P 500 (tab 1) double fLibre = pDoc->GetValue(ScAddress(7, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(7, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel); } for (SCROW i = 33; i < 44; ++i) { // Cell J34:J44 in S&P 500 (tab 1) double fLibre = pDoc->GetValue(ScAddress(9, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(9, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel); } xDocSh->DoClose(); xDocShRes->DoClose(); #endif } void ScOpenclTest::testSharedFormulaXLSGroundWater() { ScDocShellRef xDocSh = loadDoc("ground-water-daily.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("ground-water-daily.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 5; i <= 77; ++i) { double fLibre = pDoc->GetValue(ScAddress(11,i,1)); double fExcel = pDocRes->GetValue(ScAddress(11,i,1)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } xDocSh->DoClose(); xDocShRes->DoClose(); } void ScOpenclTest::testSharedFormulaXLS() { ScDocShellRef xDocSh = loadDoc("sum_ex.", XLS); enableOpenCL(xDocSh); ScDocument *pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("sum_ex.", XLS); ScDocument *pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. // AMLOEXT-5 for (SCROW i = 0; i < 5; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-6 for (SCROW i = 6; i < 14; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-8 for (SCROW i = 15; i < 18; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-10 for (SCROW i = 19; i < 22; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-9 for (SCROW i = 23; i < 25; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); //double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); // There seems to be a bug in LibreOffice beta CPPUNIT_ASSERT_EQUAL(/*fExcel*/ 60.0, fLibre); } // AMLOEXT-9 for (SCROW i = 25; i < 27; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-11 for (SCROW i = 28; i < 35; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-11; workaround for a Calc beta bug CPPUNIT_ASSERT_EQUAL(25.0, pDoc->GetValue(ScAddress(2, 35, 0))); CPPUNIT_ASSERT_EQUAL(24.0, pDoc->GetValue(ScAddress(2, 36, 0))); // AMLOEXT-12 for (SCROW i = 38; i < 43; ++i) { double fLibre = pDoc->GetValue(ScAddress(2, i, 0)); double fExcel = pDocRes->GetValue(ScAddress(2, i, 0)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-14 for (SCROW i = 5; i < 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(5, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(5, i, 1)); CPPUNIT_ASSERT_EQUAL(fExcel, fLibre); } // AMLOEXT-15, AMLOEXT-16, and AMLOEXT-17 for (SCROW i = 5; i < 10; ++i) { for (SCCOL j = 6; j < 11; ++j) { double fLibre = pDoc->GetValue(ScAddress(j, i, 1)); double fExcel = pDocRes->GetValue(ScAddress(j, i, 1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(fExcel*0.0001)); } } xDocSh->DoClose(); xDocShRes->DoClose(); } void ScOpenclTest::testFinacialFormula() { ScDocShellRef xDocSh = loadDoc("FinancialFormulaTest.", XLS); enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument(); CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true); ScDocShellRef xDocShRes = loadDoc("FinancialFormulaTest.", XLS); ScDocument* pDocRes = xDocShRes->GetDocument(); CPPUNIT_ASSERT(pDocRes); // Check the results of formula cells in the shared formula range. for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(2,i,0)); double fExcel = pDocRes->GetValue(ScAddress(2,i,0)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } // AMLOEXT-22 for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(6,i,1)); double fExcel = pDocRes->GetValue(ScAddress(6,i,1)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-23] for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(2,i,2)); double fExcel = pDocRes->GetValue(ScAddress(2,i,2)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-24] for (SCROW i = 1; i <= 10; ++i) { double fLibre = pDoc->GetValue(ScAddress(6,i,3)); double fExcel = pDocRes->GetValue(ScAddress(6,i,3)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-25] for (SCROW i = 0; i <= 9; ++i) { double fLibre = pDoc->GetValue(ScAddress(3,i,4)); double fExcel = pDocRes->GetValue(ScAddress(3,i,4)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } //[AMLOEXT-26] for (SCROW i = 0; i <= 9; ++i) { double fLibre = pDoc->GetValue(ScAddress(3,i,5)); double fExcel = pDocRes->GetValue(ScAddress(3,i,5)); CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel)); } xDocSh->DoClose(); xDocShRes->DoClose(); } ScOpenclTest::ScOpenclTest() : ScBootstrapFixture( "/sc/qa/unit/data" ) { } void ScOpenclTest::setUp() { test::BootstrapFixture::setUp(); SetEnv(); // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure, // which is a private symbol to us, gets called m_xCalcComponent = getMultiServiceFactory()-> createInstance("com.sun.star.comp.Calc.SpreadsheetDocument"); CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is()); } void ScOpenclTest::tearDown() { uno::Reference< lang::XComponent > ( m_xCalcComponent, UNO_QUERY_THROW )->dispose(); test::BootstrapFixture::tearDown(); } CPPUNIT_TEST_SUITE_REGISTRATION(ScOpenclTest); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CQLayoutMainWindow.cpp,v $ // $Revision: 1.13 $ // $Name: $ // $Author: urost $ // $Date: 2007/06/01 10:40:16 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CopasiDataModel/CCopasiDataModel.h" #include "layout/CListOfLayouts.h" #include "layout/CLayout.h" #include "layout/CLBase.h" #include"CQLayoutMainWindow.h" //#include "sbmlDocumentLoader.h" #include <string> #include <iostream> using namespace std; CQLayoutMainWindow::CQLayoutMainWindow(QWidget *parent, const char *name) : QMainWindow(parent, name) { setCaption(tr("Reaction network graph")); createActions(); createMenus(); // create split window QSplitter *splitter = new QSplitter(Qt::Horizontal, this); splitter->setCaption("Test"); //QLabel *label = new QLabel(splitter, "Test Label", 0); //QTextEdit *testEditor = new QTextEdit(splitter); ParaPanel *paraPanel = new ParaPanel; timeSlider = new QSlider(Qt::Horizontal, splitter); timeSlider->setRange(0, 100); timeSlider->setValue(0); //timeSlider->setTickmarks(QSlider::Below); timeSlider->setDisabled(TRUE); connect(timeSlider, SIGNAL(valueChanged(int)), this, SLOT(showStep(int))); // create sroll view scrollView = new QScrollView(splitter); //scrollView = new QScrollView(this); scrollView->setCaption("Network Graph Viewer"); //scrollView->viewport()->setPaletteBackgroundColor(QColor(255,255,240)); scrollView->viewport()->setPaletteBackgroundColor(QColor(219, 235, 255)); //scrollView->viewport()->setMouseTracking(TRUE); // Create OpenGL widget //cout << "viewport: " << scrollView.viewport() << endl; CListOfLayouts *pLayoutList; if (CCopasiDataModel::Global != NULL) { pLayoutList = CCopasiDataModel::Global->getListOfLayouts(); } else pLayoutList = NULL; glPainter = new CQGLNetworkPainter(scrollView->viewport()); if (pLayoutList != NULL) { CLayout * pLayout; if (pLayoutList->size() > 0) { pLayout = (*pLayoutList)[0]; CLDimensions dim = pLayout->getDimensions(); CLPoint c1; CLPoint c2(dim.getWidth(), dim.getHeight()); glPainter->setGraphSize(c1, c2); glPainter->createGraph(pLayout); // create local data structures //glPainter->drawGraph(); // create display list } } // put OpenGL widget into scrollView scrollView->addChild(glPainter); //setCentralWidget(scrollView); //scrollView->show(); setCentralWidget(splitter); splitter->show(); //glPainter->drawGraph(); } void CQLayoutMainWindow::createActions() { openSBMLFile = new QAction("SBML", "Load SBML file", CTRL + Key_F, this); openSBMLFile->setStatusTip("Load SBML file with/without layout"); connect(openSBMLFile, SIGNAL(activated()) , this, SLOT(loadSBMLFile())); openDataFile = new QAction("data", "Load Simulation Data", CTRL + Key_D, this); openDataFile->setStatusTip("Load simulation data"); connect(openDataFile, SIGNAL(activated()), this, SLOT(loadData())); closeAction = new QAction ("close", "Close Window", CTRL + Key_Q , this); closeAction->setStatusTip("Close Layout Window"); connect(closeAction, SIGNAL(activated()), this, SLOT(closeApplication())); runAnimation = new QAction("animate", "Run animation", CTRL + Key_A, this); runAnimation->setStatusTip("show complete animation sequence of current times series"); connect(runAnimation, SIGNAL(activated()), this, SLOT(showAnimation())); rectangularShape = new QAction ("rectangle", "rectangle", CTRL + Key_R , this); rectangularShape->setStatusTip("Show labels as rectangles"); connect(rectangularShape, SIGNAL(activated()), this, SLOT(mapLabelsToRectangles())); circularShape = new QAction ("circle", "circle", CTRL + Key_C , this); connect(circularShape, SIGNAL(activated()), this, SLOT(mapLabelsToCircles())); circularShape->setStatusTip("Show labels as circles"); } void CQLayoutMainWindow::createMenus() { fileMenu = new QPopupMenu(this); openSBMLFile->addTo(fileMenu); openDataFile->addTo(fileMenu); fileMenu->insertSeparator(); closeAction->addTo(fileMenu); actionsMenu = new QPopupMenu(this); runAnimation->addTo(actionsMenu); labelShapeMenu = new QPopupMenu(this); rectangularShape->addTo(labelShapeMenu); circularShape->addTo(labelShapeMenu); optionsMenu = new QPopupMenu(this); optionsMenu->insertItem("Shape of Label", labelShapeMenu); menuBar()->insertItem("File", fileMenu); menuBar()->insertItem("Actions", actionsMenu); menuBar()->insertItem("Options", optionsMenu); } //void CQLayoutMainWindow::contextMenuEvent(QContextMenuEvent *cme){ // QPopupMenu *contextMenu = new QPopupMenu(this); // exitAction->addTo(contextMenu); // contextMenu->exec(cme->globalPos()); //} void CQLayoutMainWindow::loadSBMLFile() { //string filename = "/localhome/ulla/project/data/peroxiShortNew.xml"; // test file //string filename = "/home/ulla/project/simulation/data/peroxiShortNew.xml"; //SBMLDocumentLoader docLoader; //network *networkP = docLoader.loadDocument(filename.c_str()); //glPainter->createGraph(networkP); std::cout << "load SBMLfile" << std::endl; CListOfLayouts *pLayoutList; if (CCopasiDataModel::Global != NULL) { pLayoutList = CCopasiDataModel::Global->getListOfLayouts(); } else pLayoutList = NULL; glPainter = new CQGLNetworkPainter(scrollView->viewport()); if (pLayoutList != NULL) { CLayout * pLayout; if (pLayoutList->size() > 0) { pLayout = (*pLayoutList)[0]; CLDimensions dim = pLayout->getDimensions(); CLPoint c1; CLPoint c2(dim.getWidth(), dim.getHeight()); glPainter->setGraphSize(c1, c2); glPainter->createGraph(pLayout); // create local data structures //glPainter->drawGraph(); // create display list } } } void CQLayoutMainWindow::mapLabelsToCircles() { if (glPainter != NULL) { glPainter->mapLabelsToCircles(); } } void CQLayoutMainWindow::mapLabelsToRectangles() { if (glPainter != NULL) { glPainter->mapLabelsToRectangles(); } } void CQLayoutMainWindow::loadData() { bool successfulP = glPainter->createDataSets(); if (successfulP) { this->timeSlider->setEnabled(true); int maxVal = glPainter->getNumberOfSteps(); //std::cout << "number of steps: " << maxVal << std::endl; this->timeSlider->setRange(0, maxVal); glPainter->updateGL(); } } void CQLayoutMainWindow::showAnimation() { glPainter->runAnimation(); } void CQLayoutMainWindow::showStep(int i) { glPainter->showStep(i); glPainter->updateGL(); } void CQLayoutMainWindow::closeApplication() { close(); } void CQLayoutMainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { //writeSettings(); event->accept(); } else { event->ignore(); } } // returns true because window is opened from Copasi and can be easily reopened bool CQLayoutMainWindow::maybeSave() { // int ret = QMessageBox::warning(this, "SimWiz", // "Do you really want to quit?", // // tr("Do you really want to quit?\n" // // "XXXXXXXX"), // QMessageBox::Yes | QMessageBox::Default, // QMessageBox::No, // QMessageBox::Cancel | QMessageBox::Escape); // if (ret == QMessageBox::Yes) // return true; // else if (ret == QMessageBox::Cancel) // return false; return true; } //int main(int argc, char *argv[]) { // //cout << argc << "------" << *argv << endl; // QApplication app(argc,argv); // CQLayoutMainWindow win; // //app.setMainWidget(&gui); // win.resize(400,230); // win.show(); // return app.exec(); //} <commit_msg>commented out parapanel, since the class is not known.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CQLayoutMainWindow.cpp,v $ // $Revision: 1.14 $ // $Name: $ // $Author: ssahle $ // $Date: 2007/06/01 22:37:59 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CopasiDataModel/CCopasiDataModel.h" #include "layout/CListOfLayouts.h" #include "layout/CLayout.h" #include "layout/CLBase.h" #include"CQLayoutMainWindow.h" //#include "sbmlDocumentLoader.h" #include <string> #include <iostream> using namespace std; CQLayoutMainWindow::CQLayoutMainWindow(QWidget *parent, const char *name) : QMainWindow(parent, name) { setCaption(tr("Reaction network graph")); createActions(); createMenus(); // create split window QSplitter *splitter = new QSplitter(Qt::Horizontal, this); splitter->setCaption("Test"); //QLabel *label = new QLabel(splitter, "Test Label", 0); //QTextEdit *testEditor = new QTextEdit(splitter); //ParaPanel *paraPanel = new ParaPanel; timeSlider = new QSlider(Qt::Horizontal, splitter); timeSlider->setRange(0, 100); timeSlider->setValue(0); //timeSlider->setTickmarks(QSlider::Below); timeSlider->setDisabled(TRUE); connect(timeSlider, SIGNAL(valueChanged(int)), this, SLOT(showStep(int))); // create sroll view scrollView = new QScrollView(splitter); //scrollView = new QScrollView(this); scrollView->setCaption("Network Graph Viewer"); //scrollView->viewport()->setPaletteBackgroundColor(QColor(255,255,240)); scrollView->viewport()->setPaletteBackgroundColor(QColor(219, 235, 255)); //scrollView->viewport()->setMouseTracking(TRUE); // Create OpenGL widget //cout << "viewport: " << scrollView.viewport() << endl; CListOfLayouts *pLayoutList; if (CCopasiDataModel::Global != NULL) { pLayoutList = CCopasiDataModel::Global->getListOfLayouts(); } else pLayoutList = NULL; glPainter = new CQGLNetworkPainter(scrollView->viewport()); if (pLayoutList != NULL) { CLayout * pLayout; if (pLayoutList->size() > 0) { pLayout = (*pLayoutList)[0]; CLDimensions dim = pLayout->getDimensions(); CLPoint c1; CLPoint c2(dim.getWidth(), dim.getHeight()); glPainter->setGraphSize(c1, c2); glPainter->createGraph(pLayout); // create local data structures //glPainter->drawGraph(); // create display list } } // put OpenGL widget into scrollView scrollView->addChild(glPainter); //setCentralWidget(scrollView); //scrollView->show(); setCentralWidget(splitter); splitter->show(); //glPainter->drawGraph(); } void CQLayoutMainWindow::createActions() { openSBMLFile = new QAction("SBML", "Load SBML file", CTRL + Key_F, this); openSBMLFile->setStatusTip("Load SBML file with/without layout"); connect(openSBMLFile, SIGNAL(activated()) , this, SLOT(loadSBMLFile())); openDataFile = new QAction("data", "Load Simulation Data", CTRL + Key_D, this); openDataFile->setStatusTip("Load simulation data"); connect(openDataFile, SIGNAL(activated()), this, SLOT(loadData())); closeAction = new QAction ("close", "Close Window", CTRL + Key_Q , this); closeAction->setStatusTip("Close Layout Window"); connect(closeAction, SIGNAL(activated()), this, SLOT(closeApplication())); runAnimation = new QAction("animate", "Run animation", CTRL + Key_A, this); runAnimation->setStatusTip("show complete animation sequence of current times series"); connect(runAnimation, SIGNAL(activated()), this, SLOT(showAnimation())); rectangularShape = new QAction ("rectangle", "rectangle", CTRL + Key_R , this); rectangularShape->setStatusTip("Show labels as rectangles"); connect(rectangularShape, SIGNAL(activated()), this, SLOT(mapLabelsToRectangles())); circularShape = new QAction ("circle", "circle", CTRL + Key_C , this); connect(circularShape, SIGNAL(activated()), this, SLOT(mapLabelsToCircles())); circularShape->setStatusTip("Show labels as circles"); } void CQLayoutMainWindow::createMenus() { fileMenu = new QPopupMenu(this); openSBMLFile->addTo(fileMenu); openDataFile->addTo(fileMenu); fileMenu->insertSeparator(); closeAction->addTo(fileMenu); actionsMenu = new QPopupMenu(this); runAnimation->addTo(actionsMenu); labelShapeMenu = new QPopupMenu(this); rectangularShape->addTo(labelShapeMenu); circularShape->addTo(labelShapeMenu); optionsMenu = new QPopupMenu(this); optionsMenu->insertItem("Shape of Label", labelShapeMenu); menuBar()->insertItem("File", fileMenu); menuBar()->insertItem("Actions", actionsMenu); menuBar()->insertItem("Options", optionsMenu); } //void CQLayoutMainWindow::contextMenuEvent(QContextMenuEvent *cme){ // QPopupMenu *contextMenu = new QPopupMenu(this); // exitAction->addTo(contextMenu); // contextMenu->exec(cme->globalPos()); //} void CQLayoutMainWindow::loadSBMLFile() { //string filename = "/localhome/ulla/project/data/peroxiShortNew.xml"; // test file //string filename = "/home/ulla/project/simulation/data/peroxiShortNew.xml"; //SBMLDocumentLoader docLoader; //network *networkP = docLoader.loadDocument(filename.c_str()); //glPainter->createGraph(networkP); std::cout << "load SBMLfile" << std::endl; CListOfLayouts *pLayoutList; if (CCopasiDataModel::Global != NULL) { pLayoutList = CCopasiDataModel::Global->getListOfLayouts(); } else pLayoutList = NULL; glPainter = new CQGLNetworkPainter(scrollView->viewport()); if (pLayoutList != NULL) { CLayout * pLayout; if (pLayoutList->size() > 0) { pLayout = (*pLayoutList)[0]; CLDimensions dim = pLayout->getDimensions(); CLPoint c1; CLPoint c2(dim.getWidth(), dim.getHeight()); glPainter->setGraphSize(c1, c2); glPainter->createGraph(pLayout); // create local data structures //glPainter->drawGraph(); // create display list } } } void CQLayoutMainWindow::mapLabelsToCircles() { if (glPainter != NULL) { glPainter->mapLabelsToCircles(); } } void CQLayoutMainWindow::mapLabelsToRectangles() { if (glPainter != NULL) { glPainter->mapLabelsToRectangles(); } } void CQLayoutMainWindow::loadData() { bool successfulP = glPainter->createDataSets(); if (successfulP) { this->timeSlider->setEnabled(true); int maxVal = glPainter->getNumberOfSteps(); //std::cout << "number of steps: " << maxVal << std::endl; this->timeSlider->setRange(0, maxVal); glPainter->updateGL(); } } void CQLayoutMainWindow::showAnimation() { glPainter->runAnimation(); } void CQLayoutMainWindow::showStep(int i) { glPainter->showStep(i); glPainter->updateGL(); } void CQLayoutMainWindow::closeApplication() { close(); } void CQLayoutMainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { //writeSettings(); event->accept(); } else { event->ignore(); } } // returns true because window is opened from Copasi and can be easily reopened bool CQLayoutMainWindow::maybeSave() { // int ret = QMessageBox::warning(this, "SimWiz", // "Do you really want to quit?", // // tr("Do you really want to quit?\n" // // "XXXXXXXX"), // QMessageBox::Yes | QMessageBox::Default, // QMessageBox::No, // QMessageBox::Cancel | QMessageBox::Escape); // if (ret == QMessageBox::Yes) // return true; // else if (ret == QMessageBox::Cancel) // return false; return true; } //int main(int argc, char *argv[]) { // //cout << argc << "------" << *argv << endl; // QApplication app(argc,argv); // CQLayoutMainWindow win; // //app.setMainWidget(&gui); // win.resize(400,230); // win.show(); // return app.exec(); //} <|endoftext|>
<commit_before> #pragma once #include <cinatra/http_server.hpp> #include <cinatra/http_router.hpp> #include <cinatra/request.hpp> #include <cinatra/response.hpp> #include <cinatra/logging.hpp> #include <cinatra/aop.hpp> #include <cinatra/body_parser.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> namespace cinatra { template<typename... Aspect> class Cinatra { public: template<typename F> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name,const F& f) { router_.route(name, f); return *this; } template<typename F, typename Self> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name, const F& f, Self* self) { router_.route(name, f, self); return *this; } template<typename F> typename std::enable_if<function_traits<F>::arity==0, Cinatra&>::type route(const std::string& name,const F& f) { route(name, [f](cinatra::Request& req, cinatra::Response& res) { auto r = f(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } template<typename F, typename Self> typename std::enable_if<function_traits<F>::arity == 0, Cinatra&>::type route(const std::string& name, const F& f, Self* self) { route(name, [f, self](cinatra::Request& req, cinatra::Response& res) { auto r = (*self.*f)(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } Cinatra& threads(int num) { num_threads_ = num < 1 ? 1 : num; return *this; } Cinatra& error_handler(error_handler_t error_handler) { error_handler_ = error_handler; return *this; } Cinatra& listen(const std::string& address, const std::string& port) { listen_addr_ = address; listen_port_ = port; return *this; } Cinatra& listen(const std::string& port) { listen_addr_ = "0.0.0.0"; listen_port_ = port; return *this; } Cinatra& listen(const std::string& address, unsigned short port) { listen_addr_ = address; listen_port_ = boost::lexical_cast<std::string>(port); return *this; } Cinatra& static_dir(const std::string& dir) { static_dir_ = dir; return *this; } #ifdef CINATRA_ENABLE_HTTPS Cinatra& https_config(const HttpsConfig& cfg) { config_ = cfg; return *this; } #endif // CINATRA_ENABLE_HTTPS void run() { #ifndef CINATRA_SINGLE_THREAD HTTPServer s(num_threads_); #else HTTPServer s; #endif s.set_request_handler([this](Request& req, Response& res) { return Invoke<sizeof...(Aspect)>(res, &Cinatra::dispatch, this, req, res); }) .set_error_handler([this](int code, const std::string& msg, Request& req, Response& res) { LOG_DBG << "Handle error:" << code << " " << msg << " with path " << req.path(); if (error_handler_ && error_handler_(code,msg,req,res)) { return true; } LOG_DBG << "In defaule error handler"; std::string html; auto s = status_header(code); html = "<html><head><title>" + s.second + "</title></head>"; html += "<body>"; html += "<h1>" + boost::lexical_cast<std::string>(s.first) + " " + s.second + " " + "</h1>"; if (!msg.empty()) { html += "<br> <h2>Message: " + msg + "</h2>"; } html += "</body></html>"; res.set_status_code(s.first); res.write(html); return true; }) .static_dir(static_dir_) #ifdef CINATRA_ENABLE_HTTPS .https_config(config_) #endif // CINATRA_ENABLE_HTTPS .listen(listen_addr_, listen_port_) .run(); } private: template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if<I == 0, bool>::type Invoke(Response& /* res */, Func&&f, Self* self, Args&&... args) { return (*self.*f)(std::forward<Args>(args)...); } template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if < (I > 0), bool > ::type Invoke(Response& res, Func&& /* f */, Self* /* self */, Args&&... args) { return invoke<Aspect...>(res, &Cinatra::dispatch, this, args...); } bool dispatch(Request& req, Response& res) { return router_.dispatch(req, res); } private: #ifndef CINATRA_SINGLE_THREAD int num_threads_ = 0; #else int num_threads_ = std::thread::hardware_concurrency(); #endif // CINATRA_SINGLE_THREAD std::string listen_addr_; std::string listen_port_; std::string static_dir_; #ifdef CINATRA_ENABLE_HTTPS HttpsConfig config_; #endif // CINATRA_ENABLE_HTTPS error_handler_t error_handler_; HTTPRouter router_; }; using SimpleApp = Cinatra<>; } <commit_msg>Update cinatra.hpp<commit_after> #pragma once #include <cinatra/http_server.hpp> #include <cinatra/http_router.hpp> #include <cinatra/request.hpp> #include <cinatra/response.hpp> #include <cinatra/logging.hpp> #include <cinatra/aop.hpp> #include <cinatra/body_parser.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> namespace cinatra { template<typename... Aspect> class Cinatra { public: template<typename F> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name,const F& f) { router_.route(name, f); return *this; } template<typename F, typename Self> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name, const F& f, Self* self) { router_.route(name, f, self); return *this; } template<typename F> typename std::enable_if<function_traits<F>::arity==0, Cinatra&>::type route(const std::string& name,const F& f) { route(name, [f](cinatra::Request& req, cinatra::Response& res) { auto r = f(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } template<typename F, typename Self> typename std::enable_if<function_traits<F>::arity == 0, Cinatra&>::type route(const std::string& name, const F& f, Self* self) { route(name, [f, self](cinatra::Request& req, cinatra::Response& res) { auto r = (*self.*f)(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } Cinatra& threads(int num) { num_threads_ = num < 1 ? 1 : num; return *this; } Cinatra& error_handler(error_handler_t error_handler) { error_handler_ = error_handler; return *this; } Cinatra& listen(const std::string& address, const std::string& port) { listen_addr_ = address; listen_port_ = port; return *this; } Cinatra& listen(const std::string& port) { listen_addr_ = "0.0.0.0"; listen_port_ = port; return *this; } Cinatra& listen(const std::string& address, unsigned short port) { listen_addr_ = address; listen_port_ = boost::lexical_cast<std::string>(port); return *this; } Cinatra& static_dir(const std::string& dir) { static_dir_ = dir; return *this; } #ifdef CINATRA_ENABLE_HTTPS Cinatra& https_config(const HttpsConfig& cfg) { config_ = cfg; return *this; } #endif // CINATRA_ENABLE_HTTPS void run() { #ifndef CINATRA_SINGLE_THREAD HTTPServer s(num_threads_); #else HTTPServer s; #endif s.set_request_handler([this](Request& req, Response& res) { return Invoke<sizeof...(Aspect)>(res, &Cinatra::dispatch, this, req, res); }) .set_error_handler([this](int code, const std::string& msg, Request& req, Response& res) { LOG_DBG << "Handle error:" << code << " " << msg << " with path " << req.path(); if (error_handler_ && error_handler_(code,msg,req,res)) { return true; } LOG_DBG << "In defaule error handler"; std::string html; auto s = status_header(code); html = "<html><head><title>" + s.second + "</title></head>"; html += "<body>"; html += "<h1>" + boost::lexical_cast<std::string>(s.first) + " " + s.second + " " + "</h1>"; if (!msg.empty()) { html += "<br> <h2>Message: " + msg + "</h2>"; } html += "</body></html>"; res.set_status_code(s.first); res.write(html); return true; }) .static_dir(static_dir_) #ifdef CINATRA_ENABLE_HTTPS .https_config(config_) #endif // CINATRA_ENABLE_HTTPS .listen(listen_addr_, listen_port_) .run(); } private: template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if<I == 0, bool>::type Invoke(Response& /* res */, Func&&f, Self* self, Args&&... args) { return (*self.*f)(std::forward<Args>(args)...); } template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if < (I > 0), bool > ::type Invoke(Response& res, Func&& /* f */, Self* /* self */, Args&&... args) { return invoke<Aspect...>(res, &Cinatra::dispatch, this, args...); } bool dispatch(Request& req, Response& res) { return router_.dispatch(req, res); } private: #ifndef CINATRA_SINGLE_THREAD int num_threads_ = 1; #else int num_threads_ = std::thread::hardware_concurrency(); #endif // CINATRA_SINGLE_THREAD std::string listen_addr_; std::string listen_port_; std::string static_dir_; #ifdef CINATRA_ENABLE_HTTPS HttpsConfig config_; #endif // CINATRA_ENABLE_HTTPS error_handler_t error_handler_; HTTPRouter router_; }; using SimpleApp = Cinatra<>; } <|endoftext|>
<commit_before>#pragma once #include <utility> #include <vector> #include <cmath> #include <fstream> #include <iomanip> namespace fp { template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> fixed_point(const Func& g, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(g(x0)); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = g(x_iminus1); xvec.push_back(x_i); // xi = g(x_{i - 1}) x_iplus1 = g(x_i); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename T> void printElement(T t, const int& width, std::ostream& stream) { static const char separator = ' '; stream << std::left << std::setw(width) << std::setfill(separator) << t; } template<typename Func, typename Float> void test_fixed_point(const Func& g, Float x0, Float abstol, const std::string& funcname = "g", const std::string& filename = "test_g.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the fixed points of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = fixed_point(g, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> newton_method(const Func& f, Float x0, Float abstol) { } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> secant_method(const Func& f, Float x0, Float x1, Float abstol) { } }<commit_msg>Adding the old code from main into the fixed_point.hpp file.<commit_after>#pragma once #include <utility> #include <vector> #include <cmath> #include <fstream> #include <iomanip> namespace fp { template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> fixed_point(const Func& g, Float x0, Float abstol) { // vector to store intermediate x_i values std::vector<Float> xvec; std::vector<Float> rvec; // vector of rate approximations // do the first iteration outside the while loop xvec.push_back(g(x0)); Float currtol = static_cast<Float>(std::abs(xvec[0] - x0)); // number of iterations : we have already performed one auto i = 1; Float rate = NAN; rvec.push_back(rate); Float x_iminus1; Float x_i; Float x_iplus1; Float deltaxp1; while (currtol > abstol) { x_iminus1 = xvec[i - 1]; x_i = g(x_iminus1); xvec.push_back(x_i); // xi = g(x_{i - 1}) x_iplus1 = g(x_i); currtol = std::abs(x_i - x_iminus1); deltaxp1 = std::abs(x_iplus1 - x_i); if ((i - 2) > 0) { rate = std::log(deltaxp1 / currtol) / std::log(currtol / std::abs(x_iminus1 - xvec[i - 2])); rvec.push_back(rate); } else { rvec.push_back(NAN); } ++i; } return std::make_tuple(xvec, i, rvec); } template<typename T> void printElement(T t, const int& width, std::ostream& stream) { static const char separator = ' '; stream << std::left << std::setw(width) << std::setfill(separator) << t; } template<typename Func, typename Float> void test_fixed_point(const Func& g, Float x0, Float abstol, const std::string& funcname = "g", const std::string& filename = "test_g.txt") { const int nameWidth = 24; const int numWidth = 25; std::ofstream file; file.open(filename.c_str(), std::ios::out | std::ios::app); file << std::scientific << std::setprecision(15); file << "Getting the fixed points of '" << funcname << "' given x_0 = " << x0 << " and abstol = " << abstol << std::endl; auto tuple = fixed_point(g, x0, abstol); auto xvec = std::get<0>(tuple); auto iters = std::get<1>(tuple); auto rvec = std::get<2>(tuple); printElement("i", nameWidth, file); printElement("x_i", nameWidth, file); printElement("|x_i - x_{i - 1}|", nameWidth, file); printElement("rate", nameWidth, file); file << '\n'; for (auto i = 0; i < xvec.size(); ++i) { printElement(i, numWidth, file); printElement(xvec[i], numWidth, file); if ((i - 1) >= 0) { printElement(std::abs(xvec[i] - xvec[i - 1]), numWidth, file); } printElement(rvec[i], numWidth, file); file << '\n'; } file << "END" << std::endl; } void test() { const auto g1 = [](double x) -> double { return (x * x + 2) / 3; }; // will result in NaNs because the value under the square root // will become negative at some point. const auto g2 = [](double x) -> double { return std::sqrt(3 * x - 2); }; const auto g3 = [](double x) -> double { return 3 - (2 / x); }; const auto g4 = [](double x) -> double { return (x * x - 2) / (2 * x - 3); }; std::vector<std::function<double(double)>> vec {g1, g2, g3, g4}; std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"}; std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"}; const double x0 = 0; const double abstol = 5e-7; for (auto i = 0; i < vec.size(); ++i) { fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]); } } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> newton_method(const Func& f, Float x0, Float abstol) { } template<typename Func, typename Float> std::tuple<std::vector<Float>, int, std::vector<Float>> secant_method(const Func& f, Float x0, Float x1, Float abstol) { } }<|endoftext|>
<commit_before>/* * image_preprocessor.hpp * * Created on: Apr 3, 2015 * Author: Fabian Tschopp */ #ifndef IMAGE_PROCESSOR_HPP_ #define IMAGE_PROCESSOR_HPP_ #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <functional> namespace caffe_neural { class ImageProcessor { public: ImageProcessor(int patch_size, int nr_labels); void SubmitRawImage(cv::Mat input, int img_id); void ClearImages(); void SubmitImage(cv::Mat raw, int img_id, std::vector<cv::Mat> labels); int Init(); void SetBorderParams(bool apply, int border_size); void SetClaheParams(bool apply, float clip_limit); void SetBlurParams(bool apply, float mu, float std, int blur_size); void SetCropParams(int image_crop, int label_crop); void SetNormalizationParams(bool apply); void SetRotationParams(bool apply); void SetPatchMirrorParams(bool apply); void SetLabelHistEqParams(bool apply, bool patch_prior, bool mask_prob, std::vector<float> label_boost); long BinarySearchPatch(double offset); void SetLabelConsolidateParams(bool apply, std::vector<int> labels); std::vector<cv::Mat>& raw_images(); std::vector<cv::Mat>& label_images(); std::vector<int>& image_number(); protected: std::vector<cv::Mat> raw_images_; std::vector<cv::Mat> label_images_; std::vector<std::vector<cv::Mat>> label_stack_; std::vector<int> image_number_; // General parameters int image_size_x_; int image_size_y_; int patch_size_; int nr_labels_; std::function<double()> offset_selector_; // Normalization parameters bool apply_normalization_ = false; // Final crop subtraction parameters int image_crop_ = 0; int label_crop_ = 0; // Border parameters bool apply_border_reflect_ = false; int border_size_; // CLAHE parameters bool apply_clahe_ = false; cv::Ptr<cv::CLAHE> clahe_; // Blur parameters bool apply_blur_ = false; float blur_mean_; float blur_std_; int blur_size_; std::function<float()> blur_random_selector_; // Simple rotation parameters bool apply_rotation_ = false; std::function<unsigned int()> rotation_rand_; // Patch mirroring bool apply_patch_mirroring_ = false; std::function<unsigned int()> patch_mirror_rand_; // Label histrogram equalization bool apply_label_hist_eq_ = false; bool apply_label_patch_prior_ = false; bool apply_label_pixel_mask_ = false; std::vector<double> label_running_probability_; std::vector<float> label_mask_probability_; std::vector<std::function<float()>> label_mask_prob_rand_; std::function<double()> label_patch_prior_rand_; std::vector<float> label_boost_; // Label consolidation bool label_consolidate_; std::vector<int> label_consolidate_labels_; // Patch sequence index int sequence_index_; }; class ProcessImageProcessor : public ImageProcessor { public: ProcessImageProcessor(int patch_size, int nr_labels); protected: }; class TrainImageProcessor : public ImageProcessor { public: TrainImageProcessor(int patch_size, int nr_labels); std::vector<cv::Mat> DrawPatchRandom(); protected: }; } #endif /* IMAGE_PROCESSOR_HPP_ */ <commit_msg>Label consolidate default false.<commit_after>/* * image_preprocessor.hpp * * Created on: Apr 3, 2015 * Author: Fabian Tschopp */ #ifndef IMAGE_PROCESSOR_HPP_ #define IMAGE_PROCESSOR_HPP_ #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <functional> namespace caffe_neural { class ImageProcessor { public: ImageProcessor(int patch_size, int nr_labels); void SubmitRawImage(cv::Mat input, int img_id); void ClearImages(); void SubmitImage(cv::Mat raw, int img_id, std::vector<cv::Mat> labels); int Init(); void SetBorderParams(bool apply, int border_size); void SetClaheParams(bool apply, float clip_limit); void SetBlurParams(bool apply, float mu, float std, int blur_size); void SetCropParams(int image_crop, int label_crop); void SetNormalizationParams(bool apply); void SetRotationParams(bool apply); void SetPatchMirrorParams(bool apply); void SetLabelHistEqParams(bool apply, bool patch_prior, bool mask_prob, std::vector<float> label_boost); long BinarySearchPatch(double offset); void SetLabelConsolidateParams(bool apply, std::vector<int> labels); std::vector<cv::Mat>& raw_images(); std::vector<cv::Mat>& label_images(); std::vector<int>& image_number(); protected: std::vector<cv::Mat> raw_images_; std::vector<cv::Mat> label_images_; std::vector<std::vector<cv::Mat>> label_stack_; std::vector<int> image_number_; // General parameters int image_size_x_; int image_size_y_; int patch_size_; int nr_labels_; std::function<double()> offset_selector_; // Normalization parameters bool apply_normalization_ = false; // Final crop subtraction parameters int image_crop_ = 0; int label_crop_ = 0; // Border parameters bool apply_border_reflect_ = false; int border_size_; // CLAHE parameters bool apply_clahe_ = false; cv::Ptr<cv::CLAHE> clahe_; // Blur parameters bool apply_blur_ = false; float blur_mean_; float blur_std_; int blur_size_; std::function<float()> blur_random_selector_; // Simple rotation parameters bool apply_rotation_ = false; std::function<unsigned int()> rotation_rand_; // Patch mirroring bool apply_patch_mirroring_ = false; std::function<unsigned int()> patch_mirror_rand_; // Label histrogram equalization bool apply_label_hist_eq_ = false; bool apply_label_patch_prior_ = false; bool apply_label_pixel_mask_ = false; std::vector<double> label_running_probability_; std::vector<float> label_mask_probability_; std::vector<std::function<float()>> label_mask_prob_rand_; std::function<double()> label_patch_prior_rand_; std::vector<float> label_boost_; // Label consolidation bool label_consolidate_ = false std::vector<int> label_consolidate_labels_; // Patch sequence index int sequence_index_; }; class ProcessImageProcessor : public ImageProcessor { public: ProcessImageProcessor(int patch_size, int nr_labels); protected: }; class TrainImageProcessor : public ImageProcessor { public: TrainImageProcessor(int patch_size, int nr_labels); std::vector<cv::Mat> DrawPatchRandom(); protected: }; } #endif /* IMAGE_PROCESSOR_HPP_ */ <|endoftext|>
<commit_before> //snippet-sourcedescription:[put_item.cpp demonstrates how to put an item into an Amazon DynamoDB table.] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon DynamoDB] //snippet-service:[dynamodb] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file 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. */ //snippet-start:[dynamodb.cpp.put_item.inc] #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/AttributeDefinition.h> #include <aws/dynamodb/model/PutItemRequest.h> #include <aws/dynamodb/model/PutItemResult.h> #include <iostream> //snippet-end:[dynamodb.cpp.put_item.inc] /** * Put an item in a DynamoDB table. * * Takes the name of the table, a name (primary key value) and a greeting * (associated with the key value). * * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html */ int main(int argc, char** argv) { const std::string USAGE = \ "Usage:\n" " put_item <table> <name> [field=value ...]\n\n" "Where:\n" " table - the table to put the item in.\n" " name - a name to add to the table. If the name already\n" " exists, its entry will be updated.\n\n" "Additional fields can be added by appending them to the end of the\n" "input.\n\n" "Example:\n" " put_item Cellists Pau Language=ca Born=1876\n"; if (argc < 2) { std::cout << USAGE; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String table(argv[1]); const Aws::String name(argv[2]); // snippet-start:[dynamodb.cpp.put_item.code] Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::PutItemRequest pir; pir.SetTableName(table); Aws::DynamoDB::Model::AttributeValue av; av.SetS(name); pir.AddItem("Name", av); for (int x = 3; x < argc; x++) { const Aws::String arg(argv[x]); const Aws::Vector<Aws::String>& flds = Aws::Utils::StringUtils::Split(arg, ':'); if (flds.size() == 2) { Aws::DynamoDB::Model::AttributeValue val; val.SetS(flds[1]); pir.AddItem(flds[0], val); } else { std::cout << "Invalid argument: " << arg << std::endl << USAGE; return 1; } } const Aws::DynamoDB::Model::PutItemOutcome result = dynamoClient.PutItem(pir); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; return 1; } std::cout << "Done!" << std::endl; // snippet-end:[dynamodb.cpp.put_item.code] } Aws::ShutdownAPI(options); return 0; }<commit_msg>Use the correct separator character in "field=value" arguments<commit_after> //snippet-sourcedescription:[put_item.cpp demonstrates how to put an item into an Amazon DynamoDB table.] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon DynamoDB] //snippet-service:[dynamodb] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file 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. */ //snippet-start:[dynamodb.cpp.put_item.inc] #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/AttributeDefinition.h> #include <aws/dynamodb/model/PutItemRequest.h> #include <aws/dynamodb/model/PutItemResult.h> #include <iostream> //snippet-end:[dynamodb.cpp.put_item.inc] /** * Put an item in a DynamoDB table. * * Takes the name of the table, a name (primary key value) and a greeting * (associated with the key value). * * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/credentials.html */ int main(int argc, char** argv) { const std::string USAGE = \ "Usage:\n" " put_item <table> <name> [field=value ...]\n\n" "Where:\n" " table - the table to put the item in.\n" " name - a name to add to the table. If the name already\n" " exists, its entry will be updated.\n\n" "Additional fields can be added by appending them to the end of the\n" "input.\n\n" "Example:\n" " put_item Cellists Pau Language=ca Born=1876\n"; if (argc < 2) { std::cout << USAGE; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String table(argv[1]); const Aws::String name(argv[2]); // snippet-start:[dynamodb.cpp.put_item.code] Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::PutItemRequest pir; pir.SetTableName(table); Aws::DynamoDB::Model::AttributeValue av; av.SetS(name); pir.AddItem("Name", av); for (int x = 3; x < argc; x++) { const Aws::String arg(argv[x]); const Aws::Vector<Aws::String>& flds = Aws::Utils::StringUtils::Split(arg, '='); if (flds.size() == 2) { Aws::DynamoDB::Model::AttributeValue val; val.SetS(flds[1]); pir.AddItem(flds[0], val); } else { std::cout << "Invalid argument: " << arg << std::endl << USAGE; return 1; } } const Aws::DynamoDB::Model::PutItemOutcome result = dynamoClient.PutItem(pir); if (!result.IsSuccess()) { std::cout << result.GetError().GetMessage() << std::endl; return 1; } std::cout << "Done!" << std::endl; // snippet-end:[dynamodb.cpp.put_item.code] } Aws::ShutdownAPI(options); return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../../main/models/factor/SvdppModel.h" #include "../../main/models/factor/SvdppModelUpdater.h" #include "../../main/models/factor/SvdppModelGradientUpdater.h" #define DIMENSION 10 #define MAXUSER 13 #define MAXITEM 9 namespace { class TestSvdppModel : public ::testing::Test { public: vector<RecDat*> rec_dats; TestSvdppModel(){} virtual ~TestSvdppModel(){} void SetUp() override { } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat->user = user; rec_dat->item = item; rec_dat->time = time; rec_dat->id = rec_dats.size(); rec_dat->category = 0; rec_dat->score = score; rec_dats.push_back(rec_dat); return rec_dat; } void TearDown() override { for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; } TEST_F(TestSvdppModel, test){ vector<double> user_vector_weights={1.0,0.0,1.0,0.3}; vector<double> history_weights={0.0,1.0,1.0,0.6}; for(uint i=0;i<user_vector_weights.size();i++){ double user_vector_weight=user_vector_weights[i]; double history_weight=history_weights[i]; SvdppModelParameters model_parameters; model_parameters.dimension=10; model_parameters.begin_min=-0.1; model_parameters.begin_max=0.1; model_parameters.initialize_all=false; model_parameters.use_sigmoid=false; model_parameters.user_vector_weight=user_vector_weight; model_parameters.history_weight=history_weight; model_parameters.norm_type="exponential"; model_parameters.gamma=0.8; SvdppModel model(&model_parameters); SvdppModelGradientUpdaterParameters grad_upd_parameters; grad_upd_parameters.learning_rate=0.1; grad_upd_parameters.cumulative_item_updates=false; SvdppModelGradientUpdater gradient_updater(&grad_upd_parameters); SvdppModelUpdater simple_updater; gradient_updater.set_model(&model); simple_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(gradient_updater.self_test()); EXPECT_TRUE(simple_updater.self_test()); for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } for(uint i=0;i<rec_dats.size();i++){ model.add(rec_dats[i]); simple_updater.update(rec_dats[i]); } for(uint i=0;i<rec_dats.size();i++){ double orig_pred = model.prediction(rec_dats[i]); double gradient = orig_pred - 1; gradient_updater.update(rec_dats[i],gradient); double new_pred = model.prediction(rec_dats[i]); if(gradient<0){ EXPECT_GT(new_pred,orig_pred); } } } } TEST_F(TestSvdppModel, test_norm_types){ for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } vector<string> norm_types = {"disabled", "constant", "youngest", "recency"}; for (auto norm_type : norm_types){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type=norm_type; model_params.gamma=-1; model_params.initialize_all=false; model_params.user_vector_weight=1; model_params.history_weight=1; SvdppModel model(&model_params); SvdppModelUpdater simple_updater; simple_updater.set_model(&model); SvdppModelGradientUpdaterParameters grad_upd_params; grad_upd_params.learning_rate=0.14; grad_upd_params.cumulative_item_updates=false; SvdppModelGradientUpdater gradient_updater(&grad_upd_params); gradient_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(simple_updater.self_test()); EXPECT_TRUE(gradient_updater.self_test()); for(uint i=0;i<rec_dats.size();i++){ EXPECT_EQ(0,model.prediction(rec_dats[i])); } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); model.add(rec_dats[i]); double orig_pred = model.prediction(rec_dats[i]); double gradient = orig_pred - 1; gradient_updater.update(rec_dats[i],gradient); double new_pred = model.prediction(rec_dats[i]); if(gradient<0){ EXPECT_GT(new_pred,orig_pred); } } } } TEST_F(TestSvdppModel, clear){ for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } SvdppModelParameters model_params; model_params.use_sigmoid=false; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="constant"; model_params.gamma=-1; model_params.initialize_all=true; model_params.max_item=MAXITEM; model_params.max_user=MAXUSER; model_params.user_vector_weight=0; model_params.history_weight=1; SvdppModel model(&model_params); SvdppModelUpdater simple_updater; simple_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(simple_updater.self_test()); for(uint i=0;i<rec_dats.size();i++){ EXPECT_DOUBLE_EQ(0,model.prediction(rec_dats[i])); //user_vector_weight=0-->no history, 0 pred } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); //adding history } for(uint i=0;i<rec_dats.size();i++){ double pred = model.prediction(rec_dats[i]); EXPECT_NE(0,pred); //tests initall } model.clear(); for(uint i=0;i<rec_dats.size();i++){ EXPECT_DOUBLE_EQ(0,model.prediction(rec_dats[i])); //tests clear } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); } for(uint i=0;i<rec_dats.size();i++){ double pred = model.prediction(rec_dats[i]); EXPECT_NE(0,pred); //tests if factors are initialized again after clear } } TEST_F(TestSvdppModel, self_test){ SvdppModelParameters model_params; model_params.dimension=0; model_params.begin_min=3; model_params.begin_max=3; model_params.norm_type="asdf"; model_params.gamma=-1; model_params.initialize_all=true; model_params.max_item=-1; model_params.max_user=-1; SvdppModel model(&model_params); EXPECT_FALSE(model.self_test()); //TODO self_test of gradient updater } TEST_F(TestSvdppModel, readwrite){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="exponential"; model_params.gamma=0.8; model_params.initialize_all=-1; SvdppModel model(&model_params); stringstream ss; EXPECT_ANY_THROW(model.write(ss)); //UserHistoryContainer::write is not implemented EXPECT_ANY_THROW(model.read(ss)); //UserHistoryContainer::read is not implemented } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>SvdppModel: add tests for initialize()<commit_after>#include <gtest/gtest.h> #include "../../main/models/factor/SvdppModel.h" #include "../../main/models/factor/SvdppModelUpdater.h" #include "../../main/models/factor/SvdppModelGradientUpdater.h" #define DIMENSION 10 #define MAXUSER 13 #define MAXITEM 9 namespace { class TestSvdppModel : public ::testing::Test { public: vector<RecDat*> rec_dats; TestSvdppModel(){} virtual ~TestSvdppModel(){} void SetUp() override { } RecDat* create_rec_dat(int user, int item, double time, double score){ RecDat* rec_dat = new RecDat; rec_dat->user = user; rec_dat->item = item; rec_dat->time = time; rec_dat->id = rec_dats.size(); rec_dat->category = 0; rec_dat->score = score; rec_dats.push_back(rec_dat); return rec_dat; } void TearDown() override { for (vector<RecDat*>::iterator it = rec_dats.begin();it!=rec_dats.end();it++){ delete *it; } } }; } TEST_F(TestSvdppModel, test){ vector<double> user_vector_weights={1.0,0.0,1.0,0.3}; vector<double> history_weights={0.0,1.0,1.0,0.6}; for(uint i=0;i<user_vector_weights.size();i++){ double user_vector_weight=user_vector_weights[i]; double history_weight=history_weights[i]; SvdppModelParameters model_params; model_params.dimension=10; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.initialize_all=false; model_params.use_sigmoid=false; model_params.user_vector_weight=user_vector_weight; model_params.history_weight=history_weight; model_params.norm_type="exponential"; model_params.gamma=0.8; SvdppModel model(&model_params); SvdppModelGradientUpdaterParameters grad_upd_parameters; grad_upd_parameters.learning_rate=0.1; grad_upd_parameters.cumulative_item_updates=false; SvdppModelGradientUpdater gradient_updater(&grad_upd_parameters); SvdppModelUpdater simple_updater; gradient_updater.set_model(&model); simple_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(gradient_updater.self_test()); EXPECT_TRUE(simple_updater.self_test()); for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } for(uint i=0;i<rec_dats.size();i++){ model.add(rec_dats[i]); simple_updater.update(rec_dats[i]); } for(uint i=0;i<rec_dats.size();i++){ double orig_pred = model.prediction(rec_dats[i]); double gradient = orig_pred - 1; gradient_updater.update(rec_dats[i],gradient); double new_pred = model.prediction(rec_dats[i]); if(gradient<0){ EXPECT_GT(new_pred,orig_pred); } } } } TEST_F(TestSvdppModel, test_norm_types){ for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } vector<string> norm_types = {"disabled", "constant", "youngest", "recency"}; for (auto norm_type : norm_types){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type=norm_type; model_params.gamma=-1; model_params.initialize_all=false; model_params.user_vector_weight=1; model_params.history_weight=1; SvdppModel model(&model_params); SvdppModelUpdater simple_updater; simple_updater.set_model(&model); SvdppModelGradientUpdaterParameters grad_upd_params; grad_upd_params.learning_rate=0.14; grad_upd_params.cumulative_item_updates=false; SvdppModelGradientUpdater gradient_updater(&grad_upd_params); gradient_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(simple_updater.self_test()); EXPECT_TRUE(gradient_updater.self_test()); for(uint i=0;i<rec_dats.size();i++){ EXPECT_EQ(0,model.prediction(rec_dats[i])); } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); model.add(rec_dats[i]); double orig_pred = model.prediction(rec_dats[i]); double gradient = orig_pred - 1; gradient_updater.update(rec_dats[i],gradient); double new_pred = model.prediction(rec_dats[i]); if(gradient<0){ EXPECT_GT(new_pred,orig_pred); } } } } TEST_F(TestSvdppModel, clear){ for(int i=0;i<100;i++){ create_rec_dat(i%MAXUSER,i%MAXITEM,i,1); } SvdppModelParameters model_params; model_params.use_sigmoid=false; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="constant"; model_params.gamma=-1; model_params.initialize_all=true; model_params.max_item=MAXITEM; model_params.max_user=MAXUSER; model_params.user_vector_weight=0; model_params.history_weight=1; SvdppModel model(&model_params); SvdppModelUpdater simple_updater; simple_updater.set_model(&model); EXPECT_TRUE(model.self_test()); EXPECT_TRUE(simple_updater.self_test()); for(uint i=0;i<rec_dats.size();i++){ EXPECT_DOUBLE_EQ(0,model.prediction(rec_dats[i])); //user_vector_weight=0-->no history, 0 pred } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); //adding history } for(uint i=0;i<rec_dats.size();i++){ double pred = model.prediction(rec_dats[i]); EXPECT_NE(0,pred); //tests initall } model.clear(); for(uint i=0;i<rec_dats.size();i++){ EXPECT_DOUBLE_EQ(0,model.prediction(rec_dats[i])); //tests clear } for(uint i=0;i<rec_dats.size();i++){ simple_updater.update(rec_dats[i]); } for(uint i=0;i<rec_dats.size();i++){ double pred = model.prediction(rec_dats[i]); EXPECT_NE(0,pred); //tests if factors are initialized again after clear } } TEST_F(TestSvdppModel, self_test){ SvdppModelParameters model_params; model_params.dimension=0; model_params.begin_min=3; model_params.begin_max=3; model_params.norm_type="asdf"; model_params.gamma=-1; model_params.initialize_all=true; model_params.max_item=-1; model_params.max_user=-1; model_params.user_vector_weight=1; model_params.history_weight=1; SvdppModel model(&model_params); EXPECT_FALSE(model.self_test()); //TODO self_test of gradient updater } TEST_F(TestSvdppModel, expenv){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="exponential"; model_params.gamma=0.8; model_params.initialize_all=-1; model_params.user_vector_weight=1; model_params.history_weight=1; SvdppModel model(&model_params); EXPECT_FALSE(model.initialize()); ExperimentEnvironment exp_env; model.set_experiment_environment(&exp_env); EXPECT_TRUE(model.initialize()); } TEST_F(TestSvdppModel, expenv2){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="exponential"; model_params.gamma=0.8; model_params.initialize_all=true; model_params.max_item=-1; model_params.max_user=-1; model_params.user_vector_weight=1; model_params.history_weight=1; SvdppModel model(&model_params); EXPECT_FALSE(model.initialize()); ExperimentEnvironment exp_env; model.set_experiment_environment(&exp_env); EXPECT_TRUE(model.initialize()); } TEST_F(TestSvdppModel, readwrite){ SvdppModelParameters model_params; model_params.dimension=DIMENSION; model_params.begin_min=-0.1; model_params.begin_max=0.1; model_params.norm_type="exponential"; model_params.gamma=0.8; model_params.initialize_all=-1; SvdppModel model(&model_params); stringstream ss; EXPECT_ANY_THROW(model.write(ss)); //UserHistoryContainer::write is not implemented EXPECT_ANY_THROW(model.read(ss)); //UserHistoryContainer::read is not implemented } int main (int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "Qt5DebugSession.h" #include "Qt5DebuggerThread.h" #include "Qt5CodeEditor.h" #include "Qt5CallStack.h" #include "Qt5Locals.h" #include <QThread> #ifndef _WIN32 #include <unistd.h> #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace prodbg { Qt5DebugSession* g_debugSession = 0; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Qt5DebugSession::Qt5DebugSession() { m_breakpoints = new PDBreakpointFileLine[256]; m_breakpointCount = 0; m_breakpointMaxCount = 256; m_debuggerThread = 0; m_threadRunner = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::createSession() { printf("Qt5DebugSession::createSession\n"); g_debugSession = new Qt5DebugSession; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addCodeEditor(Qt5CodeEditor* codeEditor) { m_codeEditors.push_back(codeEditor); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addLocals(Qt5Locals* locals) { m_locals.push_back(locals); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addCallStack(Qt5CallStack* callStack) { m_callStacks.push_back(callStack); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delCodeEditor(Qt5CodeEditor* codeEditor) { m_codeEditors.removeOne(codeEditor); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delLocals(Qt5Locals* locals) { m_locals.removeOne(locals); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delCallStack(Qt5CallStack* callStack) { m_callStacks.removeOne(callStack); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::begin(const char* executable) { m_threadRunner = new QThread; m_debuggerThread = new Qt5DebuggerThread; m_debuggerThread->moveToThread(m_threadRunner); connect(m_threadRunner , SIGNAL(started()), m_debuggerThread, SLOT(start())); connect(m_debuggerThread, SIGNAL(finished()), m_threadRunner , SLOT(quit())); connect(this, &Qt5DebugSession::tryStartDebugging, m_debuggerThread, &Qt5DebuggerThread::tryStartDebugging); connect(this, &Qt5DebugSession::tryStep, m_debuggerThread, &Qt5DebuggerThread::tryStep); connect(m_debuggerThread, &Qt5DebuggerThread::sendDebugDataState, this, &Qt5DebugSession::setDebugDataState); m_threadRunner->start(); printf("beginDebug %s %d\n", executable, (uint32_t)(uint64_t)QThread::currentThreadId()); emit tryStartDebugging(executable, m_breakpoints, (int)m_breakpointCount); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::getFilenameLine(const char** filename, int* line) { (void)filename; (void)line; return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: Rewrite, sort by name and such bool Qt5DebugSession::hasLineBreakpoint(const char* filename, int line) { for (int i = 0, e = m_breakpointCount; i < e; ++i) { const PDBreakpointFileLine* breakpoint = &m_breakpoints[i]; if (!strstr(breakpoint->filename, filename)) continue; if (breakpoint->line == line) return true; } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::step() { emit tryStep(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::setDebugDataState(PDDebugDataState* state) { // Might not be safe... but we do it anyway! ha! for (auto i = m_codeEditors.begin(); i != m_codeEditors.end(); i++) { (*i)->setFileLine(state->filename, state->line); } for (auto i = m_callStacks.begin(); i != m_callStacks.end(); i++) { (*i)->updateCallStack((PDCallStack*)&state->callStack, state->callStackCount); } for (auto i = m_locals.begin(); i != m_locals.end(); i++) { (*i)->updateLocals((PDLocals*)&state->locals, state->localsCount); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::addBreakpointUI(const char* file, int line) { // if we don't have a thread the session debugging session hasn't started yet so it's fine to add the bp directly if (!m_debuggerThread) { printf("Qt5DebugSession::addBreakpointUI %s %d\n", file, line); addBreakpoint(file, line, -2); return true; } else { emit tryAddBreakpoint(file, line); } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::addBreakpoint(const char* file, int line, int id) { if (m_breakpointCount + 1 >= m_breakpointMaxCount) return false; PDBreakpointFileLine* bp = &m_breakpoints[m_breakpointCount++]; *bp = { file, line, id }; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delBreakpoint(int id) { PDBreakpointFileLine* breakpoints = m_breakpoints; int count = m_breakpointCount; for (int i = 0, e = count; i < e; ++i) { if (breakpoints[i].id == id) { count--; if (count != 0) breakpoints[i] = breakpoints[count]; m_breakpointCount = count; return; } } } } <commit_msg>Minor clean<commit_after>#include "Qt5DebugSession.h" #include "Qt5DebuggerThread.h" #include "Qt5CodeEditor.h" #include "Qt5CallStack.h" #include "Qt5Locals.h" #include <QThread> #ifndef _WIN32 #include <unistd.h> #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace prodbg { Qt5DebugSession* g_debugSession = 0; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Qt5DebugSession::Qt5DebugSession() { m_breakpoints = new PDBreakpointFileLine[256]; m_breakpointCount = 0; m_breakpointMaxCount = 256; m_debuggerThread = 0; m_threadRunner = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::createSession() { printf("Qt5DebugSession::createSession\n"); g_debugSession = new Qt5DebugSession; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addCodeEditor(Qt5CodeEditor* codeEditor) { m_codeEditors.push_back(codeEditor); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addLocals(Qt5Locals* locals) { m_locals.push_back(locals); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::addCallStack(Qt5CallStack* callStack) { m_callStacks.push_back(callStack); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delCodeEditor(Qt5CodeEditor* codeEditor) { m_codeEditors.removeOne(codeEditor); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delLocals(Qt5Locals* locals) { m_locals.removeOne(locals); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delCallStack(Qt5CallStack* callStack) { m_callStacks.removeOne(callStack); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::begin(const char* executable) { m_threadRunner = new QThread; m_debuggerThread = new Qt5DebuggerThread; m_debuggerThread->moveToThread(m_threadRunner); connect(m_threadRunner , SIGNAL(started()), m_debuggerThread, SLOT(start())); connect(m_debuggerThread, SIGNAL(finished()), m_threadRunner , SLOT(quit())); connect(this, &Qt5DebugSession::tryStartDebugging, m_debuggerThread, &Qt5DebuggerThread::tryStartDebugging); connect(this, &Qt5DebugSession::tryStep, m_debuggerThread, &Qt5DebuggerThread::tryStep); connect(m_debuggerThread, &Qt5DebuggerThread::sendDebugDataState, this, &Qt5DebugSession::setDebugDataState); m_threadRunner->start(); printf("beginDebug %s %d\n", executable, (uint32_t)(uint64_t)QThread::currentThreadId()); emit tryStartDebugging(executable, m_breakpoints, (int)m_breakpointCount); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::getFilenameLine(const char** filename, int* line) { (void)filename; (void)line; return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TODO: Rewrite, sort by name and such bool Qt5DebugSession::hasLineBreakpoint(const char* filename, int line) { for (int i = 0, e = m_breakpointCount; i < e; ++i) { const PDBreakpointFileLine* breakpoint = &m_breakpoints[i]; if (!strstr(breakpoint->filename, filename)) continue; if (breakpoint->line == line) return true; } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::step() { emit tryStep(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::setDebugDataState(PDDebugDataState* state) { // Might not be safe... but we do it anyway! ha! for (auto i = m_codeEditors.begin(); i != m_codeEditors.end(); i++) (*i)->setFileLine(state->filename, state->line); for (auto i = m_callStacks.begin(); i != m_callStacks.end(); i++) (*i)->updateCallStack((PDCallStack*)&state->callStack, state->callStackCount); for (auto i = m_locals.begin(); i != m_locals.end(); i++) (*i)->updateLocals((PDLocals*)&state->locals, state->localsCount); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::addBreakpointUI(const char* file, int line) { // if we don't have a thread the session debugging session hasn't started yet so it's fine to add the bp directly if (!m_debuggerThread) { printf("Qt5DebugSession::addBreakpointUI %s %d\n", file, line); addBreakpoint(file, line, -2); return true; } else { emit tryAddBreakpoint(file, line); } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Qt5DebugSession::addBreakpoint(const char* file, int line, int id) { if (m_breakpointCount + 1 >= m_breakpointMaxCount) return false; PDBreakpointFileLine* bp = &m_breakpoints[m_breakpointCount++]; *bp = { file, line, id }; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Qt5DebugSession::delBreakpoint(int id) { PDBreakpointFileLine* breakpoints = m_breakpoints; int count = m_breakpointCount; for (int i = 0, e = count; i < e; ++i) { if (breakpoints[i].id == id) { count--; if (count != 0) breakpoints[i] = breakpoints[count]; m_breakpointCount = count; return; } } } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "gameboy_impl.hpp" using namespace mjkgb; namespace { class AccessorsTest : public testing::Test { protected: GameboyImpl gb; }; TEST_F(AccessorsTest, ByteRegister) { EXPECT_EQ(0, gb.get(ByteRegister::A)); gb.set(ByteRegister::A, 0xde); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); gb.set(ByteRegister::A, gb.get(ByteRegister::A) + 1); EXPECT_EQ(0xdf, gb.get(ByteRegister::A)); EXPECT_EQ(0, gb.get(ByteRegister::E)); gb.set(ByteRegister::E, 0xad); EXPECT_EQ(0xad, gb.get(ByteRegister::E)); gb.set(ByteRegister::E, gb.get(ByteRegister::E) + 1); EXPECT_EQ(0xae, gb.get(ByteRegister::E)); } TEST_F(AccessorsTest, WordRegister) { EXPECT_EQ(0, gb.get(WordRegister::AF)); gb.set(WordRegister::AF, 0xdead); EXPECT_EQ(0xdead, gb.get(WordRegister::AF)); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); EXPECT_EQ(0xad, gb.get(ByteRegister::F)); gb.set(WordRegister::AF, gb.get(WordRegister::AF) + 1); EXPECT_EQ(0xdeae, gb.get(WordRegister::AF)); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); EXPECT_EQ(0xae, gb.get(ByteRegister::F)); EXPECT_EQ(0, gb.get(WordRegister::DE)); gb.set(WordRegister::DE, 0xbeef); EXPECT_EQ(0xbeef, gb.get(WordRegister::DE)); EXPECT_EQ(0xbe, gb.get(ByteRegister::D)); EXPECT_EQ(0xef, gb.get(ByteRegister::E)); gb.set(WordRegister::DE, gb.get(WordRegister::DE) + 1); EXPECT_EQ(0xbef0, gb.get(WordRegister::DE)); EXPECT_EQ(0xbe, gb.get(ByteRegister::D)); EXPECT_EQ(0xf0, gb.get(ByteRegister::E)); } TEST_F(AccessorsTest, ConditionCode) { EXPECT_EQ(false, gb.get(ConditionCode::C)); gb.set(ConditionCode::C, true); EXPECT_EQ(true, gb.get(ConditionCode::C)); gb.set(ConditionCode::C, !gb.get(ConditionCode::C)); EXPECT_EQ(false, gb.get(ConditionCode::C)); EXPECT_EQ(false, gb.get(ConditionCode::Z)); gb.set(ConditionCode::Z, true); EXPECT_EQ(true, gb.get(ConditionCode::Z)); gb.set(ConditionCode::Z, !gb.get(ConditionCode::Z)); EXPECT_EQ(false, gb.get(ConditionCode::Z)); } TEST_F(AccessorsTest, BytePointer) { auto ptr0 = BytePointer<ByteRegister, 0>(ByteRegister::A); EXPECT_EQ(0, gb.get(ptr0)); gb.set(ptr0, 0xde); EXPECT_EQ(0xde, gb.get(ptr0)); gb.set(ptr0, gb.get(ptr0) + 1); EXPECT_EQ(0xdf, gb.get(ptr0)); auto ptr1 = BytePointer<WordRegister, 0>(WordRegister::HL); EXPECT_EQ(0, gb.get(ptr1)); gb.set(WordRegister::HL, 0xff00); EXPECT_EQ(0xdf, gb.get(ptr1)); gb.set(ptr1, 0xbe); EXPECT_EQ(0xbe, gb.get(ptr1)); gb.set(ptr1, gb.get(ptr1) + 1); EXPECT_EQ(0xbf, gb.get(ptr1)); auto ptr2 = BytePointer<WordRegister, 1>(WordRegister::HL); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbf, gb.get(ptr2)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr2)); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); auto ptr3 = BytePointer<WordRegister, -1>(WordRegister::HL); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbf, gb.get(ptr3)); } TEST_F(AccessorsTest, WordPointer) { auto ptr0 = WordPointer<ByteRegister, 0>(ByteRegister::A); EXPECT_EQ(0, gb.get(ptr0)); gb.set(ptr0, 0xdead); EXPECT_EQ(0xdead, gb.get(ptr0)); gb.set(ptr0, gb.get(ptr0) + 1); EXPECT_EQ(0xdeae, gb.get(ptr0)); auto ptr1 = WordPointer<WordRegister, 0>(WordRegister::HL); EXPECT_EQ(0, gb.get(ptr1)); gb.set(WordRegister::HL, 0xff00); EXPECT_EQ(0xdeae, gb.get(ptr1)); gb.set(ptr1, 0xbeef); EXPECT_EQ(0xbeef, gb.get(ptr1)); gb.set(ptr1, gb.get(ptr1) + 1); EXPECT_EQ(0xbef0, gb.get(ptr1)); auto ptr2 = WordPointer<WordRegister, 1>(WordRegister::HL); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbef0, gb.get(ptr2)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0xbe, gb.get(ptr2)); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); auto ptr3 = WordPointer<WordRegister, -1>(WordRegister::HL); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0xbe, gb.get(ptr3)); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbef0, gb.get(ptr3)); } TEST_F(AccessorsTest, ByteImmediate) { EXPECT_EQ(0, gb.get(WordRegister::PC)); EXPECT_EQ(0, gb.get(ByteImmediate())); EXPECT_EQ(1, gb.get(WordRegister::PC)); gb.set(WordRegister::HL, 1); gb.set(BytePointer<WordRegister>(WordRegister::HL), 0xde); EXPECT_EQ(0xde, gb.get(ByteImmediate())); EXPECT_EQ(2, gb.get(WordRegister::PC)); } TEST_F(AccessorsTest, WordImmediate) { EXPECT_EQ(0, gb.get(WordRegister::PC)); EXPECT_EQ(0, gb.get(WordImmediate())); EXPECT_EQ(2, gb.get(WordRegister::PC)); gb.set(WordRegister::HL, 2); gb.set(WordPointer<WordRegister>(WordRegister::HL), 0xdead); EXPECT_EQ(0xdead, gb.get(WordImmediate())); EXPECT_EQ(4, gb.get(WordRegister::PC)); } } <commit_msg>Update tests so writes to the low nibble of the F register properly fail<commit_after>#include <gtest/gtest.h> #include "gameboy_impl.hpp" using namespace mjkgb; namespace { class AccessorsTest : public testing::Test { protected: GameboyImpl gb; }; TEST_F(AccessorsTest, ByteRegister) { EXPECT_EQ(0, gb.get(ByteRegister::A)); gb.set(ByteRegister::A, 0xde); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); gb.set(ByteRegister::A, gb.get(ByteRegister::A) + 1); EXPECT_EQ(0xdf, gb.get(ByteRegister::A)); EXPECT_EQ(0, gb.get(ByteRegister::E)); gb.set(ByteRegister::E, 0xad); EXPECT_EQ(0xad, gb.get(ByteRegister::E)); gb.set(ByteRegister::E, gb.get(ByteRegister::E) + 1); EXPECT_EQ(0xae, gb.get(ByteRegister::E)); } TEST_F(AccessorsTest, WordRegister) { EXPECT_EQ(0, gb.get(WordRegister::AF)); gb.set(WordRegister::AF, 0xdead); EXPECT_EQ(0xdea0, gb.get(WordRegister::AF)); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); EXPECT_EQ(0xa0, gb.get(ByteRegister::F)); gb.set(WordRegister::AF, gb.get(WordRegister::AF) + 1); EXPECT_EQ(0xdea0, gb.get(WordRegister::AF)); EXPECT_EQ(0xde, gb.get(ByteRegister::A)); EXPECT_EQ(0xa0, gb.get(ByteRegister::F)); EXPECT_EQ(0, gb.get(WordRegister::DE)); gb.set(WordRegister::DE, 0xbeef); EXPECT_EQ(0xbeef, gb.get(WordRegister::DE)); EXPECT_EQ(0xbe, gb.get(ByteRegister::D)); EXPECT_EQ(0xef, gb.get(ByteRegister::E)); gb.set(WordRegister::DE, gb.get(WordRegister::DE) + 1); EXPECT_EQ(0xbef0, gb.get(WordRegister::DE)); EXPECT_EQ(0xbe, gb.get(ByteRegister::D)); EXPECT_EQ(0xf0, gb.get(ByteRegister::E)); } TEST_F(AccessorsTest, ConditionCode) { EXPECT_EQ(false, gb.get(ConditionCode::C)); gb.set(ConditionCode::C, true); EXPECT_EQ(true, gb.get(ConditionCode::C)); gb.set(ConditionCode::C, !gb.get(ConditionCode::C)); EXPECT_EQ(false, gb.get(ConditionCode::C)); EXPECT_EQ(false, gb.get(ConditionCode::Z)); gb.set(ConditionCode::Z, true); EXPECT_EQ(true, gb.get(ConditionCode::Z)); gb.set(ConditionCode::Z, !gb.get(ConditionCode::Z)); EXPECT_EQ(false, gb.get(ConditionCode::Z)); } TEST_F(AccessorsTest, BytePointer) { auto ptr0 = BytePointer<ByteRegister, 0>(ByteRegister::A); EXPECT_EQ(0, gb.get(ptr0)); gb.set(ptr0, 0xde); EXPECT_EQ(0xde, gb.get(ptr0)); gb.set(ptr0, gb.get(ptr0) + 1); EXPECT_EQ(0xdf, gb.get(ptr0)); auto ptr1 = BytePointer<WordRegister, 0>(WordRegister::HL); EXPECT_EQ(0, gb.get(ptr1)); gb.set(WordRegister::HL, 0xff00); EXPECT_EQ(0xdf, gb.get(ptr1)); gb.set(ptr1, 0xbe); EXPECT_EQ(0xbe, gb.get(ptr1)); gb.set(ptr1, gb.get(ptr1) + 1); EXPECT_EQ(0xbf, gb.get(ptr1)); auto ptr2 = BytePointer<WordRegister, 1>(WordRegister::HL); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbf, gb.get(ptr2)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr2)); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); auto ptr3 = BytePointer<WordRegister, -1>(WordRegister::HL); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbf, gb.get(ptr3)); } TEST_F(AccessorsTest, WordPointer) { auto ptr0 = WordPointer<ByteRegister, 0>(ByteRegister::A); EXPECT_EQ(0, gb.get(ptr0)); gb.set(ptr0, 0xdead); EXPECT_EQ(0xdead, gb.get(ptr0)); gb.set(ptr0, gb.get(ptr0) + 1); EXPECT_EQ(0xdeae, gb.get(ptr0)); auto ptr1 = WordPointer<WordRegister, 0>(WordRegister::HL); EXPECT_EQ(0, gb.get(ptr1)); gb.set(WordRegister::HL, 0xff00); EXPECT_EQ(0xdeae, gb.get(ptr1)); gb.set(ptr1, 0xbeef); EXPECT_EQ(0xbeef, gb.get(ptr1)); gb.set(ptr1, gb.get(ptr1) + 1); EXPECT_EQ(0xbef0, gb.get(ptr1)); auto ptr2 = WordPointer<WordRegister, 1>(WordRegister::HL); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbef0, gb.get(ptr2)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0xbe, gb.get(ptr2)); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); auto ptr3 = WordPointer<WordRegister, -1>(WordRegister::HL); EXPECT_EQ(0xff02, gb.get(WordRegister::HL)); EXPECT_EQ(0x0, gb.get(ptr3)); EXPECT_EQ(0xff01, gb.get(WordRegister::HL)); EXPECT_EQ(0xbe, gb.get(ptr3)); EXPECT_EQ(0xff00, gb.get(WordRegister::HL)); EXPECT_EQ(0xbef0, gb.get(ptr3)); } TEST_F(AccessorsTest, ByteImmediate) { EXPECT_EQ(0, gb.get(WordRegister::PC)); EXPECT_EQ(0, gb.get(ByteImmediate())); EXPECT_EQ(1, gb.get(WordRegister::PC)); gb.set(WordRegister::HL, 1); gb.set(BytePointer<WordRegister>(WordRegister::HL), 0xde); EXPECT_EQ(0xde, gb.get(ByteImmediate())); EXPECT_EQ(2, gb.get(WordRegister::PC)); } TEST_F(AccessorsTest, WordImmediate) { EXPECT_EQ(0, gb.get(WordRegister::PC)); EXPECT_EQ(0, gb.get(WordImmediate())); EXPECT_EQ(2, gb.get(WordRegister::PC)); gb.set(WordRegister::HL, 2); gb.set(WordPointer<WordRegister>(WordRegister::HL), 0xdead); EXPECT_EQ(0xdead, gb.get(WordImmediate())); EXPECT_EQ(4, gb.get(WordRegister::PC)); } } <|endoftext|>
<commit_before>// Frame.cpp #include "Frame.h" #include "Application.h" #include "Puzzle.h" #include "Canvas.h" #include <wx/menu.h> #include <wx/aboutdlg.h> #include <wx/msgdlg.h> #include <wx/sizer.h> Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Symmetry Group Madness" ), timer( this, ID_Timer ) { wxMenu* gameMenu = new wxMenu(); wxMenuItem* newGameMenuItem = new wxMenuItem( gameMenu, ID_NewGame, "New Game", "Start a new game at level 1." ); wxMenuItem* saveGameMenuItem = new wxMenuItem( gameMenu, ID_SaveGame, "Save Game", "Save your current game to disk." ); wxMenuItem* loadGameMenuItem = new wxMenuItem( gameMenu, ID_LoadGame, "Load Game", "Load a previously saved game from disk." ); wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, "Exit", "Exit this program." ); gameMenu->Append( newGameMenuItem ); gameMenu->AppendSeparator(); gameMenu->Append( saveGameMenuItem ); gameMenu->Append( loadGameMenuItem ); gameMenu->AppendSeparator(); gameMenu->Append( exitMenuItem ); wxMenu* helpMenu = new wxMenu(); wxMenuItem* solveMenuItem = new wxMenuItem( helpMenu, ID_Solve, "Solve", "Let the computer attempt to find a solution to the puzzle." ); wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, "About", "Show the about-box." ); helpMenu->Append( solveMenuItem ); helpMenu->AppendSeparator(); helpMenu->Append( aboutMenuItem ); wxMenuBar* menuBar = new wxMenuBar(); menuBar->Append( gameMenu, "Game" ); menuBar->Append( helpMenu, "Help" ); SetMenuBar( menuBar ); wxStatusBar* statusBar = new wxStatusBar( this ); SetStatusBar( statusBar ); Bind( wxEVT_MENU, &Frame::OnNewGame, this, ID_NewGame ); Bind( wxEVT_MENU, &Frame::OnSaveGame, this, ID_SaveGame ); Bind( wxEVT_MENU, &Frame::OnLoadGame, this, ID_LoadGame ); Bind( wxEVT_MENU, &Frame::OnSolve, this, ID_Solve ); Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit ); Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_NewGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_SaveGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LoadGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Solve ); Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer ); canvas = new Canvas( this ); wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL ); boxSizer->Add( canvas, 1, wxGROW ); SetSizer( boxSizer ); timer.Start(1); } /*virtual*/ Frame::~Frame( void ) { } void Frame::OnExit( wxCommandEvent& event ) { if( wxGetApp().SetPuzzle( nullptr ) ) Close( true ); } void Frame::OnAbout( wxCommandEvent& event ) { wxAboutDialogInfo aboutDialogInfo; aboutDialogInfo.SetName( "Symmetry Group Madness" ); aboutDialogInfo.SetVersion( "1.0" ); aboutDialogInfo.SetDescription( "This program is free software and distributed under the MIT license." ); aboutDialogInfo.SetCopyright( "Copyright (C) 2016 Spencer T. Parkin <spencertparkin@gmail.com>" ); //aboutDialogInfo.SetWebSite( "http://spencerparkin.github.io/SymmetryGroupMadness" ); wxAboutBox( aboutDialogInfo ); } void Frame::OnTimer( wxTimerEvent& event ) { canvas->Refresh(); } void Frame::OnSolve( wxCommandEvent& event ) { Puzzle* puzzle = wxGetApp().GetPuzzle(); if( puzzle ) { timer.Stop(); if( puzzle->EnqueueSolution() ) { int solutionSize = ( int )puzzle->autoRotationQueue.size(); if( wxYES != wxMessageBox( wxString::Format( "A solution was found with %d moves. Run solution?", solutionSize ), "Solution found!", wxICON_EXCLAMATION | wxYES_NO, this ) ) puzzle->autoRotationQueue.clear(); } else { wxMessageBox( "Failed to find a solution. I suck.", "Solution not found.", wxICON_ERROR, this ); } timer.Start(1); } } void Frame::OnNewGame( wxCommandEvent& event ) { if( wxGetApp().SetPuzzle( nullptr ) ) { Puzzle* puzzle = new Puzzle(); puzzle->SetupLevel(5); wxGetApp().SetPuzzle( puzzle ); canvas->Refresh(); } } void Frame::OnSaveGame( wxCommandEvent& event ) { Puzzle* puzzle = wxGetApp().GetPuzzle(); if( puzzle ) puzzle->Save(); } void Frame::OnLoadGame( wxCommandEvent& event ) { wxGetApp().SetPuzzle( nullptr ); Puzzle* puzzle = new Puzzle(); if( !puzzle->Load() ) delete puzzle; else wxGetApp().SetPuzzle( puzzle ); canvas->Refresh(); } void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event ) { switch( event.GetId() ) { case ID_NewGame: { event.Enable( true ); break; } case ID_SaveGame: { Puzzle* puzzle = wxGetApp().GetPuzzle(); event.Enable( ( puzzle && puzzle->modified ) ? true : false ); break; } case ID_LoadGame: { event.Enable( true ); break; } case ID_Solve: { Puzzle* puzzle = wxGetApp().GetPuzzle(); event.Enable( puzzle && !puzzle->GetPermutation().IsIdentity() ); break; } } } // Frame.cpp <commit_msg>start at level 1<commit_after>// Frame.cpp #include "Frame.h" #include "Application.h" #include "Puzzle.h" #include "Canvas.h" #include <wx/menu.h> #include <wx/aboutdlg.h> #include <wx/msgdlg.h> #include <wx/sizer.h> Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Symmetry Group Madness" ), timer( this, ID_Timer ) { wxMenu* gameMenu = new wxMenu(); wxMenuItem* newGameMenuItem = new wxMenuItem( gameMenu, ID_NewGame, "New Game", "Start a new game at level 1." ); wxMenuItem* saveGameMenuItem = new wxMenuItem( gameMenu, ID_SaveGame, "Save Game", "Save your current game to disk." ); wxMenuItem* loadGameMenuItem = new wxMenuItem( gameMenu, ID_LoadGame, "Load Game", "Load a previously saved game from disk." ); wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, "Exit", "Exit this program." ); gameMenu->Append( newGameMenuItem ); gameMenu->AppendSeparator(); gameMenu->Append( saveGameMenuItem ); gameMenu->Append( loadGameMenuItem ); gameMenu->AppendSeparator(); gameMenu->Append( exitMenuItem ); wxMenu* helpMenu = new wxMenu(); wxMenuItem* solveMenuItem = new wxMenuItem( helpMenu, ID_Solve, "Solve", "Let the computer attempt to find a solution to the puzzle." ); wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, "About", "Show the about-box." ); helpMenu->Append( solveMenuItem ); helpMenu->AppendSeparator(); helpMenu->Append( aboutMenuItem ); wxMenuBar* menuBar = new wxMenuBar(); menuBar->Append( gameMenu, "Game" ); menuBar->Append( helpMenu, "Help" ); SetMenuBar( menuBar ); wxStatusBar* statusBar = new wxStatusBar( this ); SetStatusBar( statusBar ); Bind( wxEVT_MENU, &Frame::OnNewGame, this, ID_NewGame ); Bind( wxEVT_MENU, &Frame::OnSaveGame, this, ID_SaveGame ); Bind( wxEVT_MENU, &Frame::OnLoadGame, this, ID_LoadGame ); Bind( wxEVT_MENU, &Frame::OnSolve, this, ID_Solve ); Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit ); Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_NewGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_SaveGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LoadGame ); Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Solve ); Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer ); canvas = new Canvas( this ); wxBoxSizer* boxSizer = new wxBoxSizer( wxVERTICAL ); boxSizer->Add( canvas, 1, wxGROW ); SetSizer( boxSizer ); timer.Start(1); } /*virtual*/ Frame::~Frame( void ) { } void Frame::OnExit( wxCommandEvent& event ) { if( wxGetApp().SetPuzzle( nullptr ) ) Close( true ); } void Frame::OnAbout( wxCommandEvent& event ) { wxAboutDialogInfo aboutDialogInfo; aboutDialogInfo.SetName( "Symmetry Group Madness" ); aboutDialogInfo.SetVersion( "1.0" ); aboutDialogInfo.SetDescription( "This program is free software and distributed under the MIT license." ); aboutDialogInfo.SetCopyright( "Copyright (C) 2016 Spencer T. Parkin <spencertparkin@gmail.com>" ); //aboutDialogInfo.SetWebSite( "http://spencerparkin.github.io/SymmetryGroupMadness" ); wxAboutBox( aboutDialogInfo ); } void Frame::OnTimer( wxTimerEvent& event ) { canvas->Refresh(); } void Frame::OnSolve( wxCommandEvent& event ) { Puzzle* puzzle = wxGetApp().GetPuzzle(); if( puzzle ) { timer.Stop(); if( puzzle->EnqueueSolution() ) { int solutionSize = ( int )puzzle->autoRotationQueue.size(); if( wxYES != wxMessageBox( wxString::Format( "A solution was found with %d moves. Run solution?", solutionSize ), "Solution found!", wxICON_EXCLAMATION | wxYES_NO, this ) ) puzzle->autoRotationQueue.clear(); } else { wxMessageBox( "Failed to find a solution. I suck.", "Solution not found.", wxICON_ERROR, this ); } timer.Start(1); } } void Frame::OnNewGame( wxCommandEvent& event ) { if( wxGetApp().SetPuzzle( nullptr ) ) { Puzzle* puzzle = new Puzzle(); puzzle->SetupLevel(1); wxGetApp().SetPuzzle( puzzle ); canvas->Refresh(); } } void Frame::OnSaveGame( wxCommandEvent& event ) { Puzzle* puzzle = wxGetApp().GetPuzzle(); if( puzzle ) puzzle->Save(); } void Frame::OnLoadGame( wxCommandEvent& event ) { wxGetApp().SetPuzzle( nullptr ); Puzzle* puzzle = new Puzzle(); if( !puzzle->Load() ) delete puzzle; else wxGetApp().SetPuzzle( puzzle ); canvas->Refresh(); } void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event ) { switch( event.GetId() ) { case ID_NewGame: { event.Enable( true ); break; } case ID_SaveGame: { Puzzle* puzzle = wxGetApp().GetPuzzle(); event.Enable( ( puzzle && puzzle->modified ) ? true : false ); break; } case ID_LoadGame: { event.Enable( true ); break; } case ID_Solve: { Puzzle* puzzle = wxGetApp().GetPuzzle(); event.Enable( puzzle && !puzzle->GetPermutation().IsIdentity() ); break; } } } // Frame.cpp <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // 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 // // https://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. // IREE source.mlir -> execution output test runner. // This is meant to be called from LIT for FileCheck tests, and tries to match // the interface of mlir-opt (featuring -split-input-file, etc) so it's easier // to work with there. If you want a more generalized runner for standalone // precompiled IREE modules use //third_party/iree/tools:run_module. // // By default all exported functions in the module will be run in order. // All input values, provided via -input-values, will be passed to the // functions (this means all input signatures must match). Results from the // executed functions will be printed to stdout for checking. // Use -output_types to set the function output data types, which like args will // be used for all functions executed. // // Example input: // // RUN: iree-run %s | FileCheck %s // // CHECK-LABEL: @foo // // CHECK: 1xf32: 2 // func @foo() -> memref<f32> attributes {iree.module.export} { // %0 = "iree.constant"() {value: dense<tensor<f32>, 2.0>} : () -> memref<f32> // return %0 : memref<f32> // } #include <iostream> #include "absl/flags/flag.h" #include "absl/strings/numbers.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "iree/base/init.h" #include "iree/base/source_location.h" #include "iree/base/status.h" #include "iree/compiler/Translation/Sequencer/SequencerModuleTranslation.h" #include "iree/hal/buffer_view_string_util.h" #include "iree/hal/driver_registry.h" #include "iree/rt/context.h" #include "iree/rt/debug/debug_server_flags.h" #include "iree/rt/instance.h" #include "iree/rt/invocation.h" #include "iree/rt/module.h" #include "iree/rt/module_printer.h" #include "iree/schemas/module_def_generated.h" #include "iree/vm/sequencer_module.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/SourceMgr.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Function.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/Parser.h" #include "mlir/Support/FileUtilities.h" ABSL_FLAG(bool, split_input_file, true, "Split the input file into multiple modules."); ABSL_FLAG(std::string, target_backends, "", "Comma-separated list of target backends to translate executables " "into. Omit to translate using all linked-in backend translators."); ABSL_FLAG( bool, export_all, true, "Automatically add the iree.module.export attribute to all functions."); ABSL_FLAG(std::string, input_values, "", "Input shapes and optional values."); ABSL_FLAG(std::string, output_types, "", "Output data types (comma delimited list of b/i/u/f for " "binary/signed int/unsigned int/float)."); // TODO(benvanik): is there a more canonical flag we can use? ABSL_FLAG(bool, print_mlir, true, "Prints MLIR IR during translation."); ABSL_FLAG(bool, print_bytecode, false, "Prints IREE bytecode after translation."); ABSL_FLAG(bool, run, true, "Option to run the file. Setting it to false just compiles it."); namespace iree { namespace { using ::iree::hal::BufferView; using ::iree::rt::Function; using ::iree::rt::Module; // Returns a driver name capable of handling input from the given backend. std::string BackendToDriverName(std::string backend) { size_t dash = backend.find('-'); if (dash == std::string::npos) { return backend; } else { return backend.substr(0, dash); } } // Prepares a module for evaluation by running MLIR import and IREE translation. StatusOr<ref_ptr<Module>> PrepareModule( std::string target_backend, std::unique_ptr<llvm::MemoryBuffer> file_buffer) { mlir::MLIRContext context; // Parse input MLIR module. llvm::SourceMgr source_mgr; source_mgr.AddNewSourceBuffer(std::move(file_buffer), llvm::SMLoc()); mlir::OwningModuleRef mlir_module = mlir::parseSourceFile(source_mgr, &context); if (absl::GetFlag(FLAGS_export_all)) { for (auto function : mlir_module->getOps<mlir::FuncOp>()) { function.setAttr("iree.module.export", mlir::UnitAttr::get(&context)); } } // Translate from MLIR to IREE bytecode. mlir::iree_compiler::ModuleTranslationOptions options; options.print_mlir = absl::GetFlag(FLAGS_print_mlir); options.target_backends = {target_backend}; auto iree_module_bytes = mlir::iree_compiler::translateMlirToIreeSequencerModule(mlir_module.get(), options); if (iree_module_bytes.empty()) { return iree::InternalErrorBuilder(IREE_LOC) << "Error translating MLIR to an IREE sequencer module"; } if (absl::GetFlag(FLAGS_print_mlir)) { mlir_module->dump(); } // Wrap module in a file handle. ASSIGN_OR_RETURN(auto iree_module_file, vm::ModuleFile::FromBuffer(ModuleDefIdentifier(), std::move(iree_module_bytes))); return vm::SequencerModule::FromFile(std::move(iree_module_file)); } // Parses a list of input shapes and values from a string of newline-separated // inputs. Expects the contents to have one value per line with each value // listed as // [shape]xtype=[value] // Example: // 4x4xi8=0,1,2,3 StatusOr<std::vector<BufferView>> ParseInputsFromFlags( hal::Allocator* allocator) { std::string file_contents = absl::StrReplaceAll(absl::GetFlag(FLAGS_input_values), {{"\\n", "\n"}}); std::vector<BufferView> inputs; for (const auto& line : absl::StrSplit(file_contents, '\n', absl::SkipWhitespace())) { ASSIGN_OR_RETURN(auto input, hal::ParseBufferViewFromString(line, allocator)); inputs.push_back(input); } return inputs; } // Outputs all results from the function to stdout in IREE BufferView format. Status OutputFunctionResults(const Function& function, absl::Span<BufferView> results) { std::vector<std::string> output_types = absl::StrSplit(absl::GetFlag(FLAGS_output_types), absl::ByAnyChar(", "), absl::SkipWhitespace()); if (!output_types.empty() && output_types.size() != results.size()) { return InvalidArgumentErrorBuilder(IREE_LOC) << "--output_types= specified but has " << output_types.size() << " types when the function returns " << results.size(); } for (int i = 0; i < results.size(); ++i) { const auto& result = results[i]; auto print_mode = hal::BufferViewPrintMode::kFloatingPoint; if (!output_types.empty()) { ASSIGN_OR_RETURN(print_mode, hal::ParseBufferViewPrintMode(output_types[i])); } ASSIGN_OR_RETURN(auto result_str, hal::PrintBufferViewToString(result, print_mode, 1024)); LOG(INFO) << "result[" << i << "]: " << result.buffer->DebugString(); std::cout << result_str << "\n"; } return OkStatus(); } // Evaluates a single function in its own fiber, printing the results to stdout. Status EvaluateFunction(const ref_ptr<rt::Context>& context, hal::Allocator* allocator, const Function& function) { std::cout << "EXEC @" << function.name() << std::endl; // Create invocation that will perform the execution. ASSIGN_OR_RETURN(auto arguments, ParseInputsFromFlags(allocator)); ASSIGN_OR_RETURN( auto invocation, rt::Invocation::Create(add_ref(context), function, make_ref<rt::Policy>(), {}, absl::MakeConstSpan(arguments))); // Wait until invocation completes. RETURN_IF_ERROR(invocation->Await(absl::InfiniteFuture())); // Print outputs. ASSIGN_OR_RETURN(auto results, invocation->ConsumeResults()); RETURN_IF_ERROR(OutputFunctionResults(function, absl::MakeSpan(results))); return OkStatus(); } // Evaluates all exported functions within given module. Status EvaluateFunctions(absl::string_view target_backend, ref_ptr<Module> module) { // Create the context we'll use for this (ensuring that we can't interfere // with other running evaluations, such as when in a multithreaded test // runner). ASSIGN_OR_RETURN(auto debug_server, rt::debug::CreateDebugServerFromFlags()); auto instance = make_ref<rt::Instance>(std::move(debug_server)); ASSIGN_OR_RETURN(auto driver, hal::DriverRegistry::shared_registry()->Create( target_backend)); ASSIGN_OR_RETURN(auto device, driver->CreateDefaultDevice()); RETURN_IF_ERROR(instance->device_manager()->RegisterDevice(device)); if (absl::GetFlag(FLAGS_print_bytecode)) { RETURN_IF_ERROR(rt::PrintModuleToStream( *module, rt::PrintModuleFlag::kDisassemble, &std::cout)); } // Evaluate all exported functions. auto policy = make_ref<rt::Policy>(); for (int i = 0; i < module->signature().export_function_count(); ++i) { // Setup a new context for this invocation. auto context = make_ref<rt::Context>(add_ref(instance), add_ref(policy)); RETURN_IF_ERROR(context->RegisterModule(add_ref(module))); // Invoke the function and print results. ASSIGN_OR_RETURN(auto function, module->LookupFunctionByOrdinal( rt::Function::Linkage::kExport, i)); RETURN_IF_ERROR(EvaluateFunction(context, device->allocator(), function)); } RETURN_IF_ERROR(instance->device_manager()->UnregisterDevice(device.get())); device.reset(); driver.reset(); return OkStatus(); } // Translates and runs a single LLVM file buffer. Status EvaluateFile(std::unique_ptr<llvm::MemoryBuffer> file_buffer) { std::vector<std::string> target_backends; if (absl::GetFlag(FLAGS_target_backends).empty()) { target_backends = hal::DriverRegistry::shared_registry()->EnumerateAvailableDrivers(); } else { // We need to map specific backends names to drivers (like 'vulkan-spirv' to // the driver 'vulkan'). target_backends = absl::StrSplit(absl::GetFlag(FLAGS_target_backends), ','); } for (auto target_backend : target_backends) { // Prepare the module for execution and evaluate it. auto cloned_file_buffer = llvm::MemoryBuffer::getMemBufferCopy( file_buffer->getBuffer(), file_buffer->getBufferIdentifier()); ASSIGN_OR_RETURN(auto module, PrepareModule(target_backend + '*', std::move(cloned_file_buffer))); if (!absl::GetFlag(FLAGS_run)) { continue; } RETURN_IF_ERROR(EvaluateFunctions(BackendToDriverName(target_backend), std::move(module))); } return OkStatus(); } // Runs the given .mlir file based on the current flags. Status RunFile(std::string mlir_filename) { // Load input file/from stdin. std::string error_message; auto file = mlir::openInputFile(mlir_filename, &error_message); if (!file) { return NotFoundErrorBuilder(IREE_LOC) << "Unable to open input file " << mlir_filename << ": " << error_message; } if (!absl::GetFlag(FLAGS_split_input_file)) { // Use entire buffer as a single module. return EvaluateFile(std::move(file)); } // Split the buffer into separate modules and evaluate independently. // This matches the -split-input-file arg to mlir-opt. const char kSplitMarker[] = "// -----\n"; auto* full_buffer = file.get(); llvm::SmallVector<llvm::StringRef, 8> source_buffers; full_buffer->getBuffer().split(source_buffers, kSplitMarker); // Add the original buffer to the source manager. llvm::SourceMgr fileSourceMgr; fileSourceMgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc()); // Process each chunk in turn. Only return the first error (but log all). Status any_failure; for (auto& sub_source_buffer : source_buffers) { auto split_loc = llvm::SMLoc::getFromPointer(sub_source_buffer.data()); unsigned split_line = fileSourceMgr.getLineAndColumn(split_loc).first; auto sub_buffer = llvm::MemoryBuffer::getMemBufferCopy( sub_source_buffer, full_buffer->getBufferIdentifier() + llvm::Twine(" split at line #") + llvm::Twine(split_line)); auto sub_failure = EvaluateFile(std::move(sub_buffer)); if (!sub_failure.ok()) { LOG(ERROR) << sub_failure; if (any_failure.ok()) { any_failure = std::move(sub_failure); } } } return any_failure; } } // namespace extern "C" int main(int argc, char** argv) { InitializeEnvironment(&argc, &argv); if (argc < 2) { LOG(ERROR) << "Must supply an input .mlir file."; return 1; } auto status = RunFile(argv[1]); if (!status.ok()) { std::cerr << "ERROR running file (" << argv[1] << "): " << status << "\n"; } QCHECK_OK(status); return 0; } } // namespace iree <commit_msg>Rework run-mlir-iree failure logic to fail-safe.<commit_after>// Copyright 2019 Google LLC // // 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 // // https://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. // IREE source.mlir -> execution output test runner. // This is meant to be called from LIT for FileCheck tests, and tries to match // the interface of mlir-opt (featuring -split-input-file, etc) so it's easier // to work with there. If you want a more generalized runner for standalone // precompiled IREE modules use //third_party/iree/tools:run_module. // // By default all exported functions in the module will be run in order. // All input values, provided via -input-values, will be passed to the // functions (this means all input signatures must match). Results from the // executed functions will be printed to stdout for checking. // Use -output_types to set the function output data types, which like args will // be used for all functions executed. // // Example input: // // RUN: iree-run %s | FileCheck %s // // CHECK-LABEL: @foo // // CHECK: 1xf32: 2 // func @foo() -> memref<f32> attributes {iree.module.export} { // %0 = "iree.constant"() {value: dense<tensor<f32>, 2.0>} : () -> memref<f32> // return %0 : memref<f32> // } #include <iostream> #include "absl/flags/flag.h" #include "absl/strings/numbers.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "iree/base/init.h" #include "iree/base/source_location.h" #include "iree/base/status.h" #include "iree/compiler/Translation/Sequencer/SequencerModuleTranslation.h" #include "iree/hal/buffer_view_string_util.h" #include "iree/hal/driver_registry.h" #include "iree/rt/context.h" #include "iree/rt/debug/debug_server_flags.h" #include "iree/rt/instance.h" #include "iree/rt/invocation.h" #include "iree/rt/module.h" #include "iree/rt/module_printer.h" #include "iree/schemas/module_def_generated.h" #include "iree/vm/sequencer_module.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/SourceMgr.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Function.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/Parser.h" #include "mlir/Support/FileUtilities.h" ABSL_FLAG(bool, split_input_file, true, "Split the input file into multiple modules."); ABSL_FLAG(std::string, target_backends, "", "Comma-separated list of target backends to translate executables " "into. Omit to translate using all linked-in backend translators."); ABSL_FLAG( bool, export_all, true, "Automatically add the iree.module.export attribute to all functions."); ABSL_FLAG(std::string, input_values, "", "Input shapes and optional values."); ABSL_FLAG(std::string, output_types, "", "Output data types (comma delimited list of b/i/u/f for " "binary/signed int/unsigned int/float)."); // TODO(benvanik): is there a more canonical flag we can use? ABSL_FLAG(bool, print_mlir, true, "Prints MLIR IR during translation."); ABSL_FLAG(bool, print_bytecode, false, "Prints IREE bytecode after translation."); ABSL_FLAG(bool, run, true, "Option to run the file. Setting it to false just compiles it."); namespace iree { namespace { using ::iree::hal::BufferView; using ::iree::rt::Function; using ::iree::rt::Module; // Returns a driver name capable of handling input from the given backend. std::string BackendToDriverName(std::string backend) { size_t dash = backend.find('-'); if (dash == std::string::npos) { return backend; } else { return backend.substr(0, dash); } } // Prepares a module for evaluation by running MLIR import and IREE translation. StatusOr<ref_ptr<Module>> PrepareModule( std::string target_backend, std::unique_ptr<llvm::MemoryBuffer> file_buffer) { mlir::MLIRContext context; // Parse input MLIR module. llvm::SourceMgr source_mgr; source_mgr.AddNewSourceBuffer(std::move(file_buffer), llvm::SMLoc()); mlir::OwningModuleRef mlir_module = mlir::parseSourceFile(source_mgr, &context); if (absl::GetFlag(FLAGS_export_all)) { for (auto function : mlir_module->getOps<mlir::FuncOp>()) { function.setAttr("iree.module.export", mlir::UnitAttr::get(&context)); } } // Translate from MLIR to IREE bytecode. mlir::iree_compiler::ModuleTranslationOptions options; options.print_mlir = absl::GetFlag(FLAGS_print_mlir); options.target_backends = {target_backend}; auto iree_module_bytes = mlir::iree_compiler::translateMlirToIreeSequencerModule(mlir_module.get(), options); if (iree_module_bytes.empty()) { return iree::InternalErrorBuilder(IREE_LOC) << "Error translating MLIR to an IREE sequencer module"; } if (absl::GetFlag(FLAGS_print_mlir)) { mlir_module->dump(); } // Wrap module in a file handle. ASSIGN_OR_RETURN(auto iree_module_file, vm::ModuleFile::FromBuffer(ModuleDefIdentifier(), std::move(iree_module_bytes))); return vm::SequencerModule::FromFile(std::move(iree_module_file)); } // Parses a list of input shapes and values from a string of newline-separated // inputs. Expects the contents to have one value per line with each value // listed as // [shape]xtype=[value] // Example: // 4x4xi8=0,1,2,3 StatusOr<std::vector<BufferView>> ParseInputsFromFlags( hal::Allocator *allocator) { std::string file_contents = absl::StrReplaceAll(absl::GetFlag(FLAGS_input_values), {{"\\n", "\n"}}); std::vector<BufferView> inputs; for (const auto &line : absl::StrSplit(file_contents, '\n', absl::SkipWhitespace())) { ASSIGN_OR_RETURN(auto input, hal::ParseBufferViewFromString(line, allocator)); inputs.push_back(input); } return inputs; } // Outputs all results from the function to stdout in IREE BufferView format. Status OutputFunctionResults(const Function &function, absl::Span<BufferView> results) { std::vector<std::string> output_types = absl::StrSplit(absl::GetFlag(FLAGS_output_types), absl::ByAnyChar(", "), absl::SkipWhitespace()); if (!output_types.empty() && output_types.size() != results.size()) { return InvalidArgumentErrorBuilder(IREE_LOC) << "--output_types= specified but has " << output_types.size() << " types when the function returns " << results.size(); } for (int i = 0; i < results.size(); ++i) { const auto &result = results[i]; auto print_mode = hal::BufferViewPrintMode::kFloatingPoint; if (!output_types.empty()) { ASSIGN_OR_RETURN(print_mode, hal::ParseBufferViewPrintMode(output_types[i])); } ASSIGN_OR_RETURN(auto result_str, hal::PrintBufferViewToString(result, print_mode, 1024)); LOG(INFO) << "result[" << i << "]: " << result.buffer->DebugString(); std::cout << result_str << "\n"; } return OkStatus(); } // Evaluates a single function in its own fiber, printing the results to stdout. Status EvaluateFunction(const ref_ptr<rt::Context> &context, hal::Allocator *allocator, const Function &function) { std::cout << "EXEC @" << function.name() << std::endl; // Create invocation that will perform the execution. ASSIGN_OR_RETURN(auto arguments, ParseInputsFromFlags(allocator)); ASSIGN_OR_RETURN( auto invocation, rt::Invocation::Create(add_ref(context), function, make_ref<rt::Policy>(), {}, absl::MakeConstSpan(arguments))); // Wait until invocation completes. RETURN_IF_ERROR(invocation->Await(absl::InfiniteFuture())); // Print outputs. ASSIGN_OR_RETURN(auto results, invocation->ConsumeResults()); RETURN_IF_ERROR(OutputFunctionResults(function, absl::MakeSpan(results))); return OkStatus(); } // Evaluates all exported functions within given module. Status EvaluateFunctions(absl::string_view target_backend, ref_ptr<Module> module) { // Create the context we'll use for this (ensuring that we can't interfere // with other running evaluations, such as when in a multithreaded test // runner). ASSIGN_OR_RETURN(auto debug_server, rt::debug::CreateDebugServerFromFlags()); auto instance = make_ref<rt::Instance>(std::move(debug_server)); ASSIGN_OR_RETURN(auto driver, hal::DriverRegistry::shared_registry()->Create( target_backend)); ASSIGN_OR_RETURN(auto device, driver->CreateDefaultDevice()); RETURN_IF_ERROR(instance->device_manager()->RegisterDevice(device)); if (absl::GetFlag(FLAGS_print_bytecode)) { RETURN_IF_ERROR(rt::PrintModuleToStream( *module, rt::PrintModuleFlag::kDisassemble, &std::cout)); } // Evaluate all exported functions. auto policy = make_ref<rt::Policy>(); auto run_function = [&](int ordinal) -> Status { // Setup a new context for this invocation. auto context = make_ref<rt::Context>(add_ref(instance), add_ref(policy)); RETURN_IF_ERROR(context->RegisterModule(add_ref(module))); // Invoke the function and print results. ASSIGN_OR_RETURN(auto function, module->LookupFunctionByOrdinal( rt::Function::Linkage::kExport, ordinal)); RETURN_IF_ERROR(EvaluateFunction(context, device->allocator(), function)); return OkStatus(); }; Status evaluate_status = OkStatus(); for (int i = 0; i < module->signature().export_function_count(); ++i) { evaluate_status = run_function(i); if (!evaluate_status.ok()) { break; } } RETURN_IF_ERROR(instance->device_manager()->UnregisterDevice(device.get())); device.reset(); driver.reset(); return evaluate_status; } // Translates and runs a single LLVM file buffer. Status EvaluateFile(std::unique_ptr<llvm::MemoryBuffer> file_buffer) { std::vector<std::string> target_backends; if (absl::GetFlag(FLAGS_target_backends).empty()) { target_backends = hal::DriverRegistry::shared_registry()->EnumerateAvailableDrivers(); } else { // We need to map specific backends names to drivers (like 'vulkan-spirv' to // the driver 'vulkan'). target_backends = absl::StrSplit(absl::GetFlag(FLAGS_target_backends), ','); } for (auto target_backend : target_backends) { // Prepare the module for execution and evaluate it. auto cloned_file_buffer = llvm::MemoryBuffer::getMemBufferCopy( file_buffer->getBuffer(), file_buffer->getBufferIdentifier()); ASSIGN_OR_RETURN(auto module, PrepareModule(target_backend + '*', std::move(cloned_file_buffer))); if (!absl::GetFlag(FLAGS_run)) { continue; } RETURN_IF_ERROR(EvaluateFunctions(BackendToDriverName(target_backend), std::move(module))); } return OkStatus(); } // Runs the given .mlir file based on the current flags. Status RunFile(std::string mlir_filename) { // Load input file/from stdin. std::string error_message; auto file = mlir::openInputFile(mlir_filename, &error_message); if (!file) { return NotFoundErrorBuilder(IREE_LOC) << "Unable to open input file " << mlir_filename << ": " << error_message; } if (!absl::GetFlag(FLAGS_split_input_file)) { // Use entire buffer as a single module. return EvaluateFile(std::move(file)); } // Split the buffer into separate modules and evaluate independently. // This matches the -split-input-file arg to mlir-opt. const char kSplitMarker[] = "// -----\n"; auto *full_buffer = file.get(); llvm::SmallVector<llvm::StringRef, 8> source_buffers; full_buffer->getBuffer().split(source_buffers, kSplitMarker); // Add the original buffer to the source manager. llvm::SourceMgr fileSourceMgr; fileSourceMgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc()); // Process each chunk in turn. Only return the first error (but log all). Status any_failure; for (auto &sub_source_buffer : source_buffers) { auto split_loc = llvm::SMLoc::getFromPointer(sub_source_buffer.data()); unsigned split_line = fileSourceMgr.getLineAndColumn(split_loc).first; auto sub_buffer = llvm::MemoryBuffer::getMemBufferCopy( sub_source_buffer, full_buffer->getBufferIdentifier() + llvm::Twine(" split at line #") + llvm::Twine(split_line)); auto sub_failure = EvaluateFile(std::move(sub_buffer)); if (!sub_failure.ok()) { LOG(ERROR) << sub_failure; if (any_failure.ok()) { any_failure = std::move(sub_failure); } } } return any_failure; } } // namespace extern "C" int main(int argc, char **argv) { InitializeEnvironment(&argc, &argv); if (argc < 2) { LOG(ERROR) << "Must supply an input .mlir file."; return 1; } auto status = RunFile(argv[1]); if (!status.ok()) { std::cerr << "ERROR running file (" << argv[1] << "): " << status << "\n"; return 1; } return 0; } } // namespace iree <|endoftext|>
<commit_before>#include "boost/filesystem.hpp" #include "boost/program_options.hpp" #include <assert.h> #include "itkCenteredSimilarity2DTransform.h" // my files #include "Stack.hpp" #include "NormalizeImages.hpp" #include "StackInitializers.hpp" #include "RegistrationBuilder.hpp" #include "StackAligner.hpp" #include "StackIOHelpers.hpp" #include "IOHelpers.hpp" #include "Dirs.hpp" #include "Parameters.hpp" #include "StackTransforms.hpp" #include "OptimizerConfig.hpp" #include "Profiling.hpp" namespace po = boost::program_options; using namespace boost::filesystem; po::variables_map parse_arguments(int argc, char *argv[]); int main(int argc, char *argv[]) { // Parse command line arguments po::variables_map vm = parse_arguments(argc, argv); // Process command line arguments Dirs::SetDataSet( vm["dataSet"].as<string>() ); Dirs::SetOutputDirName( vm["outputDir"].as<string>() ); string blockDir = vm.count("blockDir") ? vm["blockDir"].as<string>() + "/" : Dirs::BlockDir(); string sliceDir = vm.count("sliceDir") ? vm["sliceDir"].as<string>() + "/" : Dirs::SliceDir(); const bool writeImages = vm["writeImages"].as<bool>(); // basenames is either single name from command line // or list from config file vector< string > basenames = vm.count("slice") ? vector< string >(1, vm["slice"].as<string>()) : basenames = getFileNames(Dirs::ImageList()); // prepend directory to each filename in list vector< string > LoResFilePaths = constructPaths(blockDir, basenames, ".bmp"); vector< string > HiResFilePaths = constructPaths(sliceDir, basenames, ".bmp"); // initialise stack objects with correct spacings, sizes etc typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType; StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFilePaths); StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFilePaths); normalizeImages< StackType >(LoResImages); normalizeImages< StackType >(HiResImages); boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages); boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages); // Assert stacks have the same number of slices assert(LoResStack->GetSize() == HiResStack->GetSize()); // initialize stacks' transforms so that 2D images line up at their centres. if( vm.count("blockDir") ) // if working with segmentations already in the right coordinate system, // no need to apply transforms StackTransforms::InitializeToIdentity(*LoResStack); else { // if working from the original images, apply the necessary translation StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") ); ApplyAdjustments( *LoResStack, LoResFilePaths, Dirs::ConfigDir() + "LoRes_adjustments/"); } // Generate fixed images to register against LoResStack->updateVolumes(); if( vm["pca"].as<bool>() ) { // update both volumes so that their principal components align StackTransforms::InitializeWithPCA(*LoResStack, *HiResStack); } else { StackTransforms::InitializeToCommonCentre( *HiResStack ); StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack ); } // create output dir before write operations create_directory( Dirs::ResultsDir() ); if( writeImages ) { writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" ); } // initialise registration framework typedef RegistrationBuilder< StackType > RegistrationBuilderType; RegistrationBuilderType registrationBuilder; RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration(); StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration); // Scale parameter space OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() ); // Add time and memory probes itkProbesCreate(); // perform centered rigid 2D registration on each pair of slices itkProbesStart( "Aligning stacks" ); stackAligner.Update(); itkProbesStop( "Aligning stacks" ); // Report the time and memory taken by the registration itkProbesReport( std::cout ); // write rigid transforms if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" ); // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" ); } StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack); // Scale parameter space OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() ); // perform similarity rigid 2D registration stackAligner.Update(); // write similarity transforms if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" ); } // repeat registration with affine transform StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack); OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() ); stackAligner.Update(); if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" ); // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" ); } // Update LoRes as the masks might have shrunk LoResStack->updateVolumes(); // persist mask numberOfTimesTooBig and final metric values saveVectorToFiles(HiResStack->GetNumberOfTimesTooBig(), "number_of_times_too_big", basenames ); saveVectorToFiles(stackAligner.GetFinalMetricValues(), "metric_values", basenames ); // write transforms to directories labeled by both ds ratios create_directory(Dirs::LoResTransformsDir()); create_directory(Dirs::HiResTransformsDir()); Save(*LoResStack, LoResFilePaths, Dirs::LoResTransformsDir()); Save(*HiResStack, HiResFilePaths, Dirs::HiResTransformsDir()); return EXIT_SUCCESS; } po::variables_map parse_arguments(int argc, char *argv[]) { // Declare the supported options. po::options_description opts("Options"); opts.add_options() ("help,h", "produce help message") ("dataSet", po::value<string>(), "which rat to use") ("outputDir", po::value<string>(), "directory to place results") ("slice", po::value<string>(), "optional individual slice to register") ("blockDir", po::value<string>(), "directory containing LoRes originals") ("sliceDir", po::value<string>(), "directory containing HiRes originals") ("writeImages", po::bool_switch(), "output images and masks") ("pca", po::bool_switch(), "align principal axes of HiRes images with LoRes") ; po::positional_options_description p; p.add("dataSet", 1) .add("outputDir", 1) .add("slice", 1); // parse command line po::variables_map vm; try { po::store(po::command_line_parser(argc, argv) .options(opts) .positional(p) .run(), vm); } catch (std::exception& e) { cerr << "caught command-line parsing error" << endl; std::cerr << e.what() << std::endl; exit(EXIT_FAILURE); } po::notify(vm); // if help is specified, or positional args aren't present if (vm.count("help") || !vm.count("dataSet") || !vm.count("outputDir")) { cerr << "Usage: " << argv[0] << " [--dataSet=]RatX [--outputDir=]my_dir [Options]" << endl << endl; cerr << opts << "\n"; exit(EXIT_FAILURE); } return vm; } <commit_msg>Superfluous initialisation.<commit_after>#include "boost/filesystem.hpp" #include "boost/program_options.hpp" #include <assert.h> #include "itkCenteredSimilarity2DTransform.h" // my files #include "Stack.hpp" #include "NormalizeImages.hpp" #include "StackInitializers.hpp" #include "RegistrationBuilder.hpp" #include "StackAligner.hpp" #include "StackIOHelpers.hpp" #include "IOHelpers.hpp" #include "Dirs.hpp" #include "Parameters.hpp" #include "StackTransforms.hpp" #include "OptimizerConfig.hpp" #include "Profiling.hpp" namespace po = boost::program_options; using namespace boost::filesystem; po::variables_map parse_arguments(int argc, char *argv[]); int main(int argc, char *argv[]) { // Parse command line arguments po::variables_map vm = parse_arguments(argc, argv); // Process command line arguments Dirs::SetDataSet( vm["dataSet"].as<string>() ); Dirs::SetOutputDirName( vm["outputDir"].as<string>() ); string blockDir = vm.count("blockDir") ? vm["blockDir"].as<string>() + "/" : Dirs::BlockDir(); string sliceDir = vm.count("sliceDir") ? vm["sliceDir"].as<string>() + "/" : Dirs::SliceDir(); const bool writeImages = vm["writeImages"].as<bool>(); // basenames is either single name from command line // or list from config file vector< string > basenames = vm.count("slice") ? vector< string >(1, vm["slice"].as<string>()) : getFileNames(Dirs::ImageList()); // prepend directory to each filename in list vector< string > LoResFilePaths = constructPaths(blockDir, basenames, ".bmp"); vector< string > HiResFilePaths = constructPaths(sliceDir, basenames, ".bmp"); // initialise stack objects with correct spacings, sizes etc typedef Stack< float, itk::ResampleImageFilter, itk::LinearInterpolateImageFunction > StackType; StackType::SliceVectorType LoResImages = readImages< StackType >(LoResFilePaths); StackType::SliceVectorType HiResImages = readImages< StackType >(HiResFilePaths); normalizeImages< StackType >(LoResImages); normalizeImages< StackType >(HiResImages); boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImages); boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImages); // Assert stacks have the same number of slices assert(LoResStack->GetSize() == HiResStack->GetSize()); // initialize stacks' transforms so that 2D images line up at their centres. if( vm.count("blockDir") ) // if working with segmentations already in the right coordinate system, // no need to apply transforms StackTransforms::InitializeToIdentity(*LoResStack); else { // if working from the original images, apply the necessary translation StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") ); ApplyAdjustments( *LoResStack, LoResFilePaths, Dirs::ConfigDir() + "LoRes_adjustments/"); } // Generate fixed images to register against LoResStack->updateVolumes(); if( vm["pca"].as<bool>() ) { // update both volumes so that their principal components align StackTransforms::InitializeWithPCA(*LoResStack, *HiResStack); } else { StackTransforms::InitializeToCommonCentre( *HiResStack ); StackTransforms::SetMovingStackCenterWithFixedStack( *LoResStack, *HiResStack ); } // create output dir before write operations create_directory( Dirs::ResultsDir() ); if( writeImages ) { writeImage< StackType::VolumeType >( LoResStack->GetVolume(), Dirs::ResultsDir() + "LoResStack.mha" ); } // initialise registration framework typedef RegistrationBuilder< StackType > RegistrationBuilderType; RegistrationBuilderType registrationBuilder; RegistrationBuilderType::RegistrationType::Pointer registration = registrationBuilder.GetRegistration(); StackAligner< StackType > stackAligner(*LoResStack, *HiResStack, registration); // Scale parameter space OptimizerConfig::SetOptimizerScalesForCenteredRigid2DTransform( registration->GetOptimizer() ); // Add time and memory probes itkProbesCreate(); // perform centered rigid 2D registration on each pair of slices itkProbesStart( "Aligning stacks" ); stackAligner.Update(); itkProbesStop( "Aligning stacks" ); // Report the time and memory taken by the registration itkProbesReport( std::cout ); // write rigid transforms if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResRigidStack.mha" ); // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResRigidMask.mha" ); } StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredSimilarity2DTransform< double > >(*HiResStack); // Scale parameter space OptimizerConfig::SetOptimizerScalesForCenteredSimilarity2DTransform( registration->GetOptimizer() ); // perform similarity rigid 2D registration stackAligner.Update(); // write similarity transforms if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResSimilarityStack.mha" ); } // repeat registration with affine transform StackTransforms::InitializeFromCurrentTransforms< StackType, itk::CenteredAffineTransform< double, 2 > >(*HiResStack); OptimizerConfig::SetOptimizerScalesForCenteredAffineTransform( registration->GetOptimizer() ); stackAligner.Update(); if( writeImages ) { HiResStack->updateVolumes(); writeImage< StackType::VolumeType >( HiResStack->GetVolume(), Dirs::ResultsDir() + "HiResAffineStack.mha" ); // writeImage< StackType::MaskVolumeType >( HiResStack->Get3DMask()->GetImage(), Dirs::ResultsDir() + "HiResAffineMask.mha" ); } // Update LoRes as the masks might have shrunk LoResStack->updateVolumes(); // persist mask numberOfTimesTooBig and final metric values saveVectorToFiles(HiResStack->GetNumberOfTimesTooBig(), "number_of_times_too_big", basenames ); saveVectorToFiles(stackAligner.GetFinalMetricValues(), "metric_values", basenames ); // write transforms to directories labeled by both ds ratios create_directory(Dirs::LoResTransformsDir()); create_directory(Dirs::HiResTransformsDir()); Save(*LoResStack, LoResFilePaths, Dirs::LoResTransformsDir()); Save(*HiResStack, HiResFilePaths, Dirs::HiResTransformsDir()); return EXIT_SUCCESS; } po::variables_map parse_arguments(int argc, char *argv[]) { // Declare the supported options. po::options_description opts("Options"); opts.add_options() ("help,h", "produce help message") ("dataSet", po::value<string>(), "which rat to use") ("outputDir", po::value<string>(), "directory to place results") ("slice", po::value<string>(), "optional individual slice to register") ("blockDir", po::value<string>(), "directory containing LoRes originals") ("sliceDir", po::value<string>(), "directory containing HiRes originals") ("writeImages", po::bool_switch(), "output images and masks") ("pca", po::bool_switch(), "align principal axes of HiRes images with LoRes") ; po::positional_options_description p; p.add("dataSet", 1) .add("outputDir", 1) .add("slice", 1); // parse command line po::variables_map vm; try { po::store(po::command_line_parser(argc, argv) .options(opts) .positional(p) .run(), vm); } catch (std::exception& e) { cerr << "caught command-line parsing error" << endl; std::cerr << e.what() << std::endl; exit(EXIT_FAILURE); } po::notify(vm); // if help is specified, or positional args aren't present if (vm.count("help") || !vm.count("dataSet") || !vm.count("outputDir")) { cerr << "Usage: " << argv[0] << " [--dataSet=]RatX [--outputDir=]my_dir [Options]" << endl << endl; cerr << opts << "\n"; exit(EXIT_FAILURE); } return vm; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: proplinelistener.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:31:45 $ * * 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 _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ #define _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ #ifndef _STRING_HXX #include <tools/string.hxx> #endif //........................................................................ namespace pcr { //........................................................................ //==================================================================== class IPropertyLineListener { public: virtual void Clicked( const ::rtl::OUString& _rName, sal_Bool _bPrimary ) = 0; virtual void Commit( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Any& _rVal ) = 0; }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ <commit_msg>INTEGRATION: CWS oihelp (1.5.154); FILE MERGED 2006/11/13 14:34:00 fs 1.5.154.1: #i71485# PropertyControlObserver notifications<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: proplinelistener.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-13 12:03:09 $ * * 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 _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ #define _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ #ifndef _STRING_HXX #include <tools/string.hxx> #endif //........................................................................ namespace pcr { //........................................................................ //==================================================================== class IPropertyLineListener { public: virtual void Clicked( const ::rtl::OUString& _rName, sal_Bool _bPrimary ) = 0; virtual void Commit( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Any& _rVal ) = 0; }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_PROPLINELISTENER_HXX_ <|endoftext|>
<commit_before>/* * Copyright 2021 Google LLC * * 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 "fcp/client/engine/caching_error_reporter.h" #include <string> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "fcp/testing/testing.h" #include "tensorflow/lite/core/api/error_reporter.h" namespace fcp { namespace client { namespace engine { namespace { using ::testing::IsEmpty; TEST(CachingErrorReporterTest, CachingMultiple) { CachingErrorReporter reporter; std::string first_error = "Op a is not found."; static_cast<tflite::ErrorReporter*>(&reporter)->Report( "%s%d", first_error.c_str(), 1); std::string second_error = "Op b is not found."; static_cast<tflite::ErrorReporter*>(&reporter)->Report( "%s%d", second_error.c_str(), 2); EXPECT_THAT(reporter.GetFirstErrorMessage(), absl::StrCat(first_error, "1")); } TEST(CachingErrorReporterTest, Empty) { CachingErrorReporter reporter; EXPECT_THAT(reporter.GetFirstErrorMessage(), IsEmpty()); } } // anonymous namespace } // namespace engine } // namespace client } // namespace fcp <commit_msg>Automated rollback<commit_after>/* * Copyright 2021 Google LLC * * 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 "fcp/client/engine/caching_error_reporter.h" #include <string> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "fcp/testing/testing.h" #include "tensorflow/lite/core/api/error_reporter.h" namespace fcp { namespace client { namespace engine { namespace { using ::testing::IsEmpty; TEST(CachingErrorReporterTest, CachingMultiple) { CachingErrorReporter reporter; std::string first_error = "Op a is not found."; TF_LITE_REPORT_ERROR(&reporter, "%s%d", first_error.c_str(), 1); std::string second_error = "Op b is not found."; TF_LITE_REPORT_ERROR(&reporter, "%s%d", second_error.c_str(), 2); EXPECT_THAT(reporter.GetFirstErrorMessage(), absl::StrCat(first_error, "1")); } TEST(CachingErrorReporterTest, Empty) { CachingErrorReporter reporter; EXPECT_THAT(reporter.GetFirstErrorMessage(), IsEmpty()); } } // anonymous namespace } // namespace engine } // namespace client } // namespace fcp <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: addonstoolbarmanager.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:28:08 $ * * 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 __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_ #include <uielement/toolbarmanager.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class AddonsToolBarManager : public ToolBarManager { public: AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~AddonsToolBarManager(); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); virtual void RefreshImages(); void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar ); protected: DECL_LINK( Click, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Command, CommandEvent * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); private: struct AddonsParams { rtl::OUString aImageId; rtl::OUString aTarget; }; }; } #endif // __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.4.128); FILE MERGED 2005/09/05 13:05:29 rt 1.4.128.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addonstoolbarmanager.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:41:44 $ * * 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 __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ #define __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UILEMENT_TOOLBARMANAGER_HXX_ #include <uielement/toolbarmanager.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vcl/toolbox.hxx> namespace framework { class ToolBar; class AddonsToolBarManager : public ToolBarManager { public: AddonsToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const rtl::OUString& rResourceName, ToolBar* pToolBar ); virtual ~AddonsToolBarManager(); // XComponent void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException ); virtual void RefreshImages(); void FillToolbar( const com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonToolbar ); protected: DECL_LINK( Click, ToolBox * ); DECL_LINK( DoubleClick, ToolBox * ); DECL_LINK( Command, CommandEvent * ); DECL_LINK( Select, ToolBox * ); DECL_LINK( Highlight, ToolBox * ); DECL_LINK( Activate, ToolBox * ); DECL_LINK( Deactivate, ToolBox * ); DECL_LINK( StateChanged, StateChangedType* ); DECL_LINK( DataChanged, DataChangedEvent* ); private: struct AddonsParams { rtl::OUString aImageId; rtl::OUString aTarget; }; }; } #endif // __FRAMEWORK_UIELEMENT_ADDONSTOOLBARMANAGER_HXX_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtGui/QtGui> #include "../../shared/util.h" //TESTED_CLASS= //TESTED_FILES= QT_FORWARD_DECLARE_CLASS(QtTestEventThread) class tst_QColorDialog : public QObject { Q_OBJECT public: tst_QColorDialog(); virtual ~tst_QColorDialog(); #ifndef Q_WS_MAC public slots: void postKeyReturn(); private slots: void defaultOkButton(); #endif public slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: void native_activeModalWidget(); void task247349_alpha(); }; class TestNativeDialog : public QColorDialog { Q_OBJECT public: QWidget *m_activeModalWidget; TestNativeDialog(QWidget *parent = 0) : QColorDialog(parent), m_activeModalWidget(0) { QTimer::singleShot(1, this, SLOT(test_activeModalWidgetSignal())); } public slots: void test_activeModalWidgetSignal() { m_activeModalWidget = qApp->activeModalWidget(); } }; tst_QColorDialog::tst_QColorDialog() { } tst_QColorDialog::~tst_QColorDialog() { } void tst_QColorDialog::native_activeModalWidget() { // Check that QApplication::activeModalWidget retruns the // color dialog when it is executing, even when using a native // dialog: TestNativeDialog d; QTimer::singleShot(100, &d, SLOT(hide())); d.exec(); QVERIFY(&d == d.m_activeModalWidget); } void tst_QColorDialog::initTestCase() { } void tst_QColorDialog::cleanupTestCase() { } void tst_QColorDialog::init() { } void tst_QColorDialog::cleanup() { } #ifndef Q_WS_MAC //copied from QFontDialogTest void tst_QColorDialog::postKeyReturn() { QWidgetList list = QApplication::topLevelWidgets(); for (int i=0; i<list.count(); ++i) { QColorDialog *dialog = qobject_cast<QColorDialog *>(list[i]); if (dialog) { QTest::keyClick( list[i], Qt::Key_Return, Qt::NoModifier ); return; } } } void tst_QColorDialog::defaultOkButton() { bool ok = false; QTimer::singleShot(500, this, SLOT(postKeyReturn())); QColorDialog::getRgba(0xffffffff, &ok); QVERIFY(ok); } #endif void tst_QColorDialog::task247349_alpha() { QColorDialog dialog; dialog.setOption(QColorDialog::ShowAlphaChannel, true); int alpha = 0x17; dialog.setCurrentColor(QColor(0x01, 0x02, 0x03, alpha)); QCOMPARE(alpha, dialog.currentColor().alpha()); QCOMPARE(alpha, qAlpha(dialog.currentColor().rgba())); } QTEST_MAIN(tst_QColorDialog) #include "tst_qcolordialog.moc" <commit_msg>increase waiting time<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtGui/QtGui> #include "../../shared/util.h" //TESTED_CLASS= //TESTED_FILES= QT_FORWARD_DECLARE_CLASS(QtTestEventThread) class tst_QColorDialog : public QObject { Q_OBJECT public: tst_QColorDialog(); virtual ~tst_QColorDialog(); #ifndef Q_WS_MAC public slots: void postKeyReturn(); private slots: void defaultOkButton(); #endif public slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: void native_activeModalWidget(); void task247349_alpha(); }; class TestNativeDialog : public QColorDialog { Q_OBJECT public: QWidget *m_activeModalWidget; TestNativeDialog(QWidget *parent = 0) : QColorDialog(parent), m_activeModalWidget(0) { QTimer::singleShot(1, this, SLOT(test_activeModalWidgetSignal())); } public slots: void test_activeModalWidgetSignal() { m_activeModalWidget = qApp->activeModalWidget(); } }; tst_QColorDialog::tst_QColorDialog() { } tst_QColorDialog::~tst_QColorDialog() { } void tst_QColorDialog::native_activeModalWidget() { // Check that QApplication::activeModalWidget retruns the // color dialog when it is executing, even when using a native // dialog: TestNativeDialog d; QTimer::singleShot(1000, &d, SLOT(hide())); d.exec(); QVERIFY(&d == d.m_activeModalWidget); } void tst_QColorDialog::initTestCase() { } void tst_QColorDialog::cleanupTestCase() { } void tst_QColorDialog::init() { } void tst_QColorDialog::cleanup() { } #ifndef Q_WS_MAC //copied from QFontDialogTest void tst_QColorDialog::postKeyReturn() { QWidgetList list = QApplication::topLevelWidgets(); for (int i=0; i<list.count(); ++i) { QColorDialog *dialog = qobject_cast<QColorDialog *>(list[i]); if (dialog) { QTest::keyClick( list[i], Qt::Key_Return, Qt::NoModifier ); return; } } } void tst_QColorDialog::defaultOkButton() { bool ok = false; QTimer::singleShot(500, this, SLOT(postKeyReturn())); QColorDialog::getRgba(0xffffffff, &ok); QVERIFY(ok); } #endif void tst_QColorDialog::task247349_alpha() { QColorDialog dialog; dialog.setOption(QColorDialog::ShowAlphaChannel, true); int alpha = 0x17; dialog.setCurrentColor(QColor(0x01, 0x02, 0x03, alpha)); QCOMPARE(alpha, dialog.currentColor().alpha()); QCOMPARE(alpha, qAlpha(dialog.currentColor().rgba())); } QTEST_MAIN(tst_QColorDialog) #include "tst_qcolordialog.moc" <|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "CoreThread.h" #include "CoreContext.h" #include <boost/thread.hpp> CoreThread::CoreThread(const char* pName): ContextMember(pName), m_priority(ThreadPriority::Default), m_state(std::make_shared<State>()), m_lock(m_state->m_lock), m_canAccept(false), m_stateCondition(m_state->m_stateCondition) { } void CoreThread::DoRun(void) { ASSERT(m_running); // Make our own session current before we do anything else: CurrentContextPusher pusher(GetContext()); // Set the thread name no matter what: if(GetName()) SetCurrentThreadName(); // Now we wait for the thread to be good to go: try { Run(); } catch(dispatch_aborted_exception&) { // Okay, this is fine, a dispatcher is terminating--this is a normal way to // end a dispatcher loop. } catch(...) { try { // Ask that the enclosing context filter this exception, if possible: GetContext()->FilterException(); } catch(...) { // Generic exception, unhandled, we can't print anything off. CoreContext::DebugPrintCurrentExceptionInformation(); } // Signal shutdown on the enclosing context--cannot wait, if we wait we WILL deadlock GetContext()->SignalShutdown(false); } // Unconditionally shut off dispatch delivery: RejectDispatchDelivery(); try { // If we are asked to rundown while we still have elements in our dispatch queue, // we must try to process them: DispatchAllEvents(); } catch(...) { // We failed to run down the dispatch queue gracefully, we now need to abort it Abort(); } // Notify everyone that we're completed: boost::lock_guard<boost::mutex> lk(m_lock); m_stop = true; m_completed = true; m_running = false; // Notify other threads that we are done m_stateCondition.notify_all(); // Perform a manual notification of teardown listeners NotifyTeardownListeners(); // No longer running, we MUST release the thread pointer to ensure proper teardown order m_thisThread.detach(); } bool CoreThread::ShouldStop(void) const { shared_ptr<CoreContext> context = ContextMember::GetContext(); return m_stop || !context || context->IsShutdown(); } void CoreThread::ThreadSleep(long millisecond) { boost::this_thread::sleep(boost::posix_time::milliseconds(millisecond)); } bool CoreThread::DelayUntilCanAccept(void) { boost::unique_lock<boost::mutex> lk(m_lock); m_stateCondition.wait(lk, [this] {return ShouldStop() || CanAccept(); }); return !ShouldStop(); } bool CoreThread::Start(std::shared_ptr<Object> outstanding) { std::shared_ptr<CoreContext> context = m_context.lock(); if(!context) return false; { boost::lock_guard<boost::mutex> lk(m_lock); if(m_running) // Already running, short-circuit return true; // Currently running: m_running = true; m_stateCondition.notify_all(); } // Kick off a thread and return here m_thisThread = boost::thread( [this, outstanding] { this->DoRun(); } ); return true; } void CoreThread::Run() { AcceptDispatchDelivery(); while(!ShouldStop()) WaitForEvent(); } <commit_msg>State block is now extracted and held separately while the current context is released<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "CoreThread.h" #include "CoreContext.h" #include <boost/thread.hpp> CoreThread::CoreThread(const char* pName): ContextMember(pName), m_priority(ThreadPriority::Default), m_state(std::make_shared<State>()), m_lock(m_state->m_lock), m_canAccept(false), m_stateCondition(m_state->m_stateCondition) { } void CoreThread::DoRun(void) { ASSERT(m_running); // Make our own session current before we do anything else: CurrentContextPusher pusher(GetContext()); // Set the thread name no matter what: if(GetName()) SetCurrentThreadName(); // Now we wait for the thread to be good to go: try { Run(); } catch(dispatch_aborted_exception&) { // Okay, this is fine, a dispatcher is terminating--this is a normal way to // end a dispatcher loop. } catch(...) { try { // Ask that the enclosing context filter this exception, if possible: GetContext()->FilterException(); } catch(...) { // Generic exception, unhandled, we can't print anything off. CoreContext::DebugPrintCurrentExceptionInformation(); } // Signal shutdown on the enclosing context--cannot wait, if we wait we WILL deadlock GetContext()->SignalShutdown(false); } // Unconditionally shut off dispatch delivery: RejectDispatchDelivery(); try { // If we are asked to rundown while we still have elements in our dispatch queue, // we must try to process them: DispatchAllEvents(); } catch(...) { // We failed to run down the dispatch queue gracefully, we now need to abort it Abort(); } // Notify everyone that we're completed: boost::lock_guard<boost::mutex> lk(m_lock); m_stop = true; m_completed = true; m_running = false; // Perform a manual notification of teardown listeners NotifyTeardownListeners(); // No longer running, we MUST release the thread pointer to ensure proper teardown order m_thisThread.detach(); // Take a copy of our state condition shared pointer while we still hold a reference to // ourselves. This is the only member out of our collection of members that we actually // need to hold a reference to. auto state = m_state; // Release our hold on the context. After this point, we have to be VERY CAREFUL that we // don't try to refer to any of our own member variables, because our own object may have // already gone out of scope. [this] is potentially dangling. pusher.Pop(); // Notify other threads that we are done. At this point, any held references that might // still exist are held by entities other than ourselves. state->m_stateCondition.notify_all(); } bool CoreThread::ShouldStop(void) const { shared_ptr<CoreContext> context = ContextMember::GetContext(); return m_stop || !context || context->IsShutdown(); } void CoreThread::ThreadSleep(long millisecond) { boost::this_thread::sleep(boost::posix_time::milliseconds(millisecond)); } bool CoreThread::DelayUntilCanAccept(void) { boost::unique_lock<boost::mutex> lk(m_lock); m_stateCondition.wait(lk, [this] {return ShouldStop() || CanAccept(); }); return !ShouldStop(); } bool CoreThread::Start(std::shared_ptr<Object> outstanding) { std::shared_ptr<CoreContext> context = m_context.lock(); if(!context) return false; { boost::lock_guard<boost::mutex> lk(m_lock); if(m_running) // Already running, short-circuit return true; // Currently running: m_running = true; m_stateCondition.notify_all(); } // Kick off a thread and return here m_thisThread = boost::thread( [this, outstanding] { this->DoRun(); } ); return true; } void CoreThread::Run() { AcceptDispatchDelivery(); while(!ShouldStop()) WaitForEvent(); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Plugins * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Binding_BaseObject.h" #include "Binding_Base.h" #include "PythonFactory.h" using namespace sofa::core::objectmodel; extern "C" PyObject * BaseObject_init(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->init(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_bwdInit(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->bwdInit(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_reinit(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->reinit(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_storeResetState(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->storeResetState(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_reset(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->reset(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_cleanup(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->cleanup(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_getContext(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return sofa::PythonFactory::toPython(obj->getContext()); } extern "C" PyObject * BaseObject_getMaster(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return sofa::PythonFactory::toPython(obj->getMaster()); } extern "C" PyObject * BaseObject_setSrc(PyObject *self, PyObject * args) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); char *valueString; PyObject *pyLoader; if (!PyArg_ParseTuple(args, "sO",&valueString,&pyLoader)) { PyErr_BadArgument(); Py_RETURN_NONE; } BaseObject* loader=((PySPtr<Base>*)self)->object->toBaseObject(); obj->setSrc(valueString,loader); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_getPathName(PyObject * self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return PyString_FromString(obj->getPathName().c_str()); } // the same as 'getPathName' with a extra prefix '@' extern "C" PyObject * BaseObject_getLinkPath(PyObject * self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return PyString_FromString(("@"+obj->getPathName()).c_str()); } SP_CLASS_METHODS_BEGIN(BaseObject) SP_CLASS_METHOD(BaseObject,init) SP_CLASS_METHOD(BaseObject,bwdInit) SP_CLASS_METHOD(BaseObject,reinit) SP_CLASS_METHOD(BaseObject,storeResetState) SP_CLASS_METHOD(BaseObject,reset) SP_CLASS_METHOD(BaseObject,cleanup) SP_CLASS_METHOD(BaseObject,getContext) SP_CLASS_METHOD(BaseObject,getMaster) SP_CLASS_METHOD(BaseObject,setSrc) SP_CLASS_METHOD(BaseObject,getPathName) SP_CLASS_METHOD(BaseObject,getLinkPath) SP_CLASS_METHODS_END SP_CLASS_TYPE_SPTR(BaseObject,BaseObject,Base) <commit_msg>ADD: binding python to get slaves and names on baseObjects<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Plugins * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Binding_BaseObject.h" #include "Binding_Base.h" #include "PythonFactory.h" using namespace sofa::core::objectmodel; extern "C" PyObject * BaseObject_init(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->init(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_bwdInit(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->bwdInit(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_reinit(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->reinit(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_storeResetState(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->storeResetState(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_reset(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->reset(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_cleanup(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); obj->cleanup(); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_getContext(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return sofa::PythonFactory::toPython(obj->getContext()); } extern "C" PyObject * BaseObject_getMaster(PyObject *self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return sofa::PythonFactory::toPython(obj->getMaster()); } extern "C" PyObject * BaseObject_setSrc(PyObject *self, PyObject * args) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); char *valueString; PyObject *pyLoader; if (!PyArg_ParseTuple(args, "sO",&valueString,&pyLoader)) { PyErr_BadArgument(); Py_RETURN_NONE; } BaseObject* loader=((PySPtr<Base>*)self)->object->toBaseObject(); obj->setSrc(valueString,loader); Py_RETURN_NONE; } extern "C" PyObject * BaseObject_getPathName(PyObject * self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return PyString_FromString(obj->getPathName().c_str()); } // the same as 'getPathName' with a extra prefix '@' extern "C" PyObject * BaseObject_getLinkPath(PyObject * self, PyObject * /*args*/) { BaseObject* obj=((PySPtr<Base>*)self)->object->toBaseObject(); return PyString_FromString(("@"+obj->getPathName()).c_str()); } extern "C" PyObject * BaseObject_getSlaves(PyObject * self, PyObject * /*args*/) { BaseObject* node=dynamic_cast<BaseObject*>(((PySPtr<Base>*)self)->object.get()); const BaseObject::VecSlaves& slaves = node->getSlaves(); PyObject *list = PyList_New(slaves.size()); for (unsigned int i=0; i<slaves.size(); ++i) PyList_SetItem(list,i,sofa::PythonFactory::toPython(slaves[i].get())); return list; } extern "C" PyObject * BaseObject_getName(PyObject * self, PyObject * /*args*/) { // BaseNode is not binded in SofaPython, so getChildNode is binded in Node instead of BaseNode BaseObject* node=dynamic_cast<BaseObject*>(((PySPtr<Base>*)self)->object.get()); return PyString_FromString((node->getName()).c_str()); } SP_CLASS_METHODS_BEGIN(BaseObject) SP_CLASS_METHOD(BaseObject,init) SP_CLASS_METHOD(BaseObject,bwdInit) SP_CLASS_METHOD(BaseObject,reinit) SP_CLASS_METHOD(BaseObject,storeResetState) SP_CLASS_METHOD(BaseObject,reset) SP_CLASS_METHOD(BaseObject,cleanup) SP_CLASS_METHOD(BaseObject,getContext) SP_CLASS_METHOD(BaseObject,getMaster) SP_CLASS_METHOD(BaseObject,setSrc) SP_CLASS_METHOD(BaseObject,getPathName) SP_CLASS_METHOD(BaseObject,getLinkPath) SP_CLASS_METHOD(BaseObject,getSlaves) SP_CLASS_METHOD(BaseObject,getName) SP_CLASS_METHODS_END SP_CLASS_TYPE_SPTR(BaseObject,BaseObject,Base) <|endoftext|>
<commit_before>/*********************************************************************** filename: ShaderWrapper.cpp created: 9th December 2013 author: Lukas Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 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/Direct3D11/ShaderWrapper.h" #include "CEGUI/RendererModules/Direct3D11/Texture.h" #include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/Exceptions.h" #include <glm/gtc/type_ptr.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// Direct3D11ShaderWrapper::Direct3D11ShaderWrapper(Direct3D11Shader& shader, Direct3D11Renderer* renderer) : d_shader(shader) , d_device(renderer->getDirect3DDevice()) , d_deviceContext(renderer->getDirect3DDeviceContext()) , d_perObjectUniformVarBufferVert(0) , d_perObjectUniformVarBufferPixel(0) { createPerObjectBuffer(ST_VERTEX); createPerObjectBuffer(ST_PIXEL); D3D11_SAMPLER_DESC samplerDescription; ZeroMemory( &samplerDescription, sizeof(samplerDescription) ); samplerDescription.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDescription.MinLOD = 0; samplerDescription.MaxLOD = D3D11_FLOAT32_MAX; HRESULT result = d_device->CreateSamplerState( &samplerDescription, &d_samplerState ); if(FAILED(result)) CEGUI_THROW(RendererException("SamplerDescription creation failed")); } //----------------------------------------------------------------------------// Direct3D11ShaderWrapper::~Direct3D11ShaderWrapper() { if(d_perObjectUniformVarBufferVert != 0) d_perObjectUniformVarBufferVert->Release(); if(d_perObjectUniformVarBufferPixel != 0) d_perObjectUniformVarBufferPixel->Release(); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::addUniformVariable(const std::string& variableName, ShaderType shaderType, ShaderParamType paramType) { UINT variableBindingLoc = -1; UINT size = -1; if(paramType == SPT_TEXTURE) { D3D11_SHADER_INPUT_BIND_DESC variableDesc = d_shader.getTextureBindingDesc(variableName, shaderType); variableBindingLoc = variableDesc.BindPoint; size = variableDesc.BindCount; } else { D3D11_SHADER_VARIABLE_DESC variableDesc = d_shader.getUniformVariableDescription(variableName, shaderType); variableBindingLoc = variableDesc.StartOffset; size = variableDesc.Size; } Direct3D11ParamDesc parameter = {variableBindingLoc, size, shaderType, paramType}; d_uniformVariables.insert(std::pair<std::string, Direct3D11ParamDesc>(variableName, parameter)); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) { d_shader.bind(); d_deviceContext->PSSetSamplers(0, 1, &d_samplerState); D3D11_MAPPED_SUBRESOURCE mappedResourceVertShader, mappedResourcePixelShader; prepareUniformVariableMapping(mappedResourceVertShader, mappedResourcePixelShader); const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings->getShaderParameterBindings(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); while(iter != end) { const CEGUI::ShaderParameter* parameter = iter->second; const ShaderParamType parameterType = parameter->getType(); std::map<std::string, Direct3D11ParamDesc>::iterator foundIter = d_uniformVariables.find(iter->first); if(foundIter == d_uniformVariables.end()) { std::string errorMessage = std::string("Variable was not found in the set of uniform variables of the shader. Variable name was: \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } const Direct3D11ParamDesc& parameterDescription = foundIter->second; if(parameterType != parameterDescription.d_shaderParamType) { std::string errorMessage = std::string("Supplied parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } std::map<std::string, ShaderParameter*>::iterator found_iterator = d_shaderParameterStates.find(iter->first); if(found_iterator != d_shaderParameterStates.end()) { ShaderParameter* last_shader_parameter = found_iterator->second; if(last_shader_parameter->getType() != parameterDescription.d_shaderParamType) { std::string errorMessage = std::string("The last shader parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } if(parameter->equal(last_shader_parameter)) { ++iter; continue; } else last_shader_parameter->takeOverParameterValue(parameter); } switch(parameterType) { case SPT_INT: { /* const CEGUI::ShaderParameterInt* parameterInt = static_cast<const CEGUI::ShaderParameterInt*>(parameter); glUniform1i(location, parameterInt->d_parameterValue);*/ } break; case SPT_FLOAT: { /* const CEGUI::ShaderParameterFloat* parameterFloat = static_cast<const CEGUI::ShaderParameterFloat*>(parameter); glUniform1f(location, parameterFloat->d_parameterValue);*/ } break; case SPT_MATRIX_4X4: { const CEGUI::ShaderParameterMatrix* parameterMatrix = static_cast<const CEGUI::ShaderParameterMatrix*>(parameter); // Get the pointer to the mapped resource data unsigned char* dataInBytes = 0; if (parameterDescription.d_shaderType == ST_VERTEX) dataInBytes = static_cast<unsigned char*>(mappedResourceVertShader.pData); else if (parameterDescription.d_shaderType == ST_PIXEL) dataInBytes = static_cast<unsigned char*>(mappedResourcePixelShader.pData); // Go to the memory position of our uniform variable dataInBytes += parameterDescription.d_boundLocation; memcpy(dataInBytes, glm::value_ptr(parameterMatrix->d_parameterValue), parameterDescription.d_boundSize); } break; case SPT_TEXTURE: { const CEGUI::ShaderParameterTexture* parameterTexture = static_cast<const CEGUI::ShaderParameterTexture*>(parameter); const CEGUI::Direct3D11Texture* texture = static_cast<const CEGUI::Direct3D11Texture*>(parameterTexture->d_parameterValue); ID3D11ShaderResourceView* shaderResourceView = texture->getDirect3DShaderResourceView(); if (parameterDescription.d_shaderType == ST_PIXEL) d_deviceContext->PSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); else if (parameterDescription.d_shaderType == ST_VERTEX) d_deviceContext->VSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); } break; default: break; } ++iter; } finishUniformVariableMapping(); } //----------------------------------------------------------------------------// void* Direct3D11ShaderWrapper::getVertShaderBufferPointer() { ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); return vertexShaderBuffer->GetBufferPointer(); } //----------------------------------------------------------------------------// SIZE_T Direct3D11ShaderWrapper::getVertShaderBufferSize() { ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); return vertexShaderBuffer->GetBufferSize(); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::createPerObjectBuffer(ShaderType shaderType) { HRESULT result; ID3D11ShaderReflectionConstantBuffer* shaderReflectionConstBuff = d_shader.getShaderReflectionConstBuffer(shaderType); D3D11_SHADER_BUFFER_DESC shaderBufferDesc; result = shaderReflectionConstBuff->GetDesc(&shaderBufferDesc); if (FAILED(result)) return; if(shaderBufferDesc.Size > 0) { // create the constant buffers D3D11_BUFFER_DESC bufferDescription; ZeroMemory(&bufferDescription, sizeof(bufferDescription)); bufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDescription.Usage = D3D11_USAGE_DYNAMIC; bufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDescription.MiscFlags = 0; bufferDescription.ByteWidth = shaderBufferDesc.Size; if (shaderType == ST_VERTEX) d_device->CreateBuffer(&bufferDescription, nullptr, &d_perObjectUniformVarBufferVert); else if (shaderType == ST_PIXEL) d_device->CreateBuffer(&bufferDescription, nullptr, &d_perObjectUniformVarBufferPixel); } } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::prepareUniformVariableMapping(D3D11_MAPPED_SUBRESOURCE& mappedResourceVertShader, D3D11_MAPPED_SUBRESOURCE& mappedResourcePixelShader) { if(d_perObjectUniformVarBufferVert != 0) { d_deviceContext->VSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferVert); HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferVert, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourceVertShader); if(FAILED(result)) CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); } if(d_perObjectUniformVarBufferPixel != 0) { d_deviceContext->PSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferPixel); HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferPixel, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourcePixelShader); if(FAILED(result)) CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); } } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::finishUniformVariableMapping() { if(d_perObjectUniformVarBufferVert != 0) d_deviceContext->Unmap(d_perObjectUniformVarBufferVert, 0); if(d_perObjectUniformVarBufferPixel != 0) d_deviceContext->Unmap(d_perObjectUniformVarBufferPixel, 0); } //----------------------------------------------------------------------------// } <commit_msg>MOD: Corrected the date<commit_after>/*********************************************************************** filename: ShaderWrapper.cpp created: Sun, 6th April 2014 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 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/Direct3D11/ShaderWrapper.h" #include "CEGUI/RendererModules/Direct3D11/Texture.h" #include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/Exceptions.h" #include <glm/gtc/type_ptr.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// Direct3D11ShaderWrapper::Direct3D11ShaderWrapper(Direct3D11Shader& shader, Direct3D11Renderer* renderer) : d_shader(shader) , d_device(renderer->getDirect3DDevice()) , d_deviceContext(renderer->getDirect3DDeviceContext()) , d_perObjectUniformVarBufferVert(0) , d_perObjectUniformVarBufferPixel(0) { createPerObjectBuffer(ST_VERTEX); createPerObjectBuffer(ST_PIXEL); D3D11_SAMPLER_DESC samplerDescription; ZeroMemory( &samplerDescription, sizeof(samplerDescription) ); samplerDescription.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDescription.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDescription.MinLOD = 0; samplerDescription.MaxLOD = D3D11_FLOAT32_MAX; HRESULT result = d_device->CreateSamplerState( &samplerDescription, &d_samplerState ); if(FAILED(result)) CEGUI_THROW(RendererException("SamplerDescription creation failed")); } //----------------------------------------------------------------------------// Direct3D11ShaderWrapper::~Direct3D11ShaderWrapper() { if(d_perObjectUniformVarBufferVert != 0) d_perObjectUniformVarBufferVert->Release(); if(d_perObjectUniformVarBufferPixel != 0) d_perObjectUniformVarBufferPixel->Release(); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::addUniformVariable(const std::string& variableName, ShaderType shaderType, ShaderParamType paramType) { UINT variableBindingLoc = -1; UINT size = -1; if(paramType == SPT_TEXTURE) { D3D11_SHADER_INPUT_BIND_DESC variableDesc = d_shader.getTextureBindingDesc(variableName, shaderType); variableBindingLoc = variableDesc.BindPoint; size = variableDesc.BindCount; } else { D3D11_SHADER_VARIABLE_DESC variableDesc = d_shader.getUniformVariableDescription(variableName, shaderType); variableBindingLoc = variableDesc.StartOffset; size = variableDesc.Size; } Direct3D11ParamDesc parameter = {variableBindingLoc, size, shaderType, paramType}; d_uniformVariables.insert(std::pair<std::string, Direct3D11ParamDesc>(variableName, parameter)); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) { d_shader.bind(); d_deviceContext->PSSetSamplers(0, 1, &d_samplerState); D3D11_MAPPED_SUBRESOURCE mappedResourceVertShader, mappedResourcePixelShader; prepareUniformVariableMapping(mappedResourceVertShader, mappedResourcePixelShader); const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings->getShaderParameterBindings(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); while(iter != end) { const CEGUI::ShaderParameter* parameter = iter->second; const ShaderParamType parameterType = parameter->getType(); std::map<std::string, Direct3D11ParamDesc>::iterator foundIter = d_uniformVariables.find(iter->first); if(foundIter == d_uniformVariables.end()) { std::string errorMessage = std::string("Variable was not found in the set of uniform variables of the shader. Variable name was: \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } const Direct3D11ParamDesc& parameterDescription = foundIter->second; if(parameterType != parameterDescription.d_shaderParamType) { std::string errorMessage = std::string("Supplied parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } std::map<std::string, ShaderParameter*>::iterator found_iterator = d_shaderParameterStates.find(iter->first); if(found_iterator != d_shaderParameterStates.end()) { ShaderParameter* last_shader_parameter = found_iterator->second; if(last_shader_parameter->getType() != parameterDescription.d_shaderParamType) { std::string errorMessage = std::string("The last shader parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } if(parameter->equal(last_shader_parameter)) { ++iter; continue; } else last_shader_parameter->takeOverParameterValue(parameter); } switch(parameterType) { case SPT_INT: { /* const CEGUI::ShaderParameterInt* parameterInt = static_cast<const CEGUI::ShaderParameterInt*>(parameter); glUniform1i(location, parameterInt->d_parameterValue);*/ } break; case SPT_FLOAT: { /* const CEGUI::ShaderParameterFloat* parameterFloat = static_cast<const CEGUI::ShaderParameterFloat*>(parameter); glUniform1f(location, parameterFloat->d_parameterValue);*/ } break; case SPT_MATRIX_4X4: { const CEGUI::ShaderParameterMatrix* parameterMatrix = static_cast<const CEGUI::ShaderParameterMatrix*>(parameter); // Get the pointer to the mapped resource data unsigned char* dataInBytes = 0; if (parameterDescription.d_shaderType == ST_VERTEX) dataInBytes = static_cast<unsigned char*>(mappedResourceVertShader.pData); else if (parameterDescription.d_shaderType == ST_PIXEL) dataInBytes = static_cast<unsigned char*>(mappedResourcePixelShader.pData); // Go to the memory position of our uniform variable dataInBytes += parameterDescription.d_boundLocation; memcpy(dataInBytes, glm::value_ptr(parameterMatrix->d_parameterValue), parameterDescription.d_boundSize); } break; case SPT_TEXTURE: { const CEGUI::ShaderParameterTexture* parameterTexture = static_cast<const CEGUI::ShaderParameterTexture*>(parameter); const CEGUI::Direct3D11Texture* texture = static_cast<const CEGUI::Direct3D11Texture*>(parameterTexture->d_parameterValue); ID3D11ShaderResourceView* shaderResourceView = texture->getDirect3DShaderResourceView(); if (parameterDescription.d_shaderType == ST_PIXEL) d_deviceContext->PSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); else if (parameterDescription.d_shaderType == ST_VERTEX) d_deviceContext->VSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); } break; default: break; } ++iter; } finishUniformVariableMapping(); } //----------------------------------------------------------------------------// void* Direct3D11ShaderWrapper::getVertShaderBufferPointer() { ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); return vertexShaderBuffer->GetBufferPointer(); } //----------------------------------------------------------------------------// SIZE_T Direct3D11ShaderWrapper::getVertShaderBufferSize() { ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); return vertexShaderBuffer->GetBufferSize(); } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::createPerObjectBuffer(ShaderType shaderType) { HRESULT result; ID3D11ShaderReflectionConstantBuffer* shaderReflectionConstBuff = d_shader.getShaderReflectionConstBuffer(shaderType); D3D11_SHADER_BUFFER_DESC shaderBufferDesc; result = shaderReflectionConstBuff->GetDesc(&shaderBufferDesc); if (FAILED(result)) return; if(shaderBufferDesc.Size > 0) { // create the constant buffers D3D11_BUFFER_DESC bufferDescription; ZeroMemory(&bufferDescription, sizeof(bufferDescription)); bufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDescription.Usage = D3D11_USAGE_DYNAMIC; bufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bufferDescription.MiscFlags = 0; bufferDescription.ByteWidth = shaderBufferDesc.Size; if (shaderType == ST_VERTEX) d_device->CreateBuffer(&bufferDescription, nullptr, &d_perObjectUniformVarBufferVert); else if (shaderType == ST_PIXEL) d_device->CreateBuffer(&bufferDescription, nullptr, &d_perObjectUniformVarBufferPixel); } } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::prepareUniformVariableMapping(D3D11_MAPPED_SUBRESOURCE& mappedResourceVertShader, D3D11_MAPPED_SUBRESOURCE& mappedResourcePixelShader) { if(d_perObjectUniformVarBufferVert != 0) { d_deviceContext->VSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferVert); HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferVert, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourceVertShader); if(FAILED(result)) CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); } if(d_perObjectUniformVarBufferPixel != 0) { d_deviceContext->PSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferPixel); HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferPixel, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourcePixelShader); if(FAILED(result)) CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); } } //----------------------------------------------------------------------------// void Direct3D11ShaderWrapper::finishUniformVariableMapping() { if(d_perObjectUniformVarBufferVert != 0) d_deviceContext->Unmap(d_perObjectUniformVarBufferVert, 0); if(d_perObjectUniformVarBufferPixel != 0) d_deviceContext->Unmap(d_perObjectUniformVarBufferPixel, 0); } //----------------------------------------------------------------------------// } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_devtools_bridge.h" #include "base/json/json_writer.h" #include "base/message_loop.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/values.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/extensions/extension_devtools_events.h" #include "chrome/browser/extensions/extension_devtools_manager.h" #include "chrome/browser/extensions/extension_event_router.h" #include "chrome/browser/extensions/extension_tabs_module.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/devtools_messages.h" #include "content/browser/tab_contents/tab_contents.h" ExtensionDevToolsBridge::ExtensionDevToolsBridge(int tab_id, Profile* profile) : tab_id_(tab_id), profile_(profile), on_page_event_name_( ExtensionDevToolsEvents::OnPageEventNameForTab(tab_id)), on_tab_close_event_name_( ExtensionDevToolsEvents::OnTabCloseEventNameForTab(tab_id)) { extension_devtools_manager_ = profile_->GetExtensionDevToolsManager(); DCHECK(extension_devtools_manager_.get()); } ExtensionDevToolsBridge::~ExtensionDevToolsBridge() { } static std::string FormatDevToolsMessage(int seq, const std::string& domain, const std::string& command, DictionaryValue* arguments) { DictionaryValue message; message.SetInteger("seq", seq); message.SetString("domain", domain); message.SetString("command", command); message.Set("arguments", arguments); std::string json; base::JSONWriter::Write(&message, false, &json); return json; } bool ExtensionDevToolsBridge::RegisterAsDevToolsClientHost() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); Browser* browser; TabStripModel* tab_strip; TabContentsWrapper* contents; int tab_index; if (ExtensionTabUtil::GetTabById(tab_id_, profile_, true, &browser, &tab_strip, &contents, &tab_index)) { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); if (devtools_manager->GetDevToolsClientHostFor(contents-> render_view_host()) != NULL) return false; devtools_manager->RegisterDevToolsClientHostFor( contents->render_view_host(), this); // Following messages depend on inspector protocol that is not yet // finalized. // 1. Set injected script content. DictionaryValue* arguments = new DictionaryValue(); arguments->SetString("scriptSource", "'{}'"); devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_DispatchOnInspectorBackend( FormatDevToolsMessage(0, "Inspector", "setInjectedScriptSource", arguments))); // 2. Report front-end is loaded. devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_FrontendLoaded()); // 3. Do not break on exceptions. arguments = new DictionaryValue(); arguments->SetInteger("pauseOnExceptionsState", 0); devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_DispatchOnInspectorBackend( FormatDevToolsMessage(1, "Debugger", "setPauseOnExceptionsState", arguments))); // 4. Start timeline profiler. devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_DispatchOnInspectorBackend( FormatDevToolsMessage(2, "Inspector", "startTimelineProfiler", new DictionaryValue()))); return true; } return false; } void ExtensionDevToolsBridge::UnregisterAsDevToolsClientHost() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); NotifyCloseListener(); } // If the tab we are looking at is going away then we fire a closing event at // the extension. void ExtensionDevToolsBridge::InspectedTabClosing() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); // TODO(knorton): Remove this event in favor of the standard tabs.onRemoved // event in extensions. std::string json("[{}]"); profile_->GetExtensionEventRouter()->DispatchEventToRenderers( on_tab_close_event_name_, json, profile_, GURL()); // This may result in this object being destroyed. extension_devtools_manager_->BridgeClosingForTab(tab_id_); } void ExtensionDevToolsBridge::SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(ExtensionDevToolsBridge, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void ExtensionDevToolsBridge::TabReplaced(TabContentsWrapper* new_tab) { DCHECK_EQ(profile_, new_tab->profile()); // We don't update the tab id as it needs to remain the same so that we can // properly unregister. } void ExtensionDevToolsBridge::OnDispatchOnInspectorFrontend( const std::string& data) { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); std::string json = base::StringPrintf("[%s]", data.c_str()); profile_->GetExtensionEventRouter()->DispatchEventToRenderers( on_page_event_name_, json, profile_, GURL()); } <commit_msg>Updates special case Speed Tracer code after inspector protocol changes. Original code review: http://codereview.chromium.org/6594124/<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_devtools_bridge.h" #include "base/json/json_writer.h" #include "base/message_loop.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/values.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/extensions/extension_devtools_events.h" #include "chrome/browser/extensions/extension_devtools_manager.h" #include "chrome/browser/extensions/extension_event_router.h" #include "chrome/browser/extensions/extension_tabs_module.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/devtools_messages.h" #include "content/browser/tab_contents/tab_contents.h" ExtensionDevToolsBridge::ExtensionDevToolsBridge(int tab_id, Profile* profile) : tab_id_(tab_id), profile_(profile), on_page_event_name_( ExtensionDevToolsEvents::OnPageEventNameForTab(tab_id)), on_tab_close_event_name_( ExtensionDevToolsEvents::OnTabCloseEventNameForTab(tab_id)) { extension_devtools_manager_ = profile_->GetExtensionDevToolsManager(); DCHECK(extension_devtools_manager_.get()); } ExtensionDevToolsBridge::~ExtensionDevToolsBridge() { } static std::string FormatDevToolsMessage(int seq, const std::string& domain, const std::string& command, DictionaryValue* arguments) { DictionaryValue message; message.SetInteger("seq", seq); message.SetString("domain", domain); message.SetString("command", command); message.Set("arguments", arguments); std::string json; base::JSONWriter::Write(&message, false, &json); return json; } bool ExtensionDevToolsBridge::RegisterAsDevToolsClientHost() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); Browser* browser; TabStripModel* tab_strip; TabContentsWrapper* contents; int tab_index; if (ExtensionTabUtil::GetTabById(tab_id_, profile_, true, &browser, &tab_strip, &contents, &tab_index)) { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); if (devtools_manager->GetDevToolsClientHostFor(contents-> render_view_host()) != NULL) return false; devtools_manager->RegisterDevToolsClientHostFor( contents->render_view_host(), this); // Following messages depend on inspector protocol that is not yet // finalized. // 1. Report front-end is loaded. devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_FrontendLoaded()); // 2. Start timeline profiler. devtools_manager->ForwardToDevToolsAgent( this, DevToolsAgentMsg_DispatchOnInspectorBackend( FormatDevToolsMessage(2, "Timeline", "start", new DictionaryValue()))); return true; } return false; } void ExtensionDevToolsBridge::UnregisterAsDevToolsClientHost() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); NotifyCloseListener(); } // If the tab we are looking at is going away then we fire a closing event at // the extension. void ExtensionDevToolsBridge::InspectedTabClosing() { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); // TODO(knorton): Remove this event in favor of the standard tabs.onRemoved // event in extensions. std::string json("[{}]"); profile_->GetExtensionEventRouter()->DispatchEventToRenderers( on_tab_close_event_name_, json, profile_, GURL()); // This may result in this object being destroyed. extension_devtools_manager_->BridgeClosingForTab(tab_id_); } void ExtensionDevToolsBridge::SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(ExtensionDevToolsBridge, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void ExtensionDevToolsBridge::TabReplaced(TabContentsWrapper* new_tab) { DCHECK_EQ(profile_, new_tab->profile()); // We don't update the tab id as it needs to remain the same so that we can // properly unregister. } void ExtensionDevToolsBridge::OnDispatchOnInspectorFrontend( const std::string& data) { DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI); std::string json = base::StringPrintf("[%s]", data.c_str()); profile_->GetExtensionEventRouter()->DispatchEventToRenderers( on_page_event_name_, json, profile_, GURL()); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/managed_mode/managed_mode_url_filter.h" #include "base/files/file_path.h" #include "base/hash_tables.h" #include "base/json/json_file_value_serializer.h" #include "base/metrics/histogram.h" #include "base/sha1.h" #include "base/string_util.h" #include "base/strings/string_number_conversions.h" #include "base/task_runner_util.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/policy/url_blacklist_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/matcher/url_matcher.h" #include "googleurl/src/gurl.h" using content::BrowserThread; using extensions::URLMatcher; using extensions::URLMatcherConditionSet; struct ManagedModeURLFilter::Contents { URLMatcher url_matcher; std::map<URLMatcherConditionSet::ID, int> matcher_site_map; base::hash_multimap<std::string, int> hash_site_map; std::vector<ManagedModeSiteList::Site> sites; }; namespace { // This class encapsulates all the state that is required during construction of // a new ManagedModeURLFilter::Contents. class FilterBuilder { public: FilterBuilder(); ~FilterBuilder(); // Adds a single URL pattern for the site identified by |site_id|. bool AddPattern(const std::string& pattern, int site_id); // Adds a single hostname SHA1 hash for the site identified by |site_id|. void AddHostnameHash(const std::string& hash, int site_id); // Adds all the sites in |site_list|, with URL patterns and hostname hashes. void AddSiteList(ManagedModeSiteList* site_list); // Finalizes construction of the ManagedModeURLFilter::Contents and returns // them. This method should be called before this object is destroyed. scoped_ptr<ManagedModeURLFilter::Contents> Build(); private: scoped_ptr<ManagedModeURLFilter::Contents> contents_; URLMatcherConditionSet::Vector all_conditions_; URLMatcherConditionSet::ID matcher_id_; }; FilterBuilder::FilterBuilder() : contents_(new ManagedModeURLFilter::Contents()), matcher_id_(0) {} FilterBuilder::~FilterBuilder() { DCHECK(!contents_.get()); } bool FilterBuilder::AddPattern(const std::string& pattern, int site_id) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); #if defined(ENABLE_CONFIGURATION_POLICY) std::string scheme; std::string host; uint16 port; std::string path; bool match_subdomains = true; if (!policy::URLBlacklist::FilterToComponents( pattern, &scheme, &host, &match_subdomains, &port, &path)) { LOG(ERROR) << "Invalid pattern " << pattern; return false; } scoped_refptr<extensions::URLMatcherConditionSet> condition_set = policy::URLBlacklist::CreateConditionSet( &contents_->url_matcher, ++matcher_id_, scheme, host, match_subdomains, port, path); all_conditions_.push_back(condition_set); contents_->matcher_site_map[matcher_id_] = site_id; return true; #else NOTREACHED(); return false; #endif } void FilterBuilder::AddHostnameHash(const std::string& hash, int site_id) { contents_->hash_site_map.insert(std::make_pair(StringToUpperASCII(hash), site_id)); } void FilterBuilder::AddSiteList(ManagedModeSiteList* site_list) { std::vector<ManagedModeSiteList::Site> sites; site_list->GetSites(&sites); int site_id = contents_->sites.size(); for (std::vector<ManagedModeSiteList::Site>::const_iterator it = sites.begin(); it != sites.end(); ++it) { const ManagedModeSiteList::Site& site = *it; contents_->sites.push_back(site); for (std::vector<std::string>::const_iterator pattern_it = site.patterns.begin(); pattern_it != site.patterns.end(); ++pattern_it) { AddPattern(*pattern_it, site_id); } for (std::vector<std::string>::const_iterator hash_it = site.hostname_hashes.begin(); hash_it != site.hostname_hashes.end(); ++hash_it) { AddHostnameHash(*hash_it, site_id); } site_id++; } } scoped_ptr<ManagedModeURLFilter::Contents> FilterBuilder::Build() { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); contents_->url_matcher.AddConditionSets(all_conditions_); return contents_.Pass(); } scoped_ptr<ManagedModeURLFilter::Contents> CreateWhitelistFromPatterns( const std::vector<std::string>& patterns) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); FilterBuilder builder; for (std::vector<std::string>::const_iterator it = patterns.begin(); it != patterns.end(); ++it) { // TODO(bauerb): We should create a fake site for the whitelist. builder.AddPattern(*it, -1); } return builder.Build(); } scoped_ptr<ManagedModeURLFilter::Contents> LoadWhitelistsOnBlockingPoolThread( ScopedVector<ManagedModeSiteList> site_lists) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); FilterBuilder builder; for (ScopedVector<ManagedModeSiteList>::iterator it = site_lists.begin(); it != site_lists.end(); ++it) { builder.AddSiteList(*it); } return builder.Build(); } } // namespace ManagedModeURLFilter::ManagedModeURLFilter() : default_behavior_(ALLOW), contents_(new Contents()) { // Detach from the current thread so we can be constructed on a different // thread than the one where we're used. DetachFromThread(); } ManagedModeURLFilter::~ManagedModeURLFilter() { DCHECK(CalledOnValidThread()); } // static ManagedModeURLFilter::FilteringBehavior ManagedModeURLFilter::BehaviorFromInt(int behavior_value) { DCHECK_GE(behavior_value, ALLOW); DCHECK_LE(behavior_value, BLOCK); return static_cast<FilteringBehavior>(behavior_value); } // static GURL ManagedModeURLFilter::Normalize(const GURL& url) { GURL normalized_url = url; GURL::Replacements replacements; // Strip username, password, query, and ref. replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); } ManagedModeURLFilter::FilteringBehavior ManagedModeURLFilter::GetFilteringBehaviorForURL(const GURL& url) const { DCHECK(CalledOnValidThread()); // If the default behavior is to allow, we don't need to check anything else. if (default_behavior_ == ALLOW) return ALLOW; #if defined(ENABLE_CONFIGURATION_POLICY) // URLs with a non-standard scheme (e.g. chrome://) are always allowed. if (!policy::URLBlacklist::HasStandardScheme(url)) return ALLOW; #endif // Check manual overrides for the exact URL. std::map<GURL, bool>::const_iterator url_it = url_map_.find(Normalize(url)); if (url_it != url_map_.end()) return url_it->second ? ALLOW : BLOCK; // Check manual overrides for the hostname. std::map<std::string, bool>::const_iterator host_it = host_map_.find(url.host()); if (host_it != host_map_.end()) return host_it->second ? ALLOW : BLOCK; // Check the list of URL patterns. std::set<URLMatcherConditionSet::ID> matching_ids = contents_->url_matcher.MatchURL(url); if (!matching_ids.empty()) return ALLOW; // Check the list of hostname hashes. std::string hash = base::SHA1HashString(url.host()); std::string hash_hex = base::HexEncode(hash.data(), hash.length()); if (contents_->hash_site_map.count(hash_hex)) return ALLOW; // Fall back to the default behavior. return default_behavior_; } void ManagedModeURLFilter::GetSites( const GURL& url, std::vector<ManagedModeSiteList::Site*>* sites) const { std::set<URLMatcherConditionSet::ID> matching_ids = contents_->url_matcher.MatchURL(url); for (std::set<URLMatcherConditionSet::ID>::const_iterator it = matching_ids.begin(); it != matching_ids.end(); ++it) { std::map<URLMatcherConditionSet::ID, int>::const_iterator entry = contents_->matcher_site_map.find(*it); if (entry == contents_->matcher_site_map.end()) { NOTREACHED(); continue; } sites->push_back(&contents_->sites[entry->second]); } typedef base::hash_map<std::string, int>::const_iterator hash_site_map_iterator; std::pair<hash_site_map_iterator, hash_site_map_iterator> bounds = contents_->hash_site_map.equal_range(url.host()); for (hash_site_map_iterator hash_it = bounds.first; hash_it != bounds.second; hash_it++) { sites->push_back(&contents_->sites[hash_it->second]); } } void ManagedModeURLFilter::SetDefaultFilteringBehavior( FilteringBehavior behavior) { DCHECK(CalledOnValidThread()); default_behavior_ = behavior; } void ManagedModeURLFilter::LoadWhitelists( ScopedVector<ManagedModeSiteList> site_lists) { DCHECK(CalledOnValidThread()); base::PostTaskAndReplyWithResult( BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&LoadWhitelistsOnBlockingPoolThread, base::Passed(&site_lists)), base::Bind(&ManagedModeURLFilter::SetContents, this)); } void ManagedModeURLFilter::SetFromPatterns( const std::vector<std::string>& patterns) { DCHECK(CalledOnValidThread()); base::PostTaskAndReplyWithResult( BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&CreateWhitelistFromPatterns, patterns), base::Bind(&ManagedModeURLFilter::SetContents, this)); } void ManagedModeURLFilter::SetManualHosts( const std::map<std::string, bool>* host_map) { DCHECK(CalledOnValidThread()); host_map_ = *host_map; UMA_HISTOGRAM_CUSTOM_COUNTS("ManagedMode.ManualHostsEntries", host_map->size(), 1, 1000, 50); } void ManagedModeURLFilter::SetManualURLs( const std::map<GURL, bool>* url_map) { DCHECK(CalledOnValidThread()); url_map_ = *url_map; UMA_HISTOGRAM_CUSTOM_COUNTS("ManagedMode.ManualURLsEntries", url_map->size(), 1, 1000, 50); } void ManagedModeURLFilter::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void ManagedModeURLFilter::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void ManagedModeURLFilter::SetContents(scoped_ptr<Contents> contents) { DCHECK(CalledOnValidThread()); contents_ = contents.Pass(); FOR_EACH_OBSERVER(Observer, observers_, OnSiteListUpdated()); } <commit_msg>[Managed users] Don't early-return when the default filtering behavior is ALLOW.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/managed_mode/managed_mode_url_filter.h" #include "base/files/file_path.h" #include "base/hash_tables.h" #include "base/json/json_file_value_serializer.h" #include "base/metrics/histogram.h" #include "base/sha1.h" #include "base/string_util.h" #include "base/strings/string_number_conversions.h" #include "base/task_runner_util.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/policy/url_blacklist_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/matcher/url_matcher.h" #include "googleurl/src/gurl.h" using content::BrowserThread; using extensions::URLMatcher; using extensions::URLMatcherConditionSet; struct ManagedModeURLFilter::Contents { URLMatcher url_matcher; std::map<URLMatcherConditionSet::ID, int> matcher_site_map; base::hash_multimap<std::string, int> hash_site_map; std::vector<ManagedModeSiteList::Site> sites; }; namespace { // This class encapsulates all the state that is required during construction of // a new ManagedModeURLFilter::Contents. class FilterBuilder { public: FilterBuilder(); ~FilterBuilder(); // Adds a single URL pattern for the site identified by |site_id|. bool AddPattern(const std::string& pattern, int site_id); // Adds a single hostname SHA1 hash for the site identified by |site_id|. void AddHostnameHash(const std::string& hash, int site_id); // Adds all the sites in |site_list|, with URL patterns and hostname hashes. void AddSiteList(ManagedModeSiteList* site_list); // Finalizes construction of the ManagedModeURLFilter::Contents and returns // them. This method should be called before this object is destroyed. scoped_ptr<ManagedModeURLFilter::Contents> Build(); private: scoped_ptr<ManagedModeURLFilter::Contents> contents_; URLMatcherConditionSet::Vector all_conditions_; URLMatcherConditionSet::ID matcher_id_; }; FilterBuilder::FilterBuilder() : contents_(new ManagedModeURLFilter::Contents()), matcher_id_(0) {} FilterBuilder::~FilterBuilder() { DCHECK(!contents_.get()); } bool FilterBuilder::AddPattern(const std::string& pattern, int site_id) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); #if defined(ENABLE_CONFIGURATION_POLICY) std::string scheme; std::string host; uint16 port; std::string path; bool match_subdomains = true; if (!policy::URLBlacklist::FilterToComponents( pattern, &scheme, &host, &match_subdomains, &port, &path)) { LOG(ERROR) << "Invalid pattern " << pattern; return false; } scoped_refptr<extensions::URLMatcherConditionSet> condition_set = policy::URLBlacklist::CreateConditionSet( &contents_->url_matcher, ++matcher_id_, scheme, host, match_subdomains, port, path); all_conditions_.push_back(condition_set); contents_->matcher_site_map[matcher_id_] = site_id; return true; #else NOTREACHED(); return false; #endif } void FilterBuilder::AddHostnameHash(const std::string& hash, int site_id) { contents_->hash_site_map.insert(std::make_pair(StringToUpperASCII(hash), site_id)); } void FilterBuilder::AddSiteList(ManagedModeSiteList* site_list) { std::vector<ManagedModeSiteList::Site> sites; site_list->GetSites(&sites); int site_id = contents_->sites.size(); for (std::vector<ManagedModeSiteList::Site>::const_iterator it = sites.begin(); it != sites.end(); ++it) { const ManagedModeSiteList::Site& site = *it; contents_->sites.push_back(site); for (std::vector<std::string>::const_iterator pattern_it = site.patterns.begin(); pattern_it != site.patterns.end(); ++pattern_it) { AddPattern(*pattern_it, site_id); } for (std::vector<std::string>::const_iterator hash_it = site.hostname_hashes.begin(); hash_it != site.hostname_hashes.end(); ++hash_it) { AddHostnameHash(*hash_it, site_id); } site_id++; } } scoped_ptr<ManagedModeURLFilter::Contents> FilterBuilder::Build() { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); contents_->url_matcher.AddConditionSets(all_conditions_); return contents_.Pass(); } scoped_ptr<ManagedModeURLFilter::Contents> CreateWhitelistFromPatterns( const std::vector<std::string>& patterns) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); FilterBuilder builder; for (std::vector<std::string>::const_iterator it = patterns.begin(); it != patterns.end(); ++it) { // TODO(bauerb): We should create a fake site for the whitelist. builder.AddPattern(*it, -1); } return builder.Build(); } scoped_ptr<ManagedModeURLFilter::Contents> LoadWhitelistsOnBlockingPoolThread( ScopedVector<ManagedModeSiteList> site_lists) { DCHECK(BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); FilterBuilder builder; for (ScopedVector<ManagedModeSiteList>::iterator it = site_lists.begin(); it != site_lists.end(); ++it) { builder.AddSiteList(*it); } return builder.Build(); } } // namespace ManagedModeURLFilter::ManagedModeURLFilter() : default_behavior_(ALLOW), contents_(new Contents()) { // Detach from the current thread so we can be constructed on a different // thread than the one where we're used. DetachFromThread(); } ManagedModeURLFilter::~ManagedModeURLFilter() { DCHECK(CalledOnValidThread()); } // static ManagedModeURLFilter::FilteringBehavior ManagedModeURLFilter::BehaviorFromInt(int behavior_value) { DCHECK_GE(behavior_value, ALLOW); DCHECK_LE(behavior_value, BLOCK); return static_cast<FilteringBehavior>(behavior_value); } // static GURL ManagedModeURLFilter::Normalize(const GURL& url) { GURL normalized_url = url; GURL::Replacements replacements; // Strip username, password, query, and ref. replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); } ManagedModeURLFilter::FilteringBehavior ManagedModeURLFilter::GetFilteringBehaviorForURL(const GURL& url) const { DCHECK(CalledOnValidThread()); #if defined(ENABLE_CONFIGURATION_POLICY) // URLs with a non-standard scheme (e.g. chrome://) are always allowed. if (!policy::URLBlacklist::HasStandardScheme(url)) return ALLOW; #endif // Check manual overrides for the exact URL. std::map<GURL, bool>::const_iterator url_it = url_map_.find(Normalize(url)); if (url_it != url_map_.end()) return url_it->second ? ALLOW : BLOCK; // Check manual overrides for the hostname. std::map<std::string, bool>::const_iterator host_it = host_map_.find(url.host()); if (host_it != host_map_.end()) return host_it->second ? ALLOW : BLOCK; // If the default behavior is to allow, we don't need to check anything else. if (default_behavior_ == ALLOW) return ALLOW; // Check the list of URL patterns. std::set<URLMatcherConditionSet::ID> matching_ids = contents_->url_matcher.MatchURL(url); if (!matching_ids.empty()) return ALLOW; // Check the list of hostname hashes. std::string hash = base::SHA1HashString(url.host()); std::string hash_hex = base::HexEncode(hash.data(), hash.length()); if (contents_->hash_site_map.count(hash_hex)) return ALLOW; // Fall back to the default behavior. return default_behavior_; } void ManagedModeURLFilter::GetSites( const GURL& url, std::vector<ManagedModeSiteList::Site*>* sites) const { std::set<URLMatcherConditionSet::ID> matching_ids = contents_->url_matcher.MatchURL(url); for (std::set<URLMatcherConditionSet::ID>::const_iterator it = matching_ids.begin(); it != matching_ids.end(); ++it) { std::map<URLMatcherConditionSet::ID, int>::const_iterator entry = contents_->matcher_site_map.find(*it); if (entry == contents_->matcher_site_map.end()) { NOTREACHED(); continue; } sites->push_back(&contents_->sites[entry->second]); } typedef base::hash_map<std::string, int>::const_iterator hash_site_map_iterator; std::pair<hash_site_map_iterator, hash_site_map_iterator> bounds = contents_->hash_site_map.equal_range(url.host()); for (hash_site_map_iterator hash_it = bounds.first; hash_it != bounds.second; hash_it++) { sites->push_back(&contents_->sites[hash_it->second]); } } void ManagedModeURLFilter::SetDefaultFilteringBehavior( FilteringBehavior behavior) { DCHECK(CalledOnValidThread()); default_behavior_ = behavior; } void ManagedModeURLFilter::LoadWhitelists( ScopedVector<ManagedModeSiteList> site_lists) { DCHECK(CalledOnValidThread()); base::PostTaskAndReplyWithResult( BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&LoadWhitelistsOnBlockingPoolThread, base::Passed(&site_lists)), base::Bind(&ManagedModeURLFilter::SetContents, this)); } void ManagedModeURLFilter::SetFromPatterns( const std::vector<std::string>& patterns) { DCHECK(CalledOnValidThread()); base::PostTaskAndReplyWithResult( BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&CreateWhitelistFromPatterns, patterns), base::Bind(&ManagedModeURLFilter::SetContents, this)); } void ManagedModeURLFilter::SetManualHosts( const std::map<std::string, bool>* host_map) { DCHECK(CalledOnValidThread()); host_map_ = *host_map; UMA_HISTOGRAM_CUSTOM_COUNTS("ManagedMode.ManualHostsEntries", host_map->size(), 1, 1000, 50); } void ManagedModeURLFilter::SetManualURLs( const std::map<GURL, bool>* url_map) { DCHECK(CalledOnValidThread()); url_map_ = *url_map; UMA_HISTOGRAM_CUSTOM_COUNTS("ManagedMode.ManualURLsEntries", url_map->size(), 1, 1000, 50); } void ManagedModeURLFilter::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void ManagedModeURLFilter::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void ManagedModeURLFilter::SetContents(scoped_ptr<Contents> contents) { DCHECK(CalledOnValidThread()); contents_ = contents.Pass(); FOR_EACH_OBSERVER(Observer, observers_, OnSiteListUpdated()); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/media/media_internals_proxy.h" #include "base/bind.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/media/media_internals.h" #include "chrome/browser/ui/webui/media/media_internals_handler.h" #include "content/common/notification_service.h" #include "content/browser/renderer_host/render_process_host.h" static const int kMediaInternalsProxyEventDelayMilliseconds = 100; static const net::NetLog::EventType kNetEventTypeFilter[] = { net::NetLog::TYPE_DISK_CACHE_ENTRY_IMPL, net::NetLog::TYPE_SPARSE_READ, net::NetLog::TYPE_SPARSE_WRITE, net::NetLog::TYPE_URL_REQUEST_START_JOB, net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS, }; MediaInternalsProxy::MediaInternalsProxy() : ThreadSafeObserverImpl(net::NetLog::LOG_ALL_BUT_BYTES) { io_thread_ = g_browser_process->io_thread(); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, NotificationService::AllSources()); } void MediaInternalsProxy::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(type, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED); RenderProcessHost* process = Source<RenderProcessHost>(source).ptr(); CallJavaScriptFunctionOnUIThread("media.onRendererTerminated", base::Value::CreateIntegerValue(process->id())); } void MediaInternalsProxy::Attach(MediaInternalsMessageHandler* handler) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); handler_ = handler; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&MediaInternalsProxy::ObserveMediaInternalsOnIOThread, this)); } void MediaInternalsProxy::Detach() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); handler_ = NULL; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &MediaInternalsProxy::StopObservingMediaInternalsOnIOThread, this)); } void MediaInternalsProxy::GetEverything() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Ask MediaInternals for all its data. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&MediaInternalsProxy::GetEverythingOnIOThread, this)); // Send the page names for constants. CallJavaScriptFunctionOnUIThread("media.onReceiveConstants", GetConstants()); } void MediaInternalsProxy::OnUpdate(const string16& update) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaInternalsProxy::UpdateUIOnUIThread, this, update)); } void MediaInternalsProxy::OnAddEntry(net::NetLog::EventType type, const base::TimeTicks& time, const net::NetLog::Source& source, net::NetLog::EventPhase phase, net::NetLog::EventParameters* params) { bool is_event_interesting = false; for (size_t i = 0; i < arraysize(kNetEventTypeFilter); i++) { if (type == kNetEventTypeFilter[i]) { is_event_interesting = true; break; } } if (!is_event_interesting) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaInternalsProxy::AddNetEventOnUIThread, this, net::NetLog::EntryToDictionaryValue(type, time, source, phase, params, false))); } MediaInternalsProxy::~MediaInternalsProxy() {} Value* MediaInternalsProxy::GetConstants() { DictionaryValue* event_types = new DictionaryValue(); std::vector<net::NetLog::EventType> types_vec = net::NetLog::GetAllEventTypes(); for (size_t i = 0; i < types_vec.size(); ++i) { const char* name = net::NetLog::EventTypeToString(types_vec[i]); event_types->SetInteger(name, static_cast<int>(types_vec[i])); } DictionaryValue* event_phases = new DictionaryValue(); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_NONE), net::NetLog::PHASE_NONE); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_BEGIN), net::NetLog::PHASE_BEGIN); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_END), net::NetLog::PHASE_END); DictionaryValue* constants = new DictionaryValue(); constants->Set("eventTypes", event_types); constants->Set("eventPhases", event_phases); return constants; } void MediaInternalsProxy::ObserveMediaInternalsOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->AddObserver(this); // TODO(scottfr): Get the passive log data as well. AddAsObserver(io_thread_->net_log()); } void MediaInternalsProxy::StopObservingMediaInternalsOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->RemoveObserver(this); RemoveAsObserver(); } void MediaInternalsProxy::GetEverythingOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->SendEverything(); } void MediaInternalsProxy::UpdateUIOnUIThread(const string16& update) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Don't forward updates to a destructed UI. if (handler_) handler_->OnUpdate(update); } void MediaInternalsProxy::AddNetEventOnUIThread(Value* entry) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Send the updates to the page in kMediaInternalsProxyEventDelayMilliseconds // if an update is not already pending. if (!pending_net_updates_.get()) { pending_net_updates_.reset(new ListValue()); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MediaInternalsProxy::SendNetEventsOnUIThread, this), kMediaInternalsProxyEventDelayMilliseconds); } pending_net_updates_->Append(entry); } void MediaInternalsProxy::SendNetEventsOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CallJavaScriptFunctionOnUIThread("media.onNetUpdate", pending_net_updates_.release()); } void MediaInternalsProxy::CallJavaScriptFunctionOnUIThread( const std::string& function, Value* args) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); scoped_ptr<Value> args_value(args); std::vector<const Value*> args_vector; args_vector.push_back(args_value.get()); string16 update = WebUI::GetJavascriptCall(function, args_vector); UpdateUIOnUIThread(update); } <commit_msg>Change usage of AllSources to AllBrowserContextsAndSources to indicate that usage is safe for multiprofiles. <commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/media/media_internals_proxy.h" #include "base/bind.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/media/media_internals.h" #include "chrome/browser/ui/webui/media/media_internals_handler.h" #include "content/common/notification_service.h" #include "content/browser/renderer_host/render_process_host.h" static const int kMediaInternalsProxyEventDelayMilliseconds = 100; static const net::NetLog::EventType kNetEventTypeFilter[] = { net::NetLog::TYPE_DISK_CACHE_ENTRY_IMPL, net::NetLog::TYPE_SPARSE_READ, net::NetLog::TYPE_SPARSE_WRITE, net::NetLog::TYPE_URL_REQUEST_START_JOB, net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS, }; MediaInternalsProxy::MediaInternalsProxy() : ThreadSafeObserverImpl(net::NetLog::LOG_ALL_BUT_BYTES) { io_thread_ = g_browser_process->io_thread(); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, NotificationService::AllBrowserContextsAndSources()); } void MediaInternalsProxy::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(type, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED); RenderProcessHost* process = Source<RenderProcessHost>(source).ptr(); CallJavaScriptFunctionOnUIThread("media.onRendererTerminated", base::Value::CreateIntegerValue(process->id())); } void MediaInternalsProxy::Attach(MediaInternalsMessageHandler* handler) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); handler_ = handler; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&MediaInternalsProxy::ObserveMediaInternalsOnIOThread, this)); } void MediaInternalsProxy::Detach() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); handler_ = NULL; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &MediaInternalsProxy::StopObservingMediaInternalsOnIOThread, this)); } void MediaInternalsProxy::GetEverything() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Ask MediaInternals for all its data. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&MediaInternalsProxy::GetEverythingOnIOThread, this)); // Send the page names for constants. CallJavaScriptFunctionOnUIThread("media.onReceiveConstants", GetConstants()); } void MediaInternalsProxy::OnUpdate(const string16& update) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaInternalsProxy::UpdateUIOnUIThread, this, update)); } void MediaInternalsProxy::OnAddEntry(net::NetLog::EventType type, const base::TimeTicks& time, const net::NetLog::Source& source, net::NetLog::EventPhase phase, net::NetLog::EventParameters* params) { bool is_event_interesting = false; for (size_t i = 0; i < arraysize(kNetEventTypeFilter); i++) { if (type == kNetEventTypeFilter[i]) { is_event_interesting = true; break; } } if (!is_event_interesting) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&MediaInternalsProxy::AddNetEventOnUIThread, this, net::NetLog::EntryToDictionaryValue(type, time, source, phase, params, false))); } MediaInternalsProxy::~MediaInternalsProxy() {} Value* MediaInternalsProxy::GetConstants() { DictionaryValue* event_types = new DictionaryValue(); std::vector<net::NetLog::EventType> types_vec = net::NetLog::GetAllEventTypes(); for (size_t i = 0; i < types_vec.size(); ++i) { const char* name = net::NetLog::EventTypeToString(types_vec[i]); event_types->SetInteger(name, static_cast<int>(types_vec[i])); } DictionaryValue* event_phases = new DictionaryValue(); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_NONE), net::NetLog::PHASE_NONE); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_BEGIN), net::NetLog::PHASE_BEGIN); event_phases->SetInteger( net::NetLog::EventPhaseToString(net::NetLog::PHASE_END), net::NetLog::PHASE_END); DictionaryValue* constants = new DictionaryValue(); constants->Set("eventTypes", event_types); constants->Set("eventPhases", event_phases); return constants; } void MediaInternalsProxy::ObserveMediaInternalsOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->AddObserver(this); // TODO(scottfr): Get the passive log data as well. AddAsObserver(io_thread_->net_log()); } void MediaInternalsProxy::StopObservingMediaInternalsOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->RemoveObserver(this); RemoveAsObserver(); } void MediaInternalsProxy::GetEverythingOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_thread_->globals()->media.media_internals->SendEverything(); } void MediaInternalsProxy::UpdateUIOnUIThread(const string16& update) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Don't forward updates to a destructed UI. if (handler_) handler_->OnUpdate(update); } void MediaInternalsProxy::AddNetEventOnUIThread(Value* entry) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Send the updates to the page in kMediaInternalsProxyEventDelayMilliseconds // if an update is not already pending. if (!pending_net_updates_.get()) { pending_net_updates_.reset(new ListValue()); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MediaInternalsProxy::SendNetEventsOnUIThread, this), kMediaInternalsProxyEventDelayMilliseconds); } pending_net_updates_->Append(entry); } void MediaInternalsProxy::SendNetEventsOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CallJavaScriptFunctionOnUIThread("media.onNetUpdate", pending_net_updates_.release()); } void MediaInternalsProxy::CallJavaScriptFunctionOnUIThread( const std::string& function, Value* args) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); scoped_ptr<Value> args_value(args); std::vector<const Value*> args_vector; args_vector.push_back(args_value.get()); string16 update = WebUI::GetJavascriptCall(function, args_vector); UpdateUIOnUIThread(update); } <|endoftext|>
<commit_before>// Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "m2ts/webm2pes.h" #include <cstdint> #include <cstdio> #include <limits> #include <vector> #include "gtest/gtest.h" #include "common/file_util.h" #include "common/libwebm_util.h" #include "testing/test_util.h" namespace { struct PesOptionalHeader { int marker = 0; int scrambling = 0; int priority = 0; int data_alignment = 0; int copyright = 0; int original = 0; int has_pts = 0; int has_dts = 0; int unused_fields = 0; int remaining_size = 0; int pts_dts_flag = 0; std::uint64_t pts = 0; int stuffing_byte = 0; }; struct BcmvHeader { BcmvHeader() = default; ~BcmvHeader() = default; BcmvHeader(const BcmvHeader&) = delete; BcmvHeader(BcmvHeader&&) = delete; // Convenience ctor for quick validation of expected values via operator== // after parsing input. explicit BcmvHeader(std::uint32_t len) : length(len) { id[0] = 'B'; id[1] = 'C'; id[2] = 'M'; id[3] = 'V'; } bool operator==(const BcmvHeader& other) const { return (other.length == length && other.id[0] == id[0] && other.id[1] == id[1] && other.id[2] == id[2] && other.id[3] == id[3]); } bool Valid() const { return (length > 0 && length <= std::numeric_limits<std::uint16_t>::max() && id[0] == 'B' && id[1] == 'C' && id[2] == 'M' && id[3] == 'V'); } char id[4] = {0}; std::uint32_t length = 0; }; struct PesHeader { std::uint16_t packet_length = 0; PesOptionalHeader opt_header; BcmvHeader bcmv_header; }; class Webm2PesTests : public ::testing::Test { public: typedef std::vector<std::uint8_t> PesFileData; enum ParseState { kParsePesHeader, kParsePesOptionalHeader, kParseBcmvHeader, }; // Constants for validating known values from input data. const std::uint8_t kMinVideoStreamId = 0xE0; const std::uint8_t kMaxVideoStreamId = 0xEF; const int kPesHeaderSize = 6; const int kPesOptionalHeaderStartOffset = kPesHeaderSize; const int kPesOptionalHeaderSize = 9; const int kPesOptionalHeaderMarkerValue = 0x2; const int kWebm2PesOptHeaderRemainingSize = 6; const int kBcmvHeaderSize = 10; Webm2PesTests() : read_pos_(0), parse_state_(kParsePesHeader) {} void CreateAndLoadTestInput() { libwebm::Webm2Pes converter(input_file_name_, temp_file_name_.name()); ASSERT_TRUE(converter.ConvertToFile()); pes_file_size_ = libwebm::GetFileSize(pes_file_name()); ASSERT_GT(pes_file_size_, 0); pes_file_data_.reserve(pes_file_size_); libwebm::FilePtr file = libwebm::FilePtr( std::fopen(pes_file_name().c_str(), "rb"), libwebm::FILEDeleter()); int byte; while ((byte = fgetc(file.get())) != EOF) pes_file_data_.push_back(static_cast<std::uint8_t>(byte)); ASSERT_TRUE(feof(file.get()) && !ferror(file.get())); ASSERT_EQ(pes_file_size_, static_cast<std::int64_t>(pes_file_data_.size())); read_pos_ = 0; parse_state_ = kParsePesHeader; } bool VerifyPacketStartCode() { EXPECT_LT(read_pos_ + 2, pes_file_data_.size()); // PES packets all start with the byte sequence 0x0 0x0 0x1. if (pes_file_data_[read_pos_] != 0 || pes_file_data_[read_pos_ + 1] != 0 || pes_file_data_[read_pos_ + 2] != 1) { return false; } return true; } std::uint8_t ReadStreamId() { EXPECT_LT(read_pos_ + 3, pes_file_data_.size()); return pes_file_data_[read_pos_ + 3]; } std::uint16_t ReadPacketLength() { EXPECT_LT(read_pos_ + 5, pes_file_data_.size()); // Read and byte swap 16 bit big endian length. return (pes_file_data_[read_pos_ + 4] << 8) | pes_file_data_[read_pos_ + 5]; } void ParsePesHeader(PesHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParsePesHeader, parse_state_); EXPECT_TRUE(VerifyPacketStartCode()); // PES Video stream IDs start at E0. EXPECT_GE(ReadStreamId(), kMinVideoStreamId); EXPECT_LE(ReadStreamId(), kMaxVideoStreamId); header->packet_length = ReadPacketLength(); read_pos_ += kPesHeaderSize; parse_state_ = kParsePesOptionalHeader; } // Parses a PES optional header. // https://en.wikipedia.org/wiki/Packetized_elementary_stream // TODO(tomfinegan): Make these masks constants. void ParsePesOptionalHeader(PesOptionalHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParsePesOptionalHeader, parse_state_); int offset = read_pos_; EXPECT_LT(offset, pes_file_size_); header->marker = (pes_file_data_[offset] & 0x80) >> 6; header->scrambling = (pes_file_data_[offset] & 0x30) >> 4; header->priority = (pes_file_data_[offset] & 0x8) >> 3; header->data_alignment = (pes_file_data_[offset] & 0xc) >> 2; header->copyright = (pes_file_data_[offset] & 0x2) >> 1; header->original = pes_file_data_[offset] & 0x1; offset++; header->has_pts = (pes_file_data_[offset] & 0x80) >> 7; header->has_dts = (pes_file_data_[offset] & 0x40) >> 6; header->unused_fields = pes_file_data_[offset] & 0x3f; offset++; header->remaining_size = pes_file_data_[offset]; EXPECT_EQ(kWebm2PesOptHeaderRemainingSize, header->remaining_size); int bytes_left = header->remaining_size; if (header->has_pts) { // Read PTS markers. Format: // PTS: 5 bytes // 4 bits (flag: PTS present, but no DTS): 0x2 ('0010') // 36 bits (90khz PTS): // top 3 bits // marker ('1') // middle 15 bits // marker ('1') // bottom 15 bits // marker ('1') // TODO(tomfinegan): Extract some golden timestamp values and actually // read the timestamp. offset++; header->pts_dts_flag = (pes_file_data_[offset] & 0x20) >> 4; // Check the marker bits. int marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); offset += 2; marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); offset += 2; marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); bytes_left -= 5; offset++; } // Validate stuffing byte(s). for (int i = 0; i < bytes_left; ++i) EXPECT_EQ(0xff, pes_file_data_[offset + i]); offset += bytes_left; EXPECT_EQ(kPesHeaderSize + kPesOptionalHeaderSize, offset); read_pos_ += kPesOptionalHeaderSize; parse_state_ = kParseBcmvHeader; } // Parses and validates a BCMV header. void ParseBcmvHeader(BcmvHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParseBcmvHeader, kParseBcmvHeader); std::size_t offset = read_pos_; header->id[0] = pes_file_data_[offset++]; header->id[1] = pes_file_data_[offset++]; header->id[2] = pes_file_data_[offset++]; header->id[3] = pes_file_data_[offset++]; header->length |= pes_file_data_[offset++] << 24; header->length |= pes_file_data_[offset++] << 16; header->length |= pes_file_data_[offset++] << 8; header->length |= pes_file_data_[offset++]; // Length stored in the BCMV header is followed by 2 bytes of 0 padding. EXPECT_EQ(0, pes_file_data_[offset++]); EXPECT_EQ(0, pes_file_data_[offset++]); EXPECT_TRUE(header->Valid()); // TODO(tomfinegan): Verify data instead of jumping to the next packet. read_pos_ += kBcmvHeaderSize + header->length; parse_state_ = kParsePesHeader; } ~Webm2PesTests() = default; const std::string& pes_file_name() const { return temp_file_name_.name(); } std::uint64_t pes_file_size() const { return pes_file_size_; } const PesFileData& pes_file_data() const { return pes_file_data_; } private: const libwebm::TempFileDeleter temp_file_name_; const std::string input_file_name_ = libwebm::test::GetTestFilePath("bbb_480p_vp9_opus_1second.webm"); std::int64_t pes_file_size_ = 0; PesFileData pes_file_data_; std::size_t read_pos_; ParseState parse_state_; }; TEST_F(Webm2PesTests, CreatePesFile) { CreateAndLoadTestInput(); } TEST_F(Webm2PesTests, CanParseFirstPacket) { CreateAndLoadTestInput(); // // Parse the PES Header. // This is number of bytes following the final byte in the 6 byte static PES // header. PES optional header is 9 bytes. Payload is 83 bytes. PesHeader header; ParsePesHeader(&header); const std::size_t kPesOptionalHeaderLength = 9; const std::size_t kFirstFrameLength = 83; const std::size_t kPesPayloadLength = kPesOptionalHeaderLength + kFirstFrameLength; EXPECT_EQ(kPesPayloadLength, header.packet_length); // // Parse the PES optional header. // ParsePesOptionalHeader(&header.opt_header); EXPECT_EQ(kPesOptionalHeaderMarkerValue, header.opt_header.marker); EXPECT_EQ(0, header.opt_header.scrambling); EXPECT_EQ(0, header.opt_header.priority); EXPECT_EQ(0, header.opt_header.data_alignment); EXPECT_EQ(0, header.opt_header.copyright); EXPECT_EQ(0, header.opt_header.original); EXPECT_EQ(1, header.opt_header.has_pts); EXPECT_EQ(0, header.opt_header.has_dts); EXPECT_EQ(0, header.opt_header.unused_fields); // // Parse the BCMV Header // ParseBcmvHeader(&header.bcmv_header); EXPECT_EQ(kFirstFrameLength, header.bcmv_header.length); // Parse the next PES header to confirm correct parsing and consumption of // payload. ParsePesHeader(&header); } } // namespace int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>iwyu/webm2pes_tests: Update includes.<commit_after>// Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "m2ts/webm2pes.h" #include <cstddef> #include <cstdint> #include <cstdio> #include <limits> #include <string> #include <vector> #include "gtest/gtest.h" #include "common/file_util.h" #include "common/libwebm_util.h" #include "testing/test_util.h" namespace { struct PesOptionalHeader { int marker = 0; int scrambling = 0; int priority = 0; int data_alignment = 0; int copyright = 0; int original = 0; int has_pts = 0; int has_dts = 0; int unused_fields = 0; int remaining_size = 0; int pts_dts_flag = 0; std::uint64_t pts = 0; int stuffing_byte = 0; }; struct BcmvHeader { BcmvHeader() = default; ~BcmvHeader() = default; BcmvHeader(const BcmvHeader&) = delete; BcmvHeader(BcmvHeader&&) = delete; // Convenience ctor for quick validation of expected values via operator== // after parsing input. explicit BcmvHeader(std::uint32_t len) : length(len) { id[0] = 'B'; id[1] = 'C'; id[2] = 'M'; id[3] = 'V'; } bool operator==(const BcmvHeader& other) const { return (other.length == length && other.id[0] == id[0] && other.id[1] == id[1] && other.id[2] == id[2] && other.id[3] == id[3]); } bool Valid() const { return (length > 0 && length <= std::numeric_limits<std::uint16_t>::max() && id[0] == 'B' && id[1] == 'C' && id[2] == 'M' && id[3] == 'V'); } char id[4] = {0}; std::uint32_t length = 0; }; struct PesHeader { std::uint16_t packet_length = 0; PesOptionalHeader opt_header; BcmvHeader bcmv_header; }; class Webm2PesTests : public ::testing::Test { public: typedef std::vector<std::uint8_t> PesFileData; enum ParseState { kParsePesHeader, kParsePesOptionalHeader, kParseBcmvHeader, }; // Constants for validating known values from input data. const std::uint8_t kMinVideoStreamId = 0xE0; const std::uint8_t kMaxVideoStreamId = 0xEF; const int kPesHeaderSize = 6; const int kPesOptionalHeaderStartOffset = kPesHeaderSize; const int kPesOptionalHeaderSize = 9; const int kPesOptionalHeaderMarkerValue = 0x2; const int kWebm2PesOptHeaderRemainingSize = 6; const int kBcmvHeaderSize = 10; Webm2PesTests() : read_pos_(0), parse_state_(kParsePesHeader) {} void CreateAndLoadTestInput() { libwebm::Webm2Pes converter(input_file_name_, temp_file_name_.name()); ASSERT_TRUE(converter.ConvertToFile()); pes_file_size_ = libwebm::GetFileSize(pes_file_name()); ASSERT_GT(pes_file_size_, 0); pes_file_data_.reserve(pes_file_size_); libwebm::FilePtr file = libwebm::FilePtr( std::fopen(pes_file_name().c_str(), "rb"), libwebm::FILEDeleter()); int byte; while ((byte = fgetc(file.get())) != EOF) pes_file_data_.push_back(static_cast<std::uint8_t>(byte)); ASSERT_TRUE(feof(file.get()) && !ferror(file.get())); ASSERT_EQ(pes_file_size_, static_cast<std::int64_t>(pes_file_data_.size())); read_pos_ = 0; parse_state_ = kParsePesHeader; } bool VerifyPacketStartCode() { EXPECT_LT(read_pos_ + 2, pes_file_data_.size()); // PES packets all start with the byte sequence 0x0 0x0 0x1. if (pes_file_data_[read_pos_] != 0 || pes_file_data_[read_pos_ + 1] != 0 || pes_file_data_[read_pos_ + 2] != 1) { return false; } return true; } std::uint8_t ReadStreamId() { EXPECT_LT(read_pos_ + 3, pes_file_data_.size()); return pes_file_data_[read_pos_ + 3]; } std::uint16_t ReadPacketLength() { EXPECT_LT(read_pos_ + 5, pes_file_data_.size()); // Read and byte swap 16 bit big endian length. return (pes_file_data_[read_pos_ + 4] << 8) | pes_file_data_[read_pos_ + 5]; } void ParsePesHeader(PesHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParsePesHeader, parse_state_); EXPECT_TRUE(VerifyPacketStartCode()); // PES Video stream IDs start at E0. EXPECT_GE(ReadStreamId(), kMinVideoStreamId); EXPECT_LE(ReadStreamId(), kMaxVideoStreamId); header->packet_length = ReadPacketLength(); read_pos_ += kPesHeaderSize; parse_state_ = kParsePesOptionalHeader; } // Parses a PES optional header. // https://en.wikipedia.org/wiki/Packetized_elementary_stream // TODO(tomfinegan): Make these masks constants. void ParsePesOptionalHeader(PesOptionalHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParsePesOptionalHeader, parse_state_); int offset = read_pos_; EXPECT_LT(offset, pes_file_size_); header->marker = (pes_file_data_[offset] & 0x80) >> 6; header->scrambling = (pes_file_data_[offset] & 0x30) >> 4; header->priority = (pes_file_data_[offset] & 0x8) >> 3; header->data_alignment = (pes_file_data_[offset] & 0xc) >> 2; header->copyright = (pes_file_data_[offset] & 0x2) >> 1; header->original = pes_file_data_[offset] & 0x1; offset++; header->has_pts = (pes_file_data_[offset] & 0x80) >> 7; header->has_dts = (pes_file_data_[offset] & 0x40) >> 6; header->unused_fields = pes_file_data_[offset] & 0x3f; offset++; header->remaining_size = pes_file_data_[offset]; EXPECT_EQ(kWebm2PesOptHeaderRemainingSize, header->remaining_size); int bytes_left = header->remaining_size; if (header->has_pts) { // Read PTS markers. Format: // PTS: 5 bytes // 4 bits (flag: PTS present, but no DTS): 0x2 ('0010') // 36 bits (90khz PTS): // top 3 bits // marker ('1') // middle 15 bits // marker ('1') // bottom 15 bits // marker ('1') // TODO(tomfinegan): Extract some golden timestamp values and actually // read the timestamp. offset++; header->pts_dts_flag = (pes_file_data_[offset] & 0x20) >> 4; // Check the marker bits. int marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); offset += 2; marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); offset += 2; marker_bit = pes_file_data_[offset] & 1; EXPECT_EQ(1, marker_bit); bytes_left -= 5; offset++; } // Validate stuffing byte(s). for (int i = 0; i < bytes_left; ++i) EXPECT_EQ(0xff, pes_file_data_[offset + i]); offset += bytes_left; EXPECT_EQ(kPesHeaderSize + kPesOptionalHeaderSize, offset); read_pos_ += kPesOptionalHeaderSize; parse_state_ = kParseBcmvHeader; } // Parses and validates a BCMV header. void ParseBcmvHeader(BcmvHeader* header) { ASSERT_TRUE(header != nullptr); EXPECT_EQ(kParseBcmvHeader, kParseBcmvHeader); std::size_t offset = read_pos_; header->id[0] = pes_file_data_[offset++]; header->id[1] = pes_file_data_[offset++]; header->id[2] = pes_file_data_[offset++]; header->id[3] = pes_file_data_[offset++]; header->length |= pes_file_data_[offset++] << 24; header->length |= pes_file_data_[offset++] << 16; header->length |= pes_file_data_[offset++] << 8; header->length |= pes_file_data_[offset++]; // Length stored in the BCMV header is followed by 2 bytes of 0 padding. EXPECT_EQ(0, pes_file_data_[offset++]); EXPECT_EQ(0, pes_file_data_[offset++]); EXPECT_TRUE(header->Valid()); // TODO(tomfinegan): Verify data instead of jumping to the next packet. read_pos_ += kBcmvHeaderSize + header->length; parse_state_ = kParsePesHeader; } ~Webm2PesTests() = default; const std::string& pes_file_name() const { return temp_file_name_.name(); } std::uint64_t pes_file_size() const { return pes_file_size_; } const PesFileData& pes_file_data() const { return pes_file_data_; } private: const libwebm::TempFileDeleter temp_file_name_; const std::string input_file_name_ = libwebm::test::GetTestFilePath("bbb_480p_vp9_opus_1second.webm"); std::int64_t pes_file_size_ = 0; PesFileData pes_file_data_; std::size_t read_pos_; ParseState parse_state_; }; TEST_F(Webm2PesTests, CreatePesFile) { CreateAndLoadTestInput(); } TEST_F(Webm2PesTests, CanParseFirstPacket) { CreateAndLoadTestInput(); // // Parse the PES Header. // This is number of bytes following the final byte in the 6 byte static PES // header. PES optional header is 9 bytes. Payload is 83 bytes. PesHeader header; ParsePesHeader(&header); const std::size_t kPesOptionalHeaderLength = 9; const std::size_t kFirstFrameLength = 83; const std::size_t kPesPayloadLength = kPesOptionalHeaderLength + kFirstFrameLength; EXPECT_EQ(kPesPayloadLength, header.packet_length); // // Parse the PES optional header. // ParsePesOptionalHeader(&header.opt_header); EXPECT_EQ(kPesOptionalHeaderMarkerValue, header.opt_header.marker); EXPECT_EQ(0, header.opt_header.scrambling); EXPECT_EQ(0, header.opt_header.priority); EXPECT_EQ(0, header.opt_header.data_alignment); EXPECT_EQ(0, header.opt_header.copyright); EXPECT_EQ(0, header.opt_header.original); EXPECT_EQ(1, header.opt_header.has_pts); EXPECT_EQ(0, header.opt_header.has_dts); EXPECT_EQ(0, header.opt_header.unused_fields); // // Parse the BCMV Header // ParseBcmvHeader(&header.bcmv_header); EXPECT_EQ(kFirstFrameLength, header.bcmv_header.length); // Parse the next PES header to confirm correct parsing and consumption of // payload. ParsePesHeader(&header); } } // namespace int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "config.h" #include "vm.hpp" #include "state.hpp" #include "on_stack.hpp" #include "memory.hpp" #include "call_frame.hpp" #include "metrics.hpp" #include "exception_point.hpp" #include "thread_phase.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/module.hpp" #include "builtin/thread.hpp" #include "builtin/native_method.hpp" #include "builtin/call_site.hpp" #include "capi/handle.hpp" #include "memory/finalizer.hpp" #include "logger.hpp" #include "dtrace/dtrace.h" namespace rubinius { namespace memory { void NativeFinalizer::finalize(STATE) { (*finalizer_)(state, object()); } void NativeFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(object())) { object(fwd); } } void ExtensionFinalizer::finalize(STATE) { ManagedPhase managed(state); NativeMethodEnvironment* env = state->vm()->native_method_environment; NativeMethodFrame nmf(env, 0, 0); ExceptionPoint ep(env); CallFrame* previous_frame = 0; CallFrame* call_frame = ALLOCA_CALL_FRAME(0); call_frame->previous = NULL; call_frame->constant_scope_ = 0; call_frame->dispatch_data = (void*)&nmf; call_frame->compiled_code = 0; call_frame->flags = CallFrame::cNativeMethod; call_frame->top_scope_ = 0; call_frame->scope = 0; call_frame->arguments = 0; env->set_current_call_frame(0); env->set_current_native_frame(&nmf); // Register the CallFrame, because we might GC below this. if(state->vm()->push_call_frame(state, call_frame, previous_frame)) { nmf.setup(Qnil, Qnil, Qnil, Qnil); PLACE_EXCEPTION_POINT(ep); if(unlikely(ep.jumped_to())) { logger::warn( "finalizer: an exception occurred running a NativeMethod finalizer"); } else { (*finalizer_)(state, object()); } state->vm()->pop_call_frame(state, previous_frame); env->set_current_call_frame(0); env->set_current_native_frame(0); } else { logger::warn("finalizer: stack error"); } } void ExtensionFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(object())) { object(fwd); } } void ManagedFinalizer::finalize(STATE) { ManagedPhase managed(state); /* Rubinius specific code. If the finalizer is cTrue, then send the * object the __finalize__ message. */ if(finalizer_->true_p()) { object()->send(state, state->symbol("__finalize__")); } else { Array* ary = Array::create(state, 1); ary->set(state, 0, object()->id(state)); if(!finalizer_->send(state, G(sym_call), ary)) { if(state->vm()->thread_state()->raise_reason() == cException) { logger::warn( "finalizer: an exception occurred running a Ruby finalizer: %s", state->vm()->thread_state()->current_exception()->message_c_str(state)); } } } } void ManagedFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(finalizer_)) { finalizer_ = fwd; } if(Object* fwd = gc->saw_object(object())) { object(fwd); } } bool ManagedFinalizer::match_p(STATE, Object* object, Object* finalizer) { bool match = false; if(this->object() == object) { if(!finalizer->nil_p()) { Array* args = Array::create(state, 1); args->set(state, 0, finalizer_); Object* result = finalizer->send(state, G(sym_equal), args); match = result && CBOOL(result); } } return match; } FinalizerThread::FinalizerThread(STATE) : MachineThread(state, "rbx.finalizer", MachineThread::eLarge) , live_list_() , process_list_() , synchronization_(NULL) , finishing_(false) { initialize(state); state->shared().set_finalizer(this); } FinalizerThread::~FinalizerThread() { if(!live_list_.empty()) { rubinius::bug("FinalizerThread destructed with remaining finalizer objects"); } if(!process_list_.empty()) { rubinius::bug("FinalizerThread destructed with remaining to-be-finalized objects"); } cleanup(); } void FinalizerThread::cleanup() { if(synchronization_) { delete synchronization_; synchronization_ = NULL; } } void FinalizerThread::after_fork_child(STATE) { cleanup(); MachineThread::after_fork_child(state); } void FinalizerThread::initialize(STATE) { synchronization_ = new Synchronization(); } void FinalizerThread::wakeup(STATE) { MachineThread::wakeup(state); while(thread_running_) { synchronization_->list_condition().notify_one(); } } void FinalizerThread::stop(STATE) { state->shared().machine_threads()->unregister_thread(this); stop_thread(state); } void FinalizerThread::run(STATE) { state->vm()->managed_phase(); while(true) { FinalizerObject* object = 0; { std::unique_lock<std::mutex> lk(synchronization_->list_mutex()); while(!thread_exit_ && process_list_.empty()) { UnmanagedPhase unmanaged(state); synchronization_->list_condition().wait(lk); } if(thread_exit_) return; if(!process_list_.empty()) { object = process_list_.back(); process_list_.pop_back(); } } state->vm()->thread_nexus()->yield(state->vm()); if(object) { object->finalize(state); delete object; vm()->metrics().gc.objects_finalized++; } } } void FinalizerThread::finish(STATE) { finishing_ = true; // TODO: cleanup while(!process_list_.empty()) { FinalizerObject* fo = process_list_.back(); process_list_.pop_back(); fo->finalize(state); delete fo; vm()->metrics().gc.objects_finalized++; } while(!live_list_.empty()) { FinalizerObject* fo = live_list_.back(); live_list_.pop_back(); fo->finalize(state); delete fo; vm()->metrics().gc.objects_finalized++; } } void FinalizerThread::native_finalizer(STATE, Object* obj, FinalizerFunction func) { if(finishing_) return; add_finalizer(state, new NativeFinalizer(state, obj, func)); } void FinalizerThread::extension_finalizer(STATE, Object* obj, FinalizerFunction func) { if(finishing_) return; add_finalizer(state, new ExtensionFinalizer(state, obj, func)); } void FinalizerThread::managed_finalizer(STATE, Object* obj, Object* finalizer) { if(finishing_) return; { std::lock_guard<std::mutex> guard(synchronization_->list_mutex()); for(FinalizerObjects::iterator i = live_list_.begin(); i != live_list_.end(); ++i) { FinalizerObject* fo = *i; /* TODO: Since Ruby allows any number of finalizers on a single * object as long as the finalizer "callable" is different, we have * to do a complex comparison to determine if the "callable" is * different. This results in a method send, which can cause a * CompiledCode instance to be internalized, adding CallSite object * finalizers, so we cannot keep this locked across this call. * * This is an utter mess and either needs to be moved into the Ruby * .define_finalizer method or locking handled differently on this * list. */ synchronization_->list_mutex().unlock(); if(fo->match_p(state, obj, finalizer)) { if(finalizer->nil_p()) { live_list_.erase(i); } else { synchronization_->list_mutex().lock(); return; } } synchronization_->list_mutex().lock(); } } add_finalizer(state, new ManagedFinalizer(state, obj, finalizer)); } void FinalizerThread::add_finalizer(STATE, FinalizerObject* obj) { std::lock_guard<std::mutex> guard(synchronization_->list_mutex()); live_list_.push_back(obj); vm()->metrics().gc.objects_queued++; } void FinalizerThread::gc_scan(ImmixGC* gc, Memory* memory) { for(FinalizerObjects::iterator i = live_list_.begin(); i != live_list_.end(); /* advance is handled in the loop */) { FinalizerObject* fo = *i; if(!fo->object()->marked_p(memory->mark())) { process_list_.push_back(*i); i = live_list_.erase(i); } else { ++i; } } for(FinalizerObjects::iterator i = process_list_.begin(); i != process_list_.end(); ++i) { FinalizerObject* fo = *i; fo->mark(gc); } synchronization_->list_condition().notify_one(); } } } <commit_msg>Re-added Rubinius define_finalizer extension.<commit_after>#include "config.h" #include "vm.hpp" #include "state.hpp" #include "on_stack.hpp" #include "memory.hpp" #include "call_frame.hpp" #include "metrics.hpp" #include "exception_point.hpp" #include "thread_phase.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/module.hpp" #include "builtin/thread.hpp" #include "builtin/native_method.hpp" #include "builtin/call_site.hpp" #include "capi/handle.hpp" #include "memory/finalizer.hpp" #include "logger.hpp" #include "dtrace/dtrace.h" namespace rubinius { namespace memory { void NativeFinalizer::finalize(STATE) { (*finalizer_)(state, object()); } void NativeFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(object())) { object(fwd); } } void ExtensionFinalizer::finalize(STATE) { ManagedPhase managed(state); NativeMethodEnvironment* env = state->vm()->native_method_environment; NativeMethodFrame nmf(env, 0, 0); ExceptionPoint ep(env); CallFrame* previous_frame = 0; CallFrame* call_frame = ALLOCA_CALL_FRAME(0); call_frame->previous = NULL; call_frame->constant_scope_ = 0; call_frame->dispatch_data = (void*)&nmf; call_frame->compiled_code = 0; call_frame->flags = CallFrame::cNativeMethod; call_frame->top_scope_ = 0; call_frame->scope = 0; call_frame->arguments = 0; env->set_current_call_frame(0); env->set_current_native_frame(&nmf); // Register the CallFrame, because we might GC below this. if(state->vm()->push_call_frame(state, call_frame, previous_frame)) { nmf.setup(Qnil, Qnil, Qnil, Qnil); PLACE_EXCEPTION_POINT(ep); if(unlikely(ep.jumped_to())) { logger::warn( "finalizer: an exception occurred running a NativeMethod finalizer"); } else { (*finalizer_)(state, object()); } state->vm()->pop_call_frame(state, previous_frame); env->set_current_call_frame(0); env->set_current_native_frame(0); } else { logger::warn("finalizer: stack error"); } } void ExtensionFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(object())) { object(fwd); } } void ManagedFinalizer::finalize(STATE) { ManagedPhase managed(state); /* Rubinius specific code. If the finalizer is cTrue, then send the * object the __finalize__ message. */ if(finalizer_->true_p()) { object()->send(state, state->symbol("__finalize__")); } else { Array* ary = Array::create(state, 1); ary->set(state, 0, object()->id(state)); if(!finalizer_->send(state, G(sym_call), ary)) { if(state->vm()->thread_state()->raise_reason() == cException) { logger::warn( "finalizer: an exception occurred running a Ruby finalizer: %s", state->vm()->thread_state()->current_exception()->message_c_str(state)); } } } } void ManagedFinalizer::mark(ImmixGC* gc) { if(Object* fwd = gc->saw_object(finalizer_)) { finalizer_ = fwd; } if(Object* fwd = gc->saw_object(object())) { object(fwd); } } bool ManagedFinalizer::match_p(STATE, Object* object, Object* finalizer) { bool match = false; if(this->object() == object) { if(!finalizer->nil_p()) { Array* args = Array::create(state, 1); args->set(state, 0, finalizer_); Object* result = finalizer->send(state, G(sym_equal), args); match = result && CBOOL(result); } } return match; } FinalizerThread::FinalizerThread(STATE) : MachineThread(state, "rbx.finalizer", MachineThread::eLarge) , live_list_() , process_list_() , synchronization_(NULL) , finishing_(false) { initialize(state); state->shared().set_finalizer(this); } FinalizerThread::~FinalizerThread() { if(!live_list_.empty()) { rubinius::bug("FinalizerThread destructed with remaining finalizer objects"); } if(!process_list_.empty()) { rubinius::bug("FinalizerThread destructed with remaining to-be-finalized objects"); } cleanup(); } void FinalizerThread::cleanup() { if(synchronization_) { delete synchronization_; synchronization_ = NULL; } } void FinalizerThread::after_fork_child(STATE) { cleanup(); MachineThread::after_fork_child(state); } void FinalizerThread::initialize(STATE) { synchronization_ = new Synchronization(); } void FinalizerThread::wakeup(STATE) { MachineThread::wakeup(state); while(thread_running_) { synchronization_->list_condition().notify_one(); } } void FinalizerThread::stop(STATE) { state->shared().machine_threads()->unregister_thread(this); stop_thread(state); } void FinalizerThread::run(STATE) { state->vm()->managed_phase(); while(true) { FinalizerObject* object = 0; { std::unique_lock<std::mutex> lk(synchronization_->list_mutex()); while(!thread_exit_ && process_list_.empty()) { UnmanagedPhase unmanaged(state); synchronization_->list_condition().wait(lk); } if(thread_exit_) return; if(!process_list_.empty()) { object = process_list_.back(); process_list_.pop_back(); } } state->vm()->thread_nexus()->yield(state->vm()); if(object) { object->finalize(state); delete object; vm()->metrics().gc.objects_finalized++; } } } void FinalizerThread::finish(STATE) { finishing_ = true; // TODO: cleanup while(!process_list_.empty()) { FinalizerObject* fo = process_list_.back(); process_list_.pop_back(); fo->finalize(state); delete fo; vm()->metrics().gc.objects_finalized++; } while(!live_list_.empty()) { FinalizerObject* fo = live_list_.back(); live_list_.pop_back(); fo->finalize(state); delete fo; vm()->metrics().gc.objects_finalized++; } } void FinalizerThread::native_finalizer(STATE, Object* obj, FinalizerFunction func) { if(finishing_) return; add_finalizer(state, new NativeFinalizer(state, obj, func)); } void FinalizerThread::extension_finalizer(STATE, Object* obj, FinalizerFunction func) { if(finishing_) return; add_finalizer(state, new ExtensionFinalizer(state, obj, func)); } void FinalizerThread::managed_finalizer(STATE, Object* obj, Object* finalizer) { if(finishing_) return; { std::lock_guard<std::mutex> guard(synchronization_->list_mutex()); for(FinalizerObjects::iterator i = live_list_.begin(); i != live_list_.end(); ++i) { FinalizerObject* fo = *i; /* TODO: Since Ruby allows any number of finalizers on a single * object as long as the finalizer "callable" is different, we have * to do a complex comparison to determine if the "callable" is * different. This results in a method send, which can cause a * CompiledCode instance to be internalized, adding CallSite object * finalizers, so we cannot keep this locked across this call. * * This is an utter mess and either needs to be moved into the Ruby * .define_finalizer method or locking handled differently on this * list. */ synchronization_->list_mutex().unlock(); if(fo->match_p(state, obj, finalizer)) { if(finalizer->nil_p()) { live_list_.erase(i); } else { synchronization_->list_mutex().lock(); return; } } synchronization_->list_mutex().lock(); } } /* Rubinius specific API. If the finalizer is the object, we're going to * send the object __finalize__. We mark that the user wants this by * putting cTrue as the ruby_finalizer. */ add_finalizer(state, new ManagedFinalizer(state, obj, obj == finalizer ? cTrue : finalizer)); } void FinalizerThread::add_finalizer(STATE, FinalizerObject* obj) { std::lock_guard<std::mutex> guard(synchronization_->list_mutex()); live_list_.push_back(obj); vm()->metrics().gc.objects_queued++; } void FinalizerThread::gc_scan(ImmixGC* gc, Memory* memory) { for(FinalizerObjects::iterator i = live_list_.begin(); i != live_list_.end(); /* advance is handled in the loop */) { FinalizerObject* fo = *i; if(!fo->object()->marked_p(memory->mark())) { process_list_.push_back(*i); i = live_list_.erase(i); } else { ++i; } } for(FinalizerObjects::iterator i = process_list_.begin(); i != process_list_.end(); ++i) { FinalizerObject* fo = *i; fo->mark(gc); } synchronization_->list_condition().notify_one(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSLCReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSLCReader.h" #include "vtkDataArray.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include <ctype.h> vtkStandardNewMacro(vtkSLCReader); // Constructor for a vtkSLCReader. vtkSLCReader::vtkSLCReader() { this->FileName = NULL; this->Error = 0; } vtkSLCReader::~vtkSLCReader() { } // Decodes an array of eight bit run-length encoded data. unsigned char* vtkSLCReader::Decode8BitData( unsigned char *in_ptr, int size ) { unsigned char *curr_ptr; unsigned char *decode_ptr; unsigned char *return_ptr; unsigned char current_value; unsigned char remaining; int done=0; curr_ptr = in_ptr; decode_ptr = return_ptr = new unsigned char[size]; while( !done ) { current_value = *(curr_ptr++); if( !(remaining = (current_value & 0x7f)) ) { break; } if( current_value & 0x80 ) { while( remaining-- ) { *(decode_ptr++) = *(curr_ptr++); } } else { current_value = *(curr_ptr++); while ( remaining-- ) { *(decode_ptr++) = current_value; } } } return return_ptr; } // This will be needed when we make this an imaging filter. int vtkSLCReader::RequestInformation ( vtkInformation * request, vtkInformationVector** inputVector, vtkInformationVector * outputVector) { FILE *fp; int temp; double f[3]; int size[3]; int magic_num; this->Error = 1; if (!this->FileName) { vtkErrorMacro(<<"A FileName must be specified."); return 0; } // Initialize if ((fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<< "File " << this->FileName << " not found"); return 0; } this->FileDimensionality = 3; if (fscanf( fp, "%d", &magic_num ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read magic number"); return 1; } if( magic_num != 11111 ) { vtkErrorMacro(<< "SLC magic number is not correct"); return 1; } f[0] = f[1] = f[2] = 0.0; this->SetDataOrigin(f); if (fscanf( fp, "%d", size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[0]"); return 1; } if (fscanf( fp, "%d", size+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[1]"); return 1; } if (fscanf( fp, "%d", size+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[2]"); return 1; } this->SetDataExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); // Skip Over bits_per_voxel Field */ if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over bits per pixel"); return 1; } if (fscanf( fp, "%lf", f ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[0]"); return 1; } if (fscanf( fp, "%lf", f+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[1]"); return 1; } if (fscanf( fp, "%lf", f+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[2]"); return 1; } this->SetDataSpacing(f); // Skip Over unit_type, data_origin, and data_modification if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over unit type"); return 1; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data origin"); return 1; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data modification"); return 1; } this->SetDataScalarType(VTK_UNSIGNED_CHAR); this->SetNumberOfScalarComponents(1); fclose( fp ); return this->Superclass::RequestInformation(request, inputVector, outputVector); } // Reads an SLC file and creates a vtkStructuredPoints dataset. void vtkSLCReader::ExecuteDataWithInformation(vtkDataObject *output_do, vtkInformation *vtkNotUsed(outInfo)) { vtkImageData *output = vtkImageData::SafeDownCast(output_do); FILE *fp; int temp; int data_compression; int plane_size; double f[3]; int size[3]; int magic_num; int z_counter; int icon_width, icon_height; int compressed_size; unsigned char *icon_ptr; unsigned char *compressed_ptr; unsigned char *scan_ptr = NULL; this->Error = 1; if (!this->FileName) { vtkErrorMacro(<<"A FileName must be specified."); return; } // Initialize if ((fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<< "File " << this->FileName << " not found"); return; } if (fscanf( fp, "%d", &magic_num ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read magic number"); return; } if( magic_num != 11111 ) { vtkErrorMacro(<< "SLC magic number is not correct"); return; } f[0] = f[1] = f[2] = 0.0; output->SetOrigin(f); if (fscanf( fp, "%d", size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[0]"); return; } if (fscanf( fp, "%d", size+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[1]"); return; } if (fscanf( fp, "%d", size+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[2]"); return; } output->SetDimensions(size); output->AllocateScalars(VTK_UNSIGNED_CHAR, 1); output->GetPointData()->GetScalars()->SetName("SLCImage"); // Skip Over bits_per_voxel Field */ if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over bits per voxel"); return; } if (fscanf( fp, "%lf", f ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[0]"); return; } if (fscanf( fp, "%lf", f+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[1]"); return; } if (fscanf( fp, "%lf", f+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[2]"); return; } output->SetSpacing(f); // Skip Over unit_type, data_origin, and data_modification if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over unit type"); return; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data origin"); return; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data modification"); return; } if (fscanf( fp, "%d\n", &data_compression ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read data compression"); return; } plane_size = size[0] * size[1]; #ifndef NDEBUG int volume_size = plane_size * size[2]; #endif // Skip Over Icon if (fscanf( fp, "%d %d X", &icon_width, &icon_height ) != 2) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over icon"); return; } icon_ptr = new unsigned char[(icon_width*icon_height)]; if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { vtkErrorMacro ("SLCReader error reading file: " << this->FileName << " Premature EOF while reading icon."); return; } if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { vtkErrorMacro ("SLCReader error reading file: " << this->FileName << " Premature EOF while reading icon."); return; } if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { } delete [] icon_ptr; // Read In Data Plane By Plane for( z_counter=0; z_counter<size[2]; z_counter++ ) { if ( !(z_counter % 10) && !z_counter ) { this->UpdateProgress((float)z_counter/size[2]); } // Read a single plane into temp memory switch( data_compression ) { case 0: if( !scan_ptr ) { scan_ptr = new unsigned char[plane_size]; } if( fread( scan_ptr, 1, plane_size, fp ) != (unsigned int)plane_size ) { vtkErrorMacro( << "Unable to read slice " << z_counter << " from SLC File" ); return; } break; case 1: if( scan_ptr ) { delete [] scan_ptr; } if (fscanf( fp, "%d X", &compressed_size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read compressed size"); return; } compressed_ptr = new unsigned char[compressed_size]; if( fread(compressed_ptr, 1, compressed_size, fp) != (unsigned int)compressed_size ) { vtkErrorMacro( << "Unable to read compressed slice " << z_counter << " from SLC File" ); return; } scan_ptr = this->Decode8BitData( compressed_ptr, plane_size ); delete [] compressed_ptr; break; default: vtkErrorMacro(<< "Unknown SLC compression type: " << data_compression ); break; } void* outputSlice = output->GetScalarPointer(0, 0, z_counter); memcpy(outputSlice, scan_ptr, plane_size); } delete [] scan_ptr; vtkDebugMacro(<< "Read " << volume_size << " points"); fclose( fp ); this->Error = 0; } int vtkSLCReader::CanReadFile(const char* fname) { FILE* fp; int magic_num = 0; if ((fp = fopen(fname, "rb")) == NULL) { return 0; } if (fscanf( fp, "%d", &magic_num ) != 1) { return 0; } if( magic_num != 11111 ) { fclose(fp); return 0; } fclose(fp); return 3; } void vtkSLCReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Error: " << this->Error << "\n"; os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <commit_msg>Prevent a file descriptor leak in vtkSLCReader<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSLCReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSLCReader.h" #include "vtkDataArray.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include <ctype.h> vtkStandardNewMacro(vtkSLCReader); // Constructor for a vtkSLCReader. vtkSLCReader::vtkSLCReader() { this->FileName = NULL; this->Error = 0; } vtkSLCReader::~vtkSLCReader() { } // Decodes an array of eight bit run-length encoded data. unsigned char* vtkSLCReader::Decode8BitData( unsigned char *in_ptr, int size ) { unsigned char *curr_ptr; unsigned char *decode_ptr; unsigned char *return_ptr; unsigned char current_value; unsigned char remaining; int done=0; curr_ptr = in_ptr; decode_ptr = return_ptr = new unsigned char[size]; while( !done ) { current_value = *(curr_ptr++); if( !(remaining = (current_value & 0x7f)) ) { break; } if( current_value & 0x80 ) { while( remaining-- ) { *(decode_ptr++) = *(curr_ptr++); } } else { current_value = *(curr_ptr++); while ( remaining-- ) { *(decode_ptr++) = current_value; } } } return return_ptr; } // This will be needed when we make this an imaging filter. int vtkSLCReader::RequestInformation ( vtkInformation * request, vtkInformationVector** inputVector, vtkInformationVector * outputVector) { FILE *fp; int temp; double f[3]; int size[3]; int magic_num; this->Error = 1; if (!this->FileName) { vtkErrorMacro(<<"A FileName must be specified."); return 0; } // Initialize if ((fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<< "File " << this->FileName << " not found"); return 0; } this->FileDimensionality = 3; if (fscanf( fp, "%d", &magic_num ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read magic number"); return 1; } if( magic_num != 11111 ) { vtkErrorMacro(<< "SLC magic number is not correct"); return 1; } f[0] = f[1] = f[2] = 0.0; this->SetDataOrigin(f); if (fscanf( fp, "%d", size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[0]"); return 1; } if (fscanf( fp, "%d", size+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[1]"); return 1; } if (fscanf( fp, "%d", size+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read size[2]"); return 1; } this->SetDataExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); // Skip Over bits_per_voxel Field */ if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over bits per pixel"); return 1; } if (fscanf( fp, "%lf", f ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[0]"); return 1; } if (fscanf( fp, "%lf", f+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[1]"); return 1; } if (fscanf( fp, "%lf", f+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to spacing[2]"); return 1; } this->SetDataSpacing(f); // Skip Over unit_type, data_origin, and data_modification if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over unit type"); return 1; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data origin"); return 1; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data modification"); return 1; } this->SetDataScalarType(VTK_UNSIGNED_CHAR); this->SetNumberOfScalarComponents(1); fclose( fp ); return this->Superclass::RequestInformation(request, inputVector, outputVector); } // Reads an SLC file and creates a vtkStructuredPoints dataset. void vtkSLCReader::ExecuteDataWithInformation(vtkDataObject *output_do, vtkInformation *vtkNotUsed(outInfo)) { vtkImageData *output = vtkImageData::SafeDownCast(output_do); FILE *fp; int temp; int data_compression; int plane_size; double f[3]; int size[3]; int magic_num; int z_counter; int icon_width, icon_height; int compressed_size; unsigned char *icon_ptr; unsigned char *compressed_ptr; unsigned char *scan_ptr = NULL; this->Error = 1; if (!this->FileName) { vtkErrorMacro(<<"A FileName must be specified."); return; } // Initialize if ((fp = fopen(this->FileName, "rb")) == NULL) { vtkErrorMacro(<< "File " << this->FileName << " not found"); return; } if (fscanf( fp, "%d", &magic_num ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read magic number"); return; } if( magic_num != 11111 ) { vtkErrorMacro(<< "SLC magic number is not correct"); return; } f[0] = f[1] = f[2] = 0.0; output->SetOrigin(f); if (fscanf( fp, "%d", size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[0]"); return; } if (fscanf( fp, "%d", size+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[1]"); return; } if (fscanf( fp, "%d", size+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read size[2]"); return; } output->SetDimensions(size); output->AllocateScalars(VTK_UNSIGNED_CHAR, 1); output->GetPointData()->GetScalars()->SetName("SLCImage"); // Skip Over bits_per_voxel Field */ if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over bits per voxel"); return; } if (fscanf( fp, "%lf", f ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[0]"); return; } if (fscanf( fp, "%lf", f+1 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[1]"); return; } if (fscanf( fp, "%lf", f+2 ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed read spacing[2]"); return; } output->SetSpacing(f); // Skip Over unit_type, data_origin, and data_modification if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over unit type"); return; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data origin"); return; } if (fscanf( fp, "%d", &temp ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over data modification"); return; } if (fscanf( fp, "%d\n", &data_compression ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read data compression"); return; } plane_size = size[0] * size[1]; #ifndef NDEBUG int volume_size = plane_size * size[2]; #endif // Skip Over Icon if (fscanf( fp, "%d %d X", &icon_width, &icon_height ) != 2) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to skip over icon"); return; } icon_ptr = new unsigned char[(icon_width*icon_height)]; if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { vtkErrorMacro ("SLCReader error reading file: " << this->FileName << " Premature EOF while reading icon."); return; } if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { vtkErrorMacro ("SLCReader error reading file: " << this->FileName << " Premature EOF while reading icon."); return; } if (fread( icon_ptr, (icon_width*icon_height), 1, fp ) != 1) { } delete [] icon_ptr; // Read In Data Plane By Plane for( z_counter=0; z_counter<size[2]; z_counter++ ) { if ( !(z_counter % 10) && !z_counter ) { this->UpdateProgress((float)z_counter/size[2]); } // Read a single plane into temp memory switch( data_compression ) { case 0: if( !scan_ptr ) { scan_ptr = new unsigned char[plane_size]; } if( fread( scan_ptr, 1, plane_size, fp ) != (unsigned int)plane_size ) { vtkErrorMacro( << "Unable to read slice " << z_counter << " from SLC File" ); return; } break; case 1: if( scan_ptr ) { delete [] scan_ptr; } if (fscanf( fp, "%d X", &compressed_size ) != 1) { vtkErrorMacro( <<"Error reading file: " << this->FileName << "Failed to read compressed size"); return; } compressed_ptr = new unsigned char[compressed_size]; if( fread(compressed_ptr, 1, compressed_size, fp) != (unsigned int)compressed_size ) { vtkErrorMacro( << "Unable to read compressed slice " << z_counter << " from SLC File" ); return; } scan_ptr = this->Decode8BitData( compressed_ptr, plane_size ); delete [] compressed_ptr; break; default: vtkErrorMacro(<< "Unknown SLC compression type: " << data_compression ); break; } void* outputSlice = output->GetScalarPointer(0, 0, z_counter); memcpy(outputSlice, scan_ptr, plane_size); } delete [] scan_ptr; vtkDebugMacro(<< "Read " << volume_size << " points"); fclose( fp ); this->Error = 0; } int vtkSLCReader::CanReadFile(const char* fname) { FILE* fp; int magic_num = 0; if ((fp = fopen(fname, "rb")) == NULL) { return 0; } if (fscanf( fp, "%d", &magic_num ) != 1) { fclose(fp); return 0; } if( magic_num != 11111 ) { fclose(fp); return 0; } fclose(fp); return 3; } void vtkSLCReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Error: " << this->Error << "\n"; os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <|endoftext|>
<commit_before>/** * @file forward_index.cpp * @author Sean Massung */ #include <iostream> #include <memory> #include <unordered_set> #include "index/forward_index.h" #include "index/chunk.h" using std::cerr; using std::endl; namespace meta { namespace index { forward_index::forward_index(const cpptoml::toml_group & config): disk_index{config, *cpptoml::get_as<std::string>(config, "forward-index")} { /* nothing */ } uint32_t forward_index::tokenize_docs( const std::unique_ptr<corpus::corpus> & docs) { std::vector<postings_data<doc_id, term_id>> pdata; pdata.reserve(docs->size()); uint32_t chunk_num = 0; std::string progress = "Tokenizing "; while(docs->has_next()) { corpus::document doc{docs->next()}; common::show_progress(doc.id(), docs->size(), 20, progress); _tokenizer->tokenize(doc); _doc_id_mapping.push_back(doc.path()); _doc_sizes.push_back(doc.length()); postings_data<doc_id, term_id> pd{doc.id()}; pd.set_counts(std::vector<std::pair<term_id, double>>{ doc.frequencies().begin(), doc.frequencies().end() }); pdata.push_back(pd); // Save class label information _unique_terms.push_back(doc.frequencies().size()); _labels.push_back(doc.label()); // every k documents, write a chunk // TODO: make this based on memory usage instead if(doc.id() % 500 == 0) write_chunk(chunk_num++, pdata); } common::end_progress(progress); if(!pdata.empty()) write_chunk(chunk_num++, pdata); return chunk_num; } std::string forward_index::liblinear_data(doc_id d_id) const { auto pdata = search_primary(d_id); // output the class label (starting with index 1) std::stringstream out; out << (label_id_from_doc(d_id) + 1); // output each term_id:count (starting with index 1) using term_pair = std::pair<term_id, double>; std::vector<term_pair> sorted; sorted.reserve(pdata->counts().size()); for(auto & p: pdata->counts()) sorted.emplace_back(std::piecewise_construct, std::forward_as_tuple(p.first + 1), std::forward_as_tuple(p.second)); std::sort(sorted.begin(), sorted.end(), [](const term_pair & a, const term_pair & b) { return a.first < b.first; } ); for(auto & freq: sorted) out << " " << freq.first << ":" << freq.second; out << "\n"; return out.str(); } } } <commit_msg>Add parallelization to tokenization process for forward_index.<commit_after>/** * @file forward_index.cpp * @author Sean Massung */ #include <iostream> #include <memory> #include <unordered_set> #include "index/forward_index.h" #include "index/chunk.h" using std::cerr; using std::endl; namespace meta { namespace index { forward_index::forward_index(const cpptoml::toml_group & config): disk_index{config, *cpptoml::get_as<std::string>(config, "forward-index")} { /* nothing */ } uint32_t forward_index::tokenize_docs( const std::unique_ptr<corpus::corpus> & docs) { std::atomic<uint32_t> chunk_num{0}; const uint32_t chunk_size = 500; std::string progress = "Tokenizing "; std::mutex mutex; // allocate metadata _doc_id_mapping.resize(docs->size()); _doc_sizes.resize(docs->size()); _unique_terms.resize(docs->size()); _labels.resize(docs->size()); auto task = [&]() { std::vector<postings_data<doc_id, term_id>> pdata; pdata.reserve(chunk_size); while (true) { util::optional<corpus::document> doc; { std::lock_guard<std::mutex> lock{mutex}; if (docs->has_next()) { doc = docs->next(); common::show_progress(doc->id(), docs->size(), 20, progress); } } if (!doc) { if (!pdata.empty()) write_chunk(chunk_num.fetch_add(1), pdata); return; } _tokenizer->tokenize(*doc); _doc_id_mapping[doc->id()] = doc->path(); _doc_sizes[doc->id()] = doc->length(); postings_data<doc_id, term_id> pd{doc->id()}; pd.set_counts(std::vector<std::pair<term_id, double>>{ doc->frequencies().begin(), doc->frequencies().end() }); pdata.push_back(pd); _unique_terms[doc->id()] = doc->frequencies().size(); _labels[doc->id()] = doc->label(); if (pdata.size() % chunk_size == 0) write_chunk(chunk_num.fetch_add(1), pdata); } }; parallel::thread_pool pool; std::vector<std::future<void>> futures; for (size_t i = 0; i < pool.thread_ids().size(); ++i) futures.emplace_back(pool.submit_task(task)); for (auto & fut : futures) fut.get(); common::end_progress(progress); return chunk_num; } std::string forward_index::liblinear_data(doc_id d_id) const { auto pdata = search_primary(d_id); // output the class label (starting with index 1) std::stringstream out; out << (label_id_from_doc(d_id) + 1); // output each term_id:count (starting with index 1) using term_pair = std::pair<term_id, double>; std::vector<term_pair> sorted; sorted.reserve(pdata->counts().size()); for(auto & p: pdata->counts()) sorted.emplace_back(std::piecewise_construct, std::forward_as_tuple(p.first + 1), std::forward_as_tuple(p.second)); std::sort(sorted.begin(), sorted.end(), [](const term_pair & a, const term_pair & b) { return a.first < b.first; } ); for(auto & freq: sorted) out << " " << freq.first << ":" << freq.second; out << "\n"; return out.str(); } } } <|endoftext|>
<commit_before>/* * An istream which duplicates data. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_tee.hxx" #include "istream_oo.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include <assert.h> struct TeeIstream { struct { struct istream istream; /** * A weak output is one which is closed automatically when all * "strong" outputs have been closed - it will not keep up the * istream_tee object alone. */ bool weak; bool enabled = true; } outputs[2]; struct istream *input; /** * These flags control whether istream_tee_close[12]() may restart * reading for the other output. */ bool reading = false, in_data = false; #ifndef NDEBUG bool closed_while_reading = false, closed_while_data = false; #endif /** * The number of bytes to skip for output 0. The first output has * already consumed this many bytes, but the second output * blocked. */ size_t skip = 0; TeeIstream(struct istream &_input, bool first_weak, bool second_weak) { outputs[0].weak = first_weak; outputs[1].weak = second_weak; istream_assign_handler(&input, &_input, &MakeIstreamHandler<TeeIstream>::handler, this, 0); } size_t Feed0(const char *data, size_t length); size_t Feed1(const void *data, size_t length); size_t Feed(const void *data, size_t length); /* handler */ size_t OnData(const void *data, size_t length); ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd, gcc_unused size_t max_length) { // TODO: implement that using sys_tee() gcc_unreachable(); } void OnEof(); void OnError(GError *error); }; static GQuark tee_quark(void) { return g_quark_from_static_string("tee"); } inline size_t TeeIstream::Feed0(const char *data, size_t length) { if (!outputs[0].enabled) return length; if (length <= skip) /* all of this has already been sent to the first input, but the second one didn't accept it yet */ return length; /* skip the part which was already sent */ data += skip; length -= skip; size_t nbytes = istream_invoke_data(&outputs[0].istream, data, length); if (nbytes > 0) { skip += nbytes; return skip; } if (outputs[0].enabled || !outputs[1].enabled) /* first output is blocking, or both closed: give up */ return 0; /* the first output has been closed inside the data() callback, but the second is still alive: continue with the second output */ return length; } inline size_t TeeIstream::Feed1(const void *data, size_t length) { if (!outputs[1].enabled) return length; size_t nbytes = istream_invoke_data(&outputs[1].istream, data, length); if (nbytes == 0 && !outputs[1].enabled && outputs[0].enabled) /* during the data callback, outputs[1] has been closed, but outputs[0] continues; instead of returning 0 here, use outputs[0]'s result */ return length; return nbytes; } inline size_t TeeIstream::Feed(const void *data, size_t length) { size_t nbytes0 = Feed0((const char *)data, length); if (nbytes0 == 0) return 0; size_t nbytes1 = Feed1(data, nbytes0); if (nbytes1 > 0 && outputs[0].enabled) { assert(nbytes1 <= skip); skip -= nbytes1; } return nbytes1; } /* * istream handler * */ inline size_t TeeIstream::OnData(const void *data, size_t length) { assert(!in_data); pool_ref(outputs[0].istream.pool); in_data = true; size_t nbytes = Feed(data, length); in_data = false; pool_unref(outputs[0].istream.pool); return nbytes; } inline void TeeIstream::OnEof() { assert(input != nullptr); pool_ref(outputs[0].istream.pool); input = nullptr; /* clean up in reverse order */ if (outputs[1].enabled) { outputs[1].enabled = false; istream_deinit_eof(&outputs[1].istream); } if (outputs[0].enabled) { outputs[0].enabled = false; istream_deinit_eof(&outputs[0].istream); } pool_unref(outputs[0].istream.pool); } inline void TeeIstream::OnError(GError *error) { assert(input != nullptr); pool_ref(outputs[0].istream.pool); input = nullptr; /* clean up in reverse order */ if (outputs[1].enabled) { outputs[1].enabled = false; istream_deinit_abort(&outputs[1].istream, g_error_copy(error)); } if (outputs[0].enabled) { outputs[0].enabled = false; istream_deinit_abort(&outputs[0].istream, g_error_copy(error)); } g_error_free(error); pool_unref(outputs[0].istream.pool); } /* * istream implementation 0 * */ #ifdef __clang__ #pragma GCC diagnostic ignored "-Wextended-offsetof" #endif static inline TeeIstream & istream_to_tee0(struct istream *istream) { return *ContainerCast(istream, TeeIstream, outputs[0].istream); } static off_t istream_tee_available0(struct istream *istream, bool partial) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); return istream_available(tee.input, partial); } static void istream_tee_read0(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); assert(!tee.reading); pool_ref(tee.outputs[0].istream.pool); tee.reading = true; istream_read(tee.input); tee.reading = false; pool_unref(tee.outputs[0].istream.pool); } static void istream_tee_close0(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); tee.outputs[0].enabled = false; #ifndef NDEBUG if (tee.reading) tee.closed_while_reading = true; if (tee.in_data) tee.closed_while_data = true; #endif if (tee.input != nullptr) { if (!tee.outputs[1].enabled) istream_free_handler(&tee.input); else if (tee.outputs[1].weak) { pool_ref(tee.outputs[0].istream.pool); istream_free_handler(&tee.input); if (tee.outputs[1].enabled) { tee.outputs[1].enabled = false; GError *error = g_error_new_literal(tee_quark(), 0, "closing the weak second output"); istream_deinit_abort(&tee.outputs[1].istream, error); } pool_unref(tee.outputs[0].istream.pool); } } if (tee.input != nullptr && tee.outputs[1].enabled && istream_has_handler(&tee.outputs[1].istream) && !tee.in_data && !tee.reading) istream_read(tee.input); istream_deinit(&tee.outputs[0].istream); } static const struct istream_class istream_tee0 = { .available = istream_tee_available0, .read = istream_tee_read0, .close = istream_tee_close0, }; /* * istream implementation 2 * */ static inline TeeIstream & istream_to_tee1(struct istream *istream) { return *ContainerCast(istream, TeeIstream, outputs[1].istream); } static off_t istream_tee_available1(struct istream *istream, bool partial) { TeeIstream &tee = istream_to_tee1(istream); assert(tee.outputs[1].enabled); return istream_available(tee.input, partial); } static void istream_tee_read1(struct istream *istream) { TeeIstream &tee = istream_to_tee1(istream); assert(!tee.reading); pool_ref(tee.outputs[1].istream.pool); tee.reading = true; istream_read(tee.input); tee.reading = false; pool_unref(tee.outputs[1].istream.pool); } static void istream_tee_close1(struct istream *istream) { TeeIstream &tee = istream_to_tee1(istream); assert(tee.outputs[1].enabled); tee.outputs[1].enabled = false; #ifndef NDEBUG if (tee.reading) tee.closed_while_reading = true; if (tee.in_data) tee.closed_while_data = true; #endif if (tee.input != nullptr) { if (!tee.outputs[0].enabled) istream_free_handler(&tee.input); else if (tee.outputs[0].weak) { pool_ref(tee.outputs[0].istream.pool); istream_free_handler(&tee.input); if (tee.outputs[0].enabled) { tee.outputs[0].enabled = false; GError *error = g_error_new_literal(tee_quark(), 0, "closing the weak first output"); istream_deinit_abort(&tee.outputs[0].istream, error); } pool_unref(tee.outputs[0].istream.pool); } } if (tee.input != nullptr && tee.outputs[0].enabled && istream_has_handler(&tee.outputs[0].istream) && !tee.in_data && !tee.reading) istream_read(tee.input); istream_deinit(&tee.outputs[1].istream); } static const struct istream_class istream_tee1 = { .available = istream_tee_available1, .read = istream_tee_read1, .close = istream_tee_close1, }; /* * constructor * */ struct istream * istream_tee_new(struct pool *pool, struct istream *input, bool first_weak, bool second_weak) { assert(input != nullptr); assert(!istream_has_handler(input)); auto tee = NewFromPool<TeeIstream>(*pool, *input, first_weak, second_weak); istream_init(&tee->outputs[0].istream, &istream_tee0, pool); istream_init(&tee->outputs[1].istream, &istream_tee1, pool); return &tee->outputs[0].istream; } struct istream * istream_tee_second(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); return &tee.outputs[1].istream; } <commit_msg>istream_tee: use IstreamPointer<commit_after>/* * An istream which duplicates data. * * author: Max Kellermann <mk@cm4all.com> */ #include "istream_tee.hxx" #include "istream_oo.hxx" #include "istream_pointer.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include <assert.h> struct TeeIstream { struct { struct istream istream; /** * A weak output is one which is closed automatically when all * "strong" outputs have been closed - it will not keep up the * istream_tee object alone. */ bool weak; bool enabled = true; } outputs[2]; IstreamPointer input; /** * These flags control whether istream_tee_close[12]() may restart * reading for the other output. */ bool reading = false, in_data = false; #ifndef NDEBUG bool closed_while_reading = false, closed_while_data = false; #endif /** * The number of bytes to skip for output 0. The first output has * already consumed this many bytes, but the second output * blocked. */ size_t skip = 0; TeeIstream(struct istream &_input, bool first_weak, bool second_weak) :input(_input, MakeIstreamHandler<TeeIstream>::handler, this) { outputs[0].weak = first_weak; outputs[1].weak = second_weak; } size_t Feed0(const char *data, size_t length); size_t Feed1(const void *data, size_t length); size_t Feed(const void *data, size_t length); /* handler */ size_t OnData(const void *data, size_t length); ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd, gcc_unused size_t max_length) { // TODO: implement that using sys_tee() gcc_unreachable(); } void OnEof(); void OnError(GError *error); }; static GQuark tee_quark(void) { return g_quark_from_static_string("tee"); } inline size_t TeeIstream::Feed0(const char *data, size_t length) { if (!outputs[0].enabled) return length; if (length <= skip) /* all of this has already been sent to the first input, but the second one didn't accept it yet */ return length; /* skip the part which was already sent */ data += skip; length -= skip; size_t nbytes = istream_invoke_data(&outputs[0].istream, data, length); if (nbytes > 0) { skip += nbytes; return skip; } if (outputs[0].enabled || !outputs[1].enabled) /* first output is blocking, or both closed: give up */ return 0; /* the first output has been closed inside the data() callback, but the second is still alive: continue with the second output */ return length; } inline size_t TeeIstream::Feed1(const void *data, size_t length) { if (!outputs[1].enabled) return length; size_t nbytes = istream_invoke_data(&outputs[1].istream, data, length); if (nbytes == 0 && !outputs[1].enabled && outputs[0].enabled) /* during the data callback, outputs[1] has been closed, but outputs[0] continues; instead of returning 0 here, use outputs[0]'s result */ return length; return nbytes; } inline size_t TeeIstream::Feed(const void *data, size_t length) { size_t nbytes0 = Feed0((const char *)data, length); if (nbytes0 == 0) return 0; size_t nbytes1 = Feed1(data, nbytes0); if (nbytes1 > 0 && outputs[0].enabled) { assert(nbytes1 <= skip); skip -= nbytes1; } return nbytes1; } /* * istream handler * */ inline size_t TeeIstream::OnData(const void *data, size_t length) { assert(input.IsDefined()); assert(!in_data); pool_ref(outputs[0].istream.pool); in_data = true; size_t nbytes = Feed(data, length); in_data = false; pool_unref(outputs[0].istream.pool); return nbytes; } inline void TeeIstream::OnEof() { assert(input.IsDefined()); input.Clear(); pool_ref(outputs[0].istream.pool); /* clean up in reverse order */ if (outputs[1].enabled) { outputs[1].enabled = false; istream_deinit_eof(&outputs[1].istream); } if (outputs[0].enabled) { outputs[0].enabled = false; istream_deinit_eof(&outputs[0].istream); } pool_unref(outputs[0].istream.pool); } inline void TeeIstream::OnError(GError *error) { assert(input.IsDefined()); input.Clear(); pool_ref(outputs[0].istream.pool); /* clean up in reverse order */ if (outputs[1].enabled) { outputs[1].enabled = false; istream_deinit_abort(&outputs[1].istream, g_error_copy(error)); } if (outputs[0].enabled) { outputs[0].enabled = false; istream_deinit_abort(&outputs[0].istream, g_error_copy(error)); } g_error_free(error); pool_unref(outputs[0].istream.pool); } /* * istream implementation 0 * */ #ifdef __clang__ #pragma GCC diagnostic ignored "-Wextended-offsetof" #endif static inline TeeIstream & istream_to_tee0(struct istream *istream) { return *ContainerCast(istream, TeeIstream, outputs[0].istream); } static off_t istream_tee_available0(struct istream *istream, bool partial) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); return tee.input.GetAvailable(partial); } static void istream_tee_read0(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); assert(!tee.reading); pool_ref(tee.outputs[0].istream.pool); tee.reading = true; tee.input.Read(); tee.reading = false; pool_unref(tee.outputs[0].istream.pool); } static void istream_tee_close0(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); assert(tee.outputs[0].enabled); tee.outputs[0].enabled = false; #ifndef NDEBUG if (tee.reading) tee.closed_while_reading = true; if (tee.in_data) tee.closed_while_data = true; #endif if (tee.input.IsDefined()) { if (!tee.outputs[1].enabled) tee.input.ClearAndClose(); else if (tee.outputs[1].weak) { pool_ref(tee.outputs[0].istream.pool); tee.input.ClearAndClose(); if (tee.outputs[1].enabled) { tee.outputs[1].enabled = false; GError *error = g_error_new_literal(tee_quark(), 0, "closing the weak second output"); istream_deinit_abort(&tee.outputs[1].istream, error); } pool_unref(tee.outputs[0].istream.pool); } } if (tee.input.IsDefined() && tee.outputs[1].enabled && istream_has_handler(&tee.outputs[1].istream) && !tee.in_data && !tee.reading) tee.input.Read(); istream_deinit(&tee.outputs[0].istream); } static const struct istream_class istream_tee0 = { .available = istream_tee_available0, .read = istream_tee_read0, .close = istream_tee_close0, }; /* * istream implementation 2 * */ static inline TeeIstream & istream_to_tee1(struct istream *istream) { return *ContainerCast(istream, TeeIstream, outputs[1].istream); } static off_t istream_tee_available1(struct istream *istream, bool partial) { TeeIstream &tee = istream_to_tee1(istream); assert(tee.outputs[1].enabled); return tee.input.GetAvailable(partial); } static void istream_tee_read1(struct istream *istream) { TeeIstream &tee = istream_to_tee1(istream); assert(!tee.reading); pool_ref(tee.outputs[1].istream.pool); tee.reading = true; tee.input.Read(); tee.reading = false; pool_unref(tee.outputs[1].istream.pool); } static void istream_tee_close1(struct istream *istream) { TeeIstream &tee = istream_to_tee1(istream); assert(tee.outputs[1].enabled); tee.outputs[1].enabled = false; #ifndef NDEBUG if (tee.reading) tee.closed_while_reading = true; if (tee.in_data) tee.closed_while_data = true; #endif if (tee.input.IsDefined()) { if (!tee.outputs[0].enabled) tee.input.ClearAndClose(); else if (tee.outputs[0].weak) { pool_ref(tee.outputs[0].istream.pool); tee.input.ClearAndClose(); if (tee.outputs[0].enabled) { tee.outputs[0].enabled = false; GError *error = g_error_new_literal(tee_quark(), 0, "closing the weak first output"); istream_deinit_abort(&tee.outputs[0].istream, error); } pool_unref(tee.outputs[0].istream.pool); } } if (tee.input.IsDefined() && tee.outputs[0].enabled && istream_has_handler(&tee.outputs[0].istream) && !tee.in_data && !tee.reading) tee.input.Read(); istream_deinit(&tee.outputs[1].istream); } static const struct istream_class istream_tee1 = { .available = istream_tee_available1, .read = istream_tee_read1, .close = istream_tee_close1, }; /* * constructor * */ struct istream * istream_tee_new(struct pool *pool, struct istream *input, bool first_weak, bool second_weak) { assert(input != nullptr); assert(!istream_has_handler(input)); auto tee = NewFromPool<TeeIstream>(*pool, *input, first_weak, second_weak); istream_init(&tee->outputs[0].istream, &istream_tee0, pool); istream_init(&tee->outputs[1].istream, &istream_tee1, pool); return &tee->outputs[0].istream; } struct istream * istream_tee_second(struct istream *istream) { TeeIstream &tee = istream_to_tee0(istream); return &tee.outputs[1].istream; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * 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 "lzwdecom.hxx" #define MAX_TABLE_SIZE 4096 LZWDecompressor::LZWDecompressor() : pOutBufData(NULL) { sal_uInt16 i; pTable=new LZWTableEntry[MAX_TABLE_SIZE]; pOutBuf=new sal_uInt8[MAX_TABLE_SIZE]; for (i=0; i<MAX_TABLE_SIZE; i++) { pTable[i].nPrevCode=0; pTable[i].nDataCount=1; pTable[i].nData=(sal_uInt8)i; } pIStream=NULL; bFirst = sal_True; nOldCode = 0; } LZWDecompressor::~LZWDecompressor() { delete[] pOutBuf; delete[] pTable; } void LZWDecompressor::StartDecompression(SvStream & rIStream) { pIStream=&rIStream; nTableSize=258; bEOIFound=sal_False; nOutBufDataLen=0; pIStream->ReadUChar( nInputBitsBuf ); nInputBitsBufSize=8; if ( bFirst ) { bInvert = nInputBitsBuf == 1; bFirst = sal_False; } if ( bInvert ) nInputBitsBuf = ( ( nInputBitsBuf & 1 ) << 7 ) | ( ( nInputBitsBuf & 2 ) << 5 ) | ( ( nInputBitsBuf & 4 ) << 3 ) | ( ( nInputBitsBuf & 8 ) << 1 ) | ( ( nInputBitsBuf & 16 ) >> 1 ) | ( ( nInputBitsBuf & 32 ) >> 3 ) | ( ( nInputBitsBuf & 64 ) >> 5 ) | ( (nInputBitsBuf & 128 ) >> 7 ); } sal_uLong LZWDecompressor::Decompress(sal_uInt8 * pTarget, sal_uLong nMaxCount) { sal_uLong nCount; if (pIStream==NULL) return 0; nCount=0; for (;;) { if (pIStream->GetError()) break; if (((sal_uLong)nOutBufDataLen)>=nMaxCount) { nOutBufDataLen = nOutBufDataLen - (sal_uInt16)nMaxCount; nCount+=nMaxCount; while (nMaxCount>0) { *(pTarget++)=*(pOutBufData++); nMaxCount--; } break; } nMaxCount-=(sal_uLong)nOutBufDataLen; nCount+=nOutBufDataLen; while (nOutBufDataLen>0) { *(pTarget++)=*(pOutBufData++); nOutBufDataLen--; } if (bEOIFound==sal_True) break; DecompressSome(); } return nCount; } sal_uInt16 LZWDecompressor::GetNextCode() { sal_uInt16 nBits,nCode; if (nTableSize<511) nBits=9; else if (nTableSize<1023) nBits=10; else if (nTableSize<2047) nBits=11; else nBits=12; nCode=0; do { if (nInputBitsBufSize<=nBits) { nCode=(nCode<<nInputBitsBufSize) | nInputBitsBuf; nBits = nBits - nInputBitsBufSize; pIStream->ReadUChar( nInputBitsBuf ); if ( bInvert ) nInputBitsBuf = ( ( nInputBitsBuf & 1 ) << 7 ) | ( ( nInputBitsBuf & 2 ) << 5 ) | ( ( nInputBitsBuf & 4 ) << 3 ) | ( ( nInputBitsBuf & 8 ) << 1 ) | ( ( nInputBitsBuf & 16 ) >> 1 ) | ( ( nInputBitsBuf & 32 ) >> 3 ) | ( ( nInputBitsBuf & 64 ) >> 5 ) | ( (nInputBitsBuf & 128 ) >> 7 ); nInputBitsBufSize=8; } else { nCode=(nCode<<nBits) | (nInputBitsBuf>>(nInputBitsBufSize-nBits)); nInputBitsBufSize = nInputBitsBufSize - nBits; nInputBitsBuf&=0x00ff>>(8-nInputBitsBufSize); nBits=0; } } while (nBits>0); return nCode; } void LZWDecompressor::AddToTable(sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData) { if (nTableSize >= MAX_TABLE_SIZE) { //It might be possible to force emit a 256 to flush the buffer and try //to continue later? SAL_WARN("filter.tiff", "Too much data at scanline"); bEOIFound = sal_True; return; } while (pTable[nCodeFirstData].nDataCount>1) nCodeFirstData=pTable[nCodeFirstData].nPrevCode; pTable[nTableSize].nPrevCode=nPrevCode; pTable[nTableSize].nDataCount=pTable[nPrevCode].nDataCount+1; pTable[nTableSize].nData=pTable[nCodeFirstData].nData; nTableSize++; } void LZWDecompressor::DecompressSome() { sal_uInt16 i,nCode; nCode=GetNextCode(); if (nCode==256) { nTableSize=258; nCode=GetNextCode(); if (nCode==257) { bEOIFound=sal_True; } } else if (nCode<nTableSize) AddToTable(nOldCode,nCode); else if (nCode==nTableSize) AddToTable(nOldCode,nOldCode); else { bEOIFound=sal_True; } if (bEOIFound) return; nOldCode=nCode; nOutBufDataLen=pTable[nCode].nDataCount; pOutBufData=pOutBuf+nOutBufDataLen; for (i=0; i<nOutBufDataLen; i++) { *(--pOutBufData)=pTable[nCode].nData; nCode=pTable[nCode].nPrevCode; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#707834 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * 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 "lzwdecom.hxx" #define MAX_TABLE_SIZE 4096 LZWDecompressor::LZWDecompressor() : pIStream(NULL) , nTableSize(0) , bEOIFound(false) , bInvert(false) , bFirst(true) , nOldCode(0) , pOutBufData(NULL) , nOutBufDataLen(0) , nInputBitsBuf(0) , nInputBitsBufSize(0) { sal_uInt16 i; pTable=new LZWTableEntry[MAX_TABLE_SIZE]; pOutBuf=new sal_uInt8[MAX_TABLE_SIZE]; for (i=0; i<MAX_TABLE_SIZE; i++) { pTable[i].nPrevCode=0; pTable[i].nDataCount=1; pTable[i].nData=(sal_uInt8)i; } } LZWDecompressor::~LZWDecompressor() { delete[] pOutBuf; delete[] pTable; } void LZWDecompressor::StartDecompression(SvStream & rIStream) { pIStream=&rIStream; nTableSize=258; bEOIFound=sal_False; nOutBufDataLen=0; pIStream->ReadUChar( nInputBitsBuf ); nInputBitsBufSize=8; if ( bFirst ) { bInvert = nInputBitsBuf == 1; bFirst = sal_False; } if ( bInvert ) nInputBitsBuf = ( ( nInputBitsBuf & 1 ) << 7 ) | ( ( nInputBitsBuf & 2 ) << 5 ) | ( ( nInputBitsBuf & 4 ) << 3 ) | ( ( nInputBitsBuf & 8 ) << 1 ) | ( ( nInputBitsBuf & 16 ) >> 1 ) | ( ( nInputBitsBuf & 32 ) >> 3 ) | ( ( nInputBitsBuf & 64 ) >> 5 ) | ( (nInputBitsBuf & 128 ) >> 7 ); } sal_uLong LZWDecompressor::Decompress(sal_uInt8 * pTarget, sal_uLong nMaxCount) { sal_uLong nCount; if (pIStream==NULL) return 0; nCount=0; for (;;) { if (pIStream->GetError()) break; if (((sal_uLong)nOutBufDataLen)>=nMaxCount) { nOutBufDataLen = nOutBufDataLen - (sal_uInt16)nMaxCount; nCount+=nMaxCount; while (nMaxCount>0) { *(pTarget++)=*(pOutBufData++); nMaxCount--; } break; } nMaxCount-=(sal_uLong)nOutBufDataLen; nCount+=nOutBufDataLen; while (nOutBufDataLen>0) { *(pTarget++)=*(pOutBufData++); nOutBufDataLen--; } if (bEOIFound==sal_True) break; DecompressSome(); } return nCount; } sal_uInt16 LZWDecompressor::GetNextCode() { sal_uInt16 nBits,nCode; if (nTableSize<511) nBits=9; else if (nTableSize<1023) nBits=10; else if (nTableSize<2047) nBits=11; else nBits=12; nCode=0; do { if (nInputBitsBufSize<=nBits) { nCode=(nCode<<nInputBitsBufSize) | nInputBitsBuf; nBits = nBits - nInputBitsBufSize; pIStream->ReadUChar( nInputBitsBuf ); if ( bInvert ) nInputBitsBuf = ( ( nInputBitsBuf & 1 ) << 7 ) | ( ( nInputBitsBuf & 2 ) << 5 ) | ( ( nInputBitsBuf & 4 ) << 3 ) | ( ( nInputBitsBuf & 8 ) << 1 ) | ( ( nInputBitsBuf & 16 ) >> 1 ) | ( ( nInputBitsBuf & 32 ) >> 3 ) | ( ( nInputBitsBuf & 64 ) >> 5 ) | ( (nInputBitsBuf & 128 ) >> 7 ); nInputBitsBufSize=8; } else { nCode=(nCode<<nBits) | (nInputBitsBuf>>(nInputBitsBufSize-nBits)); nInputBitsBufSize = nInputBitsBufSize - nBits; nInputBitsBuf&=0x00ff>>(8-nInputBitsBufSize); nBits=0; } } while (nBits>0); return nCode; } void LZWDecompressor::AddToTable(sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData) { if (nTableSize >= MAX_TABLE_SIZE) { //It might be possible to force emit a 256 to flush the buffer and try //to continue later? SAL_WARN("filter.tiff", "Too much data at scanline"); bEOIFound = sal_True; return; } while (pTable[nCodeFirstData].nDataCount>1) nCodeFirstData=pTable[nCodeFirstData].nPrevCode; pTable[nTableSize].nPrevCode=nPrevCode; pTable[nTableSize].nDataCount=pTable[nPrevCode].nDataCount+1; pTable[nTableSize].nData=pTable[nCodeFirstData].nData; nTableSize++; } void LZWDecompressor::DecompressSome() { sal_uInt16 i,nCode; nCode=GetNextCode(); if (nCode==256) { nTableSize=258; nCode=GetNextCode(); if (nCode==257) { bEOIFound=sal_True; } } else if (nCode<nTableSize) AddToTable(nOldCode,nCode); else if (nCode==nTableSize) AddToTable(nOldCode,nOldCode); else { bEOIFound=sal_True; } if (bEOIFound) return; nOldCode=nCode; nOutBufDataLen=pTable[nCode].nDataCount; pOutBufData=pOutBuf+nOutBufDataLen; for (i=0; i<nOutBufDataLen; i++) { *(--pOutBufData)=pTable[nCode].nData; nCode=pTable[nCode].nPrevCode; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * 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 . */ #ifndef _FILTERDETECT_HXX #define _FILTERDETECT_HXX #include <com/sun/star/document/XFilter.hpp> #include <com/sun/star/document/XExporter.hpp> #include <com/sun/star/document/XExtendedFilterDetection.hpp> #include <com/sun/star/document/XImporter.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/implbase5.hxx> #include <cppuhelper/implbase3.hxx> namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; } } } } enum FilterType { FILTER_IMPORT, FILTER_EXPORT }; /* This component will be instantiated for both import or export. Whether it calls * setSourceDocument or setTargetDocument determines which Impl function the filter * member calls */ class FilterDetect : public cppu::WeakImplHelper3 < com::sun::star::document::XExtendedFilterDetection, com::sun::star::lang::XInitialization, com::sun::star::lang::XServiceInfo > { protected: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxCtx; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc; OUString msFilterName; ::com::sun::star::uno::Sequence< OUString > msUserData; OUString msTemplateName; sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) throw (::com::sun::star::uno::RuntimeException); public: FilterDetect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxCtx) : mxCtx( rxCtx ) {} virtual ~FilterDetect() {} //XExtendedFilterDetection virtual OUString SAL_CALL detect( com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& lDescriptor ) 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::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); }; OUString SAL_CALL FilterDetect_getImplementationName(); com::sun::star::uno::Sequence< OUString > SAL_CALL FilterDetect_getSupportedServiceNames(); com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL FilterDetect_createInstance( com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context); #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>clean up messed up filterdetect.hxx<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * 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 . */ #ifndef INCLUDED_FILTER_SOURCE_XMLFILTERDETECT_FILTERDETECT_HXX #define INCLUDED_FILTER_SOURCE_XMLFILTERDETECT_FILTERDETECT_HXX #include <com/sun/star/document/XFilter.hpp> #include <com/sun/star/document/XExporter.hpp> #include <com/sun/star/document/XExtendedFilterDetection.hpp> #include <com/sun/star/document/XImporter.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/implbase3.hxx> namespace com { namespace sun { namespace star { namespace uno { class XComponentContext; } } } } enum FilterType { FILTER_IMPORT, FILTER_EXPORT }; /* This component will be instantiated for both import or export. Whether it calls * setSourceDocument or setTargetDocument determines which Impl function the filter * member calls */ class FilterDetect : public cppu::WeakImplHelper3 < css::document::XExtendedFilterDetection, css::lang::XInitialization, css::lang::XServiceInfo > { protected: css::uno::Reference< css::uno::XComponentContext > mxCtx; css::uno::Reference< css::lang::XComponent > mxDoc; OUString msFilterName; OUString msTemplateName; css::uno::Sequence< OUString > msUserData; sal_Bool SAL_CALL exportImpl( const css::uno::Sequence< css::beans::PropertyValue >& aDescriptor ) throw (css::uno::RuntimeException); sal_Bool SAL_CALL importImpl( const css::uno::Sequence< css::beans::PropertyValue >& aDescriptor ) throw (css::uno::RuntimeException); public: FilterDetect( const css::uno::Reference< css::uno::XComponentContext > &rxCtx) : mxCtx( rxCtx ) {} virtual ~FilterDetect() {} //XExtendedFilterDetection virtual OUString SAL_CALL detect( css::uno::Sequence< css::beans::PropertyValue >& lDescriptor ) throw( css::uno::RuntimeException ); // XInitialization virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& aArguments ) throw (css::uno::Exception, css::uno::RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (css::uno::RuntimeException); virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (css::uno::RuntimeException); }; OUString SAL_CALL FilterDetect_getImplementationName(); css::uno::Sequence< OUString > SAL_CALL FilterDetect_getSupportedServiceNames(); css::uno::Reference< css::uno::XInterface > SAL_CALL FilterDetect_createInstance( css::uno::Reference< css::uno::XComponentContext > const & context); #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>