text
stringlengths
54
60.6k
<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 "base/command_line.h" #include "base/logging.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/autofill_change_processor.h" #include "chrome/browser/sync/glue/autofill_data_type_controller.h" #include "chrome/browser/sync/glue/autofill_model_associator.h" #include "chrome/browser/sync/glue/bookmark_change_processor.h" #include "chrome/browser/sync/glue/bookmark_data_type_controller.h" #include "chrome/browser/sync/glue/bookmark_model_associator.h" #include "chrome/browser/sync/glue/data_type_manager_impl.h" #include "chrome/browser/sync/glue/extension_change_processor.h" #include "chrome/browser/sync/glue/extension_data_type_controller.h" #include "chrome/browser/sync/glue/extension_model_associator.h" #include "chrome/browser/sync/glue/password_change_processor.h" #include "chrome/browser/sync/glue/password_data_type_controller.h" #include "chrome/browser/sync/glue/password_model_associator.h" #include "chrome/browser/sync/glue/preference_change_processor.h" #include "chrome/browser/sync/glue/preference_data_type_controller.h" #include "chrome/browser/sync/glue/preference_model_associator.h" #include "chrome/browser/sync/glue/sync_backend_host.h" #include "chrome/browser/sync/glue/theme_change_processor.h" #include "chrome/browser/sync/glue/theme_data_type_controller.h" #include "chrome/browser/sync/glue/theme_model_associator.h" #include "chrome/browser/sync/glue/typed_url_change_processor.h" #include "chrome/browser/sync/glue/typed_url_data_type_controller.h" #include "chrome/browser/sync/glue/typed_url_model_associator.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_factory_impl.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_switches.h" using browser_sync::AutofillChangeProcessor; using browser_sync::AutofillDataTypeController; using browser_sync::AutofillModelAssociator; using browser_sync::BookmarkChangeProcessor; using browser_sync::BookmarkDataTypeController; using browser_sync::BookmarkModelAssociator; using browser_sync::DataTypeController; using browser_sync::DataTypeManager; using browser_sync::DataTypeManagerImpl; using browser_sync::ExtensionChangeProcessor; using browser_sync::ExtensionDataTypeController; using browser_sync::ExtensionModelAssociator; using browser_sync::PasswordChangeProcessor; using browser_sync::PasswordDataTypeController; using browser_sync::PasswordModelAssociator; using browser_sync::PreferenceChangeProcessor; using browser_sync::PreferenceDataTypeController; using browser_sync::PreferenceModelAssociator; using browser_sync::SyncBackendHost; using browser_sync::ThemeChangeProcessor; using browser_sync::ThemeDataTypeController; using browser_sync::ThemeModelAssociator; using browser_sync::TypedUrlChangeProcessor; using browser_sync::TypedUrlDataTypeController; using browser_sync::TypedUrlModelAssociator; using browser_sync::UnrecoverableErrorHandler; ProfileSyncFactoryImpl::ProfileSyncFactoryImpl( Profile* profile, chrome_common_net::NetworkChangeNotifierThread* network_change_notifier_thread, CommandLine* command_line) : profile_(profile), network_change_notifier_thread_(network_change_notifier_thread), command_line_(command_line) { DCHECK(network_change_notifier_thread_); } ProfileSyncService* ProfileSyncFactoryImpl::CreateProfileSyncService() { ProfileSyncService* pss = new ProfileSyncService(this, profile_, network_change_notifier_thread_, browser_defaults::kBootstrapSyncAuthentication); // Autofill sync is enabled by default. Register unless explicitly // disabled. if (!command_line_->HasSwitch(switches::kDisableSyncAutofill)) { pss->RegisterDataTypeController( new AutofillDataTypeController(this, profile_, pss)); } // Bookmark sync is enabled by default. Register unless explicitly // disabled. if (!command_line_->HasSwitch(switches::kDisableSyncBookmarks)) { pss->RegisterDataTypeController( new BookmarkDataTypeController(this, profile_, pss)); } // Extension sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(this, profile_, pss)); } // Password sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncPasswords)) { pss->RegisterDataTypeController( new PasswordDataTypeController(this, profile_, pss)); } // Preference sync is enabled by default. Register unless explicitly // disabled. if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new PreferenceDataTypeController(this, pss)); } // Theme sync is enabled by default. Register unless explicitly disabled. if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } // TypedUrl sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncTypedUrls)) { pss->RegisterDataTypeController( new TypedUrlDataTypeController(this, profile_, pss)); } return pss; } DataTypeManager* ProfileSyncFactoryImpl::CreateDataTypeManager( SyncBackendHost* backend, const DataTypeController::TypeMap& controllers) { return new DataTypeManagerImpl(backend, controllers); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateAutofillSyncComponents( ProfileSyncService* profile_sync_service, WebDatabase* web_database, PersonalDataManager* personal_data, browser_sync::UnrecoverableErrorHandler* error_handler) { AutofillModelAssociator* model_associator = new AutofillModelAssociator(profile_sync_service, web_database, personal_data); AutofillChangeProcessor* change_processor = new AutofillChangeProcessor(model_associator, web_database, personal_data, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateBookmarkSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { BookmarkModelAssociator* model_associator = new BookmarkModelAssociator(profile_sync_service, error_handler); BookmarkChangeProcessor* change_processor = new BookmarkChangeProcessor(model_associator, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateExtensionSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { ExtensionModelAssociator* model_associator = new ExtensionModelAssociator(profile_sync_service); ExtensionChangeProcessor* change_processor = new ExtensionChangeProcessor(error_handler, model_associator); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreatePasswordSyncComponents( ProfileSyncService* profile_sync_service, PasswordStore* password_store, UnrecoverableErrorHandler* error_handler) { PasswordModelAssociator* model_associator = new PasswordModelAssociator(profile_sync_service, password_store); PasswordChangeProcessor* change_processor = new PasswordChangeProcessor(model_associator, password_store, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreatePreferenceSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { PreferenceModelAssociator* model_associator = new PreferenceModelAssociator(profile_sync_service); PreferenceChangeProcessor* change_processor = new PreferenceChangeProcessor(model_associator, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateThemeSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { ThemeModelAssociator* model_associator = new ThemeModelAssociator(profile_sync_service); ThemeChangeProcessor* change_processor = new ThemeChangeProcessor(error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateTypedUrlSyncComponents( ProfileSyncService* profile_sync_service, history::HistoryBackend* history_backend, browser_sync::UnrecoverableErrorHandler* error_handler) { TypedUrlModelAssociator* model_associator = new TypedUrlModelAssociator(profile_sync_service, history_backend); TypedUrlChangeProcessor* change_processor = new TypedUrlChangeProcessor(model_associator, history_backend, error_handler); return SyncComponents(model_associator, change_processor); } <commit_msg>Revert 50311 - Turn autofill sync on by default.<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 "base/command_line.h" #include "base/logging.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/autofill_change_processor.h" #include "chrome/browser/sync/glue/autofill_data_type_controller.h" #include "chrome/browser/sync/glue/autofill_model_associator.h" #include "chrome/browser/sync/glue/bookmark_change_processor.h" #include "chrome/browser/sync/glue/bookmark_data_type_controller.h" #include "chrome/browser/sync/glue/bookmark_model_associator.h" #include "chrome/browser/sync/glue/data_type_manager_impl.h" #include "chrome/browser/sync/glue/extension_change_processor.h" #include "chrome/browser/sync/glue/extension_data_type_controller.h" #include "chrome/browser/sync/glue/extension_model_associator.h" #include "chrome/browser/sync/glue/password_change_processor.h" #include "chrome/browser/sync/glue/password_data_type_controller.h" #include "chrome/browser/sync/glue/password_model_associator.h" #include "chrome/browser/sync/glue/preference_change_processor.h" #include "chrome/browser/sync/glue/preference_data_type_controller.h" #include "chrome/browser/sync/glue/preference_model_associator.h" #include "chrome/browser/sync/glue/sync_backend_host.h" #include "chrome/browser/sync/glue/theme_change_processor.h" #include "chrome/browser/sync/glue/theme_data_type_controller.h" #include "chrome/browser/sync/glue/theme_model_associator.h" #include "chrome/browser/sync/glue/typed_url_change_processor.h" #include "chrome/browser/sync/glue/typed_url_data_type_controller.h" #include "chrome/browser/sync/glue/typed_url_model_associator.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_factory_impl.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_switches.h" using browser_sync::AutofillChangeProcessor; using browser_sync::AutofillDataTypeController; using browser_sync::AutofillModelAssociator; using browser_sync::BookmarkChangeProcessor; using browser_sync::BookmarkDataTypeController; using browser_sync::BookmarkModelAssociator; using browser_sync::DataTypeController; using browser_sync::DataTypeManager; using browser_sync::DataTypeManagerImpl; using browser_sync::ExtensionChangeProcessor; using browser_sync::ExtensionDataTypeController; using browser_sync::ExtensionModelAssociator; using browser_sync::PasswordChangeProcessor; using browser_sync::PasswordDataTypeController; using browser_sync::PasswordModelAssociator; using browser_sync::PreferenceChangeProcessor; using browser_sync::PreferenceDataTypeController; using browser_sync::PreferenceModelAssociator; using browser_sync::SyncBackendHost; using browser_sync::ThemeChangeProcessor; using browser_sync::ThemeDataTypeController; using browser_sync::ThemeModelAssociator; using browser_sync::TypedUrlChangeProcessor; using browser_sync::TypedUrlDataTypeController; using browser_sync::TypedUrlModelAssociator; using browser_sync::UnrecoverableErrorHandler; ProfileSyncFactoryImpl::ProfileSyncFactoryImpl( Profile* profile, chrome_common_net::NetworkChangeNotifierThread* network_change_notifier_thread, CommandLine* command_line) : profile_(profile), network_change_notifier_thread_(network_change_notifier_thread), command_line_(command_line) { DCHECK(network_change_notifier_thread_); } ProfileSyncService* ProfileSyncFactoryImpl::CreateProfileSyncService() { ProfileSyncService* pss = new ProfileSyncService(this, profile_, network_change_notifier_thread_, browser_defaults::kBootstrapSyncAuthentication); // Autofill sync is disabled by default. // TODO(nick): Autofill is force-disabled due to bad user experience; re- // enabled once fixed. if (command_line_->HasSwitch(switches::kEnableSyncAutofill)) { pss->RegisterDataTypeController( new AutofillDataTypeController(this, profile_, pss)); } // Bookmark sync is enabled by default. Register unless explicitly // disabled. if (!command_line_->HasSwitch(switches::kDisableSyncBookmarks)) { pss->RegisterDataTypeController( new BookmarkDataTypeController(this, profile_, pss)); } // Extension sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(this, profile_, pss)); } // Password sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncPasswords)) { pss->RegisterDataTypeController( new PasswordDataTypeController(this, profile_, pss)); } // Preference sync is enabled by default. Register unless explicitly // disabled. if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new PreferenceDataTypeController(this, pss)); } // Theme sync is enabled by default. Register unless explicitly disabled. if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } // TypedUrl sync is disabled by default. Register only if // explicitly enabled. if (command_line_->HasSwitch(switches::kEnableSyncTypedUrls)) { pss->RegisterDataTypeController( new TypedUrlDataTypeController(this, profile_, pss)); } return pss; } DataTypeManager* ProfileSyncFactoryImpl::CreateDataTypeManager( SyncBackendHost* backend, const DataTypeController::TypeMap& controllers) { return new DataTypeManagerImpl(backend, controllers); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateAutofillSyncComponents( ProfileSyncService* profile_sync_service, WebDatabase* web_database, PersonalDataManager* personal_data, browser_sync::UnrecoverableErrorHandler* error_handler) { AutofillModelAssociator* model_associator = new AutofillModelAssociator(profile_sync_service, web_database, personal_data); AutofillChangeProcessor* change_processor = new AutofillChangeProcessor(model_associator, web_database, personal_data, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateBookmarkSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { BookmarkModelAssociator* model_associator = new BookmarkModelAssociator(profile_sync_service, error_handler); BookmarkChangeProcessor* change_processor = new BookmarkChangeProcessor(model_associator, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateExtensionSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { ExtensionModelAssociator* model_associator = new ExtensionModelAssociator(profile_sync_service); ExtensionChangeProcessor* change_processor = new ExtensionChangeProcessor(error_handler, model_associator); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreatePasswordSyncComponents( ProfileSyncService* profile_sync_service, PasswordStore* password_store, UnrecoverableErrorHandler* error_handler) { PasswordModelAssociator* model_associator = new PasswordModelAssociator(profile_sync_service, password_store); PasswordChangeProcessor* change_processor = new PasswordChangeProcessor(model_associator, password_store, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreatePreferenceSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { PreferenceModelAssociator* model_associator = new PreferenceModelAssociator(profile_sync_service); PreferenceChangeProcessor* change_processor = new PreferenceChangeProcessor(model_associator, error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateThemeSyncComponents( ProfileSyncService* profile_sync_service, UnrecoverableErrorHandler* error_handler) { ThemeModelAssociator* model_associator = new ThemeModelAssociator(profile_sync_service); ThemeChangeProcessor* change_processor = new ThemeChangeProcessor(error_handler); return SyncComponents(model_associator, change_processor); } ProfileSyncFactory::SyncComponents ProfileSyncFactoryImpl::CreateTypedUrlSyncComponents( ProfileSyncService* profile_sync_service, history::HistoryBackend* history_backend, browser_sync::UnrecoverableErrorHandler* error_handler) { TypedUrlModelAssociator* model_associator = new TypedUrlModelAssociator(profile_sync_service, history_backend); TypedUrlChangeProcessor* change_processor = new TypedUrlChangeProcessor(model_associator, history_backend, error_handler); return SyncComponents(model_associator, change_processor); } <|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/views/accelerator_table_gtk.h" #include "base/basictypes.h" #include "chrome/app/chrome_command_ids.h" #include "ui/base/keycodes/keyboard_codes.h" namespace browser { // NOTE: Keep this list in the same (mostly-alphabetical) order as // the Windows accelerators in ../../app/chrome_dll.rc. const AcceleratorMapping kAcceleratorMap[] = { // Keycode Shift Ctrl Alt Command ID { ui::VKEY_A, true, true, false, IDC_AUTOFILL_DEFAULT }, { ui::VKEY_LEFT, false, false, true, IDC_BACK }, { ui::VKEY_BACK, false, false, false, IDC_BACK }, #if defined(OS_CHROMEOS) { ui::VKEY_F1, false, false, false, IDC_BACK }, { ui::VKEY_OEM_2, false, true, true, IDC_SHOW_KEYBOARD_OVERLAY }, { ui::VKEY_OEM_2, true, true, true, IDC_SHOW_KEYBOARD_OVERLAY }, #endif { ui::VKEY_D, false, true, false, IDC_BOOKMARK_PAGE }, { ui::VKEY_D, true, true, false, IDC_BOOKMARK_ALL_TABS }, { ui::VKEY_DELETE, true, true, false, IDC_CLEAR_BROWSING_DATA }, #if !defined(OS_CHROMEOS) { ui::VKEY_F4, false, true, false, IDC_CLOSE_TAB }, #endif { ui::VKEY_W, false, true, false, IDC_CLOSE_TAB }, { ui::VKEY_W, true, true, false, IDC_CLOSE_WINDOW }, #if !defined(OS_CHROMEOS) { ui::VKEY_F4, false, false, true, IDC_CLOSE_WINDOW }, #endif { ui::VKEY_Q, true, true, false, IDC_EXIT }, { ui::VKEY_F, false, true, false, IDC_FIND }, { ui::VKEY_G, false, true, false, IDC_FIND_NEXT }, #if !defined(OS_CHROMEOS) { ui::VKEY_F3, false, false, false, IDC_FIND_NEXT }, #endif { ui::VKEY_G, true, true, false, IDC_FIND_PREVIOUS }, #if !defined(OS_CHROMEOS) { ui::VKEY_F3, true, false, false, IDC_FIND_PREVIOUS }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_S, true, false, true, IDC_FOCUS_CHROMEOS_STATUS }, #endif { ui::VKEY_D, false, false, true, IDC_FOCUS_LOCATION }, { ui::VKEY_L, false, true, false, IDC_FOCUS_LOCATION }, #if !defined(OS_CHROMEOS) { ui::VKEY_F10, false, false, false, IDC_FOCUS_MENU_BAR }, #endif { ui::VKEY_MENU, false, false, false, IDC_FOCUS_MENU_BAR }, #if !defined(OS_CHROMEOS) { ui::VKEY_F6, false, false, false, IDC_FOCUS_NEXT_PANE }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_F2, false, true, false, IDC_FOCUS_NEXT_PANE }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F6, true, false, false, IDC_FOCUS_PREVIOUS_PANE }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_F1, false, true, false, IDC_FOCUS_PREVIOUS_PANE }, #endif { ui::VKEY_K, false, true, false, IDC_FOCUS_SEARCH }, { ui::VKEY_E, false, true, false, IDC_FOCUS_SEARCH }, { ui::VKEY_BROWSER_SEARCH, false, false, false, IDC_FOCUS_SEARCH }, { ui::VKEY_T, true, false, true, IDC_FOCUS_TOOLBAR }, { ui::VKEY_B, true, false, true, IDC_FOCUS_BOOKMARKS }, { ui::VKEY_RIGHT, false, false, true, IDC_FORWARD }, { ui::VKEY_BACK, true, false, false, IDC_FORWARD }, #if defined(OS_CHROMEOS) { ui::VKEY_F2, false, false, false, IDC_FORWARD }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F11, false, false, false, IDC_FULLSCREEN }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_F4, false, false, false, IDC_FULLSCREEN }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F1, false, false, false, IDC_HELP_PAGE }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_OEM_2, false, true, false, IDC_HELP_PAGE }, { ui::VKEY_OEM_2, true, true, false, IDC_HELP_PAGE }, #endif { ui::VKEY_I, true, true, false, IDC_DEV_TOOLS }, { ui::VKEY_J, true, true, false, IDC_DEV_TOOLS_CONSOLE }, { ui::VKEY_C, true, true, false, IDC_DEV_TOOLS_INSPECT }, { ui::VKEY_N, true, true, false, IDC_NEW_INCOGNITO_WINDOW }, { ui::VKEY_T, false, true, false, IDC_NEW_TAB }, { ui::VKEY_N, false, true, false, IDC_NEW_WINDOW }, { ui::VKEY_O, false, true, false, IDC_OPEN_FILE }, { ui::VKEY_P, false, true, false, IDC_PRINT}, { ui::VKEY_R, false, true, false, IDC_RELOAD }, { ui::VKEY_R, true, true, false, IDC_RELOAD_IGNORING_CACHE }, #if !defined(OS_CHROMEOS) { ui::VKEY_F5, false, false, false, IDC_RELOAD }, { ui::VKEY_F5, false, true, false, IDC_RELOAD_IGNORING_CACHE }, { ui::VKEY_F5, true, false, false, IDC_RELOAD_IGNORING_CACHE }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_F3, false, false, false, IDC_RELOAD }, { ui::VKEY_F3, false, true, false, IDC_RELOAD_IGNORING_CACHE }, { ui::VKEY_F3, true, false, false, IDC_RELOAD_IGNORING_CACHE }, #endif { ui::VKEY_HOME, false, false, true, IDC_HOME }, { ui::VKEY_T, true, true, false, IDC_RESTORE_TAB }, { ui::VKEY_S, false, true, false, IDC_SAVE_PAGE }, #if defined(OS_CHROMEOS) { ui::VKEY_LWIN, false, false, false, IDC_SEARCH }, #endif { ui::VKEY_9, false, true, false, IDC_SELECT_LAST_TAB }, { ui::VKEY_NUMPAD9, false, true, false, IDC_SELECT_LAST_TAB }, { ui::VKEY_TAB, false, true, false, IDC_SELECT_NEXT_TAB }, { ui::VKEY_NEXT, false, true, false, IDC_SELECT_NEXT_TAB }, { ui::VKEY_TAB, true, true, false, IDC_SELECT_PREVIOUS_TAB }, { ui::VKEY_PRIOR, false, true, false, IDC_SELECT_PREVIOUS_TAB }, { ui::VKEY_1, false, true, false, IDC_SELECT_TAB_0 }, { ui::VKEY_NUMPAD1, false, true, false, IDC_SELECT_TAB_0 }, { ui::VKEY_2, false, true, false, IDC_SELECT_TAB_1 }, { ui::VKEY_NUMPAD2, false, true, false, IDC_SELECT_TAB_1 }, { ui::VKEY_3, false, true, false, IDC_SELECT_TAB_2 }, { ui::VKEY_NUMPAD3, false, true, false, IDC_SELECT_TAB_2 }, { ui::VKEY_4, false, true, false, IDC_SELECT_TAB_3 }, { ui::VKEY_NUMPAD4, false, true, false, IDC_SELECT_TAB_3 }, { ui::VKEY_5, false, true, false, IDC_SELECT_TAB_4 }, { ui::VKEY_NUMPAD5, false, true, false, IDC_SELECT_TAB_4 }, { ui::VKEY_6, false, true, false, IDC_SELECT_TAB_5 }, { ui::VKEY_NUMPAD6, false, true, false, IDC_SELECT_TAB_5 }, { ui::VKEY_7, false, true, false, IDC_SELECT_TAB_6 }, { ui::VKEY_NUMPAD7, false, true, false, IDC_SELECT_TAB_6 }, { ui::VKEY_8, false, true, false, IDC_SELECT_TAB_7 }, { ui::VKEY_NUMPAD8, false, true, false, IDC_SELECT_TAB_7 }, { ui::VKEY_B, true, true, false, IDC_SHOW_BOOKMARK_BAR }, { ui::VKEY_J, false, true, false, IDC_SHOW_DOWNLOADS }, { ui::VKEY_H, false, true, false, IDC_SHOW_HISTORY }, { ui::VKEY_F, false, false, true, IDC_SHOW_APP_MENU}, { ui::VKEY_E, false, false, true, IDC_SHOW_APP_MENU}, { ui::VKEY_ESCAPE, false, false, false, IDC_STOP }, { ui::VKEY_ESCAPE, true, false, false, IDC_TASK_MANAGER }, { ui::VKEY_U, false, true, false, IDC_VIEW_SOURCE }, { ui::VKEY_OEM_MINUS, false, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_OEM_MINUS, true, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_SUBTRACT, false, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_0, false, true, false, IDC_ZOOM_NORMAL }, { ui::VKEY_NUMPAD0, false, true, false, IDC_ZOOM_NORMAL }, { ui::VKEY_OEM_PLUS, false, true, false, IDC_ZOOM_PLUS }, { ui::VKEY_OEM_PLUS, true, true, false, IDC_ZOOM_PLUS }, { ui::VKEY_ADD, false, true, false, IDC_ZOOM_PLUS }, }; const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap); } // namespace browser <commit_msg>chromeos: Use Ctrl-Shift-Backspace to clear browsing data.<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/views/accelerator_table_gtk.h" #include "base/basictypes.h" #include "chrome/app/chrome_command_ids.h" #include "ui/base/keycodes/keyboard_codes.h" namespace browser { // NOTE: Keep this list in the same (mostly-alphabetical) order as // the Windows accelerators in ../../app/chrome_dll.rc. const AcceleratorMapping kAcceleratorMap[] = { // Keycode Shift Ctrl Alt Command ID { ui::VKEY_A, true, true, false, IDC_AUTOFILL_DEFAULT }, { ui::VKEY_LEFT, false, false, true, IDC_BACK }, { ui::VKEY_BACK, false, false, false, IDC_BACK }, #if defined(OS_CHROMEOS) { ui::VKEY_F1, false, false, false, IDC_BACK }, { ui::VKEY_OEM_2, false, true, true, IDC_SHOW_KEYBOARD_OVERLAY }, { ui::VKEY_OEM_2, true, true, true, IDC_SHOW_KEYBOARD_OVERLAY }, #endif { ui::VKEY_D, false, true, false, IDC_BOOKMARK_PAGE }, { ui::VKEY_D, true, true, false, IDC_BOOKMARK_ALL_TABS }, #if !defined(OS_CHROMEOS) { ui::VKEY_DELETE, true, true, false, IDC_CLEAR_BROWSING_DATA }, #else { ui::VKEY_BACK, true, true, false, IDC_CLEAR_BROWSING_DATA }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F4, false, true, false, IDC_CLOSE_TAB }, #endif { ui::VKEY_W, false, true, false, IDC_CLOSE_TAB }, { ui::VKEY_W, true, true, false, IDC_CLOSE_WINDOW }, #if !defined(OS_CHROMEOS) { ui::VKEY_F4, false, false, true, IDC_CLOSE_WINDOW }, #endif { ui::VKEY_Q, true, true, false, IDC_EXIT }, { ui::VKEY_F, false, true, false, IDC_FIND }, { ui::VKEY_G, false, true, false, IDC_FIND_NEXT }, #if !defined(OS_CHROMEOS) { ui::VKEY_F3, false, false, false, IDC_FIND_NEXT }, #endif { ui::VKEY_G, true, true, false, IDC_FIND_PREVIOUS }, #if !defined(OS_CHROMEOS) { ui::VKEY_F3, true, false, false, IDC_FIND_PREVIOUS }, #endif #if defined(OS_CHROMEOS) { ui::VKEY_S, true, false, true, IDC_FOCUS_CHROMEOS_STATUS }, #endif { ui::VKEY_D, false, false, true, IDC_FOCUS_LOCATION }, { ui::VKEY_L, false, true, false, IDC_FOCUS_LOCATION }, #if !defined(OS_CHROMEOS) { ui::VKEY_F10, false, false, false, IDC_FOCUS_MENU_BAR }, #endif { ui::VKEY_MENU, false, false, false, IDC_FOCUS_MENU_BAR }, #if !defined(OS_CHROMEOS) { ui::VKEY_F6, false, false, false, IDC_FOCUS_NEXT_PANE }, #else { ui::VKEY_F2, false, true, false, IDC_FOCUS_NEXT_PANE }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F6, true, false, false, IDC_FOCUS_PREVIOUS_PANE }, #else { ui::VKEY_F1, false, true, false, IDC_FOCUS_PREVIOUS_PANE }, #endif { ui::VKEY_K, false, true, false, IDC_FOCUS_SEARCH }, { ui::VKEY_E, false, true, false, IDC_FOCUS_SEARCH }, { ui::VKEY_BROWSER_SEARCH, false, false, false, IDC_FOCUS_SEARCH }, { ui::VKEY_T, true, false, true, IDC_FOCUS_TOOLBAR }, { ui::VKEY_B, true, false, true, IDC_FOCUS_BOOKMARKS }, { ui::VKEY_RIGHT, false, false, true, IDC_FORWARD }, { ui::VKEY_BACK, true, false, false, IDC_FORWARD }, #if defined(OS_CHROMEOS) { ui::VKEY_F2, false, false, false, IDC_FORWARD }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F11, false, false, false, IDC_FULLSCREEN }, #else { ui::VKEY_F4, false, false, false, IDC_FULLSCREEN }, #endif #if !defined(OS_CHROMEOS) { ui::VKEY_F1, false, false, false, IDC_HELP_PAGE }, #else { ui::VKEY_OEM_2, false, true, false, IDC_HELP_PAGE }, { ui::VKEY_OEM_2, true, true, false, IDC_HELP_PAGE }, #endif { ui::VKEY_I, true, true, false, IDC_DEV_TOOLS }, { ui::VKEY_J, true, true, false, IDC_DEV_TOOLS_CONSOLE }, { ui::VKEY_C, true, true, false, IDC_DEV_TOOLS_INSPECT }, { ui::VKEY_N, true, true, false, IDC_NEW_INCOGNITO_WINDOW }, { ui::VKEY_T, false, true, false, IDC_NEW_TAB }, { ui::VKEY_N, false, true, false, IDC_NEW_WINDOW }, { ui::VKEY_O, false, true, false, IDC_OPEN_FILE }, { ui::VKEY_P, false, true, false, IDC_PRINT}, { ui::VKEY_R, false, true, false, IDC_RELOAD }, { ui::VKEY_R, true, true, false, IDC_RELOAD_IGNORING_CACHE }, #if !defined(OS_CHROMEOS) { ui::VKEY_F5, false, false, false, IDC_RELOAD }, { ui::VKEY_F5, false, true, false, IDC_RELOAD_IGNORING_CACHE }, { ui::VKEY_F5, true, false, false, IDC_RELOAD_IGNORING_CACHE }, #else { ui::VKEY_F3, false, false, false, IDC_RELOAD }, { ui::VKEY_F3, false, true, false, IDC_RELOAD_IGNORING_CACHE }, { ui::VKEY_F3, true, false, false, IDC_RELOAD_IGNORING_CACHE }, #endif { ui::VKEY_HOME, false, false, true, IDC_HOME }, { ui::VKEY_T, true, true, false, IDC_RESTORE_TAB }, { ui::VKEY_S, false, true, false, IDC_SAVE_PAGE }, #if defined(OS_CHROMEOS) { ui::VKEY_LWIN, false, false, false, IDC_SEARCH }, #endif { ui::VKEY_9, false, true, false, IDC_SELECT_LAST_TAB }, { ui::VKEY_NUMPAD9, false, true, false, IDC_SELECT_LAST_TAB }, { ui::VKEY_TAB, false, true, false, IDC_SELECT_NEXT_TAB }, { ui::VKEY_NEXT, false, true, false, IDC_SELECT_NEXT_TAB }, { ui::VKEY_TAB, true, true, false, IDC_SELECT_PREVIOUS_TAB }, { ui::VKEY_PRIOR, false, true, false, IDC_SELECT_PREVIOUS_TAB }, { ui::VKEY_1, false, true, false, IDC_SELECT_TAB_0 }, { ui::VKEY_NUMPAD1, false, true, false, IDC_SELECT_TAB_0 }, { ui::VKEY_2, false, true, false, IDC_SELECT_TAB_1 }, { ui::VKEY_NUMPAD2, false, true, false, IDC_SELECT_TAB_1 }, { ui::VKEY_3, false, true, false, IDC_SELECT_TAB_2 }, { ui::VKEY_NUMPAD3, false, true, false, IDC_SELECT_TAB_2 }, { ui::VKEY_4, false, true, false, IDC_SELECT_TAB_3 }, { ui::VKEY_NUMPAD4, false, true, false, IDC_SELECT_TAB_3 }, { ui::VKEY_5, false, true, false, IDC_SELECT_TAB_4 }, { ui::VKEY_NUMPAD5, false, true, false, IDC_SELECT_TAB_4 }, { ui::VKEY_6, false, true, false, IDC_SELECT_TAB_5 }, { ui::VKEY_NUMPAD6, false, true, false, IDC_SELECT_TAB_5 }, { ui::VKEY_7, false, true, false, IDC_SELECT_TAB_6 }, { ui::VKEY_NUMPAD7, false, true, false, IDC_SELECT_TAB_6 }, { ui::VKEY_8, false, true, false, IDC_SELECT_TAB_7 }, { ui::VKEY_NUMPAD8, false, true, false, IDC_SELECT_TAB_7 }, { ui::VKEY_B, true, true, false, IDC_SHOW_BOOKMARK_BAR }, { ui::VKEY_J, false, true, false, IDC_SHOW_DOWNLOADS }, { ui::VKEY_H, false, true, false, IDC_SHOW_HISTORY }, { ui::VKEY_F, false, false, true, IDC_SHOW_APP_MENU}, { ui::VKEY_E, false, false, true, IDC_SHOW_APP_MENU}, { ui::VKEY_ESCAPE, false, false, false, IDC_STOP }, { ui::VKEY_ESCAPE, true, false, false, IDC_TASK_MANAGER }, { ui::VKEY_U, false, true, false, IDC_VIEW_SOURCE }, { ui::VKEY_OEM_MINUS, false, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_OEM_MINUS, true, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_SUBTRACT, false, true, false, IDC_ZOOM_MINUS }, { ui::VKEY_0, false, true, false, IDC_ZOOM_NORMAL }, { ui::VKEY_NUMPAD0, false, true, false, IDC_ZOOM_NORMAL }, { ui::VKEY_OEM_PLUS, false, true, false, IDC_ZOOM_PLUS }, { ui::VKEY_OEM_PLUS, true, true, false, IDC_ZOOM_PLUS }, { ui::VKEY_ADD, false, true, false, IDC_ZOOM_PLUS }, }; const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap); } // namespace browser <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "IncrementalParser.h" #include "ASTDumper.h" #include "ChainedConsumer.h" #include "DeclExtractor.h" #include "DynamicLookup.h" #include "ValuePrinterSynthesizer.h" #include "cling/Interpreter/CIFactory.h" #include "cling/Interpreter/Interpreter.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang/Basic/FileManager.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Parse/Parser.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Serialization/ASTWriter.h" #include "llvm/LLVMContext.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_os_ostream.h" #include <ctime> #include <iostream> #include <stdio.h> #include <sstream> using namespace clang; namespace cling { IncrementalParser::IncrementalParser(Interpreter* interp, int argc, const char* const *argv, const char* llvmdir): m_Interpreter(interp), m_DynamicLookupEnabled(false), m_Consumer(0), m_FirstTopLevelDecl(0), m_LastTopLevelDecl(0), m_SyntaxOnly(false) { CompilerInstance* CI = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"), argc, argv, llvmdir); assert(CI && "CompilerInstance is (null)!"); m_CI.reset(CI); // Ugly hack to avoid the default of ProgramAction which is SyntaxOnly // and we can't override it later. This will be fixed once cling is // supports the latest changes in the clang's driver // FIXME: REIMPLEMENT m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly); CreateSLocOffsetGenerator(); m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer()); assert(m_Consumer && "Expected ChainedConsumer!"); // Add consumers to the ChainedConsumer, which owns them EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp); ES->Attach(m_Consumer); addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES); DeclExtractor* DE = new DeclExtractor(); DE->Attach(m_Consumer); addConsumer(ChainedConsumer::kDeclExtractor, DE); ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp); VPS->Attach(m_Consumer); addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS); addConsumer(ChainedConsumer::kASTDumper, new ASTDumper()); if (!m_SyntaxOnly) { CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(), "cling input", CI->getCodeGenOpts(), /*Owned by codegen*/ * new llvm::LLVMContext() ); assert(CG && "No CodeGen?!"); addConsumer(ChainedConsumer::kCodeGenerator, CG); } m_Consumer->Initialize(CI->getASTContext()); m_Consumer->InitializeSema(CI->getSema()); // Initialize the parser. m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema())); CI->getPreprocessor().EnterMainSourceFile(); m_Parser->Initialize(); } // Each input line is contained in separate memory buffer. The SourceManager // assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry // for the MemoryBuffer's FileID. That in turn is problem because invalid // SourceLocations are given to the diagnostics. Thus the diagnostics cannot // order the overloads, for example // // Our work-around is creating a virtual file, which doesn't exist on the disk // with enormous size (no allocation is done). That file has valid FileEntry // and so on... We use it for generating valid SourceLocations with valid // offsets so that it doesn't cause any troubles to the diagnostics. // // +---------------------+ // | Main memory buffer | // +---------------------+ // | Virtual file SLoc | // | address space |<-----------------+ // | ... |<------------+ | // | ... | | | // | ... |<----+ | | // | ... | | | | // +~~~~~~~~~~~~~~~~~~~~~+ | | | // | input_line_1 | ....+.......+..--+ // +---------------------+ | | // | input_line_2 | ....+.....--+ // +---------------------+ | // | ... | | // +---------------------+ | // | input_line_N | ..--+ // +---------------------+ // void IncrementalParser::CreateSLocOffsetGenerator() { SourceManager& SM = getCI()->getSourceManager(); FileManager& FM = SM.getFileManager(); const FileEntry* FE = FM.getVirtualFile("Interactrive/InputLineIncluder", 1U << 15U, time(0)); m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User); assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?"); } IncrementalParser::~IncrementalParser() { if (GetCodeGenerator()) { GetCodeGenerator()->ReleaseModule(); } } void IncrementalParser::Initialize() { // Init the consumers CompileAsIs(""); // Consume initialization. } IncrementalParser::EParseResult IncrementalParser::CompileLineFromPrompt(llvm::StringRef input) { assert(input.str()[0] != '#' && "Preprocessed line! Call CompilePreprocessed instead"); bool p, q; m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer, isDynamicLookupEnabled()); p = m_Consumer->EnableConsumer(ChainedConsumer::kDeclExtractor); q = m_Consumer->EnableConsumer(ChainedConsumer::kValuePrinterSynthesizer); EParseResult Result = Compile(input); m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p); m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q); return Result; } IncrementalParser::EParseResult IncrementalParser::CompileAsIs(llvm::StringRef input) { bool p, q; m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer, isDynamicLookupEnabled()); p = m_Consumer->DisableConsumer(ChainedConsumer::kDeclExtractor); q = m_Consumer->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer); EParseResult Result = Compile(input); m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p); m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q); return Result; } void IncrementalParser::Parse(llvm::StringRef input, llvm::SmallVector<DeclGroupRef, 4>& DGRs){ m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator); Parse(input); for (llvm::SmallVector<ChainedConsumer::DGRInfo, 64>::iterator I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end(); I != E; ++I) { DGRs.push_back((*I).D); } m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator); } IncrementalParser::EParseResult IncrementalParser::Compile(llvm::StringRef input) { // Just in case when Parse is called, we want to complete the transaction // coming from parse and then start new one. m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); // Reset the module builder to clean up global initializers, c'tors, d'tors: if (GetCodeGenerator()) { GetCodeGenerator()->Initialize(getCI()->getASTContext()); } EParseResult Result = Parse(input); // Check for errors coming from our custom consumers. DiagnosticConsumer& DClient = m_CI->getDiagnosticClient(); DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor()); m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); DClient.EndSourceFile(); m_CI->getDiagnostics().Reset(); if (!m_SyntaxOnly) { m_Interpreter->runStaticInitializersOnce(); } return Result; } IncrementalParser::EParseResult IncrementalParser::Parse(llvm::StringRef input) { // Add src to the memory buffer, parse it, and add it to // the AST. Returns the CompilerInstance (and thus the AST). // Diagnostics are reset for each call of parse: they are only covering // src. Preprocessor& PP = m_CI->getPreprocessor(); DiagnosticConsumer& DClient = m_CI->getDiagnosticClient(); DClient.BeginSourceFile(m_CI->getLangOpts(), &PP); // Reset the transaction information getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext); if (input.size()) { std::ostringstream source_name; source_name << "input_line_" << (m_MemoryBuffer.size() + 1); m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str())); SourceManager& SM = getCI()->getSourceManager(); // Create SourceLocation, which will allow clang to order the overload // candidates for example SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID); NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1); // Create FileID for the current buffer FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(), /*LoadedID*/0, /*LoadedOffset*/0, NewLoc); PP.EnterSourceFile(FID, 0, NewLoc); Token &tok = const_cast<Token&>(m_Parser->getCurToken()); tok.setKind(tok::semi); } Parser::DeclGroupPtrTy ADecl; bool atEOF = false; if (m_Parser->getCurToken().is(tok::eof)) { atEOF = true; } else { atEOF = m_Parser->ParseTopLevelDecl(ADecl); } while (!atEOF) { // Not end of file. // If we got a null return and something *was* parsed, ignore it. This // is due to a top-level semicolon, an action override, or a parse error // skipping something. if (ADecl) { DeclGroupRef DGR = ADecl.getAsVal<DeclGroupRef>(); for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) { if (!m_FirstTopLevelDecl) m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin()); m_LastTopLevelDecl = *i; } m_Consumer->HandleTopLevelDecl(DGR); } // ADecl if (m_Parser->getCurToken().is(tok::eof)) { atEOF = true; } else { atEOF = m_Parser->ParseTopLevelDecl(ADecl); } }; // Process any TopLevelDecls generated by #pragma weak. for (llvm::SmallVector<Decl*,2>::iterator I = getCI()->getSema().WeakTopLevelDecls().begin(), E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I)); } getCI()->getSema().PerformPendingInstantiations(); DClient.EndSourceFile(); DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics(); if (Diag.hasErrorOccurred()) return IncrementalParser::kFailed; else if (Diag.getNumWarnings()) return IncrementalParser::kSuccessWithWarnings; return IncrementalParser::kSuccess; } void IncrementalParser::enableDynamicLookup(bool value) { m_DynamicLookupEnabled = value; Sema& S = m_CI->getSema(); if (isDynamicLookupEnabled()) { assert(!S.ExternalSource && "Already set Sema ExternalSource"); S.ExternalSource = new DynamicIDHandler(&S); } else { delete S.ExternalSource; S.ExternalSource = 0; } } void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) { if (m_Consumer->Exists(I)) return; m_Consumer->Add(I, consumer); if (I == ChainedConsumer::kCodeGenerator) m_Consumer->EnableConsumer(I); } CodeGenerator* IncrementalParser::GetCodeGenerator() const { return (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator); } } // namespace cling <commit_msg>Remove "Do not look at this code" comment - it is fixed.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "IncrementalParser.h" #include "ASTDumper.h" #include "ChainedConsumer.h" #include "DeclExtractor.h" #include "DynamicLookup.h" #include "ValuePrinterSynthesizer.h" #include "cling/Interpreter/CIFactory.h" #include "cling/Interpreter/Interpreter.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang/Basic/FileManager.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Parse/Parser.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Serialization/ASTWriter.h" #include "llvm/LLVMContext.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_os_ostream.h" #include <ctime> #include <iostream> #include <stdio.h> #include <sstream> using namespace clang; namespace cling { IncrementalParser::IncrementalParser(Interpreter* interp, int argc, const char* const *argv, const char* llvmdir): m_Interpreter(interp), m_DynamicLookupEnabled(false), m_Consumer(0), m_FirstTopLevelDecl(0), m_LastTopLevelDecl(0), m_SyntaxOnly(false) { CompilerInstance* CI = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"), argc, argv, llvmdir); assert(CI && "CompilerInstance is (null)!"); m_CI.reset(CI); m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly); CreateSLocOffsetGenerator(); m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer()); assert(m_Consumer && "Expected ChainedConsumer!"); // Add consumers to the ChainedConsumer, which owns them EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp); ES->Attach(m_Consumer); addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES); DeclExtractor* DE = new DeclExtractor(); DE->Attach(m_Consumer); addConsumer(ChainedConsumer::kDeclExtractor, DE); ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp); VPS->Attach(m_Consumer); addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS); addConsumer(ChainedConsumer::kASTDumper, new ASTDumper()); if (!m_SyntaxOnly) { CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(), "cling input", CI->getCodeGenOpts(), /*Owned by codegen*/ * new llvm::LLVMContext() ); assert(CG && "No CodeGen?!"); addConsumer(ChainedConsumer::kCodeGenerator, CG); } m_Consumer->Initialize(CI->getASTContext()); m_Consumer->InitializeSema(CI->getSema()); // Initialize the parser. m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema())); CI->getPreprocessor().EnterMainSourceFile(); m_Parser->Initialize(); } // Each input line is contained in separate memory buffer. The SourceManager // assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry // for the MemoryBuffer's FileID. That in turn is problem because invalid // SourceLocations are given to the diagnostics. Thus the diagnostics cannot // order the overloads, for example // // Our work-around is creating a virtual file, which doesn't exist on the disk // with enormous size (no allocation is done). That file has valid FileEntry // and so on... We use it for generating valid SourceLocations with valid // offsets so that it doesn't cause any troubles to the diagnostics. // // +---------------------+ // | Main memory buffer | // +---------------------+ // | Virtual file SLoc | // | address space |<-----------------+ // | ... |<------------+ | // | ... | | | // | ... |<----+ | | // | ... | | | | // +~~~~~~~~~~~~~~~~~~~~~+ | | | // | input_line_1 | ....+.......+..--+ // +---------------------+ | | // | input_line_2 | ....+.....--+ // +---------------------+ | // | ... | | // +---------------------+ | // | input_line_N | ..--+ // +---------------------+ // void IncrementalParser::CreateSLocOffsetGenerator() { SourceManager& SM = getCI()->getSourceManager(); FileManager& FM = SM.getFileManager(); const FileEntry* FE = FM.getVirtualFile("Interactrive/InputLineIncluder", 1U << 15U, time(0)); m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User); assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?"); } IncrementalParser::~IncrementalParser() { if (GetCodeGenerator()) { GetCodeGenerator()->ReleaseModule(); } } void IncrementalParser::Initialize() { // Init the consumers CompileAsIs(""); // Consume initialization. } IncrementalParser::EParseResult IncrementalParser::CompileLineFromPrompt(llvm::StringRef input) { assert(input.str()[0] != '#' && "Preprocessed line! Call CompilePreprocessed instead"); bool p, q; m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer, isDynamicLookupEnabled()); p = m_Consumer->EnableConsumer(ChainedConsumer::kDeclExtractor); q = m_Consumer->EnableConsumer(ChainedConsumer::kValuePrinterSynthesizer); EParseResult Result = Compile(input); m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p); m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q); return Result; } IncrementalParser::EParseResult IncrementalParser::CompileAsIs(llvm::StringRef input) { bool p, q; m_Consumer->RestorePreviousState(ChainedConsumer::kEvaluateTSynthesizer, isDynamicLookupEnabled()); p = m_Consumer->DisableConsumer(ChainedConsumer::kDeclExtractor); q = m_Consumer->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer); EParseResult Result = Compile(input); m_Consumer->RestorePreviousState(ChainedConsumer::kDeclExtractor, p); m_Consumer->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q); return Result; } void IncrementalParser::Parse(llvm::StringRef input, llvm::SmallVector<DeclGroupRef, 4>& DGRs){ m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator); Parse(input); for (llvm::SmallVector<ChainedConsumer::DGRInfo, 64>::iterator I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end(); I != E; ++I) { DGRs.push_back((*I).D); } m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator); } IncrementalParser::EParseResult IncrementalParser::Compile(llvm::StringRef input) { // Just in case when Parse is called, we want to complete the transaction // coming from parse and then start new one. m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); // Reset the module builder to clean up global initializers, c'tors, d'tors: if (GetCodeGenerator()) { GetCodeGenerator()->Initialize(getCI()->getASTContext()); } EParseResult Result = Parse(input); // Check for errors coming from our custom consumers. DiagnosticConsumer& DClient = m_CI->getDiagnosticClient(); DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor()); m_Consumer->HandleTranslationUnit(getCI()->getASTContext()); DClient.EndSourceFile(); m_CI->getDiagnostics().Reset(); if (!m_SyntaxOnly) { m_Interpreter->runStaticInitializersOnce(); } return Result; } IncrementalParser::EParseResult IncrementalParser::Parse(llvm::StringRef input) { // Add src to the memory buffer, parse it, and add it to // the AST. Returns the CompilerInstance (and thus the AST). // Diagnostics are reset for each call of parse: they are only covering // src. Preprocessor& PP = m_CI->getPreprocessor(); DiagnosticConsumer& DClient = m_CI->getDiagnosticClient(); DClient.BeginSourceFile(m_CI->getLangOpts(), &PP); // Reset the transaction information getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext); if (input.size()) { std::ostringstream source_name; source_name << "input_line_" << (m_MemoryBuffer.size() + 1); m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str())); SourceManager& SM = getCI()->getSourceManager(); // Create SourceLocation, which will allow clang to order the overload // candidates for example SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID); NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1); // Create FileID for the current buffer FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(), /*LoadedID*/0, /*LoadedOffset*/0, NewLoc); PP.EnterSourceFile(FID, 0, NewLoc); Token &tok = const_cast<Token&>(m_Parser->getCurToken()); tok.setKind(tok::semi); } Parser::DeclGroupPtrTy ADecl; bool atEOF = false; if (m_Parser->getCurToken().is(tok::eof)) { atEOF = true; } else { atEOF = m_Parser->ParseTopLevelDecl(ADecl); } while (!atEOF) { // Not end of file. // If we got a null return and something *was* parsed, ignore it. This // is due to a top-level semicolon, an action override, or a parse error // skipping something. if (ADecl) { DeclGroupRef DGR = ADecl.getAsVal<DeclGroupRef>(); for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) { if (!m_FirstTopLevelDecl) m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin()); m_LastTopLevelDecl = *i; } m_Consumer->HandleTopLevelDecl(DGR); } // ADecl if (m_Parser->getCurToken().is(tok::eof)) { atEOF = true; } else { atEOF = m_Parser->ParseTopLevelDecl(ADecl); } }; // Process any TopLevelDecls generated by #pragma weak. for (llvm::SmallVector<Decl*,2>::iterator I = getCI()->getSema().WeakTopLevelDecls().begin(), E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I)); } getCI()->getSema().PerformPendingInstantiations(); DClient.EndSourceFile(); DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics(); if (Diag.hasErrorOccurred()) return IncrementalParser::kFailed; else if (Diag.getNumWarnings()) return IncrementalParser::kSuccessWithWarnings; return IncrementalParser::kSuccess; } void IncrementalParser::enableDynamicLookup(bool value) { m_DynamicLookupEnabled = value; Sema& S = m_CI->getSema(); if (isDynamicLookupEnabled()) { assert(!S.ExternalSource && "Already set Sema ExternalSource"); S.ExternalSource = new DynamicIDHandler(&S); } else { delete S.ExternalSource; S.ExternalSource = 0; } } void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) { if (m_Consumer->Exists(I)) return; m_Consumer->Add(I, consumer); if (I == ChainedConsumer::kCodeGenerator) m_Consumer->EnableConsumer(I); } CodeGenerator* IncrementalParser::GetCodeGenerator() const { return (CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator); } } // namespace cling <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: lngreg.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-11-17 12:37:38 $ * * 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 <cppuhelper/factory.hxx> // helper for factories #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #include <com/sun/star/registry/XRegistryKey.hpp> using namespace com::sun::star::lang; using namespace com::sun::star::registry; //////////////////////////////////////// // declaration of external RegEntry-functions defined by the service objects // extern sal_Bool SAL_CALL LngSvcMgr_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern sal_Bool SAL_CALL DicList_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern sal_Bool SAL_CALL LinguProps_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern void * SAL_CALL LngSvcMgr_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * /*pRegistryKey*/ ); extern void * SAL_CALL DicList_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * ); void * SAL_CALL LinguProps_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * ); //////////////////////////////////////// // definition of the two functions that are used to provide the services // extern "C" { sal_Bool SAL_CALL component_writeInfo ( void * pServiceManager, XRegistryKey * pRegistryKey ) { sal_Bool bRet = LngSvcMgr_writeInfo( pServiceManager, pRegistryKey ); if(bRet) bRet = LinguProps_writeInfo( pServiceManager, pRegistryKey ); if(bRet) bRet = DicList_writeInfo( pServiceManager, pRegistryKey ); return bRet; } void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = LngSvcMgr_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); if(!pRet) pRet = LinguProps_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); if(!pRet) pRet = DicList_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); return pRet; } } /////////////////////////////////////////////////////////////////////////// <commit_msg>INTEGRATION: CWS tl01 (1.1.1.1.86); FILE MERGED 2003/07/25 13:19:24 tl 1.1.1.1.86.1: #110762# API for Hangul/Hanja text conversion user-dictionaries<commit_after>/************************************************************************* * * $RCSfile: lngreg.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-04-27 16:08:14 $ * * 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 <cppuhelper/factory.hxx> // helper for factories #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #include <com/sun/star/registry/XRegistryKey.hpp> using namespace com::sun::star::lang; using namespace com::sun::star::registry; //////////////////////////////////////// // declaration of external RegEntry-functions defined by the service objects // extern sal_Bool SAL_CALL LngSvcMgr_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern sal_Bool SAL_CALL DicList_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern sal_Bool SAL_CALL LinguProps_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern sal_Bool SAL_CALL ConvDicList_writeInfo ( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern void * SAL_CALL LngSvcMgr_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * /*pRegistryKey*/ ); extern void * SAL_CALL DicList_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * ); void * SAL_CALL LinguProps_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * ); extern void * SAL_CALL ConvDicList_getFactory ( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * ); //////////////////////////////////////// // definition of the two functions that are used to provide the services // extern "C" { sal_Bool SAL_CALL component_writeInfo ( void * pServiceManager, XRegistryKey * pRegistryKey ) { sal_Bool bRet = LngSvcMgr_writeInfo( pServiceManager, pRegistryKey ); if(bRet) bRet = LinguProps_writeInfo( pServiceManager, pRegistryKey ); if(bRet) bRet = DicList_writeInfo( pServiceManager, pRegistryKey ); if(bRet) bRet = ConvDicList_writeInfo( pServiceManager, pRegistryKey ); return bRet; } void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = LngSvcMgr_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); if(!pRet) pRet = LinguProps_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); if(!pRet) pRet = DicList_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); if(!pRet) pRet = ConvDicList_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); return pRet; } } /////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: genericpropertyset.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2005-02-16 15:55:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COMPHELPER_GENERICPROPERTYSET_HXX_ #define _COMPHELPER_GENERICPROPERTYSET_HXX_ #ifndef _COMPHELPER_PROPERTSETINFO_HXX_ #include <comphelper/propertysetinfo.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef INCLUDED_COMPHELPERDLLAPI_H #include "comphelper/comphelperdllapi.h" #endif namespace comphelper { COMPHELPER_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GenericPropertySet_CreateInstance( PropertySetInfo* pInfo ); } #endif // _COMPHELPER_GENERICPROPERTYSET_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.56); FILE MERGED 2005/09/05 15:23:42 rt 1.2.56.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: genericpropertyset.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:31:23 $ * * 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 _COMPHELPER_GENERICPROPERTYSET_HXX_ #define _COMPHELPER_GENERICPROPERTYSET_HXX_ #ifndef _COMPHELPER_PROPERTSETINFO_HXX_ #include <comphelper/propertysetinfo.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef INCLUDED_COMPHELPERDLLAPI_H #include "comphelper/comphelperdllapi.h" #endif namespace comphelper { COMPHELPER_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GenericPropertySet_CreateInstance( PropertySetInfo* pInfo ); } #endif // _COMPHELPER_GENERICPROPERTYSET_HXX_ <|endoftext|>
<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/SIR/ASTStmt.h" #include "dawn/SIR/ASTExpr.h" #include "dawn/SIR/ASTVisitor.h" #include "dawn/SIR/SIR.h" #include "dawn/Support/Assert.h" #include "dawn/Support/Casting.h" namespace dawn { //===------------------------------------------------------------------------------------------===// // BlockStmt //===------------------------------------------------------------------------------------------===// BlockStmt::BlockStmt(SourceLocation loc) : Stmt(SK_BlockStmt, loc) {} BlockStmt::BlockStmt(const std::vector<std::shared_ptr<Stmt>>& statements, SourceLocation loc) : Stmt(SK_BlockStmt, loc), statements_(statements) {} BlockStmt::BlockStmt(const BlockStmt& stmt) : Stmt(SK_BlockStmt, stmt.getSourceLocation()) { for(auto s : stmt.getStatements()) statements_.push_back(s->clone()); } BlockStmt& BlockStmt::operator=(BlockStmt stmt) { assign(stmt); statements_ = std::move(stmt.statements_); return *this; } BlockStmt::~BlockStmt() {} std::shared_ptr<Stmt> BlockStmt::clone() const { return std::make_shared<BlockStmt>(*this); } bool BlockStmt::equals(const Stmt* other) const { const BlockStmt* otherPtr = dyn_cast<BlockStmt>(other); return otherPtr && Stmt::equals(other) && otherPtr->statements_.size() == statements_.size() && std::equal(statements_.begin(), statements_.end(), otherPtr->statements_.begin(), [](const std::shared_ptr<Stmt>& a, const std::shared_ptr<Stmt>& b) { return a->equals(b.get()); }); } void BlockStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<BlockStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // ExprStmt //===------------------------------------------------------------------------------------------===// ExprStmt::ExprStmt(const std::shared_ptr<Expr>& expr, SourceLocation loc) : Stmt(SK_ExprStmt, loc), expr_(expr) {} ExprStmt::ExprStmt(const ExprStmt& stmt) : Stmt(SK_ExprStmt, stmt.getSourceLocation()), expr_(stmt.getExpr()->clone()) {} ExprStmt& ExprStmt::operator=(ExprStmt stmt) { assign(stmt); expr_ = stmt.getExpr(); return *this; } ExprStmt::~ExprStmt() {} std::shared_ptr<Stmt> ExprStmt::clone() const { return std::make_shared<ExprStmt>(*this); } bool ExprStmt::equals(const Stmt* other) const { const ExprStmt* otherPtr = dyn_cast<ExprStmt>(other); return otherPtr && Stmt::equals(other) && expr_->equals(otherPtr->expr_.get()); } void ExprStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<ExprStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // ReturnStmt //===------------------------------------------------------------------------------------------===// ReturnStmt::ReturnStmt(const std::shared_ptr<Expr>& expr, SourceLocation loc) : Stmt(SK_ReturnStmt, loc), expr_(expr) {} ReturnStmt::ReturnStmt(const ReturnStmt& stmt) : Stmt(SK_ReturnStmt, stmt.getSourceLocation()), expr_(stmt.getExpr()->clone()) {} ReturnStmt& ReturnStmt::operator=(ReturnStmt stmt) { assign(stmt); expr_ = stmt.getExpr(); return *this; } ReturnStmt::~ReturnStmt() {} std::shared_ptr<Stmt> ReturnStmt::clone() const { return std::make_shared<ReturnStmt>(*this); } bool ReturnStmt::equals(const Stmt* other) const { const ReturnStmt* otherPtr = dyn_cast<ReturnStmt>(other); return otherPtr && Stmt::equals(other) && expr_->equals(otherPtr->expr_.get()); } void ReturnStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<ReturnStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // VarDeclStmt //===------------------------------------------------------------------------------------------===// VarDeclStmt::VarDeclStmt(const Type& type, const std::string& name, int dimension, const char* op, std::vector<std::shared_ptr<Expr>> initList, SourceLocation loc) : Stmt(SK_VarDeclStmt, loc), type_(type), name_(name), dimension_(dimension), op_(op), initList_(std::move(initList)) {} VarDeclStmt::VarDeclStmt(const VarDeclStmt& stmt) : Stmt(SK_VarDeclStmt, stmt.getSourceLocation()), type_(stmt.getType()), name_(stmt.getName()), dimension_(stmt.getDimension()), op_(stmt.getOp()) { for(const auto& expr : stmt.getInitList()) initList_.push_back(expr->clone()); } VarDeclStmt& VarDeclStmt::operator=(VarDeclStmt stmt) { assign(stmt); type_ = std::move(stmt.getType()); name_ = std::move(stmt.getName()); dimension_ = stmt.getDimension(); op_ = stmt.getOp(); initList_ = std::move(stmt.getInitList()); return *this; } VarDeclStmt::~VarDeclStmt() {} std::shared_ptr<Stmt> VarDeclStmt::clone() const { return std::make_shared<VarDeclStmt>(*this); } bool VarDeclStmt::equals(const Stmt* other) const { const VarDeclStmt* otherPtr = dyn_cast<VarDeclStmt>(other); return otherPtr && Stmt::equals(other) && type_ == otherPtr->type_ && name_ == otherPtr->name_ && dimension_ == otherPtr->dimension_ && std::strcmp(op_, otherPtr->op_) == 0 && initList_.size() == otherPtr->initList_.size() && std::equal(initList_.begin(), initList_.end(), otherPtr->initList_.begin(), [](const std::shared_ptr<Expr>& a, const std::shared_ptr<Expr>& b) { return a->equals(b.get()); }); } void VarDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<VarDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // VerticalRegionDeclStmt //===------------------------------------------------------------------------------------------===// VerticalRegionDeclStmt::VerticalRegionDeclStmt( const std::shared_ptr<sir::VerticalRegion>& verticalRegion, SourceLocation loc) : Stmt(SK_VerticalRegionDeclStmt, loc), verticalRegion_(verticalRegion) {} VerticalRegionDeclStmt::VerticalRegionDeclStmt(const VerticalRegionDeclStmt& stmt) : Stmt(SK_VerticalRegionDeclStmt, stmt.getSourceLocation()), verticalRegion_(stmt.getVerticalRegion()->clone()) {} VerticalRegionDeclStmt& VerticalRegionDeclStmt::operator=(VerticalRegionDeclStmt stmt) { assign(stmt); verticalRegion_ = std::move(stmt.getVerticalRegion()); return *this; } VerticalRegionDeclStmt::~VerticalRegionDeclStmt() {} std::shared_ptr<Stmt> VerticalRegionDeclStmt::clone() const { return std::make_shared<VerticalRegionDeclStmt>(*this); } bool VerticalRegionDeclStmt::equals(const Stmt* other) const { const VerticalRegionDeclStmt* otherPtr = dyn_cast<VerticalRegionDeclStmt>(other); return otherPtr && Stmt::equals(other) && *(verticalRegion_.get()) == *(otherPtr->verticalRegion_.get()); } void VerticalRegionDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<VerticalRegionDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // StencilCallDeclStmt //===------------------------------------------------------------------------------------------===// StencilCallDeclStmt::StencilCallDeclStmt(const std::shared_ptr<sir::StencilCall>& stencilCall, SourceLocation loc) : Stmt(SK_StencilCallDeclStmt, loc), stencilCall_(stencilCall) {} StencilCallDeclStmt::StencilCallDeclStmt(const StencilCallDeclStmt& stmt) : Stmt(SK_StencilCallDeclStmt, stmt.getSourceLocation()), stencilCall_(stmt.getStencilCall()->clone()) {} StencilCallDeclStmt& StencilCallDeclStmt::operator=(StencilCallDeclStmt stmt) { assign(stmt); stencilCall_ = std::move(stmt.getStencilCall()); return *this; } StencilCallDeclStmt::~StencilCallDeclStmt() {} std::shared_ptr<Stmt> StencilCallDeclStmt::clone() const { return std::make_shared<StencilCallDeclStmt>(*this); } bool StencilCallDeclStmt::equals(const Stmt* other) const { const StencilCallDeclStmt* otherPtr = dyn_cast<StencilCallDeclStmt>(other); // We just compare the shared pointers of the stencil call return otherPtr && Stmt::equals(other) && stencilCall_ == otherPtr->stencilCall_; } void StencilCallDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<StencilCallDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // BoundaryConditionDeclStmt //===------------------------------------------------------------------------------------------===// BoundaryConditionDeclStmt::BoundaryConditionDeclStmt(const std::string& callee, SourceLocation loc) : Stmt(SK_BoundaryConditionDeclStmt, loc), functor_(callee) {} BoundaryConditionDeclStmt::BoundaryConditionDeclStmt(const BoundaryConditionDeclStmt& stmt) : Stmt(SK_BoundaryConditionDeclStmt, stmt.getSourceLocation()), functor_(stmt.functor_), fields_(stmt.fields_) {} BoundaryConditionDeclStmt& BoundaryConditionDeclStmt::operator=(BoundaryConditionDeclStmt stmt) { assign(stmt); functor_ = std::move(stmt.functor_); fields_ = std::move(stmt.fields_); return *this; } BoundaryConditionDeclStmt::~BoundaryConditionDeclStmt() {} std::shared_ptr<Stmt> BoundaryConditionDeclStmt::clone() const { return std::make_shared<BoundaryConditionDeclStmt>(*this); } bool BoundaryConditionDeclStmt::equals(const Stmt* other) const { const BoundaryConditionDeclStmt* otherPtr = dyn_cast<BoundaryConditionDeclStmt>(other); return otherPtr && Stmt::equals(other) && functor_ == otherPtr->functor_ && fields_.size() == otherPtr->fields_.size() && std::equal(fields_.begin(), fields_.end(), otherPtr->fields_.begin(), [](const std::shared_ptr<sir::Field>& a, const std::shared_ptr<sir::Field>& b) { return a->Name == b->Name && a->IsTemporary == b->IsTemporary; }); } void BoundaryConditionDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<BoundaryConditionDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // IfStmt //===------------------------------------------------------------------------------------------===// IfStmt::IfStmt(const std::shared_ptr<Stmt>& condStmt, const std::shared_ptr<Stmt>& thenStmt, const std::shared_ptr<Stmt>& elseStmt, SourceLocation loc) : Stmt(SK_IfStmt, loc), subStmts_{condStmt, thenStmt, elseStmt} {} IfStmt::IfStmt(const IfStmt& stmt) : Stmt(SK_IfStmt, stmt.getSourceLocation()), subStmts_{stmt.getCondStmt()->clone(), stmt.getThenStmt()->clone(), stmt.hasElse() ? stmt.getElseStmt()->clone() : nullptr} {} IfStmt& IfStmt::operator=(IfStmt stmt) { assign(stmt); subStmts_[OK_Cond] = std::move(stmt.getCondStmt()); subStmts_[OK_Then] = std::move(stmt.getThenStmt()); subStmts_[OK_Else] = std::move(stmt.getElseStmt()); return *this; } IfStmt::~IfStmt() {} std::shared_ptr<Stmt> IfStmt::clone() const { return std::make_shared<IfStmt>(*this); } bool IfStmt::equals(const Stmt* other) const { const IfStmt* otherPtr = dyn_cast<IfStmt>(other); bool sameElse = true; if(hasElse() && otherPtr->hasElse()) { sameElse = subStmts_[OK_Else]->equals(otherPtr->subStmts_[OK_Else].get()); } return otherPtr && Stmt::equals(other) && subStmts_[OK_Cond]->equals(otherPtr->subStmts_[OK_Cond].get()) && subStmts_[OK_Then]->equals(otherPtr->subStmts_[OK_Then].get()) && sameElse; } void IfStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<IfStmt>(shared_from_this())); } } // namespace dawn <commit_msg>prettier comparison<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/SIR/ASTStmt.h" #include "dawn/SIR/ASTExpr.h" #include "dawn/SIR/ASTVisitor.h" #include "dawn/SIR/SIR.h" #include "dawn/Support/Assert.h" #include "dawn/Support/Casting.h" namespace dawn { //===------------------------------------------------------------------------------------------===// // BlockStmt //===------------------------------------------------------------------------------------------===// BlockStmt::BlockStmt(SourceLocation loc) : Stmt(SK_BlockStmt, loc) {} BlockStmt::BlockStmt(const std::vector<std::shared_ptr<Stmt>>& statements, SourceLocation loc) : Stmt(SK_BlockStmt, loc), statements_(statements) {} BlockStmt::BlockStmt(const BlockStmt& stmt) : Stmt(SK_BlockStmt, stmt.getSourceLocation()) { for(auto s : stmt.getStatements()) statements_.push_back(s->clone()); } BlockStmt& BlockStmt::operator=(BlockStmt stmt) { assign(stmt); statements_ = std::move(stmt.statements_); return *this; } BlockStmt::~BlockStmt() {} std::shared_ptr<Stmt> BlockStmt::clone() const { return std::make_shared<BlockStmt>(*this); } bool BlockStmt::equals(const Stmt* other) const { const BlockStmt* otherPtr = dyn_cast<BlockStmt>(other); return otherPtr && Stmt::equals(other) && otherPtr->statements_.size() == statements_.size() && std::equal(statements_.begin(), statements_.end(), otherPtr->statements_.begin(), [](const std::shared_ptr<Stmt>& a, const std::shared_ptr<Stmt>& b) { return a->equals(b.get()); }); } void BlockStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<BlockStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // ExprStmt //===------------------------------------------------------------------------------------------===// ExprStmt::ExprStmt(const std::shared_ptr<Expr>& expr, SourceLocation loc) : Stmt(SK_ExprStmt, loc), expr_(expr) {} ExprStmt::ExprStmt(const ExprStmt& stmt) : Stmt(SK_ExprStmt, stmt.getSourceLocation()), expr_(stmt.getExpr()->clone()) {} ExprStmt& ExprStmt::operator=(ExprStmt stmt) { assign(stmt); expr_ = stmt.getExpr(); return *this; } ExprStmt::~ExprStmt() {} std::shared_ptr<Stmt> ExprStmt::clone() const { return std::make_shared<ExprStmt>(*this); } bool ExprStmt::equals(const Stmt* other) const { const ExprStmt* otherPtr = dyn_cast<ExprStmt>(other); return otherPtr && Stmt::equals(other) && expr_->equals(otherPtr->expr_.get()); } void ExprStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<ExprStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // ReturnStmt //===------------------------------------------------------------------------------------------===// ReturnStmt::ReturnStmt(const std::shared_ptr<Expr>& expr, SourceLocation loc) : Stmt(SK_ReturnStmt, loc), expr_(expr) {} ReturnStmt::ReturnStmt(const ReturnStmt& stmt) : Stmt(SK_ReturnStmt, stmt.getSourceLocation()), expr_(stmt.getExpr()->clone()) {} ReturnStmt& ReturnStmt::operator=(ReturnStmt stmt) { assign(stmt); expr_ = stmt.getExpr(); return *this; } ReturnStmt::~ReturnStmt() {} std::shared_ptr<Stmt> ReturnStmt::clone() const { return std::make_shared<ReturnStmt>(*this); } bool ReturnStmt::equals(const Stmt* other) const { const ReturnStmt* otherPtr = dyn_cast<ReturnStmt>(other); return otherPtr && Stmt::equals(other) && expr_->equals(otherPtr->expr_.get()); } void ReturnStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<ReturnStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // VarDeclStmt //===------------------------------------------------------------------------------------------===// VarDeclStmt::VarDeclStmt(const Type& type, const std::string& name, int dimension, const char* op, std::vector<std::shared_ptr<Expr>> initList, SourceLocation loc) : Stmt(SK_VarDeclStmt, loc), type_(type), name_(name), dimension_(dimension), op_(op), initList_(std::move(initList)) {} VarDeclStmt::VarDeclStmt(const VarDeclStmt& stmt) : Stmt(SK_VarDeclStmt, stmt.getSourceLocation()), type_(stmt.getType()), name_(stmt.getName()), dimension_(stmt.getDimension()), op_(stmt.getOp()) { for(const auto& expr : stmt.getInitList()) initList_.push_back(expr->clone()); } VarDeclStmt& VarDeclStmt::operator=(VarDeclStmt stmt) { assign(stmt); type_ = std::move(stmt.getType()); name_ = std::move(stmt.getName()); dimension_ = stmt.getDimension(); op_ = stmt.getOp(); initList_ = std::move(stmt.getInitList()); return *this; } VarDeclStmt::~VarDeclStmt() {} std::shared_ptr<Stmt> VarDeclStmt::clone() const { return std::make_shared<VarDeclStmt>(*this); } bool VarDeclStmt::equals(const Stmt* other) const { const VarDeclStmt* otherPtr = dyn_cast<VarDeclStmt>(other); return otherPtr && Stmt::equals(other) && type_ == otherPtr->type_ && name_ == otherPtr->name_ && dimension_ == otherPtr->dimension_ && std::strcmp(op_, otherPtr->op_) == 0 && initList_.size() == otherPtr->initList_.size() && std::equal(initList_.begin(), initList_.end(), otherPtr->initList_.begin(), [](const std::shared_ptr<Expr>& a, const std::shared_ptr<Expr>& b) { return a->equals(b.get()); }); } void VarDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<VarDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // VerticalRegionDeclStmt //===------------------------------------------------------------------------------------------===// VerticalRegionDeclStmt::VerticalRegionDeclStmt( const std::shared_ptr<sir::VerticalRegion>& verticalRegion, SourceLocation loc) : Stmt(SK_VerticalRegionDeclStmt, loc), verticalRegion_(verticalRegion) {} VerticalRegionDeclStmt::VerticalRegionDeclStmt(const VerticalRegionDeclStmt& stmt) : Stmt(SK_VerticalRegionDeclStmt, stmt.getSourceLocation()), verticalRegion_(stmt.getVerticalRegion()->clone()) {} VerticalRegionDeclStmt& VerticalRegionDeclStmt::operator=(VerticalRegionDeclStmt stmt) { assign(stmt); verticalRegion_ = std::move(stmt.getVerticalRegion()); return *this; } VerticalRegionDeclStmt::~VerticalRegionDeclStmt() {} std::shared_ptr<Stmt> VerticalRegionDeclStmt::clone() const { return std::make_shared<VerticalRegionDeclStmt>(*this); } bool VerticalRegionDeclStmt::equals(const Stmt* other) const { const VerticalRegionDeclStmt* otherPtr = dyn_cast<VerticalRegionDeclStmt>(other); return otherPtr && Stmt::equals(other) && *(verticalRegion_.get()) == *(otherPtr->verticalRegion_.get()); } void VerticalRegionDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<VerticalRegionDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // StencilCallDeclStmt //===------------------------------------------------------------------------------------------===// StencilCallDeclStmt::StencilCallDeclStmt(const std::shared_ptr<sir::StencilCall>& stencilCall, SourceLocation loc) : Stmt(SK_StencilCallDeclStmt, loc), stencilCall_(stencilCall) {} StencilCallDeclStmt::StencilCallDeclStmt(const StencilCallDeclStmt& stmt) : Stmt(SK_StencilCallDeclStmt, stmt.getSourceLocation()), stencilCall_(stmt.getStencilCall()->clone()) {} StencilCallDeclStmt& StencilCallDeclStmt::operator=(StencilCallDeclStmt stmt) { assign(stmt); stencilCall_ = std::move(stmt.getStencilCall()); return *this; } StencilCallDeclStmt::~StencilCallDeclStmt() {} std::shared_ptr<Stmt> StencilCallDeclStmt::clone() const { return std::make_shared<StencilCallDeclStmt>(*this); } bool StencilCallDeclStmt::equals(const Stmt* other) const { const StencilCallDeclStmt* otherPtr = dyn_cast<StencilCallDeclStmt>(other); // We just compare the shared pointers of the stencil call return otherPtr && Stmt::equals(other) && stencilCall_ == otherPtr->stencilCall_; } void StencilCallDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<StencilCallDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // BoundaryConditionDeclStmt //===------------------------------------------------------------------------------------------===// BoundaryConditionDeclStmt::BoundaryConditionDeclStmt(const std::string& callee, SourceLocation loc) : Stmt(SK_BoundaryConditionDeclStmt, loc), functor_(callee) {} BoundaryConditionDeclStmt::BoundaryConditionDeclStmt(const BoundaryConditionDeclStmt& stmt) : Stmt(SK_BoundaryConditionDeclStmt, stmt.getSourceLocation()), functor_(stmt.functor_), fields_(stmt.fields_) {} BoundaryConditionDeclStmt& BoundaryConditionDeclStmt::operator=(BoundaryConditionDeclStmt stmt) { assign(stmt); functor_ = std::move(stmt.functor_); fields_ = std::move(stmt.fields_); return *this; } BoundaryConditionDeclStmt::~BoundaryConditionDeclStmt() {} std::shared_ptr<Stmt> BoundaryConditionDeclStmt::clone() const { return std::make_shared<BoundaryConditionDeclStmt>(*this); } bool BoundaryConditionDeclStmt::equals(const Stmt* other) const { const BoundaryConditionDeclStmt* otherPtr = dyn_cast<BoundaryConditionDeclStmt>(other); return otherPtr && Stmt::equals(other) && functor_ == otherPtr->functor_ && fields_.size() == otherPtr->fields_.size() && std::equal(fields_.begin(), fields_.end(), otherPtr->fields_.begin(), [](const std::shared_ptr<sir::Field>& a, const std::shared_ptr<sir::Field>& b) { return a->Name == b->Name && a->IsTemporary == b->IsTemporary; }); } void BoundaryConditionDeclStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<BoundaryConditionDeclStmt>(shared_from_this())); } //===------------------------------------------------------------------------------------------===// // IfStmt //===------------------------------------------------------------------------------------------===// IfStmt::IfStmt(const std::shared_ptr<Stmt>& condStmt, const std::shared_ptr<Stmt>& thenStmt, const std::shared_ptr<Stmt>& elseStmt, SourceLocation loc) : Stmt(SK_IfStmt, loc), subStmts_{condStmt, thenStmt, elseStmt} {} IfStmt::IfStmt(const IfStmt& stmt) : Stmt(SK_IfStmt, stmt.getSourceLocation()), subStmts_{stmt.getCondStmt()->clone(), stmt.getThenStmt()->clone(), stmt.hasElse() ? stmt.getElseStmt()->clone() : nullptr} {} IfStmt& IfStmt::operator=(IfStmt stmt) { assign(stmt); subStmts_[OK_Cond] = std::move(stmt.getCondStmt()); subStmts_[OK_Then] = std::move(stmt.getThenStmt()); subStmts_[OK_Else] = std::move(stmt.getElseStmt()); return *this; } IfStmt::~IfStmt() {} std::shared_ptr<Stmt> IfStmt::clone() const { return std::make_shared<IfStmt>(*this); } bool IfStmt::equals(const Stmt* other) const { const IfStmt* otherPtr = dyn_cast<IfStmt>(other); bool sameElse; if(hasElse() && otherPtr->hasElse()) sameElse = subStmts_[OK_Else]->equals(otherPtr->subStmts_[OK_Else].get()); else sameElse = !(hasElse() ^ otherPtr->hasElse()); return otherPtr && Stmt::equals(other) && subStmts_[OK_Cond]->equals(otherPtr->subStmts_[OK_Cond].get()) && subStmts_[OK_Then]->equals(otherPtr->subStmts_[OK_Then].get()) && sameElse; } void IfStmt::accept(ASTVisitor& visitor) { visitor.visit(std::static_pointer_cast<IfStmt>(shared_from_this())); } } // namespace dawn <|endoftext|>
<commit_before>/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QMutexLocker> #include <QFileInfo> #include <QDir> #include <TSqlDatabasePool> #include <TWebApplication> #include "tsystemglobal.h" #define CONN_NAME_FORMAT "rdb%02d_%d" static TSqlDatabasePool *databasePool = 0; static void cleanup() { if (databasePool) { delete databasePool; databasePool = 0; } } TSqlDatabasePool::~TSqlDatabasePool() { timer.stop(); QMutexLocker locker(&mutex); for (int j = 0; j < pooledConnections.count(); ++j) { QMap<QString, uint> &map = pooledConnections[j]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { QSqlDatabase::database(it.key(), false).close(); it = map.erase(it); } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { QString name = QString::number(j) + '_' + QString::number(i); if (QSqlDatabase::contains(name)) { QSqlDatabase::removeDatabase(name); } else { break; } } } } TSqlDatabasePool::TSqlDatabasePool(const QString &environment) : QObject(), dbEnvironment(environment) { // Starts the timer to close extra-connection timer.start(10000, this); } void TSqlDatabasePool::init() { if (!Tf::app()->isSqlDatabaseAvailable()) { tSystemWarn("SQL database not available"); return; } else { tSystemInfo("SQL database available"); } // Adds databases previously for (int j = 0; j < Tf::app()->sqlDatabaseSettingsCount(); ++j) { QString type = driverType(dbEnvironment, j); if (type.isEmpty()) { continue; } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { QSqlDatabase db = QSqlDatabase::addDatabase(type, QString().sprintf(CONN_NAME_FORMAT, j, i)); if (!db.isValid()) { tWarn("Parameter 'DriverType' is invalid"); break; } setDatabaseSettings(db, dbEnvironment, j); tSystemDebug("Add Database successfully. name:%s", qPrintable(db.connectionName())); } pooledConnections.append(QMap<QString, uint>()); } } QSqlDatabase TSqlDatabasePool::database(int databaseId) { T_TRACEFUNC(""); QMutexLocker locker(&mutex); QSqlDatabase db; if (!Tf::app()->isSqlDatabaseAvailable()) { return db; } if (databaseId >= 0 && databaseId < pooledConnections.count()) { QMap<QString, uint> &map = pooledConnections[databaseId]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { db = QSqlDatabase::database(it.key(), false); it = map.erase(it); if (db.isOpen()) { tSystemDebug("Gets database: %s", qPrintable(db.connectionName())); return db; } else { tSystemError("Pooled database is not open: %s [%s:%d]", qPrintable(db.connectionName()), __FILE__, __LINE__); } } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { db = QSqlDatabase::database(QString().sprintf(CONN_NAME_FORMAT, databaseId, i), false); if (!db.isOpen()) { if (!db.open()) { tError("Database open error"); return QSqlDatabase(); } tSystemDebug("Database opened successfully (env:%s)", qPrintable(dbEnvironment)); tSystemDebug("Gets database: %s", qPrintable(db.connectionName())); return db; } } } throw RuntimeException("No pooled connection", __FILE__, __LINE__); } bool TSqlDatabasePool::setDatabaseSettings(QSqlDatabase &database, const QString &env, int databaseId) { // Initiates database QSettings &settings = Tf::app()->sqlDatabaseSettings(databaseId); settings.beginGroup(env); QString databaseName = settings.value("DatabaseName").toString().trimmed(); if (databaseName.isEmpty()) { tError("Database name empty string"); settings.endGroup(); return false; } tSystemDebug("SQL driver name:%s dbname:%s", qPrintable(database.driverName()), qPrintable(databaseName)); if (database.driverName().toUpper().startsWith("QSQLITE")) { QFileInfo fi(databaseName); if (fi.isRelative()) { // For SQLite databaseName = Tf::app()->webRootPath() + databaseName; } } database.setDatabaseName(databaseName); QString hostName = settings.value("HostName").toString().trimmed(); tSystemDebug("Database HostName: %s", qPrintable(hostName)); if (!hostName.isEmpty()) database.setHostName(hostName); int port = settings.value("Port").toInt(); tSystemDebug("Database Port: %d", port); if (port > 0) database.setPort(port); QString userName = settings.value("UserName").toString().trimmed(); tSystemDebug("Database UserName: %s", qPrintable(userName)); if (!userName.isEmpty()) database.setUserName(userName); QString password = settings.value("Password").toString().trimmed(); tSystemDebug("Database Password: %s", qPrintable(password)); if (!password.isEmpty()) database.setPassword(password); QString connectOptions = settings.value("ConnectOptions").toString().trimmed(); tSystemDebug("Database ConnectOptions: %s", qPrintable(connectOptions)); if (!connectOptions.isEmpty()) database.setConnectOptions(connectOptions); settings.endGroup(); return true; } void TSqlDatabasePool::pool(QSqlDatabase &database) { T_TRACEFUNC(""); QMutexLocker locker(&mutex); if (database.isValid()) { int databaseId = getDatabaseId(database); if (databaseId >= 0 && databaseId < pooledConnections.count()) { pooledConnections[databaseId].insert(database.connectionName(), QDateTime::currentDateTime().toTime_t()); tSystemDebug("Pooled database: %s", qPrintable(database.connectionName())); } else { tSystemError("Pooled invalid database [%s:%d]", __FILE__, __LINE__); } } database = QSqlDatabase(); // Sets an invalid object } void TSqlDatabasePool::timerEvent(QTimerEvent *event) { T_TRACEFUNC(""); if (event->timerId() == timer.timerId()) { // Closes extra-connection if (mutex.tryLock()) { for (int i = 0; i < pooledConnections.count(); ++i) { QMap<QString, uint> &map = pooledConnections[i]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { uint tm = it.value(); if (tm < QDateTime::currentDateTime().toTime_t() - 30) { // 30sec QSqlDatabase::database(it.key(), false).close(); tSystemDebug("Closed database connection, name: %s", qPrintable(it.key())); it = map.erase(it); } else { ++it; } } } mutex.unlock(); } } else { QObject::timerEvent(event); } } /*! * Initializes. * Call this in main thread. */ void TSqlDatabasePool::instantiate() { if (!databasePool) { databasePool = new TSqlDatabasePool(Tf::app()->databaseEnvironment()); databasePool->init(); qAddPostRoutine(::cleanup); } } TSqlDatabasePool *TSqlDatabasePool::instance() { if (!databasePool) { tFatal("Call TSqlDatabasePool::initialize() function first"); } return databasePool; } QString TSqlDatabasePool::driverType(const QString &env, int databaseId) { QSettings &settings = Tf::app()->sqlDatabaseSettings(databaseId); settings.beginGroup(env); QString type = settings.value("DriverType").toString().trimmed(); settings.endGroup(); if (type.isEmpty()) { tDebug("Parameter 'DriverType' is empty"); } return type; } int TSqlDatabasePool::maxDbConnectionsPerProcess() { static int maxConnections = 0; if (!maxConnections) { switch (Tf::app()->multiProcessingModule()) { case TWebApplication::Thread: maxConnections = Tf::app()->maxNumberOfServers(); break; case TWebApplication::Prefork: maxConnections = 1; break; case TWebApplication::Hybrid: maxConnections = Tf::app()->maxNumberOfServers(10); break; default: break; } } return maxConnections; } int TSqlDatabasePool::getDatabaseId(const QSqlDatabase &database) { bool ok; int id = database.connectionName().mid(3,2).toInt(&ok); if (ok && id >= 0) { return id; } return -1; } <commit_msg>modified error message.<commit_after>/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QMutexLocker> #include <QFileInfo> #include <QDir> #include <TSqlDatabasePool> #include <TWebApplication> #include "tsystemglobal.h" #define CONN_NAME_FORMAT "rdb%02d_%d" static TSqlDatabasePool *databasePool = 0; static void cleanup() { if (databasePool) { delete databasePool; databasePool = 0; } } TSqlDatabasePool::~TSqlDatabasePool() { timer.stop(); QMutexLocker locker(&mutex); for (int j = 0; j < pooledConnections.count(); ++j) { QMap<QString, uint> &map = pooledConnections[j]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { QSqlDatabase::database(it.key(), false).close(); it = map.erase(it); } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { QString name = QString::number(j) + '_' + QString::number(i); if (QSqlDatabase::contains(name)) { QSqlDatabase::removeDatabase(name); } else { break; } } } } TSqlDatabasePool::TSqlDatabasePool(const QString &environment) : QObject(), dbEnvironment(environment) { // Starts the timer to close extra-connection timer.start(10000, this); } void TSqlDatabasePool::init() { if (!Tf::app()->isSqlDatabaseAvailable()) { tSystemWarn("SQL database not available"); return; } else { tSystemInfo("SQL database available"); } // Adds databases previously for (int j = 0; j < Tf::app()->sqlDatabaseSettingsCount(); ++j) { QString type = driverType(dbEnvironment, j); if (type.isEmpty()) { continue; } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { QSqlDatabase db = QSqlDatabase::addDatabase(type, QString().sprintf(CONN_NAME_FORMAT, j, i)); if (!db.isValid()) { tWarn("Parameter 'DriverType' is invalid"); break; } setDatabaseSettings(db, dbEnvironment, j); tSystemDebug("Add Database successfully. name:%s", qPrintable(db.connectionName())); } pooledConnections.append(QMap<QString, uint>()); } } QSqlDatabase TSqlDatabasePool::database(int databaseId) { T_TRACEFUNC(""); QMutexLocker locker(&mutex); QSqlDatabase db; if (!Tf::app()->isSqlDatabaseAvailable()) { return db; } if (databaseId >= 0 && databaseId < pooledConnections.count()) { QMap<QString, uint> &map = pooledConnections[databaseId]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { db = QSqlDatabase::database(it.key(), false); it = map.erase(it); if (db.isOpen()) { tSystemDebug("Gets database: %s", qPrintable(db.connectionName())); return db; } else { tSystemError("Pooled database is not open: %s [%s:%d]", qPrintable(db.connectionName()), __FILE__, __LINE__); } } for (int i = 0; i < maxDbConnectionsPerProcess(); ++i) { db = QSqlDatabase::database(QString().sprintf(CONN_NAME_FORMAT, databaseId, i), false); if (!db.isOpen()) { if (!db.open()) { tError("Database open error. Invalid database settings, or maximum number of SQL connection exceeded."); tSystemError("Database open error: %s", qPrintable(db.connectionName())); return QSqlDatabase(); } tSystemDebug("Database opened successfully (env:%s)", qPrintable(dbEnvironment)); tSystemDebug("Gets database: %s", qPrintable(db.connectionName())); return db; } } } throw RuntimeException("No pooled connection", __FILE__, __LINE__); } bool TSqlDatabasePool::setDatabaseSettings(QSqlDatabase &database, const QString &env, int databaseId) { // Initiates database QSettings &settings = Tf::app()->sqlDatabaseSettings(databaseId); settings.beginGroup(env); QString databaseName = settings.value("DatabaseName").toString().trimmed(); if (databaseName.isEmpty()) { tError("Database name empty string"); settings.endGroup(); return false; } tSystemDebug("SQL driver name:%s dbname:%s", qPrintable(database.driverName()), qPrintable(databaseName)); if (database.driverName().toUpper().startsWith("QSQLITE")) { QFileInfo fi(databaseName); if (fi.isRelative()) { // For SQLite databaseName = Tf::app()->webRootPath() + databaseName; } } database.setDatabaseName(databaseName); QString hostName = settings.value("HostName").toString().trimmed(); tSystemDebug("Database HostName: %s", qPrintable(hostName)); if (!hostName.isEmpty()) database.setHostName(hostName); int port = settings.value("Port").toInt(); tSystemDebug("Database Port: %d", port); if (port > 0) database.setPort(port); QString userName = settings.value("UserName").toString().trimmed(); tSystemDebug("Database UserName: %s", qPrintable(userName)); if (!userName.isEmpty()) database.setUserName(userName); QString password = settings.value("Password").toString().trimmed(); tSystemDebug("Database Password: %s", qPrintable(password)); if (!password.isEmpty()) database.setPassword(password); QString connectOptions = settings.value("ConnectOptions").toString().trimmed(); tSystemDebug("Database ConnectOptions: %s", qPrintable(connectOptions)); if (!connectOptions.isEmpty()) database.setConnectOptions(connectOptions); settings.endGroup(); return true; } void TSqlDatabasePool::pool(QSqlDatabase &database) { T_TRACEFUNC(""); QMutexLocker locker(&mutex); if (database.isValid()) { int databaseId = getDatabaseId(database); if (databaseId >= 0 && databaseId < pooledConnections.count()) { pooledConnections[databaseId].insert(database.connectionName(), QDateTime::currentDateTime().toTime_t()); tSystemDebug("Pooled database: %s", qPrintable(database.connectionName())); } else { tSystemError("Pooled invalid database [%s:%d]", __FILE__, __LINE__); } } database = QSqlDatabase(); // Sets an invalid object } void TSqlDatabasePool::timerEvent(QTimerEvent *event) { T_TRACEFUNC(""); if (event->timerId() == timer.timerId()) { // Closes extra-connection if (mutex.tryLock()) { for (int i = 0; i < pooledConnections.count(); ++i) { QMap<QString, uint> &map = pooledConnections[i]; QMap<QString, uint>::iterator it = map.begin(); while (it != map.end()) { uint tm = it.value(); if (tm < QDateTime::currentDateTime().toTime_t() - 30) { // 30sec QSqlDatabase::database(it.key(), false).close(); tSystemDebug("Closed database connection, name: %s", qPrintable(it.key())); it = map.erase(it); } else { ++it; } } } mutex.unlock(); } } else { QObject::timerEvent(event); } } /*! * Initializes. * Call this in main thread. */ void TSqlDatabasePool::instantiate() { if (!databasePool) { databasePool = new TSqlDatabasePool(Tf::app()->databaseEnvironment()); databasePool->init(); qAddPostRoutine(::cleanup); } } TSqlDatabasePool *TSqlDatabasePool::instance() { if (!databasePool) { tFatal("Call TSqlDatabasePool::initialize() function first"); } return databasePool; } QString TSqlDatabasePool::driverType(const QString &env, int databaseId) { QSettings &settings = Tf::app()->sqlDatabaseSettings(databaseId); settings.beginGroup(env); QString type = settings.value("DriverType").toString().trimmed(); settings.endGroup(); if (type.isEmpty()) { tDebug("Parameter 'DriverType' is empty"); } return type; } int TSqlDatabasePool::maxDbConnectionsPerProcess() { static int maxConnections = 0; if (!maxConnections) { switch (Tf::app()->multiProcessingModule()) { case TWebApplication::Thread: maxConnections = Tf::app()->maxNumberOfServers(); break; case TWebApplication::Prefork: maxConnections = 1; break; case TWebApplication::Hybrid: maxConnections = Tf::app()->maxNumberOfServers(10); break; default: break; } } return maxConnections; } int TSqlDatabasePool::getDatabaseId(const QSqlDatabase &database) { bool ok; int id = database.connectionName().mid(3,2).toInt(&ok); if (ok && id >= 0) { return id; } return -1; } <|endoftext|>
<commit_before>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/file_storage.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { void set_hash(create_torrent& c, int p, char const* hash) { c.set_hash(p, sha1_hash(hash)); } void call_python_object(boost::python::object const& obj, int i) { obj(i); } #ifndef BOOST_NO_EXCEPTIONS void set_piece_hashes_callback(create_torrent& c, std::string const& p , boost::python::object cb) { set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1)); } #else void set_piece_hashes_callback(create_torrent& c, std::string const& p , boost::python::object cb) { error_code ec; set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec); } void set_piece_hashes0(create_torrent& c, std::string const & s) { error_code ec; set_piece_hashes(c, s, ec); } #endif void add_node(create_torrent& ct, std::string const& addr, int port) { ct.add_node(std::make_pair(addr, port)); } } void bind_create_torrent() { void (file_storage::*add_file0)(file_entry const&) = &file_storage::add_file; void (file_storage::*add_file1)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file; #if TORRENT_USE_WSTRING void (file_storage::*add_file2)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file; #endif void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name; #if TORRENT_USE_WSTRING void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name; #endif #ifndef BOOST_NO_EXCEPTIONS void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes; #endif void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files; class_<file_storage>("file_storage") .def("is_valid", &file_storage::is_valid) .def("add_file", add_file0) .def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = "")) #if TORRENT_USE_WSTRING .def("add_file", add_file2, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = "")) #endif .def("num_files", &file_storage::num_files) .def("at", &file_storage::at, return_internal_reference<>()) .def("total_size", &file_storage::total_size) .def("set_num_pieces", &file_storage::set_num_pieces) .def("num_pieces", &file_storage::num_pieces) .def("set_piece_length", &file_storage::set_piece_length) .def("piece_length", &file_storage::piece_length) .def("piece_size", &file_storage::piece_size) .def("set_name", set_name0) #if TORRENT_USE_WSTRING .def("set_name", set_name1) #endif .def("name", &file_storage::name, return_internal_reference<>()) ; class_<create_torrent>("create_torrent", no_init) .def(init<file_storage&>()) .def(init<file_storage&, int>()) .def("generate", &create_torrent::generate) .def("files", &create_torrent::files, return_internal_reference<>()) .def("set_comment", &create_torrent::set_comment) .def("set_creator", &create_torrent::set_creator) .def("set_hash", &set_hash) .def("add_url_seed", &create_torrent::add_url_seed) .def("add_node", &add_node) .def("add_tracker", &create_torrent::add_tracker) .def("set_priv", &create_torrent::set_priv) .def("num_pieces", &create_torrent::num_pieces) .def("piece_length", &create_torrent::piece_length) .def("piece_size", &create_torrent::piece_size) .def("priv", &create_torrent::priv) ; def("add_files", add_files0); def("set_piece_hashes", set_piece_hashes0); def("set_piece_hashes", set_piece_hashes_callback); } <commit_msg>add default value for flags argument to add_files() in python bindings<commit_after>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/file_storage.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { void set_hash(create_torrent& c, int p, char const* hash) { c.set_hash(p, sha1_hash(hash)); } void call_python_object(boost::python::object const& obj, int i) { obj(i); } #ifndef BOOST_NO_EXCEPTIONS void set_piece_hashes_callback(create_torrent& c, std::string const& p , boost::python::object cb) { set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1)); } #else void set_piece_hashes_callback(create_torrent& c, std::string const& p , boost::python::object cb) { error_code ec; set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec); } void set_piece_hashes0(create_torrent& c, std::string const & s) { error_code ec; set_piece_hashes(c, s, ec); } #endif void add_node(create_torrent& ct, std::string const& addr, int port) { ct.add_node(std::make_pair(addr, port)); } } void bind_create_torrent() { void (file_storage::*add_file0)(file_entry const&) = &file_storage::add_file; void (file_storage::*add_file1)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file; #if TORRENT_USE_WSTRING void (file_storage::*add_file2)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file; #endif void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name; #if TORRENT_USE_WSTRING void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name; #endif #ifndef BOOST_NO_EXCEPTIONS void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes; #endif void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files; class_<file_storage>("file_storage") .def("is_valid", &file_storage::is_valid) .def("add_file", add_file0) .def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = "")) #if TORRENT_USE_WSTRING .def("add_file", add_file2, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = "")) #endif .def("num_files", &file_storage::num_files) .def("at", &file_storage::at, return_internal_reference<>()) .def("total_size", &file_storage::total_size) .def("set_num_pieces", &file_storage::set_num_pieces) .def("num_pieces", &file_storage::num_pieces) .def("set_piece_length", &file_storage::set_piece_length) .def("piece_length", &file_storage::piece_length) .def("piece_size", &file_storage::piece_size) .def("set_name", set_name0) #if TORRENT_USE_WSTRING .def("set_name", set_name1) #endif .def("name", &file_storage::name, return_internal_reference<>()) ; class_<create_torrent>("create_torrent", no_init) .def(init<file_storage&>()) .def(init<file_storage&, int>()) .def("generate", &create_torrent::generate) .def("files", &create_torrent::files, return_internal_reference<>()) .def("set_comment", &create_torrent::set_comment) .def("set_creator", &create_torrent::set_creator) .def("set_hash", &set_hash) .def("add_url_seed", &create_torrent::add_url_seed) .def("add_node", &add_node) .def("add_tracker", &create_torrent::add_tracker) .def("set_priv", &create_torrent::set_priv) .def("num_pieces", &create_torrent::num_pieces) .def("piece_length", &create_torrent::piece_length) .def("piece_size", &create_torrent::piece_size) .def("priv", &create_torrent::priv) ; def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0)); def("set_piece_hashes", set_piece_hashes0); def("set_piece_hashes", set_piece_hashes_callback); } <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2014 Max Kellermann <max@duempel.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONST_BUFFER_HPP #define CONST_BUFFER_HPP #include <inline/compiler.h> #include <cstddef> #ifndef NDEBUG #include <assert.h> #endif template<typename T> struct ConstBuffer; template<> struct ConstBuffer<void> { typedef size_t size_type; typedef const void *pointer_type; typedef pointer_type const_pointer_type; typedef pointer_type iterator; typedef pointer_type const_iterator; pointer_type data; size_type size; ConstBuffer() = default; constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {} constexpr ConstBuffer(pointer_type _data, size_type _size) :data(_data), size(_size) {} constexpr static ConstBuffer Null() { return ConstBuffer(nullptr, 0); } constexpr static ConstBuffer<void> FromVoid(ConstBuffer<void> other) { return other; } constexpr ConstBuffer<void> ToVoid() const { return *this; } constexpr bool IsNull() const { return data == nullptr; } constexpr bool IsEmpty() const { return size == 0; } }; /** * A reference to a memory area that is read-only. */ template<typename T> struct ConstBuffer { typedef size_t size_type; typedef const T &reference_type; typedef reference_type const_reference_type; typedef const T *pointer_type; typedef pointer_type const_pointer_type; typedef pointer_type iterator; typedef pointer_type const_iterator; pointer_type data; size_type size; ConstBuffer() = default; constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {} constexpr ConstBuffer(pointer_type _data, size_type _size) :data(_data), size(_size) {} constexpr static ConstBuffer Null() { return ConstBuffer(nullptr, 0); } /** * Cast a ConstBuffer<void> to a ConstBuffer<T>. A "void" * buffer records its size in bytes, and when casting to "T", * the assertion below ensures that the size is a multiple of * sizeof(T). */ #ifdef NDEBUG constexpr #endif static ConstBuffer<T> FromVoid(ConstBuffer<void> other) { static_assert(sizeof(T) > 0, "Empty base type"); #ifndef NDEBUG assert(other.size % sizeof(T) == 0); #endif return ConstBuffer<T>(pointer_type(other.data), other.size / sizeof(T)); } constexpr ConstBuffer<void> ToVoid() const { static_assert(sizeof(T) > 0, "Empty base type"); return ConstBuffer<void>(data, size * sizeof(T)); } constexpr bool IsNull() const { return data == nullptr; } constexpr bool IsEmpty() const { return size == 0; } template<typename U> gcc_pure bool Contains(U &&u) const { for (const auto &i : *this) if (u == i) return true; return false; } constexpr iterator begin() const { return data; } constexpr iterator end() const { return data + size; } constexpr const_iterator cbegin() const { return data; } constexpr const_iterator cend() const { return data + size; } #ifdef NDEBUG constexpr #endif reference_type operator[](size_type i) const { #ifndef NDEBUG assert(i < size); #endif return data[i]; } /** * Returns a reference to the first element. Buffer must not * be empty. */ #ifdef NDEBUG constexpr #endif reference_type front() const { #ifndef NDEBUG assert(!IsEmpty()); #endif return data[0]; } /** * Returns a reference to the last element. Buffer must not * be empty. */ #ifdef NDEBUG constexpr #endif reference_type back() const { #ifndef NDEBUG assert(!IsEmpty()); #endif return data[size - 1]; } /** * Remove the first element (by moving the head pointer, does * not actually modify the buffer). Buffer must not be empty. */ void pop_front() { assert(!IsEmpty()); ++data; --size; } /** * Remove the last element (by moving the tail pointer, does * not actually modify the buffer). Buffer must not be empty. */ void pop_back() { assert(!IsEmpty()); --size; } /** * Remove the first element and return a reference to it. * Buffer must not be empty. */ reference_type shift() { reference_type result = front(); pop_front(); return result; } }; #endif <commit_msg>util/ConstBuffer: wrap assert() in NDEBUG check<commit_after>/* * Copyright (C) 2013-2014 Max Kellermann <max@duempel.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONST_BUFFER_HPP #define CONST_BUFFER_HPP #include <inline/compiler.h> #include <cstddef> #ifndef NDEBUG #include <assert.h> #endif template<typename T> struct ConstBuffer; template<> struct ConstBuffer<void> { typedef size_t size_type; typedef const void *pointer_type; typedef pointer_type const_pointer_type; typedef pointer_type iterator; typedef pointer_type const_iterator; pointer_type data; size_type size; ConstBuffer() = default; constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {} constexpr ConstBuffer(pointer_type _data, size_type _size) :data(_data), size(_size) {} constexpr static ConstBuffer Null() { return ConstBuffer(nullptr, 0); } constexpr static ConstBuffer<void> FromVoid(ConstBuffer<void> other) { return other; } constexpr ConstBuffer<void> ToVoid() const { return *this; } constexpr bool IsNull() const { return data == nullptr; } constexpr bool IsEmpty() const { return size == 0; } }; /** * A reference to a memory area that is read-only. */ template<typename T> struct ConstBuffer { typedef size_t size_type; typedef const T &reference_type; typedef reference_type const_reference_type; typedef const T *pointer_type; typedef pointer_type const_pointer_type; typedef pointer_type iterator; typedef pointer_type const_iterator; pointer_type data; size_type size; ConstBuffer() = default; constexpr ConstBuffer(std::nullptr_t):data(nullptr), size(0) {} constexpr ConstBuffer(pointer_type _data, size_type _size) :data(_data), size(_size) {} constexpr static ConstBuffer Null() { return ConstBuffer(nullptr, 0); } /** * Cast a ConstBuffer<void> to a ConstBuffer<T>. A "void" * buffer records its size in bytes, and when casting to "T", * the assertion below ensures that the size is a multiple of * sizeof(T). */ #ifdef NDEBUG constexpr #endif static ConstBuffer<T> FromVoid(ConstBuffer<void> other) { static_assert(sizeof(T) > 0, "Empty base type"); #ifndef NDEBUG assert(other.size % sizeof(T) == 0); #endif return ConstBuffer<T>(pointer_type(other.data), other.size / sizeof(T)); } constexpr ConstBuffer<void> ToVoid() const { static_assert(sizeof(T) > 0, "Empty base type"); return ConstBuffer<void>(data, size * sizeof(T)); } constexpr bool IsNull() const { return data == nullptr; } constexpr bool IsEmpty() const { return size == 0; } template<typename U> gcc_pure bool Contains(U &&u) const { for (const auto &i : *this) if (u == i) return true; return false; } constexpr iterator begin() const { return data; } constexpr iterator end() const { return data + size; } constexpr const_iterator cbegin() const { return data; } constexpr const_iterator cend() const { return data + size; } #ifdef NDEBUG constexpr #endif reference_type operator[](size_type i) const { #ifndef NDEBUG assert(i < size); #endif return data[i]; } /** * Returns a reference to the first element. Buffer must not * be empty. */ #ifdef NDEBUG constexpr #endif reference_type front() const { #ifndef NDEBUG assert(!IsEmpty()); #endif return data[0]; } /** * Returns a reference to the last element. Buffer must not * be empty. */ #ifdef NDEBUG constexpr #endif reference_type back() const { #ifndef NDEBUG assert(!IsEmpty()); #endif return data[size - 1]; } /** * Remove the first element (by moving the head pointer, does * not actually modify the buffer). Buffer must not be empty. */ void pop_front() { #ifndef NDEBUG assert(!IsEmpty()); #endif ++data; --size; } /** * Remove the last element (by moving the tail pointer, does * not actually modify the buffer). Buffer must not be empty. */ void pop_back() { #ifndef NDEBUG assert(!IsEmpty()); #endif --size; } /** * Remove the first element and return a reference to it. * Buffer must not be empty. */ reference_type shift() { reference_type result = front(); pop_front(); return result; } }; #endif <|endoftext|>
<commit_before>#include "parser.h" #include "platform.h" #include <assert.h> extern "C" void parse(const char* json, command* wifiRC_command); #ifndef DESKTOP #include "edison_platform.h" #else #include "desktop_platform.h" #endif #define RC_ADDRESS_BASE "http://192.168.1." #define RC_JSON_ADDRESS_SUFFIX ":8080/CommandServer/currentJsonCommand" static void getAddress(char* address_buffer, int size) { assert(size == 64); //Need to do something smarter here like search for servers on the local network char buffer[4]; memset(buffer, '\0', 4); memset(address_buffer, '\0', 64); strcat(address_buffer, RC_ADDRESS_BASE); sprintf(buffer, "%i", DEV); strcat(address_buffer, buffer); strcat(address_buffer, RC_JSON_ADDRESS_SUFFIX); } #ifndef DESKTOP void platform_setup() { pinMode(LIGHTS_ENABLE_PIN, OUTPUT); pinMode(DRIVE_MOTOR_PIN, OUTPUT); pinMode(REVERSE_ENGAGE_PIN, OUTPUT); pinMode(RIGHT_ENGAGE_PIN, OUTPUT); Serial.begin(9600); while(status != WL_CONNECTED) { status = WiFi.begin("", ""); delay(200); } } const char* platform_getName() { return "Intel Edison"; } void platform_send(void* params) { http_request("POST /CommandServer/currentJsonCommand HTTP/1.1\nHost: 192.168.1.6:8080\nAccept: */*\nContent-Length: 15\nContent-Type: application/x-www-form-urlencoded\nConnection: close\n\nPLATFORM:EDISON\n"); } int platform_getCommand() { // http_request("GET /CommandServer/currentJsonCommand HTTP/1.1\nHost: 192.168.1.6:8080\nAccept: */*\n"); return IDLE; } void platform_cleanup() { } #else void platform_setup() { curl_global_init(CURL_GLOBAL_DEFAULT); } const char* platform_getName() { return "Desktop"; } void platform_send(void* params) { CURL* pCURL = curl_easy_init(); if(pCURL) { char address_buffer[64]; getAddress(address_buffer, 64); curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer); curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, params); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { } curl_easy_cleanup(pCURL); } } int platform_getCommand() { int command = IDLE; CURL* pCURL = curl_easy_init(); if(pCURL) { int temp; char address_buffer[64]; getAddress(address_buffer, 64); curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer); curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_json_function); curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { command = temp; } curl_easy_cleanup(pCURL); } return command; } void platform_cleanup() { curl_global_cleanup(); } #endif <commit_msg>Add GET to Arduino<commit_after>#include "parser.h" #include "platform.h" #include <assert.h> extern "C" void parse(const char* json, command* wifiRC_command); #ifndef DESKTOP #include "edison_platform.h" #else #include "desktop_platform.h" #endif #define RC_ADDRESS_BASE "http://192.168.1." #define RC_JSON_ADDRESS_SUFFIX ":8080/CommandServer/currentJsonCommand" static void getAddress(char* address_buffer, int size) { assert(size == 64); //Need to do something smarter here like search for servers on the local network char buffer[4]; memset(buffer, '\0', 4); memset(address_buffer, '\0', 64); strcat(address_buffer, RC_ADDRESS_BASE); sprintf(buffer, "%i", DEV); strcat(address_buffer, buffer); strcat(address_buffer, RC_JSON_ADDRESS_SUFFIX); } #ifndef DESKTOP void platform_setup() { pinMode(LIGHTS_ENABLE_PIN, OUTPUT); pinMode(DRIVE_MOTOR_PIN, OUTPUT); pinMode(REVERSE_ENGAGE_PIN, OUTPUT); pinMode(RIGHT_ENGAGE_PIN, OUTPUT); Serial.begin(9600); while(status != WL_CONNECTED) { status = WiFi.begin("", ""); delay(200); } } const char* platform_getName() { return "Intel Edison"; } void platform_send(void* params) { http_request("POST /CommandServer/currentJsonCommand HTTP/1.1\nHost: 192.168.1.6:8080\nAccept: */*\nContent-Length: 15\nContent-Type: application/x-www-form-urlencoded\nConnection: close\n\nPLATFORM:EDISON\n"); } int platform_getCommand() { http_request("GET /CommandServer/currentJsonCommand HTTP/1.1\nHost: 192.168.1.6:8080\nAccept: */*\n"); return IDLE; } void platform_cleanup() { } #else void platform_setup() { curl_global_init(CURL_GLOBAL_DEFAULT); } const char* platform_getName() { return "Desktop"; } void platform_send(void* params) { CURL* pCURL = curl_easy_init(); if(pCURL) { char address_buffer[64]; getAddress(address_buffer, 64); curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer); curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, params); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { } curl_easy_cleanup(pCURL); } } int platform_getCommand() { int command = IDLE; CURL* pCURL = curl_easy_init(); if(pCURL) { int temp; char address_buffer[64]; getAddress(address_buffer, 64); curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer); curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_json_function); curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp); CURLcode result = curl_easy_perform(pCURL); if(result == CURLE_OK) { command = temp; } curl_easy_cleanup(pCURL); } return command; } void platform_cleanup() { curl_global_cleanup(); } #endif <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/effects/GrBlendFragmentProcessor.h" #include "src/gpu/GrFragmentProcessor.h" #include "src/gpu/KeyBuilder.h" #include "src/gpu/SkGr.h" #include "src/gpu/glsl/GrGLSLBlend.h" #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h" // Some of the CPU implementations of blend modes differ from the GPU enough that // we can't use the CPU implementation to implement constantOutputForConstantInput. static inline bool does_cpu_blend_impl_match_gpu(SkBlendMode mode) { // The non-separable modes differ too much. So does SoftLight. ColorBurn differs too much on our // test iOS device, but we just disable it across the board since it might differ on untested // GPUs. return mode <= SkBlendMode::kLastSeparableMode && mode != SkBlendMode::kSoftLight && mode != SkBlendMode::kColorBurn; } static bool supports_shared_blend_logic(SkBlendMode mode) { switch (mode) { case SkBlendMode::kSrcOver: case SkBlendMode::kDstOver: case SkBlendMode::kSrcIn: case SkBlendMode::kDstIn: case SkBlendMode::kSrcOut: case SkBlendMode::kDstOut: case SkBlendMode::kSrcATop: case SkBlendMode::kDstATop: case SkBlendMode::kXor: case SkBlendMode::kPlus: return true; default: return false; } } ////////////////////////////////////////////////////////////////////////////// class BlendFragmentProcessor : public GrFragmentProcessor { public: static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) { return std::unique_ptr<GrFragmentProcessor>( new BlendFragmentProcessor(std::move(src), std::move(dst), mode, shareBlendLogic)); } const char* name() const override { return "Blend"; } std::unique_ptr<GrFragmentProcessor> clone() const override; private: BlendFragmentProcessor(std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) : INHERITED(kBlendFragmentProcessor_ClassID, OptFlags(src.get(), dst.get(), mode)) , fMode(mode) , fShareBlendLogic(shareBlendLogic && supports_shared_blend_logic(mode)) { this->setIsBlendFunction(); this->registerChild(std::move(src)); this->registerChild(std::move(dst)); } BlendFragmentProcessor(const BlendFragmentProcessor& that) : INHERITED(that) , fMode(that.fMode) , fShareBlendLogic(that.fShareBlendLogic) {} #if GR_TEST_UTILS SkString onDumpInfo() const override { return SkStringPrintf("(fMode=%s)", SkBlendMode_Name(fMode)); } #endif static OptimizationFlags OptFlags(const GrFragmentProcessor* src, const GrFragmentProcessor* dst, SkBlendMode mode) { OptimizationFlags flags; switch (mode) { case SkBlendMode::kClear: case SkBlendMode::kSrc: case SkBlendMode::kDst: SkDEBUGFAIL("Shouldn't have created a Blend FP as 'clear', 'src', or 'dst'."); flags = kNone_OptimizationFlags; break; // Produces opaque if both src and dst are opaque. These also will modulate the child's // output by either the input color or alpha. However, if the child is not compatible // with the coverage as alpha then it may produce a color that is not valid premul. case SkBlendMode::kSrcIn: case SkBlendMode::kDstIn: case SkBlendMode::kModulate: if (src && dst) { flags = ProcessorOptimizationFlags(src) & ProcessorOptimizationFlags(dst) & kPreservesOpaqueInput_OptimizationFlag; } else if (src) { flags = ProcessorOptimizationFlags(src) & ~kConstantOutputForConstantInput_OptimizationFlag; } else if (dst) { flags = ProcessorOptimizationFlags(dst) & ~kConstantOutputForConstantInput_OptimizationFlag; } else { flags = kNone_OptimizationFlags; } break; // Produces zero when both are opaque, indeterminate if one is opaque. case SkBlendMode::kSrcOut: case SkBlendMode::kDstOut: case SkBlendMode::kXor: flags = kNone_OptimizationFlags; break; // Is opaque if the dst is opaque. case SkBlendMode::kSrcATop: flags = ProcessorOptimizationFlags(dst) & kPreservesOpaqueInput_OptimizationFlag; break; // DstATop is the converse of kSrcATop. Screen is also opaque if the src is a opaque. case SkBlendMode::kDstATop: case SkBlendMode::kScreen: flags = ProcessorOptimizationFlags(src) & kPreservesOpaqueInput_OptimizationFlag; break; // These modes are all opaque if either src or dst is opaque. All the advanced modes // compute alpha as src-over. case SkBlendMode::kSrcOver: case SkBlendMode::kDstOver: case SkBlendMode::kPlus: case SkBlendMode::kOverlay: case SkBlendMode::kDarken: case SkBlendMode::kLighten: case SkBlendMode::kColorDodge: case SkBlendMode::kColorBurn: case SkBlendMode::kHardLight: case SkBlendMode::kSoftLight: case SkBlendMode::kDifference: case SkBlendMode::kExclusion: case SkBlendMode::kMultiply: case SkBlendMode::kHue: case SkBlendMode::kSaturation: case SkBlendMode::kColor: case SkBlendMode::kLuminosity: flags = (ProcessorOptimizationFlags(src) | ProcessorOptimizationFlags(dst)) & kPreservesOpaqueInput_OptimizationFlag; break; } if (does_cpu_blend_impl_match_gpu(mode) && (!src || src->hasConstantOutputForConstantInput()) && (!dst || dst->hasConstantOutputForConstantInput())) { flags |= kConstantOutputForConstantInput_OptimizationFlag; } return flags; } void onAddToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override { if (fShareBlendLogic) { b->add32(-1); } else { b->add32((int)fMode); } } bool onIsEqual(const GrFragmentProcessor& other) const override { const BlendFragmentProcessor& cs = other.cast<BlendFragmentProcessor>(); return fMode == cs.fMode; } SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override { const auto* src = this->childProcessor(0); const auto* dst = this->childProcessor(1); SkPMColor4f srcColor = ConstantOutputForConstantInput(src, input); SkPMColor4f dstColor = ConstantOutputForConstantInput(dst, input); return SkBlendMode_Apply(fMode, srcColor, dstColor); } std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override; SkBlendMode fMode; bool fShareBlendLogic; GR_DECLARE_FRAGMENT_PROCESSOR_TEST using INHERITED = GrFragmentProcessor; }; ///////////////////////////////////////////////////////////////////// GR_DEFINE_FRAGMENT_PROCESSOR_TEST(BlendFragmentProcessor); #if GR_TEST_UTILS std::unique_ptr<GrFragmentProcessor> BlendFragmentProcessor::TestCreate(GrProcessorTestData* d) { // Create one or two random fragment processors. std::unique_ptr<GrFragmentProcessor> src(GrProcessorUnitTest::MakeOptionalChildFP(d)); std::unique_ptr<GrFragmentProcessor> dst(GrProcessorUnitTest::MakeChildFP(d)); if (d->fRandom->nextBool()) { std::swap(src, dst); } bool shareLogic = d->fRandom->nextBool(); SkBlendMode mode; do { mode = static_cast<SkBlendMode>(d->fRandom->nextRangeU(0, (int)SkBlendMode::kLastMode)); } while (SkBlendMode::kClear == mode || SkBlendMode::kSrc == mode || SkBlendMode::kDst == mode); return std::unique_ptr<GrFragmentProcessor>( new BlendFragmentProcessor(std::move(src), std::move(dst), mode, shareLogic)); } #endif std::unique_ptr<GrFragmentProcessor> BlendFragmentProcessor::clone() const { return std::unique_ptr<GrFragmentProcessor>(new BlendFragmentProcessor(*this)); } std::unique_ptr<GrFragmentProcessor::ProgramImpl> BlendFragmentProcessor::onMakeProgramImpl() const { class Impl : public ProgramImpl { public: void emitCode(EmitArgs& args) override { GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; const BlendFragmentProcessor& bfp = args.fFp.cast<BlendFragmentProcessor>(); const SkBlendMode mode = bfp.fMode; // Invoke src/dst with our input color (or substitute input color if no child FP) SkString srcColor = this->invokeChild(0, args); SkString dstColor = this->invokeChild(1, args); if (bfp.fShareBlendLogic) { // Handle basic Porter-Duff blend ops by multiplying with uniforms. const char* blendOp; fBlendOpUniform = args.fUniformHandler->addUniform(&args.fFp, kFragment_GrShaderFlag, SkSLType::kHalf4, "blendOp", &blendOp); fragBuilder->codeAppendf( "half4 src = %s, dst = %s;" "return min(half4(1), " "src * (%s.x + (%s.z * (dst.a + min(%s.z, 0)))) + " "dst * (%s.y + (%s.w * (src.a + min(%s.w, 0)))));", srcColor.c_str(), dstColor.c_str(), blendOp, blendOp, blendOp, blendOp, blendOp, blendOp); } else { // Blend src and dst colors together using a built-in blend function. fragBuilder->codeAppendf("return %s(%s, %s);", GrGLSLBlend::BlendFuncName(mode), srcColor.c_str(), dstColor.c_str()); } } void onSetData(const GrGLSLProgramDataManager& pdman, const GrFragmentProcessor& fp) override { const BlendFragmentProcessor& bfp = fp.cast<BlendFragmentProcessor>(); const SkBlendMode mode = bfp.fMode; if (bfp.fShareBlendLogic) { switch (mode) { case SkBlendMode::kSrcOver: pdman.set4f(fBlendOpUniform, 1, 0, 0, -1); break; case SkBlendMode::kDstOver: pdman.set4f(fBlendOpUniform, 0, 1, -1, 0); break; case SkBlendMode::kSrcIn: pdman.set4f(fBlendOpUniform, 0, 0, 1, 0); break; case SkBlendMode::kDstIn: pdman.set4f(fBlendOpUniform, 0, 0, 0, 1); break; case SkBlendMode::kSrcOut: pdman.set4f(fBlendOpUniform, 0, 0, -1, 0); break; case SkBlendMode::kDstOut: pdman.set4f(fBlendOpUniform, 0, 0, 0, -1); break; case SkBlendMode::kSrcATop: pdman.set4f(fBlendOpUniform, 0, 0, 1, -1); break; case SkBlendMode::kDstATop: pdman.set4f(fBlendOpUniform, 0, 0, -1, 1); break; case SkBlendMode::kXor: pdman.set4f(fBlendOpUniform, 0, 0, -1, -1); break; case SkBlendMode::kPlus: pdman.set4f(fBlendOpUniform, 1, 1, 0, 0); break; default: SkDEBUGFAIL("unexpected blend mode"); break; } } } UniformHandle fBlendOpUniform; }; return std::make_unique<Impl>(); } ////////////////////////////////////////////////////////////////////////////// std::unique_ptr<GrFragmentProcessor> GrBlendFragmentProcessor::Make( std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) { switch (mode) { case SkBlendMode::kClear: return GrFragmentProcessor::MakeColor(SK_PMColor4fTRANSPARENT); case SkBlendMode::kSrc: return src; case SkBlendMode::kDst: return dst; default: return BlendFragmentProcessor::Make( std::move(src), std::move(dst), mode, shareBlendLogic); } } <commit_msg>Simplify Porter-Duff coefficient blending expression.<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/effects/GrBlendFragmentProcessor.h" #include "src/gpu/GrFragmentProcessor.h" #include "src/gpu/KeyBuilder.h" #include "src/gpu/SkGr.h" #include "src/gpu/glsl/GrGLSLBlend.h" #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h" // Some of the CPU implementations of blend modes differ from the GPU enough that // we can't use the CPU implementation to implement constantOutputForConstantInput. static inline bool does_cpu_blend_impl_match_gpu(SkBlendMode mode) { // The non-separable modes differ too much. So does SoftLight. ColorBurn differs too much on our // test iOS device, but we just disable it across the board since it might differ on untested // GPUs. return mode <= SkBlendMode::kLastSeparableMode && mode != SkBlendMode::kSoftLight && mode != SkBlendMode::kColorBurn; } static bool supports_shared_blend_logic(SkBlendMode mode) { switch (mode) { case SkBlendMode::kSrcOver: case SkBlendMode::kDstOver: case SkBlendMode::kSrcIn: case SkBlendMode::kDstIn: case SkBlendMode::kSrcOut: case SkBlendMode::kDstOut: case SkBlendMode::kSrcATop: case SkBlendMode::kDstATop: case SkBlendMode::kXor: case SkBlendMode::kPlus: return true; default: return false; } } ////////////////////////////////////////////////////////////////////////////// class BlendFragmentProcessor : public GrFragmentProcessor { public: static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) { return std::unique_ptr<GrFragmentProcessor>( new BlendFragmentProcessor(std::move(src), std::move(dst), mode, shareBlendLogic)); } const char* name() const override { return "Blend"; } std::unique_ptr<GrFragmentProcessor> clone() const override; private: BlendFragmentProcessor(std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) : INHERITED(kBlendFragmentProcessor_ClassID, OptFlags(src.get(), dst.get(), mode)) , fMode(mode) , fShareBlendLogic(shareBlendLogic && supports_shared_blend_logic(mode)) { this->setIsBlendFunction(); this->registerChild(std::move(src)); this->registerChild(std::move(dst)); } BlendFragmentProcessor(const BlendFragmentProcessor& that) : INHERITED(that) , fMode(that.fMode) , fShareBlendLogic(that.fShareBlendLogic) {} #if GR_TEST_UTILS SkString onDumpInfo() const override { return SkStringPrintf("(fMode=%s)", SkBlendMode_Name(fMode)); } #endif static OptimizationFlags OptFlags(const GrFragmentProcessor* src, const GrFragmentProcessor* dst, SkBlendMode mode) { OptimizationFlags flags; switch (mode) { case SkBlendMode::kClear: case SkBlendMode::kSrc: case SkBlendMode::kDst: SkDEBUGFAIL("Shouldn't have created a Blend FP as 'clear', 'src', or 'dst'."); flags = kNone_OptimizationFlags; break; // Produces opaque if both src and dst are opaque. These also will modulate the child's // output by either the input color or alpha. However, if the child is not compatible // with the coverage as alpha then it may produce a color that is not valid premul. case SkBlendMode::kSrcIn: case SkBlendMode::kDstIn: case SkBlendMode::kModulate: if (src && dst) { flags = ProcessorOptimizationFlags(src) & ProcessorOptimizationFlags(dst) & kPreservesOpaqueInput_OptimizationFlag; } else if (src) { flags = ProcessorOptimizationFlags(src) & ~kConstantOutputForConstantInput_OptimizationFlag; } else if (dst) { flags = ProcessorOptimizationFlags(dst) & ~kConstantOutputForConstantInput_OptimizationFlag; } else { flags = kNone_OptimizationFlags; } break; // Produces zero when both are opaque, indeterminate if one is opaque. case SkBlendMode::kSrcOut: case SkBlendMode::kDstOut: case SkBlendMode::kXor: flags = kNone_OptimizationFlags; break; // Is opaque if the dst is opaque. case SkBlendMode::kSrcATop: flags = ProcessorOptimizationFlags(dst) & kPreservesOpaqueInput_OptimizationFlag; break; // DstATop is the converse of kSrcATop. Screen is also opaque if the src is a opaque. case SkBlendMode::kDstATop: case SkBlendMode::kScreen: flags = ProcessorOptimizationFlags(src) & kPreservesOpaqueInput_OptimizationFlag; break; // These modes are all opaque if either src or dst is opaque. All the advanced modes // compute alpha as src-over. case SkBlendMode::kSrcOver: case SkBlendMode::kDstOver: case SkBlendMode::kPlus: case SkBlendMode::kOverlay: case SkBlendMode::kDarken: case SkBlendMode::kLighten: case SkBlendMode::kColorDodge: case SkBlendMode::kColorBurn: case SkBlendMode::kHardLight: case SkBlendMode::kSoftLight: case SkBlendMode::kDifference: case SkBlendMode::kExclusion: case SkBlendMode::kMultiply: case SkBlendMode::kHue: case SkBlendMode::kSaturation: case SkBlendMode::kColor: case SkBlendMode::kLuminosity: flags = (ProcessorOptimizationFlags(src) | ProcessorOptimizationFlags(dst)) & kPreservesOpaqueInput_OptimizationFlag; break; } if (does_cpu_blend_impl_match_gpu(mode) && (!src || src->hasConstantOutputForConstantInput()) && (!dst || dst->hasConstantOutputForConstantInput())) { flags |= kConstantOutputForConstantInput_OptimizationFlag; } return flags; } void onAddToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override { if (fShareBlendLogic) { b->add32(-1); } else { b->add32((int)fMode); } } bool onIsEqual(const GrFragmentProcessor& other) const override { const BlendFragmentProcessor& cs = other.cast<BlendFragmentProcessor>(); return fMode == cs.fMode; } SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override { const auto* src = this->childProcessor(0); const auto* dst = this->childProcessor(1); SkPMColor4f srcColor = ConstantOutputForConstantInput(src, input); SkPMColor4f dstColor = ConstantOutputForConstantInput(dst, input); return SkBlendMode_Apply(fMode, srcColor, dstColor); } std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override; SkBlendMode fMode; bool fShareBlendLogic; GR_DECLARE_FRAGMENT_PROCESSOR_TEST using INHERITED = GrFragmentProcessor; }; ///////////////////////////////////////////////////////////////////// GR_DEFINE_FRAGMENT_PROCESSOR_TEST(BlendFragmentProcessor); #if GR_TEST_UTILS std::unique_ptr<GrFragmentProcessor> BlendFragmentProcessor::TestCreate(GrProcessorTestData* d) { // Create one or two random fragment processors. std::unique_ptr<GrFragmentProcessor> src(GrProcessorUnitTest::MakeOptionalChildFP(d)); std::unique_ptr<GrFragmentProcessor> dst(GrProcessorUnitTest::MakeChildFP(d)); if (d->fRandom->nextBool()) { std::swap(src, dst); } bool shareLogic = d->fRandom->nextBool(); SkBlendMode mode; do { mode = static_cast<SkBlendMode>(d->fRandom->nextRangeU(0, (int)SkBlendMode::kLastMode)); } while (SkBlendMode::kClear == mode || SkBlendMode::kSrc == mode || SkBlendMode::kDst == mode); return std::unique_ptr<GrFragmentProcessor>( new BlendFragmentProcessor(std::move(src), std::move(dst), mode, shareLogic)); } #endif std::unique_ptr<GrFragmentProcessor> BlendFragmentProcessor::clone() const { return std::unique_ptr<GrFragmentProcessor>(new BlendFragmentProcessor(*this)); } std::unique_ptr<GrFragmentProcessor::ProgramImpl> BlendFragmentProcessor::onMakeProgramImpl() const { class Impl : public ProgramImpl { public: void emitCode(EmitArgs& args) override { GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; const BlendFragmentProcessor& bfp = args.fFp.cast<BlendFragmentProcessor>(); const SkBlendMode mode = bfp.fMode; // Invoke src/dst with our input color (or substitute input color if no child FP) SkString srcColor = this->invokeChild(0, args); SkString dstColor = this->invokeChild(1, args); if (bfp.fShareBlendLogic) { // Handle basic Porter-Duff blend ops by multiplying with uniforms. const char* blendOp; fBlendOpUniform = args.fUniformHandler->addUniform(&args.fFp, kFragment_GrShaderFlag, SkSLType::kHalf4, "blendOp", &blendOp); fragBuilder->codeAppendf( "half4 src = %s;" "half4 dst = %s;" "half2 coeff = %s.xy + (%s.zw * (half2(dst.a, src.a) + min(%s.zw, 0)));" "return min(half4(1), src * coeff.x + dst * coeff.y);", srcColor.c_str(), dstColor.c_str(), blendOp, blendOp, blendOp); } else { // Blend src and dst colors together using a built-in blend function. fragBuilder->codeAppendf("return %s(%s, %s);", GrGLSLBlend::BlendFuncName(mode), srcColor.c_str(), dstColor.c_str()); } } void onSetData(const GrGLSLProgramDataManager& pdman, const GrFragmentProcessor& fp) override { const BlendFragmentProcessor& bfp = fp.cast<BlendFragmentProcessor>(); const SkBlendMode mode = bfp.fMode; if (bfp.fShareBlendLogic) { switch (mode) { case SkBlendMode::kSrcOver: pdman.set4f(fBlendOpUniform, 1, 0, 0, -1); break; case SkBlendMode::kDstOver: pdman.set4f(fBlendOpUniform, 0, 1, -1, 0); break; case SkBlendMode::kSrcIn: pdman.set4f(fBlendOpUniform, 0, 0, 1, 0); break; case SkBlendMode::kDstIn: pdman.set4f(fBlendOpUniform, 0, 0, 0, 1); break; case SkBlendMode::kSrcOut: pdman.set4f(fBlendOpUniform, 0, 0, -1, 0); break; case SkBlendMode::kDstOut: pdman.set4f(fBlendOpUniform, 0, 0, 0, -1); break; case SkBlendMode::kSrcATop: pdman.set4f(fBlendOpUniform, 0, 0, 1, -1); break; case SkBlendMode::kDstATop: pdman.set4f(fBlendOpUniform, 0, 0, -1, 1); break; case SkBlendMode::kXor: pdman.set4f(fBlendOpUniform, 0, 0, -1, -1); break; case SkBlendMode::kPlus: pdman.set4f(fBlendOpUniform, 1, 1, 0, 0); break; default: SkDEBUGFAIL("unexpected blend mode"); break; } } } UniformHandle fBlendOpUniform; }; return std::make_unique<Impl>(); } ////////////////////////////////////////////////////////////////////////////// std::unique_ptr<GrFragmentProcessor> GrBlendFragmentProcessor::Make( std::unique_ptr<GrFragmentProcessor> src, std::unique_ptr<GrFragmentProcessor> dst, SkBlendMode mode, bool shareBlendLogic) { switch (mode) { case SkBlendMode::kClear: return GrFragmentProcessor::MakeColor(SK_PMColor4fTRANSPARENT); case SkBlendMode::kSrc: return src; case SkBlendMode::kDst: return dst; default: return BlendFragmentProcessor::Make( std::move(src), std::move(dst), mode, shareBlendLogic); } } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/log/log.h> LOG_SETUP("configmanager"); #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/noncopyable.hpp> #include <vespa/config/common/configmanager.h> #include <vespa/config/common/exceptions.h> #include <vespa/config/subscription/sourcespec.h> #include <vespa/config/raw/rawsource.h> #include "config-my.h" using namespace config; namespace { ConfigValue createValue(const std::string & myField, const std::string & md5) { std::vector< vespalib::string > lines; lines.push_back("myField \"" + myField + "\""); return ConfigValue(lines, md5); } struct TestContext { int numGetConfig; int numUpdate; int numClose; int64_t generation; bool respond; TestContext() : numGetConfig(0), numUpdate(0), numClose(0), generation(-1), respond(true) { } }; class MySource : public Source { public: MySource(TestContext * data, const IConfigHolder::SP & holder) : _holder(holder), _data(data) { } void getConfig() { _data->numGetConfig++; if (_data->respond) { LOG(info, "put into holder"); _holder->handle(ConfigUpdate::UP(new ConfigUpdate(ConfigValue(), true, _data->generation))); } } void reload(int64_t generation) { _data->numUpdate++; _data->generation = generation; } void close() { _data->numClose++; } IConfigHolder::SP _holder; TestContext * _data; }; class MySourceFactory : public SourceFactory { public: MySourceFactory(TestContext * d) : data(d) { } Source::UP createSource(const IConfigHolder::SP & holder, const ConfigKey & key) const { (void) key; return Source::UP(new MySource(data, holder)); } TestContext * data; }; class MySpec : public SourceSpec { public: MySpec(TestContext * data) : _key("foo"), _data(data) { } SourceSpecKey createKey() const { return SourceSpecKey(_key); } SourceFactory::UP createSourceFactory(const TimingValues & timingValues) const { (void) timingValues; return SourceFactory::UP(new MySourceFactory(_data)); } SourceSpec * clone() const { return new MySpec(*this); } private: const std::string _key; TestContext * _data; }; static TimingValues testTimingValues( 2000, // successTimeout 500, // errorTimeout 500, // initialTimeout 4000, // unsubscribeTimeout 0, // fixedDelay 250, // successDelay 250, // unconfiguredDelay 500, // configuredErrorDelay 5, 1000, 2000); // maxDelayMultiplier class ManagerTester { public: ConfigKey key; ConfigManager _mgr; ConfigSubscription::SP sub; ManagerTester(const ConfigKey & k, const MySpec & s) : key(k), _mgr(s.createSourceFactory(testTimingValues), 1) { } void subscribe() { sub = _mgr.subscribe(key, 5000); } }; } TEST("requireThatSubscriptionTimesout") { const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); { // No valid response TestContext data; data.respond = false; ManagerTester tester(ConfigKey::create<MyConfig>("myid"), MySpec(&data)); bool thrown = false; try { tester.subscribe(); } catch (const ConfigRuntimeException & e) { thrown = true; } ASSERT_TRUE(thrown); ASSERT_EQUAL(1, data.numGetConfig); } } TEST("requireThatSourceIsAskedForRequest") { TestContext data; const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); try { ManagerTester tester(key, MySpec(&data)); tester.subscribe(); ASSERT_EQUAL(1, data.numGetConfig); } catch (ConfigRuntimeException & e) { ASSERT_TRUE(false); } ASSERT_EQUAL(1, data.numClose); } TEST("require that new sources are given the correct generation") { TestContext data; const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); try { ManagerTester tester(key, MySpec(&data)); tester._mgr.reload(30); tester.subscribe(); ASSERT_EQUAL(30, data.generation); } catch (ConfigRuntimeException & e) { ASSERT_TRUE(false); } } void waitForGet(TestContext & data, int preferred, double timeout) { FastOS_Time timer; timer.SetNow(); int numGet = -1; while (timer.MilliSecsToNow() < timeout) { numGet = data.numGetConfig; if (numGet == preferred) break; FastOS_Thread::Sleep(50); } ASSERT_EQUAL(preferred, numGet); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>GC unused code<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/log/log.h> LOG_SETUP("configmanager"); #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/vespalib/util/noncopyable.hpp> #include <vespa/config/common/configmanager.h> #include <vespa/config/common/exceptions.h> #include <vespa/config/subscription/sourcespec.h> #include <vespa/config/raw/rawsource.h> #include "config-my.h" using namespace config; namespace { ConfigValue createValue(const std::string & myField, const std::string & md5) { std::vector< vespalib::string > lines; lines.push_back("myField \"" + myField + "\""); return ConfigValue(lines, md5); } struct TestContext { int numGetConfig; int numUpdate; int numClose; int64_t generation; bool respond; TestContext() : numGetConfig(0), numUpdate(0), numClose(0), generation(-1), respond(true) { } }; class MySource : public Source { public: MySource(TestContext * data, const IConfigHolder::SP & holder) : _holder(holder), _data(data) { } void getConfig() { _data->numGetConfig++; if (_data->respond) { LOG(info, "put into holder"); _holder->handle(ConfigUpdate::UP(new ConfigUpdate(ConfigValue(), true, _data->generation))); } } void reload(int64_t generation) { _data->numUpdate++; _data->generation = generation; } void close() { _data->numClose++; } IConfigHolder::SP _holder; TestContext * _data; }; class MySourceFactory : public SourceFactory { public: MySourceFactory(TestContext * d) : data(d) { } Source::UP createSource(const IConfigHolder::SP & holder, const ConfigKey & key) const { (void) key; return Source::UP(new MySource(data, holder)); } TestContext * data; }; class MySpec : public SourceSpec { public: MySpec(TestContext * data) : _key("foo"), _data(data) { } SourceSpecKey createKey() const { return SourceSpecKey(_key); } SourceFactory::UP createSourceFactory(const TimingValues & timingValues) const { (void) timingValues; return SourceFactory::UP(new MySourceFactory(_data)); } SourceSpec * clone() const { return new MySpec(*this); } private: const std::string _key; TestContext * _data; }; static TimingValues testTimingValues( 2000, // successTimeout 500, // errorTimeout 500, // initialTimeout 4000, // unsubscribeTimeout 0, // fixedDelay 250, // successDelay 250, // unconfiguredDelay 500, // configuredErrorDelay 5, 1000, 2000); // maxDelayMultiplier class ManagerTester { public: ConfigKey key; ConfigManager _mgr; ConfigSubscription::SP sub; ManagerTester(const ConfigKey & k, const MySpec & s) : key(k), _mgr(s.createSourceFactory(testTimingValues), 1) { } void subscribe() { sub = _mgr.subscribe(key, 5000); } }; } TEST("requireThatSubscriptionTimesout") { const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); { // No valid response TestContext data; data.respond = false; ManagerTester tester(ConfigKey::create<MyConfig>("myid"), MySpec(&data)); bool thrown = false; try { tester.subscribe(); } catch (const ConfigRuntimeException & e) { thrown = true; } ASSERT_TRUE(thrown); ASSERT_EQUAL(1, data.numGetConfig); } } TEST("requireThatSourceIsAskedForRequest") { TestContext data; const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); try { ManagerTester tester(key, MySpec(&data)); tester.subscribe(); ASSERT_EQUAL(1, data.numGetConfig); } catch (ConfigRuntimeException & e) { ASSERT_TRUE(false); } ASSERT_EQUAL(1, data.numClose); } TEST("require that new sources are given the correct generation") { TestContext data; const ConfigKey key(ConfigKey::create<MyConfig>("myid")); const ConfigValue testValue(createValue("l33t", "a")); try { ManagerTester tester(key, MySpec(&data)); tester._mgr.reload(30); tester.subscribe(); ASSERT_EQUAL(30, data.generation); } catch (ConfigRuntimeException & e) { ASSERT_TRUE(false); } } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2013--2016 */ /* Simple rolling stats management. */ #include "OTV0P2BASE_Stats.h" #include "OTV0P2BASE_QuickPRNG.h" namespace OTV0P2BASE { // Helper functions namespace { // Check if we hare dealing with a special hour, and resolve it to the correct hour. // Note this does not deal with invalid values of hour/currentHour uint8_t getSpecialHour(uint8_t hour, uint8_t currentHour) { switch (hour) { case (NVByHourByteStatsBase::SPECIAL_HOUR_CURRENT_HOUR): { return currentHour; } case (NVByHourByteStatsBase::SPECIAL_HOUR_NEXT_HOUR): { // Taken from logic in OTV0P2BASE::getNextHourLT() return (currentHour >= 23) ? 0 : (currentHour + 1); } case (NVByHourByteStatsBase::SPECIAL_HOUR_PREV_HOUR): { // Taken from logic in OTV0P2BASE::getPrevHourLT() return (0 == currentHour) ? 23 : (currentHour - 1); } } return (hour); } } // Get raw stats value for specified hour [0,23]/current/next from stats set N from non-volatile (EEPROM) store. // A value of STATS_UNSET_BYTE (0xff (255)) means unset (or out of range, or invalid); other values depend on which stats set is being used. // * hour hour of day to use, or ~0/0xff for current hour (default), 0xfe for next hour, or 0xfd for the previous hour. // If the hour is invalid, an UNSET_BYTE will be returned. // Note the three special values that implicitly make use of the RTC to select the hour to read. uint8_t NVByHourByteStatsBase::getByHourStatRTC(uint8_t statsSet, uint8_t hour) const { const uint8_t hh {getSpecialHour(hour, getHour())}; // The invalid cases for statsSet and hh are checked in getByHourStatSimple. return(getByHourStatSimple(statsSet, hh)); } // Compute new linearly-smoothed value given old smoothed value and new value. // Guaranteed not to produce a value higher than the max of the old smoothed value and the new value. // Uses stochastic rounding to nearest to allow nominally sub-lsb values to have an effect over time. uint8_t NVByHourByteStatsBase::smoothStatsValue(const uint8_t oldSmoothed, const uint8_t newValue) { // Optimisation: smoothed value is unchanged if new value is same as extant. if(oldSmoothed == newValue) { return(oldSmoothed); } // Compute and update with new stochastically-rounded exponentially-smoothed ("Brown's simple exponential smoothing") value. // Stochastic rounding allows sub-lsb values to have an effect over time. const uint8_t stocAdd = OTV0P2BASE::randRNG8() & ((1 << STATS_SMOOTH_SHIFT) - 1); // Do arithmetic in 16 bits to avoid over-/under- flows. return((uint8_t) (((((uint16_t) oldSmoothed) << STATS_SMOOTH_SHIFT) - ((uint16_t)oldSmoothed) + ((uint16_t)newValue) + stocAdd) >> STATS_SMOOTH_SHIFT)); } // Compute the number of stats samples in specified set less than the specified value; returns 0 for invalid stats set. // (With the UNSET value specified, count will be of all samples that have been set, ie are not unset.) uint8_t NVByHourByteStatsBase::countStatSamplesBelow(const uint8_t statsSet, const uint8_t value) const { if(0 == value) { return(0); } // Optimisation for common value. uint8_t result = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // Implicitly, since UNSET_BYTE is max uint8_t value, no unset values get counted. if(v < value) { ++result; } } return(result); } // Get minimum sample from given stats set ignoring all unset samples; STATS_UNSET_BYTE if all samples are unset. uint8_t NVByHourByteStatsBase::getMinByHourStat(const uint8_t statsSet) const { uint8_t result = UNSET_BYTE; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // Optimisation/cheat: all valid samples are less than STATS_UNSET_BYTE. if(v < result) { result = v; } } return(result); } // Get maximum sample from given stats set ignoring all unset samples; STATS_UNSET_BYTE if all samples are unset. uint8_t NVByHourByteStatsBase::getMaxByHourStat(const uint8_t statsSet) const { uint8_t result = UNSET_BYTE; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); if((UNSET_BYTE != v) && ((UNSET_BYTE == result) || (v > result))) { result = v; } } return(result); } // Returns true iff there is a near-full set of stats (none unset) and 3/4s of the values are higher than the supplied sample. // Always returns false if all samples are the same or unset (or the stats set is invalid). // * sample to be tested for being in lower quartile; if UNSET_BYTE routine returns false bool NVByHourByteStatsBase::inBottomQuartile(const uint8_t statsSet, const uint8_t sample) const { // Optimisation for size: explicit test not needed // if(UNSET_BYTE == sample) { return(false); } uint8_t valuesHigher = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // const uint8_t v = eeprom_read_byte(sE); if(UNSET_BYTE == v) { return(false); } // Abort if not a full set of stats (eg at least one full day's worth). if(v > sample) { if(++valuesHigher >= 18) { return(true); } } // Stop as soon as known to be in lower quartile. } return(false); // Not in lower quartile. } // Returns true iff there is a near-full set of stats (none unset) and 3/4s of the values are lower than the supplied sample. // Always returns false if all samples are the same or unset (or the stats set is invalid). // * sample to be tested for being in lower quartile; if UNSET_BYTE routine returns false bool NVByHourByteStatsBase::inTopQuartile(const uint8_t statsSet, const uint8_t sample) const { if(UNSET_BYTE == sample) { return(false); } uint8_t valuesLower = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // const uint8_t v = eeprom_read_byte(sE); if(UNSET_BYTE == v) { return(false); } // Abort if not a full set of stats (eg at least one full day's worth). if(v < sample) { if(++valuesLower >= 18) { return(true); } } // Stop as soon as known to be in upper quartile. } return(false); // Not in upper quartile. } // Returns true if specified hour is (conservatively) in the specified outlier quartile for the specified stats set. // Returns false if a full set of stats not available, eg including the specified hour. // Always returns false if all samples are the same. // * inTop test for membership of the top quartile if true, bottom quartile if false // * statsSet stats set number to use. // * hour hour of day to use, or ~0 for current hour, or >23 for next hour. bool NVByHourByteStatsBase::inOutlierQuartile(const bool inTop, const uint8_t statsSet, const uint8_t hh) const { // Rely on getByHourStatXXX() to validate statsSet, // returning UNSET if invalid or if the sample is unset. const uint8_t sample = (hh > 23) ? getByHourStatRTC(statsSet, hh) : getByHourStatSimple(statsSet, hh); if(UNSET_BYTE == sample) { return(false); } // Abort if not a valid/set sample. if(inTop) { return(inTopQuartile(statsSet, sample)); } return(inBottomQuartile(statsSet, sample)); } // Stats-, EEPROM- (and Flash-) friendly single-byte unary incrementable encoding. // A single byte can be used to hold a single value [0,8] // such that increment requires only a write of one bit (no erase) // and in general increasing the value up to the maximum only requires a single write. // An erase is required only to decrease the value (eg back to zero). // An initial EEPROM (erased) value of 0xff is mapped to zero. // The two byte version can hold values in the range [0,16]. // Corruption can be detected if an unexpected bit pattern is encountered on decode. // For the single byte versions, encodings are: // 0 -> 0xff // 1 -> 0xfe // 2 -> 0xfc // 3 -> 0xf8 // 4 -> 0xf0 // 5 -> 0xe0 // 6 -> 0xc0 // 7 -> 0x80 // 8 -> 0x00 // // Decode routines return -1 in case of unexpected/invalid input patterns. // All other (valid non-negative) return values can be safely cast to unit8_t. int8_t eeprom_unary_1byte_decode(const uint8_t v) { switch(v) { case 0xff: return(0); case 0xfe: return(1); case 0xfc: return(2); case 0xf8: return(3); case 0xf0: return(4); case 0xe0: return(5); case 0xc0: return(6); case 0x80: return(7); case 0x00: return(8); default: return(-1); // ERROR } } // Decode routines return -1 in case of unexpected/invalid input patterns. int8_t eeprom_unary_2byte_decode(const uint8_t vm, const uint8_t vl) { if(0xff == vm) { return(eeprom_unary_1byte_decode(vl)); } else if(0 == vl) { return(eeprom_unary_1byte_decode(vm) + 8); } return(-1); } //int8_t eeprom_unary_2byte_decode(uint16_t v) // { // switch(v) // { // case 0xffff: return(0); // case 0xfffe: return(1); // case 0xfffc: return(2); // case 0xfff8: return(3); // case 0xfff0: return(4); // case 0xffe0: return(5); // case 0xffc0: return(6); // case 0xff80: return(7); // case 0xff00: return(8); // case 0xfe00: return(9); // case 0xfc00: return(10); // case 0xf800: return(11); // case 0xf000: return(12); // case 0xe000: return(13); // case 0xc000: return(14); // case 0x8000: return(15); // case 0x0000: return(16); // default: return(-1); // ERROR // } // } // Range-compress an signed int 16ths-Celsius temperature to a unsigned single-byte value < 0xff. // This preserves at least the first bit after the binary point for all values, // and three bits after binary point for values in the most interesting mid range around normal room temperatures, // with transitions at whole degrees Celsius. // Input values below 0C are treated as 0C, and above 100C as 100C, thus allowing air and DHW temperature values. uint8_t compressTempC16(const int16_t tempC16) { if(tempC16 <= 0) { return(0); } // Clamp negative values to zero. if(tempC16 < COMPRESSION_C16_LOW_THRESHOLD) { return(uint8_t(tempC16 >> 3)); } // Preserve 1 bit after the binary point (0.5C precision). if(tempC16 < COMPRESSION_C16_HIGH_THRESHOLD) { return(uint8_t(((tempC16 - COMPRESSION_C16_LOW_THRESHOLD) >> 1) + COMPRESSION_C16_LOW_THR_AFTER)); } if(tempC16 < COMPRESSION_C16_CEIL_VAL) { return(uint8_t(((tempC16 - COMPRESSION_C16_HIGH_THRESHOLD) >> 3) + COMPRESSION_C16_HIGH_THR_AFTER)); } return(COMPRESSION_C16_CEIL_VAL_AFTER); } // Reverses range compression done by compressTempC16(); results in range [0,100], with varying precision based on original value. // 0xff (or other invalid) input results in STATS_UNSET_INT. int16_t expandTempC16(const uint8_t cTemp) { if(cTemp < COMPRESSION_C16_LOW_THR_AFTER) { return(int16_t(cTemp << 3)); } if(cTemp < COMPRESSION_C16_HIGH_THR_AFTER) { return(int16_t(((cTemp - COMPRESSION_C16_LOW_THR_AFTER) << 1) + COMPRESSION_C16_LOW_THRESHOLD)); } if(cTemp <= COMPRESSION_C16_CEIL_VAL_AFTER) { return(int16_t(((cTemp - COMPRESSION_C16_HIGH_THR_AFTER) << 3) + COMPRESSION_C16_HIGH_THRESHOLD)); } return(OTV0P2BASE::NVByHourByteStatsBase::UNSET_INT); // Invalid/unset input. } } <commit_msg>trying to fix travis<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2013--2016 */ /* Simple rolling stats management. */ #include "OTV0P2BASE_Stats.h" #include "OTV0P2BASE_QuickPRNG.h" namespace OTV0P2BASE { // Helper functions namespace { // Check if we hare dealing with a special hour, and resolve it to the correct hour. // Note this does not deal with invalid values of hour/currentHour uint8_t getSpecialHour(uint8_t hour, uint8_t currentHour) { switch (hour) { case (NVByHourByteStatsBase::SPECIAL_HOUR_CURRENT_HOUR): { return currentHour; } case (NVByHourByteStatsBase::SPECIAL_HOUR_NEXT_HOUR): { // Taken from logic in OTV0P2BASE::getNextHourLT() return (currentHour >= 23) ? 0 : (currentHour + 1); } case (NVByHourByteStatsBase::SPECIAL_HOUR_PREV_HOUR): { // Taken from logic in OTV0P2BASE::getPrevHourLT() return (0 == currentHour) ? 23 : (currentHour - 1); } default: break; } return (hour); } } // Get raw stats value for specified hour [0,23]/current/next from stats set N from non-volatile (EEPROM) store. // A value of STATS_UNSET_BYTE (0xff (255)) means unset (or out of range, or invalid); other values depend on which stats set is being used. // * hour hour of day to use, or ~0/0xff for current hour (default), 0xfe for next hour, or 0xfd for the previous hour. // If the hour is invalid, an UNSET_BYTE will be returned. // Note the three special values that implicitly make use of the RTC to select the hour to read. uint8_t NVByHourByteStatsBase::getByHourStatRTC(uint8_t statsSet, uint8_t hour) const { const uint8_t hh {getSpecialHour(hour, getHour())}; // The invalid cases for statsSet and hh are checked in getByHourStatSimple. return(getByHourStatSimple(statsSet, hh)); } // Compute new linearly-smoothed value given old smoothed value and new value. // Guaranteed not to produce a value higher than the max of the old smoothed value and the new value. // Uses stochastic rounding to nearest to allow nominally sub-lsb values to have an effect over time. uint8_t NVByHourByteStatsBase::smoothStatsValue(const uint8_t oldSmoothed, const uint8_t newValue) { // Optimisation: smoothed value is unchanged if new value is same as extant. if(oldSmoothed == newValue) { return(oldSmoothed); } // Compute and update with new stochastically-rounded exponentially-smoothed ("Brown's simple exponential smoothing") value. // Stochastic rounding allows sub-lsb values to have an effect over time. const uint8_t stocAdd = OTV0P2BASE::randRNG8() & ((1 << STATS_SMOOTH_SHIFT) - 1); // Do arithmetic in 16 bits to avoid over-/under- flows. return((uint8_t) (((((uint16_t) oldSmoothed) << STATS_SMOOTH_SHIFT) - ((uint16_t)oldSmoothed) + ((uint16_t)newValue) + stocAdd) >> STATS_SMOOTH_SHIFT)); } // Compute the number of stats samples in specified set less than the specified value; returns 0 for invalid stats set. // (With the UNSET value specified, count will be of all samples that have been set, ie are not unset.) uint8_t NVByHourByteStatsBase::countStatSamplesBelow(const uint8_t statsSet, const uint8_t value) const { if(0 == value) { return(0); } // Optimisation for common value. uint8_t result = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // Implicitly, since UNSET_BYTE is max uint8_t value, no unset values get counted. if(v < value) { ++result; } } return(result); } // Get minimum sample from given stats set ignoring all unset samples; STATS_UNSET_BYTE if all samples are unset. uint8_t NVByHourByteStatsBase::getMinByHourStat(const uint8_t statsSet) const { uint8_t result = UNSET_BYTE; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // Optimisation/cheat: all valid samples are less than STATS_UNSET_BYTE. if(v < result) { result = v; } } return(result); } // Get maximum sample from given stats set ignoring all unset samples; STATS_UNSET_BYTE if all samples are unset. uint8_t NVByHourByteStatsBase::getMaxByHourStat(const uint8_t statsSet) const { uint8_t result = UNSET_BYTE; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); if((UNSET_BYTE != v) && ((UNSET_BYTE == result) || (v > result))) { result = v; } } return(result); } // Returns true iff there is a near-full set of stats (none unset) and 3/4s of the values are higher than the supplied sample. // Always returns false if all samples are the same or unset (or the stats set is invalid). // * sample to be tested for being in lower quartile; if UNSET_BYTE routine returns false bool NVByHourByteStatsBase::inBottomQuartile(const uint8_t statsSet, const uint8_t sample) const { // Optimisation for size: explicit test not needed // if(UNSET_BYTE == sample) { return(false); } uint8_t valuesHigher = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // const uint8_t v = eeprom_read_byte(sE); if(UNSET_BYTE == v) { return(false); } // Abort if not a full set of stats (eg at least one full day's worth). if(v > sample) { if(++valuesHigher >= 18) { return(true); } } // Stop as soon as known to be in lower quartile. } return(false); // Not in lower quartile. } // Returns true iff there is a near-full set of stats (none unset) and 3/4s of the values are lower than the supplied sample. // Always returns false if all samples are the same or unset (or the stats set is invalid). // * sample to be tested for being in lower quartile; if UNSET_BYTE routine returns false bool NVByHourByteStatsBase::inTopQuartile(const uint8_t statsSet, const uint8_t sample) const { if(UNSET_BYTE == sample) { return(false); } uint8_t valuesLower = 0; for(int8_t hh = 24; --hh >= 0; ) { const uint8_t v = getByHourStatSimple(statsSet, hh); // const uint8_t v = eeprom_read_byte(sE); if(UNSET_BYTE == v) { return(false); } // Abort if not a full set of stats (eg at least one full day's worth). if(v < sample) { if(++valuesLower >= 18) { return(true); } } // Stop as soon as known to be in upper quartile. } return(false); // Not in upper quartile. } // Returns true if specified hour is (conservatively) in the specified outlier quartile for the specified stats set. // Returns false if a full set of stats not available, eg including the specified hour. // Always returns false if all samples are the same. // * inTop test for membership of the top quartile if true, bottom quartile if false // * statsSet stats set number to use. // * hour hour of day to use, or ~0 for current hour, or >23 for next hour. bool NVByHourByteStatsBase::inOutlierQuartile(const bool inTop, const uint8_t statsSet, const uint8_t hh) const { // Rely on getByHourStatXXX() to validate statsSet, // returning UNSET if invalid or if the sample is unset. const uint8_t sample = (hh > 23) ? getByHourStatRTC(statsSet, hh) : getByHourStatSimple(statsSet, hh); if(UNSET_BYTE == sample) { return(false); } // Abort if not a valid/set sample. if(inTop) { return(inTopQuartile(statsSet, sample)); } return(inBottomQuartile(statsSet, sample)); } // Stats-, EEPROM- (and Flash-) friendly single-byte unary incrementable encoding. // A single byte can be used to hold a single value [0,8] // such that increment requires only a write of one bit (no erase) // and in general increasing the value up to the maximum only requires a single write. // An erase is required only to decrease the value (eg back to zero). // An initial EEPROM (erased) value of 0xff is mapped to zero. // The two byte version can hold values in the range [0,16]. // Corruption can be detected if an unexpected bit pattern is encountered on decode. // For the single byte versions, encodings are: // 0 -> 0xff // 1 -> 0xfe // 2 -> 0xfc // 3 -> 0xf8 // 4 -> 0xf0 // 5 -> 0xe0 // 6 -> 0xc0 // 7 -> 0x80 // 8 -> 0x00 // // Decode routines return -1 in case of unexpected/invalid input patterns. // All other (valid non-negative) return values can be safely cast to unit8_t. int8_t eeprom_unary_1byte_decode(const uint8_t v) { switch(v) { case 0xff: return(0); case 0xfe: return(1); case 0xfc: return(2); case 0xf8: return(3); case 0xf0: return(4); case 0xe0: return(5); case 0xc0: return(6); case 0x80: return(7); case 0x00: return(8); default: return(-1); // ERROR } } // Decode routines return -1 in case of unexpected/invalid input patterns. int8_t eeprom_unary_2byte_decode(const uint8_t vm, const uint8_t vl) { if(0xff == vm) { return(eeprom_unary_1byte_decode(vl)); } else if(0 == vl) { return(eeprom_unary_1byte_decode(vm) + 8); } return(-1); } //int8_t eeprom_unary_2byte_decode(uint16_t v) // { // switch(v) // { // case 0xffff: return(0); // case 0xfffe: return(1); // case 0xfffc: return(2); // case 0xfff8: return(3); // case 0xfff0: return(4); // case 0xffe0: return(5); // case 0xffc0: return(6); // case 0xff80: return(7); // case 0xff00: return(8); // case 0xfe00: return(9); // case 0xfc00: return(10); // case 0xf800: return(11); // case 0xf000: return(12); // case 0xe000: return(13); // case 0xc000: return(14); // case 0x8000: return(15); // case 0x0000: return(16); // default: return(-1); // ERROR // } // } // Range-compress an signed int 16ths-Celsius temperature to a unsigned single-byte value < 0xff. // This preserves at least the first bit after the binary point for all values, // and three bits after binary point for values in the most interesting mid range around normal room temperatures, // with transitions at whole degrees Celsius. // Input values below 0C are treated as 0C, and above 100C as 100C, thus allowing air and DHW temperature values. uint8_t compressTempC16(const int16_t tempC16) { if(tempC16 <= 0) { return(0); } // Clamp negative values to zero. if(tempC16 < COMPRESSION_C16_LOW_THRESHOLD) { return(uint8_t(tempC16 >> 3)); } // Preserve 1 bit after the binary point (0.5C precision). if(tempC16 < COMPRESSION_C16_HIGH_THRESHOLD) { return(uint8_t(((tempC16 - COMPRESSION_C16_LOW_THRESHOLD) >> 1) + COMPRESSION_C16_LOW_THR_AFTER)); } if(tempC16 < COMPRESSION_C16_CEIL_VAL) { return(uint8_t(((tempC16 - COMPRESSION_C16_HIGH_THRESHOLD) >> 3) + COMPRESSION_C16_HIGH_THR_AFTER)); } return(COMPRESSION_C16_CEIL_VAL_AFTER); } // Reverses range compression done by compressTempC16(); results in range [0,100], with varying precision based on original value. // 0xff (or other invalid) input results in STATS_UNSET_INT. int16_t expandTempC16(const uint8_t cTemp) { if(cTemp < COMPRESSION_C16_LOW_THR_AFTER) { return(int16_t(cTemp << 3)); } if(cTemp < COMPRESSION_C16_HIGH_THR_AFTER) { return(int16_t(((cTemp - COMPRESSION_C16_LOW_THR_AFTER) << 1) + COMPRESSION_C16_LOW_THRESHOLD)); } if(cTemp <= COMPRESSION_C16_CEIL_VAL_AFTER) { return(int16_t(((cTemp - COMPRESSION_C16_HIGH_THR_AFTER) << 3) + COMPRESSION_C16_HIGH_THRESHOLD)); } return(OTV0P2BASE::NVByHourByteStatsBase::UNSET_INT); // Invalid/unset input. } } <|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 QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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 "qgraphicssceneindex.h" #include "qgraphicsscene.h" #ifndef QT_NO_GRAPHICSVIEW QT_BEGIN_NAMESPACE QGraphicsSceneIndex::QGraphicsSceneIndex() { } QGraphicsSceneIndex::~QGraphicsSceneIndex() { } QGraphicsScene* QGraphicsSceneIndex::scene() { return mscene; } void QGraphicsSceneIndex::updateItem(QGraphicsItem *item) { removeItem(item); insertItem(item); } void QGraphicsSceneIndex::insertItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) insertItem(item); } void QGraphicsSceneIndex::removeItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) removeItem(item); } void QGraphicsSceneIndex::updateItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) updateItem(item); } QT_END_NAMESPACE //#include "moc_qgraphicssceneindex.cpp" #endif // QT_NO_GRAPHICSVIEW <commit_msg>Fixes: Add API documentation for QGraphicsSceneIndex<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 QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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 "qgraphicssceneindex.h" #include "qgraphicsscene.h" #ifndef QT_NO_GRAPHICSVIEW QT_BEGIN_NAMESPACE /*! Constructs an abstract scene index. */ QGraphicsSceneIndex::QGraphicsSceneIndex() { } /*! Destroys the scene index. */ QGraphicsSceneIndex::~QGraphicsSceneIndex() { } /*! \fn virtual void setRect(const QRectF &rect) = 0 This pure virtual function is called when the scene changes its bounding rectangle. \sa rect(), QGraphicsScene::setSceneRect */ /*! \fn virtual QRectF rect() const = 0 This pure virtual function returns the bounding rectangle of this scene index. It could be as large as or larger than the scene bounding rectangle, depending on the implementation of the scene index. \sa setRect(), QGraphicsScene::sceneRect */ /*! \fn virtual void clear() = 0 This pure virtual function removes all items in the scene index. */ /*! \fn virtual void insertItem(QGraphicsItem *item) = 0 This pure virtual function inserts an item to the scene index. \sa removeItem(), updateItem(), insertItems() */ /*! \fn virtual void removeItem(QGraphicsItem *item) = 0 This pure virtual function removes an item to the scene index. \sa insertItem(), updateItem(), removeItems() */ /*! Returns the scene of this scene index. */ QGraphicsScene* QGraphicsSceneIndex::scene() { return mscene; } /*! Updates an item when its geometry has changed. The default implemention will remove the item from the index and then insert it again. \sa insertItem(), removeItem(), updateItems() */ void QGraphicsSceneIndex::updateItem(QGraphicsItem *item) { removeItem(item); insertItem(item); } /*! Inserts a list of items to the index. The default implemention will insert the items one by one. \sa insertItem(), removeItems(), updateItems() */ void QGraphicsSceneIndex::insertItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) insertItem(item); } /*! Removes a list of items from the index. The default implemention will remove the items one by one. \sa removeItem(), removeItems(), updateItems() */ void QGraphicsSceneIndex::removeItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) removeItem(item); } /*! Update a list of items which have changed the geometry. The default implemention will update the items one by one. \sa updateItem(), insertItems(), removeItems() */ void QGraphicsSceneIndex::updateItems(const QList<QGraphicsItem *> &items) { foreach (QGraphicsItem *item, items) updateItem(item); } QT_END_NAMESPACE //#include "moc_qgraphicssceneindex.cpp" #endif // QT_NO_GRAPHICSVIEW <|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/browser/download/download_id.h" #include <algorithm> #include <map> #include <set> #include <vector> #include "content/browser/download/mock_download_manager_delegate.h" #include "content/browser/download/mock_download_manager.h" #include "testing/gtest/include/gtest/gtest.h" class DownloadIdTest : public testing::Test { public: DownloadIdTest() : download_manager_delegate_(new MockDownloadManagerDelegate), ui_thread_(BrowserThread::UI, &message_loop_) { num_managers_ = ARRAYSIZE_UNSAFE(download_managers_); std::vector<MockDownloadManager*> managers; managers.resize(num_managers_); size_t i; // Create the download managers. for (i = 0; i < num_managers_; ++i) { managers[i] = new MockDownloadManager(download_manager_delegate_.get(), NULL); } // Sort by pointer value. std::sort(managers.begin(), managers.end()); // Assign to |download_managers_|. for (i = 0; i < num_managers_; ++i) { download_managers_[i] = managers[i]; managers[i] = NULL; } } ~DownloadIdTest() { for (size_t i = 0; i < num_managers_; ++i) download_managers_[i] = NULL; // Releases & deletes. } protected: scoped_ptr<MockDownloadManagerDelegate> download_manager_delegate_; scoped_refptr<DownloadManager> download_managers_[2]; MessageLoopForUI message_loop_; BrowserThread ui_thread_; // Necessary to delete |DownloadManager|s. size_t num_managers_; DISALLOW_COPY_AND_ASSIGN(DownloadIdTest); }; TEST_F(DownloadIdTest, Local) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 25); EXPECT_EQ(23, id1.local()); EXPECT_EQ(25, id2.local()); } TEST_F(DownloadIdTest, Valid) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], -1); DownloadId id3(NULL, 23); DownloadId id4(NULL, -3456); EXPECT_TRUE(id1.IsValid()); EXPECT_FALSE(id2.IsValid()); EXPECT_FALSE(id3.IsValid()); } TEST_F(DownloadIdTest, Equals) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 23); EXPECT_EQ(DownloadId::Invalid(), DownloadId::Invalid()); EXPECT_EQ(id1, id2); } TEST_F(DownloadIdTest, NotEqualsIndex) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 24); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); } TEST_F(DownloadIdTest, NotEqualsManager) { // Because it's sorted above, &download_managers_[1] > &download_managers_[0]. EXPECT_LT(download_managers_[0].get(), download_managers_[1].get()); DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[1], 23); DownloadId id3(download_managers_[1], 22); EXPECT_LT(DownloadId::Invalid(), id1); EXPECT_LT(DownloadId::Invalid(), id2); EXPECT_LT(DownloadId::Invalid(), id3); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); EXPECT_FALSE(id2 == id3); EXPECT_LT(id3, id2); EXPECT_FALSE(id1 == id3); EXPECT_LT(id1, id3); } TEST_F(DownloadIdTest, HashMap) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 24); DownloadId id3(download_managers_[1], 23); const int kLocalId[] = { 95, 1234567, -29 }; typedef base::hash_map<DownloadId, int> DownloadIdMap; DownloadIdMap map; map[id1] = kLocalId[0]; EXPECT_EQ(1U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); DownloadIdMap::iterator last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_TRUE(last == map.find(id2)); EXPECT_TRUE(last == map.find(id3)); map[id2] = kLocalId[1]; EXPECT_EQ(2U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); EXPECT_EQ(kLocalId[1], map[id2]); last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_FALSE(last == map.find(id2)); EXPECT_TRUE(last == map.find(id3)); map[id3] = kLocalId[2]; EXPECT_EQ(3U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); EXPECT_EQ(kLocalId[1], map[id2]); EXPECT_EQ(kLocalId[2], map[id3]); last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_FALSE(last == map.find(id2)); EXPECT_FALSE(last == map.find(id3)); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); } <commit_msg>Fix check_perms error from r103992.<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 "content/browser/download/download_id.h" #include <algorithm> #include <map> #include <set> #include <vector> #include "content/browser/download/mock_download_manager_delegate.h" #include "content/browser/download/mock_download_manager.h" #include "testing/gtest/include/gtest/gtest.h" class DownloadIdTest : public testing::Test { public: DownloadIdTest() : download_manager_delegate_(new MockDownloadManagerDelegate), ui_thread_(BrowserThread::UI, &message_loop_) { num_managers_ = ARRAYSIZE_UNSAFE(download_managers_); std::vector<MockDownloadManager*> managers; managers.resize(num_managers_); size_t i; // Create the download managers. for (i = 0; i < num_managers_; ++i) { managers[i] = new MockDownloadManager(download_manager_delegate_.get(), NULL); } // Sort by pointer value. std::sort(managers.begin(), managers.end()); // Assign to |download_managers_|. for (i = 0; i < num_managers_; ++i) { download_managers_[i] = managers[i]; managers[i] = NULL; } } ~DownloadIdTest() { for (size_t i = 0; i < num_managers_; ++i) download_managers_[i] = NULL; // Releases & deletes. } protected: scoped_ptr<MockDownloadManagerDelegate> download_manager_delegate_; scoped_refptr<DownloadManager> download_managers_[2]; MessageLoopForUI message_loop_; BrowserThread ui_thread_; // Necessary to delete |DownloadManager|s. size_t num_managers_; DISALLOW_COPY_AND_ASSIGN(DownloadIdTest); }; TEST_F(DownloadIdTest, Local) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 25); EXPECT_EQ(23, id1.local()); EXPECT_EQ(25, id2.local()); } TEST_F(DownloadIdTest, Valid) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], -1); DownloadId id3(NULL, 23); DownloadId id4(NULL, -3456); EXPECT_TRUE(id1.IsValid()); EXPECT_FALSE(id2.IsValid()); EXPECT_FALSE(id3.IsValid()); } TEST_F(DownloadIdTest, Equals) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 23); EXPECT_EQ(DownloadId::Invalid(), DownloadId::Invalid()); EXPECT_EQ(id1, id2); } TEST_F(DownloadIdTest, NotEqualsIndex) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 24); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); } TEST_F(DownloadIdTest, NotEqualsManager) { // Because it's sorted above, &download_managers_[1] > &download_managers_[0]. EXPECT_LT(download_managers_[0].get(), download_managers_[1].get()); DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[1], 23); DownloadId id3(download_managers_[1], 22); EXPECT_LT(DownloadId::Invalid(), id1); EXPECT_LT(DownloadId::Invalid(), id2); EXPECT_LT(DownloadId::Invalid(), id3); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); EXPECT_FALSE(id2 == id3); EXPECT_LT(id3, id2); EXPECT_FALSE(id1 == id3); EXPECT_LT(id1, id3); } TEST_F(DownloadIdTest, HashMap) { DownloadId id1(download_managers_[0], 23); DownloadId id2(download_managers_[0], 24); DownloadId id3(download_managers_[1], 23); const int kLocalId[] = { 95, 1234567, -29 }; typedef base::hash_map<DownloadId, int> DownloadIdMap; DownloadIdMap map; map[id1] = kLocalId[0]; EXPECT_EQ(1U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); DownloadIdMap::iterator last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_TRUE(last == map.find(id2)); EXPECT_TRUE(last == map.find(id3)); map[id2] = kLocalId[1]; EXPECT_EQ(2U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); EXPECT_EQ(kLocalId[1], map[id2]); last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_FALSE(last == map.find(id2)); EXPECT_TRUE(last == map.find(id3)); map[id3] = kLocalId[2]; EXPECT_EQ(3U, map.size()); EXPECT_EQ(kLocalId[0], map[id1]); EXPECT_EQ(kLocalId[1], map[id2]); EXPECT_EQ(kLocalId[2], map[id3]); last = map.end(); EXPECT_FALSE(last == map.find(id1)); EXPECT_FALSE(last == map.find(id2)); EXPECT_FALSE(last == map.find(id3)); EXPECT_FALSE(id1 == id2); EXPECT_LT(id1, id2); } <|endoftext|>
<commit_before>#include <xzero/http/HttpService.h> #include <xzero/http/HttpRequest.h> #include <xzero/http/HttpResponse.h> #include <xzero/http/v1/HttpConnectionFactory.h> #include <xzero/net/LocalConnector.h> #include <xzero/net/InetConnector.h> #include <xzero/net/Server.h> #include <algorithm> #include <stdexcept> namespace xzero { HttpService::HttpService() : server_(new Server()), localConnector_(nullptr), inetConnector_(nullptr), handlers_() { } HttpService::~HttpService() { delete server_; } LocalConnector* HttpService::configureLocal() { if (localConnector_ != nullptr) throw std::runtime_error("Multiple local connectors not supported."); localConnector_ = server_->addConnector<LocalConnector>(); enableHttp1(localConnector_); return localConnector_; } InetConnector* HttpService::configureInet(Executor* executor, Scheduler* scheduler, Selector* selector, const IPAddress& ipaddress, int port, int backlog) { if (inetConnector_ != nullptr) throw std::runtime_error("Multiple inet connectors not yet supported."); inetConnector_ = server_->addConnector<InetConnector>("http", executor, scheduler, selector, ipaddress, port, backlog, true, false); enableHttp1(inetConnector_); return inetConnector_; } void HttpService::enableHttp1(Connector* connector) { auto http = connector->addConnectionFactory<xzero::http1::HttpConnectionFactory>(); http->setHandler(std::bind(&HttpService::handleRequest, this, std::placeholders::_1, std::placeholders::_2)); } void HttpService::addHandler(Handler* handler) { handlers_.push_back(handler); } void HttpService::removeHandler(Handler* handler) { auto i = std::find(handlers_.begin(), handlers_.end(), handler); if (i != handlers_.end()) handlers_.erase(i); } void HttpService::start() { server_->start(); } void HttpService::stop() { server_->stop(); } void HttpService::handleRequest(HttpRequest* request, HttpResponse* response) { // TODO: if request contains a body, make sure we have it all available // already. // XXX maybe wrap request/response objects ? (any *real* use for this?) for (Handler* handler: handlers_) { if (handler->handleRequest(request, response)) { return; } } response->setStatus(HttpStatus::NotFound); response->completed(); } // {{{ BuiltinAssetHandler HttpService::BuiltinAssetHandler::BuiltinAssetHandler() : assets_() { } void HttpService::BuiltinAssetHandler::addAsset(const std::string& path, const std::string& mimetype, const Buffer&& data) { assets_[path] = { mimetype, DateTime(), std::move(data) }; } bool HttpService::BuiltinAssetHandler::handleRequest(HttpRequest* request, HttpResponse* response) { auto i = assets_.find(request->path()); if (i == assets_.end()) return false; // XXX ignores client cache for now response->setStatus(HttpStatus::Ok); response->setContentLength(i->second.data.size()); response->addHeader("Content-Type", i->second.mimetype); response->addHeader("Last-Modified", i->second.mtime.http_str().c_str()); response->output()->write(i->second.data.ref()); response->completed(); return true; } // }}} } // namespace xzero <commit_msg>HttpService: adds support for convenient request body processing.<commit_after>#include <xzero/http/HttpService.h> #include <xzero/http/HttpRequest.h> #include <xzero/http/HttpResponse.h> #include <xzero/http/HttpInputListener.h> #include <xzero/http/v1/HttpConnectionFactory.h> #include <xzero/net/LocalConnector.h> #include <xzero/net/InetConnector.h> #include <xzero/net/Server.h> #include <algorithm> #include <stdexcept> namespace xzero { class HttpService::InputListener : public HttpInputListener { // {{{ public: InputListener(HttpRequest* request, HttpResponse* response, HttpService* service); void onContentAvailable() override; void onAllDataRead() override; void onError(const std::string& errorMessage) override; private: HttpRequest* request_; HttpResponse* response_; HttpService* service_; }; HttpService::InputListener::InputListener(HttpRequest* request, HttpResponse* response, HttpService* service) : request_(request), response_(response), service_(service) { } void HttpService::InputListener::onContentAvailable() { /* request_->input()->fill(); */ } void HttpService::InputListener::onAllDataRead() { service_->onAllDataRead(request_, response_); delete this; } void HttpService::InputListener::onError(const std::string& errorMessage) { delete this; } // }}} HttpService::HttpService() : server_(new Server()), localConnector_(nullptr), inetConnector_(nullptr), handlers_() { } HttpService::~HttpService() { delete server_; } LocalConnector* HttpService::configureLocal() { if (localConnector_ != nullptr) throw std::runtime_error("Multiple local connectors not supported."); localConnector_ = server_->addConnector<LocalConnector>(); enableHttp1(localConnector_); return localConnector_; } InetConnector* HttpService::configureInet(Executor* executor, Scheduler* scheduler, Selector* selector, const IPAddress& ipaddress, int port, int backlog) { if (inetConnector_ != nullptr) throw std::runtime_error("Multiple inet connectors not yet supported."); inetConnector_ = server_->addConnector<InetConnector>("http", executor, scheduler, selector, ipaddress, port, backlog, true, false); enableHttp1(inetConnector_); return inetConnector_; } void HttpService::enableHttp1(Connector* connector) { auto http = connector->addConnectionFactory<xzero::http1::HttpConnectionFactory>(); http->setHandler(std::bind(&HttpService::handleRequest, this, std::placeholders::_1, std::placeholders::_2)); } void HttpService::addHandler(Handler* handler) { handlers_.push_back(handler); } void HttpService::removeHandler(Handler* handler) { auto i = std::find(handlers_.begin(), handlers_.end(), handler); if (i != handlers_.end()) handlers_.erase(i); } void HttpService::start() { server_->start(); } void HttpService::stop() { server_->stop(); } void HttpService::handleRequest(HttpRequest* request, HttpResponse* response) { if (request->expect100Continue()) response->send100Continue(); request->input()->setListener(new InputListener(request, response, this)); } void HttpService::onAllDataRead(HttpRequest* request, HttpResponse* response) { for (Handler* handler: handlers_) { if (handler->handleRequest(request, response)) { return; } } response->setStatus(HttpStatus::NotFound); response->completed(); } // {{{ BuiltinAssetHandler HttpService::BuiltinAssetHandler::BuiltinAssetHandler() : assets_() { } void HttpService::BuiltinAssetHandler::addAsset(const std::string& path, const std::string& mimetype, const Buffer&& data) { assets_[path] = { mimetype, DateTime(), std::move(data) }; } bool HttpService::BuiltinAssetHandler::handleRequest(HttpRequest* request, HttpResponse* response) { auto i = assets_.find(request->path()); if (i == assets_.end()) return false; // XXX ignores client cache for now response->setStatus(HttpStatus::Ok); response->setContentLength(i->second.data.size()); response->addHeader("Content-Type", i->second.mimetype); response->addHeader("Last-Modified", i->second.mtime.http_str().c_str()); response->output()->write(i->second.data.ref()); response->completed(); return true; } // }}} } // namespace xzero <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<QSet<Filter> >("QSet<Filter>"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { QSet<QString> ret; const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types") << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"); Q_FOREACH(QString s, locations) { QSettings settings(s, QSettings::NativeFormat); ret += settings.childGroups().replaceInStrings("\\", "/").toSet(); } QStringList list = ret.toList(); qSort(list); return list; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { //end of a transaction HRESULT hr = E_FAIL; if (!objects.isEmpty()) { Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { MediaObject *mo = node->mediaObject(); if (mo && m_graphState.contains(mo)) { switch(m_graphState[mo]) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } if (mo->state() != Phonon::ErrorState) { hr = S_OK; } m_graphState.remove(mo); } } } } return SUCCEEDED(hr); } bool Backend::startConnectionChange(QSet<QObject *> objects) { //start a transaction QSet<MediaObject*> mediaObjects; //let's save the state of the graph (before we stop it) Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { if (MediaObject *mo = node->mediaObject()) { mediaObjects << mo; } } } Q_FOREACH(MediaObject *mo, mediaObjects) { m_graphState[mo] = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return !mediaObjects.isEmpty(); } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp" <commit_msg>make autotest path when reconnecting a path with the exact same source and sink.<commit_after>/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<QSet<Filter> >("QSet<Filter>"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { QSet<QString> ret; const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types") << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"); Q_FOREACH(QString s, locations) { QSettings settings(s, QSettings::NativeFormat); ret += settings.childGroups().replaceInStrings("\\", "/").toSet(); } QStringList list = ret.toList(); qSort(list); return list; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { //end of a transaction HRESULT hr = E_FAIL; if (!objects.isEmpty()) { Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { MediaObject *mo = node->mediaObject(); if (mo && m_graphState.contains(mo)) { switch(m_graphState[mo]) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } if (mo->state() != Phonon::ErrorState) { hr = S_OK; } m_graphState.remove(mo); } } } } return SUCCEEDED(hr); } bool Backend::startConnectionChange(QSet<QObject *> objects) { //start a transaction QSet<MediaObject*> mediaObjects; //let's save the state of the graph (before we stop it) Q_FOREACH(QObject *o, objects) { if (BackendNode *node = qobject_cast<BackendNode*>(o)) { if (MediaObject *mo = node->mediaObject()) { mediaObjects << mo; } } } Q_FOREACH(MediaObject *mo, mediaObjects) { m_graphState[mo] = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return objects.isEmpty() || !mediaObjects.isEmpty(); } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp" <|endoftext|>
<commit_before>/* This file is part of KAddressbook. Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <kaction.h> #include <kapplication.h> #include <kdebug.h> #include <kiconloader.h> #include <kinstance.h> #include <klocale.h> #include <kparts/genericfactory.h> #include "kabcore.h" #include "kaddressbookiface.h" #include "libkdepim/aboutdataextension.h" #include "libkdepim/infoextension.h" #include "kaddressbook_part.h" typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory; K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory ) KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const QStringList & ) : DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name ) { kdDebug(5720) << "KAddressbookPart()" << endl; kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl; setInstance( KAddressbookFactory::instance() ); kdDebug(5720) << "KAddressbookPart()..." << endl; kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl; // create a canvas to insert our widget QWidget *canvas = new QWidget( parentWidget, widgetName ); canvas->setFocusPolicy( QWidget::ClickFocus ); setWidget( canvas ); mExtension = new KAddressbookBrowserExtension( this ); QVBoxLayout *topLayout = new QVBoxLayout( canvas ); KGlobal::iconLoader()->addAppDir( "kaddressbook" ); mCore = new KABCore( this, true, canvas ); mCore->restoreSettings(); topLayout->addWidget( mCore->widget() ); KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" ); connect( mCore, SIGNAL( contactSelected( const QString& ) ), info, SIGNAL( textChanged( const QString& ) ) ); connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ), info, SIGNAL( iconChanged( const QPixmap& ) ) ); new KParts::AboutDataExtension( createAboutData(), this, "AboutData" ); setXMLFile( "kaddressbookui.rc" ); } KAddressbookPart::~KAddressbookPart() { mCore->save(); closeURL(); } KAboutData *KAddressbookPart::createAboutData() { return KABCore::createAboutData(); } void KAddressbookPart::addEmail( QString addr ) { mCore->addEmail( addr ); } ASYNC KAddressbookPart::showContactEditor( QString uid ) { mCore->editContact( uid ); } void KAddressbookPart::newContact() { mCore->newContact(); } QString KAddressbookPart::getNameByPhone( QString phone ) { return mCore->getNameByPhone( phone ); } void KAddressbookPart::save() { mCore->save(); } void KAddressbookPart::exit() { delete this; } bool KAddressbookPart::openFile() { kdDebug(5720) << "KAddressbookPart:openFile()" << endl; mCore->widget()->show(); return true; } void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e ) { kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl; KParts::ReadOnlyPart::guiActivateEvent( e ); } KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent ) : KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" ) { } KAddressbookBrowserExtension::~KAddressbookBrowserExtension() { } using namespace KParts; #include "kaddressbook_part.moc" <commit_msg>Don't need AboutDataExtension anymore.<commit_after>/* This file is part of KAddressbook. Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <kaction.h> #include <kapplication.h> #include <kdebug.h> #include <kiconloader.h> #include <kinstance.h> #include <klocale.h> #include <kparts/genericfactory.h> #include "kabcore.h" #include "kaddressbookiface.h" #include "libkdepim/infoextension.h" #include "kaddressbook_part.h" typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory; K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory ) KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const QStringList & ) : DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name ) { kdDebug(5720) << "KAddressbookPart()" << endl; kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl; setInstance( KAddressbookFactory::instance() ); kdDebug(5720) << "KAddressbookPart()..." << endl; kdDebug(5720) << " InstanceName: " << kapp->instanceName() << endl; // create a canvas to insert our widget QWidget *canvas = new QWidget( parentWidget, widgetName ); canvas->setFocusPolicy( QWidget::ClickFocus ); setWidget( canvas ); mExtension = new KAddressbookBrowserExtension( this ); QVBoxLayout *topLayout = new QVBoxLayout( canvas ); KGlobal::iconLoader()->addAppDir( "kaddressbook" ); mCore = new KABCore( this, true, canvas ); mCore->restoreSettings(); topLayout->addWidget( mCore->widget() ); KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" ); connect( mCore, SIGNAL( contactSelected( const QString& ) ), info, SIGNAL( textChanged( const QString& ) ) ); connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ), info, SIGNAL( iconChanged( const QPixmap& ) ) ); setXMLFile( "kaddressbookui.rc" ); } KAddressbookPart::~KAddressbookPart() { mCore->save(); closeURL(); } KAboutData *KAddressbookPart::createAboutData() { return KABCore::createAboutData(); } void KAddressbookPart::addEmail( QString addr ) { mCore->addEmail( addr ); } ASYNC KAddressbookPart::showContactEditor( QString uid ) { mCore->editContact( uid ); } void KAddressbookPart::newContact() { mCore->newContact(); } QString KAddressbookPart::getNameByPhone( QString phone ) { return mCore->getNameByPhone( phone ); } void KAddressbookPart::save() { mCore->save(); } void KAddressbookPart::exit() { delete this; } bool KAddressbookPart::openFile() { kdDebug(5720) << "KAddressbookPart:openFile()" << endl; mCore->widget()->show(); return true; } void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e ) { kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl; KParts::ReadOnlyPart::guiActivateEvent( e ); } KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent ) : KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" ) { } KAddressbookBrowserExtension::~KAddressbookBrowserExtension() { } using namespace KParts; #include "kaddressbook_part.moc" <|endoftext|>
<commit_before>// Copyright 2017 The Effcee Authors. // // 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 "check.h" #include <cassert> #include <algorithm> #include <memory> #include <sstream> #include <string> #include <utility> #include "cursor.h" #include "effcee.h" #include "make_unique.h" using Status = effcee::Result::Status; using StringPiece = effcee::StringPiece; using Type = effcee::Check::Type; namespace { // Returns a table of suffix to type mappings. const std::vector<std::pair<StringPiece, Type>>& TypeStringTable() { static std::vector<std::pair<StringPiece, Type>> type_str_table{ {"", Type::Simple}, {"-NEXT", Type::Next}, {"-SAME", Type::Same}, {"-DAG", Type::DAG}, {"-LABEL", Type::Label}, {"-NOT", Type::Not}}; return type_str_table; } // Returns the Check::Type value matching the suffix part of a check rule // prefix. Assumes |suffix| is valid. Type TypeForSuffix(StringPiece suffix) { const auto& type_str_table = TypeStringTable(); const auto pair_iter = std::find_if(type_str_table.begin(), type_str_table.end(), [suffix](const std::pair<StringPiece, Type>& elem) { return suffix == elem.first; }); assert(pair_iter != type_str_table.end()); return pair_iter->second; } StringPiece SuffixForType(Type type) { const auto& type_str_table = TypeStringTable(); const auto pair_iter = std::find_if(type_str_table.begin(), type_str_table.end(), [type](const std::pair<StringPiece, Type>& elem) { return type == elem.second; }); assert(pair_iter != type_str_table.end()); return pair_iter->first; } } // namespace namespace effcee { int Check::Part::CountCapturingGroups() { if (type_ == Type::Regex) return RE2(param_).NumberOfCapturingGroups(); if (type_ == Type::VarDef) return RE2(expression_).NumberOfCapturingGroups(); return 0; } Check::Check(Type type, StringPiece param) : type_(type), param_(param) { parts_.push_back(make_unique<Check::Part>(Part::Type::Fixed, param)); } bool Check::Part::MightMatch(const VarMapping& vars) const { return type_ != Type::VarUse || vars.find(VarUseName().as_string()) != vars.end(); } std::string Check::Part::Regex(const VarMapping& vars) const { switch (type_) { case Type::Fixed: return RE2::QuoteMeta(param_); case Type::Regex: return param_.as_string(); case Type::VarDef: return std::string("(") + expression_.as_string() + ")"; case Type::VarUse: { auto where = vars.find(VarUseName().as_string()); if (where != vars.end()) { // Return the escaped form of the current value of the variable. return RE2::QuoteMeta((*where).second); } else { // The variable is not yet set. Should not get here. return ""; } } } return ""; // Unreachable. But we need to satisfy GCC. } bool Check::Matches(StringPiece* input, StringPiece* captured, VarMapping* vars) const { if (parts_.empty()) return false; for (auto& part : parts_) { if (!part->MightMatch(*vars)) return false; } std::unordered_map<int, std::string> var_def_indices; std::ostringstream consume_regex; int num_captures = 1; // The outer capture. for (auto& part : parts_) { consume_regex << part->Regex(*vars); const auto var_def_name = part->VarDefName(); if (!var_def_name.empty()) { var_def_indices[num_captures++] = var_def_name.as_string(); } num_captures += part->NumCapturingGroups(); } std::unique_ptr<StringPiece[]> captures(new StringPiece[num_captures]); const bool matched = RE2(consume_regex.str()) .Match(*input, 0, input->size(), RE2::UNANCHORED, captures.get(), num_captures); if (matched) { *captured = captures[0]; input->remove_prefix(captured->end() - input->begin()); // Update the variable mapping. for (auto& var_def_index : var_def_indices) { const int index = var_def_index.first; (*vars)[var_def_index.second] = captures[index].as_string(); } } return matched; } std::string Check::Description(const Options& options) const { std::ostringstream out; out << options.prefix() << SuffixForType(type()) << ": " << param(); return out.str(); } namespace { // Returns a parts list for the given pattern. This splits out regular expressions as // delimited by {{ and }}, and also variable uses and definitions. Check::Parts PartsForPattern(StringPiece pattern) { Check::Parts parts; StringPiece fixed, regex, var; using Type = Check::Part::Type; while (!pattern.empty()) { const auto regex_start = pattern.find("{{"); const auto regex_end = pattern.find("}}"); const auto var_start = pattern.find("[["); const auto var_end = pattern.find("]]"); const bool regex_exists = regex_start < regex_end && regex_end < StringPiece::npos; const bool var_exists = var_start < var_end && var_end < StringPiece::npos; if (regex_exists && (!var_exists || regex_start < var_start)) { const auto consumed = RE2::Consume(&pattern, "(.*?){{(.*?)}}", &fixed, &regex); assert(consumed && "Did not make forward progress for regex in check rule"); if (!fixed.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Fixed, fixed)); } if (!regex.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Regex, regex)); } } else if (var_exists && (!regex_exists || var_start < regex_start)) { const auto consumed = RE2::Consume(&pattern, "(.*?)\\[\\[(.*?)\\]\\]", &fixed, &var); assert(consumed && "Did not make forward progress for var in check rule"); if (!fixed.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Fixed, fixed)); } if (!var.empty()) { auto colon = var.find(":"); // A colon at the end is useless anyway, so just make it a variable // use. if (colon == StringPiece::npos || colon == var.size() - 1) { parts.emplace_back(make_unique<Check::Part>(Type::VarUse, var)); } else { StringPiece name = var.substr(0, colon); StringPiece expression = var.substr(colon + 1, StringPiece::npos); parts.emplace_back( make_unique<Check::Part>(Type::VarDef, var, name, expression)); } } } else { // There is no regex, no var def, no var use. Must be a fixed string. parts.push_back(make_unique<Check::Part>(Type::Fixed, pattern)); break; } } return parts; } } // anonymous std::pair<Result, CheckList> ParseChecks(StringPiece str, const Options& options) { // Returns a pair whose first member is a result constructed from the // given status and message, and the second member is an empy pattern. auto failure = [](Status status, StringPiece message) { return std::make_pair(Result(status, message), CheckList{}); }; if (options.prefix().size() == 0) return failure(Status::BadOption, "Rule prefix is empty"); if (RE2::FullMatch(options.prefix(), "\\s+")) return failure(Status::BadOption, "Rule prefix is whitespace. That's silly."); CheckList check_list; const auto quoted_prefix = RE2::QuoteMeta(options.prefix()); // Match the following parts: // .*? - Text that is not the rule prefix // quoted_prefix - A Simple Check prefix // (-NEXT|-SAME)? - An optional check type suffix. Two shown here. // : - Colon // \s* - Whitespace // (.*?) - Captured parameter // \s* - Whitespace // $ - End of line const RE2 regexp(std::string(".*?") + quoted_prefix + "(-NEXT|-SAME|-DAG|-LABEL|-NOT)?" ":\\s*(.*?)\\s*$"); Cursor cursor(str); while (!cursor.Exhausted()) { const auto line = cursor.RestOfLine(); StringPiece matched_param; StringPiece suffix; if (RE2::PartialMatch(line, regexp, &suffix, &matched_param)) { const Type type = TypeForSuffix(suffix); auto parts(PartsForPattern(matched_param)); check_list.push_back(Check(type, matched_param, std::move(parts))); } cursor.AdvanceLine(); } if (check_list.empty()) { return failure( Status::NoRules, std::string("No check rules specified. Looking for prefix ") + options.prefix()); } if (check_list[0].type() == Type::Same) { return failure(Status::BadRule, std::string(options.prefix()) + "-SAME can't be the first check rule"); } return std::make_pair(Result(Result::Status::Ok), check_list); } } // namespace effcee <commit_msg>Avoid unused var warning<commit_after>// Copyright 2017 The Effcee Authors. // // 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 "check.h" #include <cassert> #include <algorithm> #include <memory> #include <sstream> #include <string> #include <utility> #include "cursor.h" #include "effcee.h" #include "make_unique.h" using Status = effcee::Result::Status; using StringPiece = effcee::StringPiece; using Type = effcee::Check::Type; namespace { // Returns a table of suffix to type mappings. const std::vector<std::pair<StringPiece, Type>>& TypeStringTable() { static std::vector<std::pair<StringPiece, Type>> type_str_table{ {"", Type::Simple}, {"-NEXT", Type::Next}, {"-SAME", Type::Same}, {"-DAG", Type::DAG}, {"-LABEL", Type::Label}, {"-NOT", Type::Not}}; return type_str_table; } // Returns the Check::Type value matching the suffix part of a check rule // prefix. Assumes |suffix| is valid. Type TypeForSuffix(StringPiece suffix) { const auto& type_str_table = TypeStringTable(); const auto pair_iter = std::find_if(type_str_table.begin(), type_str_table.end(), [suffix](const std::pair<StringPiece, Type>& elem) { return suffix == elem.first; }); assert(pair_iter != type_str_table.end()); return pair_iter->second; } StringPiece SuffixForType(Type type) { const auto& type_str_table = TypeStringTable(); const auto pair_iter = std::find_if(type_str_table.begin(), type_str_table.end(), [type](const std::pair<StringPiece, Type>& elem) { return type == elem.second; }); assert(pair_iter != type_str_table.end()); return pair_iter->first; } } // namespace namespace effcee { int Check::Part::CountCapturingGroups() { if (type_ == Type::Regex) return RE2(param_).NumberOfCapturingGroups(); if (type_ == Type::VarDef) return RE2(expression_).NumberOfCapturingGroups(); return 0; } Check::Check(Type type, StringPiece param) : type_(type), param_(param) { parts_.push_back(make_unique<Check::Part>(Part::Type::Fixed, param)); } bool Check::Part::MightMatch(const VarMapping& vars) const { return type_ != Type::VarUse || vars.find(VarUseName().as_string()) != vars.end(); } std::string Check::Part::Regex(const VarMapping& vars) const { switch (type_) { case Type::Fixed: return RE2::QuoteMeta(param_); case Type::Regex: return param_.as_string(); case Type::VarDef: return std::string("(") + expression_.as_string() + ")"; case Type::VarUse: { auto where = vars.find(VarUseName().as_string()); if (where != vars.end()) { // Return the escaped form of the current value of the variable. return RE2::QuoteMeta((*where).second); } else { // The variable is not yet set. Should not get here. return ""; } } } return ""; // Unreachable. But we need to satisfy GCC. } bool Check::Matches(StringPiece* input, StringPiece* captured, VarMapping* vars) const { if (parts_.empty()) return false; for (auto& part : parts_) { if (!part->MightMatch(*vars)) return false; } std::unordered_map<int, std::string> var_def_indices; std::ostringstream consume_regex; int num_captures = 1; // The outer capture. for (auto& part : parts_) { consume_regex << part->Regex(*vars); const auto var_def_name = part->VarDefName(); if (!var_def_name.empty()) { var_def_indices[num_captures++] = var_def_name.as_string(); } num_captures += part->NumCapturingGroups(); } std::unique_ptr<StringPiece[]> captures(new StringPiece[num_captures]); const bool matched = RE2(consume_regex.str()) .Match(*input, 0, input->size(), RE2::UNANCHORED, captures.get(), num_captures); if (matched) { *captured = captures[0]; input->remove_prefix(captured->end() - input->begin()); // Update the variable mapping. for (auto& var_def_index : var_def_indices) { const int index = var_def_index.first; (*vars)[var_def_index.second] = captures[index].as_string(); } } return matched; } std::string Check::Description(const Options& options) const { std::ostringstream out; out << options.prefix() << SuffixForType(type()) << ": " << param(); return out.str(); } namespace { // Returns a parts list for the given pattern. This splits out regular expressions as // delimited by {{ and }}, and also variable uses and definitions. Check::Parts PartsForPattern(StringPiece pattern) { Check::Parts parts; StringPiece fixed, regex, var; using Type = Check::Part::Type; while (!pattern.empty()) { const auto regex_start = pattern.find("{{"); const auto regex_end = pattern.find("}}"); const auto var_start = pattern.find("[["); const auto var_end = pattern.find("]]"); const bool regex_exists = regex_start < regex_end && regex_end < StringPiece::npos; const bool var_exists = var_start < var_end && var_end < StringPiece::npos; if (regex_exists && (!var_exists || regex_start < var_start)) { const auto consumed = RE2::Consume(&pattern, "(.*?){{(.*?)}}", &fixed, &regex); if (!consumed) { assert(consumed && "Did not make forward progress for regex in check rule"); } if (!fixed.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Fixed, fixed)); } if (!regex.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Regex, regex)); } } else if (var_exists && (!regex_exists || var_start < regex_start)) { const auto consumed = RE2::Consume(&pattern, "(.*?)\\[\\[(.*?)\\]\\]", &fixed, &var); if (!consumed) { assert(consumed && "Did not make forward progress for var in check rule"); } if (!fixed.empty()) { parts.emplace_back(make_unique<Check::Part>(Type::Fixed, fixed)); } if (!var.empty()) { auto colon = var.find(":"); // A colon at the end is useless anyway, so just make it a variable // use. if (colon == StringPiece::npos || colon == var.size() - 1) { parts.emplace_back(make_unique<Check::Part>(Type::VarUse, var)); } else { StringPiece name = var.substr(0, colon); StringPiece expression = var.substr(colon + 1, StringPiece::npos); parts.emplace_back( make_unique<Check::Part>(Type::VarDef, var, name, expression)); } } } else { // There is no regex, no var def, no var use. Must be a fixed string. parts.push_back(make_unique<Check::Part>(Type::Fixed, pattern)); break; } } return parts; } } // anonymous std::pair<Result, CheckList> ParseChecks(StringPiece str, const Options& options) { // Returns a pair whose first member is a result constructed from the // given status and message, and the second member is an empy pattern. auto failure = [](Status status, StringPiece message) { return std::make_pair(Result(status, message), CheckList{}); }; if (options.prefix().size() == 0) return failure(Status::BadOption, "Rule prefix is empty"); if (RE2::FullMatch(options.prefix(), "\\s+")) return failure(Status::BadOption, "Rule prefix is whitespace. That's silly."); CheckList check_list; const auto quoted_prefix = RE2::QuoteMeta(options.prefix()); // Match the following parts: // .*? - Text that is not the rule prefix // quoted_prefix - A Simple Check prefix // (-NEXT|-SAME)? - An optional check type suffix. Two shown here. // : - Colon // \s* - Whitespace // (.*?) - Captured parameter // \s* - Whitespace // $ - End of line const RE2 regexp(std::string(".*?") + quoted_prefix + "(-NEXT|-SAME|-DAG|-LABEL|-NOT)?" ":\\s*(.*?)\\s*$"); Cursor cursor(str); while (!cursor.Exhausted()) { const auto line = cursor.RestOfLine(); StringPiece matched_param; StringPiece suffix; if (RE2::PartialMatch(line, regexp, &suffix, &matched_param)) { const Type type = TypeForSuffix(suffix); auto parts(PartsForPattern(matched_param)); check_list.push_back(Check(type, matched_param, std::move(parts))); } cursor.AdvanceLine(); } if (check_list.empty()) { return failure( Status::NoRules, std::string("No check rules specified. Looking for prefix ") + options.prefix()); } if (check_list[0].type() == Type::Same) { return failure(Status::BadRule, std::string(options.prefix()) + "-SAME can't be the first check rule"); } return std::make_pair(Result(Result::Status::Ok), check_list); } } // namespace effcee <|endoftext|>
<commit_before>/************************************************************************* * * Copyright (c) 2016 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #include "test_global.hpp" #define MDDS_MULTI_TYPE_VECTOR_DEBUG 1 #include <mdds/multi_type_vector.hpp> #include <mdds/multi_type_vector_trait.hpp> #include <mdds/multi_type_vector/side_iterator.hpp> #include <iostream> #include <vector> #include <memory> using namespace std; using namespace mdds; typedef multi_type_vector<mtv::element_block_func> mtv_type; typedef mtv::side_iterator<mtv_type> side_iterator_type; typedef mtv::collection<mtv_type> cols_type; void mtv_test_pointer_size1() { stack_printer __stack_printer__("::mtv_test_pointer_size1"); // Two vectors of size 1, both of which are totally empty. vector<mtv_type*> vectors; for (size_t i = 0; i < 2; ++i) vectors.push_back(new mtv_type(1)); cols_type collection(vectors.begin(), vectors.end()); cols_type::const_iterator it = collection.begin(), ite = collection.end(); assert(it->type == mtv::element_type_empty); assert(it->index == 0); ++it; assert(it->type == mtv::element_type_empty); assert(it->index == 1); assert(++it == ite); for_each(vectors.begin(), vectors.end(), [](const mtv_type* p) { delete p; }); } void mtv_test_unique_pointer_size1() { stack_printer __stack_printer__("::mtv_test_unique_pointer_size1"); // Two vector of size 1, with empty and numeric values. vector<unique_ptr<mtv_type>> vectors; for (size_t i = 0; i < 2; ++i) vectors.push_back(mdds::make_unique<mtv_type>(1)); vectors[1]->set(0, 1.1); cols_type collection(vectors.begin(), vectors.end()); cols_type::const_iterator it = collection.begin(), ite = collection.end(); assert((*it).type == mtv::element_type_empty); assert((*it).index == 0); ++it; assert((*it).type == mtv::element_type_numeric); assert((*it).index == 1); assert(it->get<mtv::numeric_element_block>() == 1.1); assert(++it == ite); } void mtv_test_shared_pointer_size2() { stack_printer __stack_printer__("::mtv_test_unique_pointer_size1"); vector<shared_ptr<mtv_type>> vectors; vectors.push_back(make_shared<mtv_type>(2, 2.3)); vectors.push_back(make_shared<mtv_type>(2, std::string("test"))); cols_type collection(vectors.begin(), vectors.end()); assert(collection.size() == 2); cols_type::const_iterator it = collection.begin(); assert(it->type == mtv::element_type_numeric); assert(it->index == 0); assert(it->position == 0); assert(it->get<mtv::numeric_element_block>() == 2.3); ++it; assert(it->type == mtv::element_type_string); assert(it->index == 1); assert(it->position == 0); assert(it->get<mtv::string_element_block>() == "test"); ++it; assert(it->type == mtv::element_type_numeric); assert(it->index == 0); assert(it->position == 1); assert(it->get<mtv::numeric_element_block>() == 2.3); ++it; assert(it->type == mtv::element_type_string); assert(it->index == 1); assert(it->position == 1); assert(it->get<mtv::string_element_block>() == "test"); assert(++it == collection.end()); } void mtv_test_non_pointer_size1() { stack_printer __stack_printer__("::mtv_test_non_pointer_size1"); vector<mtv_type> vectors; vectors.reserve(2); vectors.emplace_back(1); vectors.emplace_back(1); cols_type collection(vectors.begin(), vectors.end()); } int main (int argc, char **argv) { try { mtv_test_pointer_size1(); mtv_test_unique_pointer_size1(); mtv_test_shared_pointer_size2(); mtv_test_non_pointer_size1(); } catch (const std::exception& e) { cout << "Test failed: " << e.what() << endl; return EXIT_FAILURE; } cout << "Test finished successfully!" << endl; return EXIT_SUCCESS; } <commit_msg>Test 1 by 1 grid.<commit_after>/************************************************************************* * * Copyright (c) 2016 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #include "test_global.hpp" #define MDDS_MULTI_TYPE_VECTOR_DEBUG 1 #include <mdds/multi_type_vector.hpp> #include <mdds/multi_type_vector_trait.hpp> #include <mdds/multi_type_vector/side_iterator.hpp> #include <iostream> #include <vector> #include <memory> using namespace std; using namespace mdds; typedef multi_type_vector<mtv::element_block_func> mtv_type; typedef mtv::side_iterator<mtv_type> side_iterator_type; typedef mtv::collection<mtv_type> cols_type; void mtv_test_pointer_size1() { stack_printer __stack_printer__("::mtv_test_pointer_size1"); // Two vectors of size 1, both of which are totally empty. vector<mtv_type*> vectors; for (size_t i = 0; i < 2; ++i) vectors.push_back(new mtv_type(1)); cols_type collection(vectors.begin(), vectors.end()); cols_type::const_iterator it = collection.begin(), ite = collection.end(); assert(it->type == mtv::element_type_empty); assert(it->index == 0); ++it; assert(it->type == mtv::element_type_empty); assert(it->index == 1); assert(++it == ite); for_each(vectors.begin(), vectors.end(), [](const mtv_type* p) { delete p; }); } void mtv_test_unique_pointer_size1() { stack_printer __stack_printer__("::mtv_test_unique_pointer_size1"); // Two vector of size 1, with empty and numeric values. vector<unique_ptr<mtv_type>> vectors; for (size_t i = 0; i < 2; ++i) vectors.push_back(mdds::make_unique<mtv_type>(1)); vectors[1]->set(0, 1.1); cols_type collection(vectors.begin(), vectors.end()); cols_type::const_iterator it = collection.begin(), ite = collection.end(); assert((*it).type == mtv::element_type_empty); assert((*it).index == 0); ++it; assert((*it).type == mtv::element_type_numeric); assert((*it).index == 1); assert(it->get<mtv::numeric_element_block>() == 1.1); assert(++it == ite); } void mtv_test_shared_pointer_size2() { stack_printer __stack_printer__("::mtv_test_unique_pointer_size1"); vector<shared_ptr<mtv_type>> vectors; vectors.push_back(make_shared<mtv_type>(2, 2.3)); vectors.push_back(make_shared<mtv_type>(2, std::string("test"))); cols_type collection(vectors.begin(), vectors.end()); assert(collection.size() == 2); cols_type::const_iterator it = collection.begin(); assert(it->type == mtv::element_type_numeric); assert(it->index == 0); assert(it->position == 0); assert(it->get<mtv::numeric_element_block>() == 2.3); ++it; assert(it->type == mtv::element_type_string); assert(it->index == 1); assert(it->position == 0); assert(it->get<mtv::string_element_block>() == "test"); ++it; assert(it->type == mtv::element_type_numeric); assert(it->index == 0); assert(it->position == 1); assert(it->get<mtv::numeric_element_block>() == 2.3); ++it; assert(it->type == mtv::element_type_string); assert(it->index == 1); assert(it->position == 1); assert(it->get<mtv::string_element_block>() == "test"); assert(++it == collection.end()); } void mtv_test_non_pointer_size1() { stack_printer __stack_printer__("::mtv_test_non_pointer_size1"); // Test 1 by 1 grid. vector<mtv_type> vectors; vectors.reserve(1); vectors.emplace_back(1, char('c')); cols_type collection(vectors.begin(), vectors.end()); assert(collection.size() == 1); auto it = collection.begin(); assert(it->type == mtv::element_type_char); assert(it->index == 0); assert(it->position == 0); assert(it->get<mtv::char_element_block>() == 'c'); assert(++it == collection.end()); } int main (int argc, char **argv) { try { mtv_test_pointer_size1(); mtv_test_unique_pointer_size1(); mtv_test_shared_pointer_size2(); mtv_test_non_pointer_size1(); } catch (const std::exception& e) { cout << "Test failed: " << e.what() << endl; return EXIT_FAILURE; } cout << "Test finished successfully!" << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file rawdelegate.cpp * @author Florian Schlembach <florian.schlembach@tu-ilmenau.de>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * Jens Haueisen <jens.haueisen@tu-ilmenau.de> * @version 1.0 * @date January, 2014 * * @section LICENSE * * Copyright (C) 2014, Florian Schlembach, Christoph Dinh, Matti Hamalainen and Jens Haueisen. 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 Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Implementation of delegate of mne_browse_raw_qt * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "rawdelegate.h" //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QBrush> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNEBrowseRawQt; using namespace Eigen; using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RawDelegate::RawDelegate(QObject *parent) : QAbstractItemDelegate(parent) , m_qSettings() { m_dDefaultPlotHeight = m_qSettings.value("RawDelegate/plotheight").toDouble(); m_dDx = m_qSettings.value("RawDelegate/dx").toDouble(); m_nhlines = m_qSettings.value("RawDelegate/nhlines").toDouble(); } //************************************************************************************************************* void RawDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad QVariant v = index.model()->data(index,Qt::BackgroundRole); if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin(option.rect.topLeft()); painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); painter->setBrushOrigin(oldBO); } //Highlight selected channels if(option.state & QStyle::State_Selected) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin(option.rect.topLeft()); painter->fillRect(option.rect, option.palette.highlight()); painter->setBrushOrigin(oldBO); } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); QList<RowVectorPair> listPairs = variant.value<QList<RowVectorPair> >(); const RawModel* t_rawModel = (static_cast<const RawModel*>(index.model())); QPainterPath path(QPointF(option.rect.x()+t_rawModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(path,option,listPairs); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x()+t_rawModel->relFiffCursor(),option.rect.y())); createPlotPath(index, option, path, listPairs); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); painter->drawPath(path); painter->restore(); break; } } } //************************************************************************************************************* QSize RawDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: QList<RowVectorPair> listPairs = index.model()->data(index).value<QList<RowVectorPair> >(); qint32 nsamples = (static_cast<const RawModel*>(index.model()))->lastSample()-(static_cast<const RawModel*>(index.model()))->firstSample(); size = QSize(nsamples*m_dDx,option.rect.height()); break; } Q_UNUSED(option); return size; } //************************************************************************************************************* void RawDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList<RowVectorPair>& listPairs) const { //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value) qint32 kind = (static_cast<const RawModel*>(index.model()))->m_chInfolist[index.row()].kind; double dMaxValue = 1e-9; switch(kind) { case FIFFV_MEG_CH: { qint32 unit = (static_cast<const RawModel*>(index.model()))->m_pfiffIO->m_qlistRaw[0]->info.chs[index.row()].unit; if(unit == FIFF_UNIT_T_M) { dMaxValue = m_qSettings.value("RawDelegate/max_meg_grad").toDouble(); } else if(unit == FIFF_UNIT_T) dMaxValue = m_qSettings.value("RawDelegate/max_meg_mag").toDouble(); break; } case FIFFV_EEG_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_eeg").toDouble(); break; } case FIFFV_EOG_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_eog").toDouble(); break; } case FIFFV_STIM_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_stim").toDouble(); break; } } double dValue; double dScaleY = option.rect.height()/(2*dMaxValue); double y_base = path.currentPosition().y(); QPointF qSamplePosition; //plot all rows from list of pairs for(qint8 i=0; i < listPairs.size(); ++i) { //create lines from one to the next sample for(qint32 j=0; j < listPairs[i].second; ++j) { double val = *(listPairs[i].first+j); dValue = val*dScaleY; double newY = y_base+dValue; qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()+m_dDx); path.lineTo(qSamplePosition); } } // qDebug("Plot-PainterPath created!"); } //************************************************************************************************************* void RawDelegate::createGridPath(QPainterPath& path, const QStyleOptionViewItem &option, QList<RowVectorPair>& listPairs) const { //horizontal lines double distance = option.rect.height()/m_nhlines; QPointF startpos = path.currentPosition(); QPointF endpoint(path.currentPosition().x()+listPairs[0].second*listPairs.size()*m_dDx,path.currentPosition().y()); for(qint8 i=0; i < m_nhlines-1; ++i) { endpoint.setY(endpoint.y()+distance); path.moveTo(startpos.x(),endpoint.y()); path.lineTo(endpoint); } // qDebug("Grid-PainterPath created!"); } <commit_msg>- plotting first lines into raw model view<commit_after>//============================================================================================================= /** * @file rawdelegate.cpp * @author Florian Schlembach <florian.schlembach@tu-ilmenau.de>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * Jens Haueisen <jens.haueisen@tu-ilmenau.de> * @version 1.0 * @date January, 2014 * * @section LICENSE * * Copyright (C) 2014, Florian Schlembach, Christoph Dinh, Matti Hamalainen and Jens Haueisen. 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 Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Implementation of delegate of mne_browse_raw_qt * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "rawdelegate.h" //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QBrush> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNEBrowseRawQt; using namespace Eigen; using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RawDelegate::RawDelegate(QObject *parent) : QAbstractItemDelegate(parent) , m_qSettings() { m_dDefaultPlotHeight = m_qSettings.value("RawDelegate/plotheight").toDouble(); m_dDx = m_qSettings.value("RawDelegate/dx").toDouble(); m_nhlines = m_qSettings.value("RawDelegate/nhlines").toDouble(); } //************************************************************************************************************* void RawDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad QVariant v = index.model()->data(index,Qt::BackgroundRole); if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin(option.rect.topLeft()); painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); painter->setBrushOrigin(oldBO); } //Highlight selected channels if(option.state & QStyle::State_Selected) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin(option.rect.topLeft()); painter->fillRect(option.rect, option.palette.highlight()); painter->setBrushOrigin(oldBO); } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); QList<RowVectorPair> listPairs = variant.value<QList<RowVectorPair> >(); const RawModel* t_rawModel = (static_cast<const RawModel*>(index.model())); QPainterPath path(QPointF(option.rect.x()+t_rawModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(path,option,listPairs); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x()+t_rawModel->relFiffCursor(),option.rect.y())); createPlotPath(index, option, path, listPairs); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); painter->drawPath(path); painter->restore(); break; } } } //************************************************************************************************************* QSize RawDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: QList<RowVectorPair> listPairs = index.model()->data(index).value<QList<RowVectorPair> >(); qint32 nsamples = (static_cast<const RawModel*>(index.model()))->lastSample()-(static_cast<const RawModel*>(index.model()))->firstSample(); size = QSize(nsamples*m_dDx,option.rect.height()); break; } Q_UNUSED(option); return size; } //************************************************************************************************************* void RawDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList<RowVectorPair>& listPairs) const { //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value) qint32 kind = (static_cast<const RawModel*>(index.model()))->m_chInfolist[index.row()].kind; double dMaxValue = 1e-9; switch(kind) { case FIFFV_MEG_CH: { qint32 unit = (static_cast<const RawModel*>(index.model()))->m_pfiffIO->m_qlistRaw[0]->info.chs[index.row()].unit; if(unit == FIFF_UNIT_T_M) { dMaxValue = m_qSettings.value("RawDelegate/max_meg_grad").toDouble(); } else if(unit == FIFF_UNIT_T) dMaxValue = m_qSettings.value("RawDelegate/max_meg_mag").toDouble(); break; } case FIFFV_EEG_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_eeg").toDouble(); break; } case FIFFV_EOG_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_eog").toDouble(); break; } case FIFFV_STIM_CH: { dMaxValue = m_qSettings.value("RawDelegate/max_stim").toDouble(); break; } } double dValue; double dScaleY = option.rect.height()/(2*dMaxValue); double y_base = path.currentPosition().y(); QPointF qSamplePosition; //plot all rows from list of pairs int counter = 0; for(qint8 i=0; i < listPairs.size(); ++i) { //create lines from one to the next sample for(qint32 j=0; j < listPairs[i].second; ++j) { //If event add line if(counter == 40) { path.addRect(path.currentPosition().x(),option.rect.y(),1,option.rect.height()); counter = 0; } counter++; double val = *(listPairs[i].first+j); dValue = val*dScaleY; double newY = y_base+dValue; qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()+m_dDx); path.lineTo(qSamplePosition); } } // qDebug("Plot-PainterPath created!"); } //************************************************************************************************************* void RawDelegate::createGridPath(QPainterPath& path, const QStyleOptionViewItem &option, QList<RowVectorPair>& listPairs) const { //horizontal lines double distance = option.rect.height()/m_nhlines; QPointF startpos = path.currentPosition(); QPointF endpoint(path.currentPosition().x()+listPairs[0].second*listPairs.size()*m_dDx,path.currentPosition().y()); for(qint8 i=0; i < m_nhlines-1; ++i) { endpoint.setY(endpoint.y()+distance); path.moveTo(startpos.x(),endpoint.y()); path.lineTo(endpoint); } // qDebug("Grid-PainterPath created!"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "truepeakdetector.h" #include "essentiamath.h" using namespace essentia; using namespace standard; using namespace std; const char* TruePeakDetector::name = "TruePeakDetector"; const char* TruePeakDetector::category = "Audio Problems"; const char* TruePeakDetector::description = DOC("This algorithm implements the “true-peak” level meter as descripted " "in the second annex of the ITU-R BS.1770-2[1] or ITU-R BS.1770-4[2] (by default)\n" "\n" "Note: the parameters 'blockDC' and 'emphatise' only work on 'version' 2." "\n" "References:\n" " [1] Series, B. S. (2011). Recommendation ITU-R BS.1770-2. Algorithms to measure audio programme " "loudness and true-peak audio level,\n" " " "https://www.itu.int/dms_pubrec/itu-r/rec/bs/" "R-REC-BS.1770-2-201103-S!!PDF-E.pdfe\n" " [2] Series, B. S. (2011). Recommendation ITU-R BS.1770-4. Algorithms to measure audio programme " "loudness and true-peak audio level,\n" " " "https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1770-4-201510-I!!PDF-E.pdf\n"); void TruePeakDetector::configure() { _inputSampleRate = parameter("sampleRate").toReal(); _oversamplingFactor = parameter("oversamplingFactor").toReal(); _outputSampleRate = _inputSampleRate * _oversamplingFactor; _quality = parameter("quality").toInt(); _blockDC = parameter("blockDC").toBool(); _emphatise = parameter("emphatise").toBool(); _threshold = db2amp(parameter("threshold").toFloat()); _version = parameter("version").toInt(); _resampler->configure("inputSampleRate", _inputSampleRate, "outputSampleRate", _outputSampleRate, "quality", _quality); if (_emphatise) { // the parameters of the filter are extracted in the recommendation Real poleFrequency = 20e3; // Hz Real zeroFrequncy = 14.1e3; // Hz Real rPole = 1 - 4 * poleFrequency / _outputSampleRate; Real rZero = 1 - 4 * zeroFrequncy / _outputSampleRate; vector<Real> b(2, 0.0); b[0] = 1.0; b[1] = -rZero; vector<Real> a(2, 0.0); a[0] = 1.0; a[1] = rPole; _emphatiser->configure( "numerator", b, "denominator", a); } if (_blockDC) { _dcBlocker->configure("sampleRate", _outputSampleRate); } } void TruePeakDetector::compute() { vector<Real>& output = _output.get(); vector<Real>& peakLocations = _peakLocations.get(); std::vector<Real> *processed; std::vector<Real> resampled; _resampler->input("signal").set(_signal.get()); _resampler->output("signal").set(resampled); _resampler->compute(); processed = &resampled; if (_version == 2) { if (_emphatise) { std::vector<Real> emphatised; _emphatiser->input("signal").set(*processed); _emphatiser->output("signal").set(emphatised); _emphatiser->compute(); processed = &emphatised; } if (_blockDC) { std::vector<Real> dcBlocked; _dcBlocker->input("signal").set(*processed); _dcBlocker->output("signal").set(dcBlocked); _dcBlocker->compute(); for (uint i = 0; i < processed->size(); i++) (*processed)[i] = max(abs((*processed)[i]), abs(dcBlocked[i])); } else rectify((*processed)); for (uint i = 0; i < processed->size(); i++) if ((*processed)[i] >= _threshold) peakLocations.push_back((int) (i / _oversamplingFactor)); output = *processed; } if (_version == 4) { rectify((*processed)); } } <commit_msg>TruePeakDetector: fixed bug in version 4 and improved doc<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "truepeakdetector.h" #include "essentiamath.h" using namespace essentia; using namespace standard; using namespace std; const char* TruePeakDetector::name = "TruePeakDetector"; const char* TruePeakDetector::category = "Audio Problems"; const char* TruePeakDetector::description = DOC("This algorithm implements the “true-peak” level meter as descripted " "in the second annex of the ITU-R BS.1770-2[1] or the ITU-R BS.1770-4[2] (default)\n" "\n" "Note: the parameters 'blockDC' and 'emphatise' work only when 'version' is set to 2." "\n" "References:\n" " [1] Series, B. S. (2011). Recommendation ITU-R BS.1770-2. Algorithms to measure audio programme " "loudness and true-peak audio level,\n" " " "https://www.itu.int/dms_pubrec/itu-r/rec/bs/" "R-REC-BS.1770-2-201103-S!!PDF-E.pdfe\n" " [2] Series, B. S. (2011). Recommendation ITU-R BS.1770-4. Algorithms to measure audio programme " "loudness and true-peak audio level,\n" " " "https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1770-4-201510-I!!PDF-E.pdf\n"); void TruePeakDetector::configure() { _inputSampleRate = parameter("sampleRate").toReal(); _oversamplingFactor = parameter("oversamplingFactor").toReal(); _outputSampleRate = _inputSampleRate * _oversamplingFactor; _quality = parameter("quality").toInt(); _blockDC = parameter("blockDC").toBool(); _emphatise = parameter("emphatise").toBool(); _threshold = db2amp(parameter("threshold").toFloat()); _version = parameter("version").toInt(); _resampler->configure("inputSampleRate", _inputSampleRate, "outputSampleRate", _outputSampleRate, "quality", _quality); if (_emphatise) { // the parameters of the filter are extracted in the recommendation Real poleFrequency = 20e3; // Hz Real zeroFrequncy = 14.1e3; // Hz Real rPole = 1 - 4 * poleFrequency / _outputSampleRate; Real rZero = 1 - 4 * zeroFrequncy / _outputSampleRate; vector<Real> b(2, 0.0); b[0] = 1.0; b[1] = -rZero; vector<Real> a(2, 0.0); a[0] = 1.0; a[1] = rPole; _emphatiser->configure( "numerator", b, "denominator", a); } if (_blockDC) { _dcBlocker->configure("sampleRate", _outputSampleRate); } } void TruePeakDetector::compute() { vector<Real>& output = _output.get(); vector<Real>& peakLocations = _peakLocations.get(); std::vector<Real> *processed; std::vector<Real> resampled; _resampler->input("signal").set(_signal.get()); _resampler->output("signal").set(resampled); _resampler->compute(); processed = &resampled; if (_version == 2) { if (_emphatise) { std::vector<Real> emphatised; _emphatiser->input("signal").set(*processed); _emphatiser->output("signal").set(emphatised); _emphatiser->compute(); processed = &emphatised; } if (_blockDC) { std::vector<Real> dcBlocked; _dcBlocker->input("signal").set(*processed); _dcBlocker->output("signal").set(dcBlocked); _dcBlocker->compute(); for (uint i = 0; i < processed->size(); i++) (*processed)[i] = max(abs((*processed)[i]), abs(dcBlocked[i])); } } if ((_version == 4) || (!_blockDC)) rectify((*processed)); for (uint i = 0; i < processed->size(); i++) if ((*processed)[i] >= _threshold) peakLocations.push_back((int) (i / _oversamplingFactor)); output = *processed; } <|endoftext|>
<commit_before>#ifndef _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #define _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #include <deque> #include <memory> // shared_ptr #include <unordered_map> #include <vector> #include "sdd/order/strategies/force_hyperedge.hh" #include "sdd/order/strategies/force_vertex.hh" namespace sdd { namespace force { /*------------------------------------------------------------------------------------------------*/ /// @brief Represent the connections between the identifiers. template <typename C> class hypergraph { public: /// @brief The user identifier type. using identifier_type = typename C::Identifier; private: /// @brief An hypergraph's vertex. using vertex_type = vertex<identifier_type>; /// @brief An hypergraph's hyperedge. using hyperedge_type = hyperedge<identifier_type>; /// @brief All the vertices of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<vertex_type>> vertices_ptr_; /// @brief All the hyperedges of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<hyperedge_type>> hyperedges_ptr_; /// @brief Map identifiers to vertices. /// /// Enable fast retrieval of a vertex's address. std::shared_ptr<std::unordered_map<identifier_type, vertex_type*>> id_to_vertex_ptr_; public: /// @brief Default constructor. template <typename InputIterator> hypergraph(InputIterator it, InputIterator end) : vertices_ptr_(std::make_shared<std::deque<vertex_type>>()) , hyperedges_ptr_(std::make_shared<std::deque<hyperedge_type>>()) , id_to_vertex_ptr_(std::make_shared<std::unordered_map<identifier_type, vertex_type*>>()) { static double location = 0; assert(it != end); for (; it != end; ++it) { vertices_ptr_->emplace_back(*it, location++); const auto insertion = id_to_vertex_ptr_->emplace(*it, &vertices_ptr_->back()); if (not insertion.second) { std::stringstream ss; ss << "Identifier " << *it << " appears twice."; throw std::runtime_error(ss.str()); } } assert(id_to_vertex_ptr_->size() != 0); } /// @brief Add a new hyperedge with a set of identifiers. template <typename InputIterator> void add_hyperedge(InputIterator it, InputIterator end) { if (it == end) { return; } // Create, if necessary all connected vertices. std::vector<vertex_type*> vertices; vertices.reserve(std::distance(it, end)); for (; it != end; ++it) { const auto search = id_to_vertex_ptr_->find(*it); assert(search != id_to_vertex_ptr_->end()); vertices.emplace_back(search->second); } assert(vertices.size() != 0); // Create the new hyperedge. hyperedges_ptr_->emplace_back(std::move(vertices)); // Update connected vertices. assert(hyperedges_ptr_->back().vertices().size() != 0); for (auto vertex_ptr : hyperedges_ptr_->back().vertices()) { assert(vertex_ptr != nullptr); vertex_ptr->hyperedges().emplace_back(&hyperedges_ptr_->back()); } } /// @internal std::deque<vertex_type>& vertices() noexcept { return *vertices_ptr_; } /// @internal const std::deque<vertex_type>& vertices() const noexcept { return *vertices_ptr_; } /// @internal std::deque<hyperedge_type>& hyperedges() noexcept { return *hyperedges_ptr_; } /// @internal const std::deque<hyperedge_type>& hyperedges() const noexcept { return *hyperedges_ptr_; } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::force #endif // _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ <commit_msg>Fix missing #include.<commit_after>#ifndef _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #define _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #include <deque> #include <memory> // shared_ptr #include <sstream> #include <unordered_map> #include <vector> #include "sdd/order/strategies/force_hyperedge.hh" #include "sdd/order/strategies/force_vertex.hh" namespace sdd { namespace force { /*------------------------------------------------------------------------------------------------*/ /// @brief Represent the connections between the identifiers. template <typename C> class hypergraph { public: /// @brief The user identifier type. using identifier_type = typename C::Identifier; private: /// @brief An hypergraph's vertex. using vertex_type = vertex<identifier_type>; /// @brief An hypergraph's hyperedge. using hyperedge_type = hyperedge<identifier_type>; /// @brief All the vertices of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<vertex_type>> vertices_ptr_; /// @brief All the hyperedges of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<hyperedge_type>> hyperedges_ptr_; /// @brief Map identifiers to vertices. /// /// Enable fast retrieval of a vertex's address. std::shared_ptr<std::unordered_map<identifier_type, vertex_type*>> id_to_vertex_ptr_; public: /// @brief Default constructor. template <typename InputIterator> hypergraph(InputIterator it, InputIterator end) : vertices_ptr_(std::make_shared<std::deque<vertex_type>>()) , hyperedges_ptr_(std::make_shared<std::deque<hyperedge_type>>()) , id_to_vertex_ptr_(std::make_shared<std::unordered_map<identifier_type, vertex_type*>>()) { static double location = 0; assert(it != end); for (; it != end; ++it) { vertices_ptr_->emplace_back(*it, location++); const auto insertion = id_to_vertex_ptr_->emplace(*it, &vertices_ptr_->back()); if (not insertion.second) { std::stringstream ss; ss << "Identifier " << *it << " appears twice."; throw std::runtime_error(ss.str()); } } assert(id_to_vertex_ptr_->size() != 0); } /// @brief Add a new hyperedge with a set of identifiers. template <typename InputIterator> void add_hyperedge(InputIterator it, InputIterator end) { if (it == end) { return; } // Create, if necessary all connected vertices. std::vector<vertex_type*> vertices; vertices.reserve(std::distance(it, end)); for (; it != end; ++it) { const auto search = id_to_vertex_ptr_->find(*it); assert(search != id_to_vertex_ptr_->end()); vertices.emplace_back(search->second); } assert(vertices.size() != 0); // Create the new hyperedge. hyperedges_ptr_->emplace_back(std::move(vertices)); // Update connected vertices. assert(hyperedges_ptr_->back().vertices().size() != 0); for (auto vertex_ptr : hyperedges_ptr_->back().vertices()) { assert(vertex_ptr != nullptr); vertex_ptr->hyperedges().emplace_back(&hyperedges_ptr_->back()); } } /// @internal std::deque<vertex_type>& vertices() noexcept { return *vertices_ptr_; } /// @internal const std::deque<vertex_type>& vertices() const noexcept { return *vertices_ptr_; } /// @internal std::deque<hyperedge_type>& hyperedges() noexcept { return *hyperedges_ptr_; } /// @internal const std::deque<hyperedge_type>& hyperedges() const noexcept { return *hyperedges_ptr_; } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::force #endif // _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TableFieldDescription.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: oj $ $Date: 2002-08-30 11:08:26 $ * * 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 DBAUI_TABLEFIELDDESC_HXX #define DBAUI_TABLEFIELDDESC_HXX #ifndef INCLUDED_VECTOR #define INCLUDED_VECTOR #include <vector> #endif #ifndef DBAUI_ENUMTYPES_HXX #include "QEnumTypes.hxx" #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_ #include <com/sun/star/io/XObjectOutputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_ #include <com/sun/star/io/XObjectInputStream.hpp> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif class Window; namespace dbaui { class OTableFieldDesc : public ::vos::OReference { private: ::std::vector< ::rtl::OUString> m_vecCriteria; ::rtl::OUString m_aTableName; ::rtl::OUString m_aAliasName; // table range ::rtl::OUString m_aFieldName; // column ::rtl::OUString m_aFieldAlias; // column alias ::rtl::OUString m_aDatabaseName; // qualifier or catalog ::rtl::OUString m_aFunctionName; // enth"alt den Funktionsnamen, nur wenn m_eFunctionType != FKT_NONE gesetzt Window* m_pTabWindow; sal_Int32 m_eDataType; sal_Int32 m_eFunctionType; ETableFieldType m_eFieldType; EOrderDir m_eOrderDir; sal_Int32 m_nIndex; sal_Int32 m_nColWidth; sal_uInt16 m_nColumnId; sal_Bool m_bGroupBy; sal_Bool m_bVisible; // !!!! bitte bei Erweiterung um neue Felder auch IsEmpty mitpflegen !!!! public: OTableFieldDesc(); OTableFieldDesc(const ::rtl::OUString& rTable, const ::rtl::OUString& rField ); OTableFieldDesc(const OTableFieldDesc& rRS); ~OTableFieldDesc(); inline sal_Bool IsEmpty() const; sal_Bool operator==( const OTableFieldDesc& rDesc ); void clear(); sal_Bool IsVisible() const { return m_bVisible;} sal_Bool IsNumericDataType() const; sal_Bool IsGroupBy() const { return m_bGroupBy;} void SetVisible( sal_Bool bVis=sal_True ){ m_bVisible = bVis;} void SetGroupBy( sal_Bool bGb=sal_False ){ m_bGroupBy = bGb;} void SetTabWindow( Window* pWin ){ m_pTabWindow = pWin;} void SetField( const ::rtl::OUString& rF ){ m_aFieldName = rF;} void SetFieldAlias( const ::rtl::OUString& rF ){ m_aFieldAlias = rF;} void SetTable( const ::rtl::OUString& rT ){ m_aTableName = rT;} void SetAlias( const ::rtl::OUString& rT ){ m_aAliasName = rT;} void SetDatabase( const ::rtl::OUString& rT ) { m_aDatabaseName = rT;} void SetFunction( const ::rtl::OUString& rT ) { m_aFunctionName = rT;} void SetOrderDir( EOrderDir eDir ) { m_eOrderDir = eDir; } void SetDataType( sal_Int32 eTyp ) { m_eDataType = eTyp; } void SetFieldType( ETableFieldType eTyp ) { m_eFieldType = eTyp; } void SetCriteria( sal_uInt16 nIdx, const ::rtl::OUString& rCrit); void SetColWidth( sal_Int32 nWidth ) { m_nColWidth = nWidth; } void SetFieldIndex( sal_Int32 nFieldIndex ) { m_nIndex = nFieldIndex; } void SetFunctionType( sal_Int32 eTyp ) { m_eFunctionType = eTyp; } void SetColumnId(sal_uInt16 _nColumnId) { m_nColumnId = _nColumnId; } ::rtl::OUString GetField() const { return m_aFieldName;} ::rtl::OUString GetFieldAlias() const { return m_aFieldAlias;} ::rtl::OUString GetTable() const { return m_aTableName;} ::rtl::OUString GetAlias() const { return m_aAliasName;} ::rtl::OUString GetDatabase() const { return m_aDatabaseName;} ::rtl::OUString GetFunction() const { return m_aFunctionName;} sal_Int32 GetDataType() const { return m_eDataType; } ETableFieldType GetFieldType() const { return m_eFieldType; } EOrderDir GetOrderDir() const { return m_eOrderDir; } ::rtl::OUString GetCriteria( sal_uInt16 nIdx ) const; sal_Int32 GetColWidth() const { return m_nColWidth; } sal_Int32 GetFieldIndex() const { return m_nIndex; } Window* GetTabWindow() const { return m_pTabWindow;} sal_Int32 GetFunctionType() const { return m_eFunctionType; } sal_uInt16 GetColumnId() const { return m_nColumnId;} inline sal_Bool isAggreateFunction() const { return (m_eFunctionType & FKT_AGGREGATE) == FKT_AGGREGATE; } inline sal_Bool isOtherFunction() const { return (m_eFunctionType & FKT_OTHER) == FKT_OTHER; } inline sal_Bool isNumeric() const { return (m_eFunctionType & FKT_NUMERIC) == FKT_NUMERIC; } inline sal_Bool isNoneFunction() const { return m_eFunctionType == FKT_NONE; } inline sal_Bool isCondition() const { return (m_eFunctionType & FKT_CONDITION) == FKT_CONDITION; } inline sal_Bool isNumericOrAggreateFunction() const { return isNumeric() || isAggreateFunction(); } sal_Bool HasCriteria() const { ::std::vector< ::rtl::OUString>::const_iterator aIter = m_vecCriteria.begin(); for(;aIter != m_vecCriteria.end();++aIter) if(aIter->getLength()) break; return aIter != m_vecCriteria.end(); } void NextOrderDir(); const ::std::vector< ::rtl::OUString>& GetCriteria() const { return m_vecCriteria;} void Load(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxIn); void Save(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOut); }; //------------------------------------------------------------------ inline sal_Bool OTableFieldDesc::IsEmpty() const { sal_Bool bEmpty = (!m_aTableName.getLength() && !m_aAliasName.getLength() && !m_aFieldName.getLength() && !m_aFieldAlias.getLength() && !m_aDatabaseName.getLength() && !m_aFunctionName.getLength() && !HasCriteria()); return bEmpty; } //------------------------------------------------------------------ typedef ::vos::ORef< OTableFieldDesc> OTableFieldDescRef; typedef ::std::vector<OTableFieldDescRef> OTableFields; } #endif // <commit_msg>INTEGRATION: CWS insight01 (1.3.106); FILE MERGED 2003/12/17 09:16:04 oj 1.3.106.1: #111075# ongoing work<commit_after>/************************************************************************* * * $RCSfile: TableFieldDescription.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-08-02 15:54:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_TABLEFIELDDESC_HXX #define DBAUI_TABLEFIELDDESC_HXX #ifndef INCLUDED_VECTOR #define INCLUDED_VECTOR #include <vector> #endif #ifndef DBAUI_ENUMTYPES_HXX #include "QEnumTypes.hxx" #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif class Window; namespace dbaui { class OTableFieldDesc : public ::vos::OReference { private: ::std::vector< ::rtl::OUString> m_vecCriteria; ::rtl::OUString m_aTableName; ::rtl::OUString m_aAliasName; // table range ::rtl::OUString m_aFieldName; // column ::rtl::OUString m_aFieldAlias; // column alias ::rtl::OUString m_aDatabaseName; // qualifier or catalog ::rtl::OUString m_aFunctionName; // enth"alt den Funktionsnamen, nur wenn m_eFunctionType != FKT_NONE gesetzt Window* m_pTabWindow; sal_Int32 m_eDataType; sal_Int32 m_eFunctionType; ETableFieldType m_eFieldType; EOrderDir m_eOrderDir; sal_Int32 m_nIndex; sal_Int32 m_nColWidth; sal_uInt16 m_nColumnId; sal_Bool m_bGroupBy; sal_Bool m_bVisible; // !!!! bitte bei Erweiterung um neue Felder auch IsEmpty mitpflegen !!!! public: OTableFieldDesc(); OTableFieldDesc(const ::rtl::OUString& rTable, const ::rtl::OUString& rField ); OTableFieldDesc(const OTableFieldDesc& rRS); ~OTableFieldDesc(); inline sal_Bool IsEmpty() const; sal_Bool operator==( const OTableFieldDesc& rDesc ); void clear(); sal_Bool IsVisible() const { return m_bVisible;} sal_Bool IsNumericDataType() const; sal_Bool IsGroupBy() const { return m_bGroupBy;} void SetVisible( sal_Bool bVis=sal_True ){ m_bVisible = bVis;} void SetGroupBy( sal_Bool bGb=sal_False ){ m_bGroupBy = bGb;} void SetTabWindow( Window* pWin ){ m_pTabWindow = pWin;} void SetField( const ::rtl::OUString& rF ){ m_aFieldName = rF;} void SetFieldAlias( const ::rtl::OUString& rF ){ m_aFieldAlias = rF;} void SetTable( const ::rtl::OUString& rT ){ m_aTableName = rT;} void SetAlias( const ::rtl::OUString& rT ){ m_aAliasName = rT;} void SetDatabase( const ::rtl::OUString& rT ) { m_aDatabaseName = rT;} void SetFunction( const ::rtl::OUString& rT ) { m_aFunctionName = rT;} void SetOrderDir( EOrderDir eDir ) { m_eOrderDir = eDir; } void SetDataType( sal_Int32 eTyp ) { m_eDataType = eTyp; } void SetFieldType( ETableFieldType eTyp ) { m_eFieldType = eTyp; } void SetCriteria( sal_uInt16 nIdx, const ::rtl::OUString& rCrit); void SetColWidth( sal_Int32 nWidth ) { m_nColWidth = nWidth; } void SetFieldIndex( sal_Int32 nFieldIndex ) { m_nIndex = nFieldIndex; } void SetFunctionType( sal_Int32 eTyp ) { m_eFunctionType = eTyp; } void SetColumnId(sal_uInt16 _nColumnId) { m_nColumnId = _nColumnId; } ::rtl::OUString GetField() const { return m_aFieldName;} ::rtl::OUString GetFieldAlias() const { return m_aFieldAlias;} ::rtl::OUString GetTable() const { return m_aTableName;} ::rtl::OUString GetAlias() const { return m_aAliasName;} ::rtl::OUString GetDatabase() const { return m_aDatabaseName;} ::rtl::OUString GetFunction() const { return m_aFunctionName;} sal_Int32 GetDataType() const { return m_eDataType; } ETableFieldType GetFieldType() const { return m_eFieldType; } EOrderDir GetOrderDir() const { return m_eOrderDir; } ::rtl::OUString GetCriteria( sal_uInt16 nIdx ) const; sal_Int32 GetColWidth() const { return m_nColWidth; } sal_Int32 GetFieldIndex() const { return m_nIndex; } Window* GetTabWindow() const { return m_pTabWindow;} sal_Int32 GetFunctionType() const { return m_eFunctionType; } sal_uInt16 GetColumnId() const { return m_nColumnId;} inline sal_Bool isAggreateFunction() const { return (m_eFunctionType & FKT_AGGREGATE) == FKT_AGGREGATE; } inline sal_Bool isOtherFunction() const { return (m_eFunctionType & FKT_OTHER) == FKT_OTHER; } inline sal_Bool isNumeric() const { return (m_eFunctionType & FKT_NUMERIC) == FKT_NUMERIC; } inline sal_Bool isNoneFunction() const { return m_eFunctionType == FKT_NONE; } inline sal_Bool isCondition() const { return (m_eFunctionType & FKT_CONDITION) == FKT_CONDITION; } inline sal_Bool isNumericOrAggreateFunction() const { return isNumeric() || isAggreateFunction(); } sal_Bool HasCriteria() const { ::std::vector< ::rtl::OUString>::const_iterator aIter = m_vecCriteria.begin(); for(;aIter != m_vecCriteria.end();++aIter) if(aIter->getLength()) break; return aIter != m_vecCriteria.end(); } void NextOrderDir(); const ::std::vector< ::rtl::OUString>& GetCriteria() const { return m_vecCriteria;} void Load(const ::com::sun::star::beans::PropertyValue& _rProperty); void Save(::com::sun::star::beans::PropertyValue& _rProperty); }; //------------------------------------------------------------------ inline sal_Bool OTableFieldDesc::IsEmpty() const { sal_Bool bEmpty = (!m_aTableName.getLength() && !m_aAliasName.getLength() && !m_aFieldName.getLength() && !m_aFieldAlias.getLength() && !m_aDatabaseName.getLength() && !m_aFunctionName.getLength() && !HasCriteria()); return bEmpty; } //------------------------------------------------------------------ typedef ::vos::ORef< OTableFieldDesc> OTableFieldDescRef; typedef ::std::vector<OTableFieldDescRef> OTableFields; } #endif // <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Kuzma Shapran <kuzma.shapran@gmail.com> * Luís Pereira <luis.artur.pereira@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "calendar_utils.h" #include "config.h" #include <QtCore/QtGlobal> #if QT_VERSION >= 0x040800 Qt::DayOfWeek firstDayOfWeek(void) { return QLocale::system().firstDayOfWeek(); } #else #ifdef CAN_USE_BOOST #include <boost/locale/date_time.hpp> Qt::DayOfWeek firstDayOfWeek(void) { return (boost::locale::calendar().first_day_of_week() + 6) % 7; } #else // use C #ifdef HAVE__NL_TIME_FIRST_WEEKDAY #include <langinfo.h> #include <QtCore/QDebug> Qt::DayOfWeek firstDayOfWeek(void) { int firstWeekDay; int weekFirstDay = 0; int weekStart; char *locale; long weekFirstDayLong; Q_UNUSED(locale); locale = setlocale(LC_TIME, ""); // firstWeekDay: Specifies the offset of the first day-of-week in the day // list. // weekFirstDay: Some date that corresponds to the beginning of a week. // Specifies the base of the day list. It is (in glibc) either // 19971130 (Sunday) or 19971201 (Monday) firstWeekDay = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0]; weekFirstDayLong = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY); if (weekFirstDayLong == 19971130L) // Sunday { weekFirstDay = 0; } else if (weekFirstDayLong == 19971201L) // Monday { weekFirstDay = 1; } else { qDebug() << Q_FUNC_INFO << "nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value."; } weekStart = (weekFirstDay + firstWeekDay - 1) % 7; if (weekStart == 0) { return Qt::Sunday; } else { return static_cast<Qt::DayOfWeek>(weekStart); } } #else Qt::DayOfWeek firstDayOfWeek(void) { return Qt::Sunday; #endif // HAVE__NL_TIME_FIRST_WEEKDAY #endif // CAN_USE_BOOST #endif // QT_VERSION >= 0x040800 <commit_msg>Panel Clock plugin: C locale initialised only once<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Kuzma Shapran <kuzma.shapran@gmail.com> * Luís Pereira <luis.artur.pereira@gmail.com> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "calendar_utils.h" #include "config.h" #include <QtCore/QtGlobal> #if QT_VERSION >= 0x040800 Qt::DayOfWeek firstDayOfWeek(void) { return QLocale::system().firstDayOfWeek(); } #else #ifdef CAN_USE_BOOST #include <boost/locale/date_time.hpp> Qt::DayOfWeek firstDayOfWeek(void) { return (boost::locale::calendar().first_day_of_week() + 6) % 7; } #else // use C #ifdef HAVE__NL_TIME_FIRST_WEEKDAY #include <langinfo.h> #include <QtCore/QDebug> Qt::DayOfWeek firstDayOfWeek(void) { int firstWeekDay; int weekFirstDay = 0; int weekStart; static char *locale = NULL; long weekFirstDayLong; if (!locale) locale = setlocale(LC_TIME, ""); // firstWeekDay: Specifies the offset of the first day-of-week in the day // list. // weekFirstDay: Some date that corresponds to the beginning of a week. // Specifies the base of the day list. It is (in glibc) either // 19971130 (Sunday) or 19971201 (Monday) firstWeekDay = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0]; weekFirstDayLong = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY); if (weekFirstDayLong == 19971130L) // Sunday { weekFirstDay = 0; } else if (weekFirstDayLong == 19971201L) // Monday { weekFirstDay = 1; } else { qDebug() << Q_FUNC_INFO << "nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value."; } weekStart = (weekFirstDay + firstWeekDay - 1) % 7; if (weekStart == 0) { return Qt::Sunday; } else { return static_cast<Qt::DayOfWeek>(weekStart); } } #else Qt::DayOfWeek firstDayOfWeek(void) { return Qt::Sunday; #endif // HAVE__NL_TIME_FIRST_WEEKDAY #endif // CAN_USE_BOOST #endif // QT_VERSION >= 0x040800 <|endoftext|>
<commit_before>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. You may redistribute, use, and create derivate works of HOOMD-blue, in source and binary forms, provided you abide by the following conditions: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer both in the code and prominently in any materials provided with the distribution. * 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. * All publications and presentations based on HOOMD-blue, including any reports or published results obtained, in whole or in part, with HOOMD-blue, will acknowledge its use according to the terms posted at the time of submission on: http://codeblue.umich.edu/hoomd-blue/citations.html * Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website: http://codeblue.umich.edu/hoomd-blue/ * Apart from the above required attributions, neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // Maintainer: joaander #include "TwoStepBD.h" #include "saruprng.h" #ifdef ENABLE_MPI #include "HOOMDMPI.h" #endif #include <boost/python.hpp> using namespace boost::python; using namespace std; /*! \file TwoStepBD.h \brief Contains code for the TwoStepBD class */ /*! \param sysdef SystemDefinition this method will act on. Must not be NULL. \param group The group of particles this integration method is to work on \param T Temperature set point as a function of time \param seed Random seed to use in generating random numbers \param use_lambda If true, gamma=lambda*diameter, otherwise use a per-type gamma via setGamma() \param lambda Scale factor to convert diameter to gamma */ TwoStepBD::TwoStepBD(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<ParticleGroup> group, boost::shared_ptr<Variant> T, unsigned int seed, bool use_lambda, Scalar lambda) : TwoStepLangevinBase(sysdef, group, T, seed, use_lambda, lambda) { m_exec_conf->msg->notice(5) << "Constructing TwoStepBD" << endl; } TwoStepBD::~TwoStepBD() { m_exec_conf->msg->notice(5) << "Destroying TwoStepBD" << endl; } /*! \param timestep Current time step \post Particle positions are moved forward to timestep+1 The integration method here is from the book "The Langevin and Generalised Langevin Approach to the Dynamics of Atomic, Polymeric and Colloidal Systems", chapter 6. */ void TwoStepBD::integrateStepOne(unsigned int timestep) { unsigned int group_size = m_group->getNumMembers(); // profile this step if (m_prof) m_prof->push("BD step 1"); // grab some initial variables const Scalar currentTemp = m_T->getValue(timestep); const unsigned int D = Scalar(m_sysdef->getNDimensions()); const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce(); ArrayHandle<Scalar4> h_vel(m_pdata->getVelocities(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<int3> h_image(m_pdata->getImages(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_net_force(net_force, access_location::host, access_mode::read); ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::read); ArrayHandle<Scalar> h_diameter(m_pdata->getDiameters(), access_location::host, access_mode::read); /////////////// if (m_aniso) { ArrayHandle<Scalar4> h_orien(m_pdata->getOrientationArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_torque(m_pdata->getNetTorqueArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar3> h_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); ArrayHandle<Scalar3> h_angmom(m_pdata->getAltAngularMomentumArray(), access_location::host, access_mode::read); } /////////////// const BoxDim& box = m_pdata->getBox(); // initialize the RNG Saru saru(m_seed, timestep, 0xffaabb); // perform the first half step // r(t+deltaT) = r(t) + (Fc(t) + Fr)*deltaT/gamma // v(t+deltaT) = random distribution consistent with T for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); // compute the random force Scalar rx = saru.s<Scalar>(-1,1); Scalar ry = saru.s<Scalar>(-1,1); Scalar rz = saru.s<Scalar>(-1,1); Scalar gamma; if (m_use_lambda) gamma = m_lambda*h_diameter.data[j]; else { unsigned int type = __scalar_as_int(h_pos.data[j].w); gamma = h_gamma.data[type]; } // compute the bd force (the extra factor of 3 is because <rx^2> is 1/3 in the uniform -1,1 distribution // it is not the dimensionality of the system Scalar coeff = fast::sqrt(Scalar(3.0)*Scalar(2.0)*gamma*currentTemp/m_deltaT); Scalar Fr_x = rx*coeff; Scalar Fr_y = ry*coeff; Scalar Fr_z = rz*coeff; if (D < 3) Fr_z = Scalar(0.0); // update position h_pos.data[j].x += (h_net_force.data[j].x + Fr_x) * m_deltaT / gamma; h_pos.data[j].y += (h_net_force.data[j].y + Fr_y) * m_deltaT / gamma; h_pos.data[j].z += (h_net_force.data[j].z + Fr_z) * m_deltaT / gamma; // particles may have been moved slightly outside the box by the above steps, wrap them back into place box.wrap(h_pos.data[j], h_image.data[j]); // draw a new random velocity for particle j Scalar mass = h_vel.data[j].w; Scalar sigma = fast::sqrt(currentTemp/mass); h_vel.data[j].x = gaussian_rng(saru, sigma); h_vel.data[j].y = gaussian_rng(saru, sigma); if (D > 2) h_vel.data[j].z = gaussian_rng(saru, sigma); else h_vel.data[j].z = 0; /////////////// Scalar coeff_r = fast::sqrt(Scalar(2.0)*gamma_r*currentTemp/m_deltaT); Scalar tau_rz = gaussian_rng(saru, sigma); quat Scalar gamma_r; // gamma_r needs initialization // if (m_use_lambda) // gamma = m_lambda*h_diameter.data[j]; // else // { // unsigned int type = __scalar_as_int(h_pos.data[j].w); // gamma = h_gamma.data[type]; // } if (D < 3) { // h_orien.data[j].x += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].x + tau_r) ; // h_orien.data[j].y += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].y + tau_r) ; // h_orien.data[j].z += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].z + tau_r) ; vec3<Scalar> axis (0, 0, 1); Scalar theta = (h_torque.data[j].z + tau_r) / gamma_r; quat<Scalar> omega = fromAxisAngle(axis, theta); quat<Scalar> q (h_orien.data[j]); q += Scalar(0.5) * m_deltaT * q * omega; // renormalize (improves stability) q = q*(Scalar(1.0)/slow::sqrt(norm2(q))); h_orien.data[j].x = q.x; h_orien.data[j].y = q.y; h_orien.data[j].z = q.z; h_orien.data[j].w = q.w; } /////////////// } // done profiling if (m_prof) m_prof->pop(); } /*! \param timestep Current time step */ void TwoStepBD::integrateStepTwo(unsigned int timestep) { // there is no step 2 in Brownian dynamics. } void export_TwoStepBD() { class_<TwoStepBD, boost::shared_ptr<TwoStepBD>, bases<TwoStepLangevinBase>, boost::noncopyable> ("TwoStepBD", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, boost::shared_ptr<Variant>, unsigned int, bool, Scalar >()) ; } <commit_msg>bd_cpu_added<commit_after>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2009-2015 The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. You may redistribute, use, and create derivate works of HOOMD-blue, in source and binary forms, provided you abide by the following conditions: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer both in the code and prominently in any materials provided with the distribution. * 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. * All publications and presentations based on HOOMD-blue, including any reports or published results obtained, in whole or in part, with HOOMD-blue, will acknowledge its use according to the terms posted at the time of submission on: http://codeblue.umich.edu/hoomd-blue/citations.html * Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website: http://codeblue.umich.edu/hoomd-blue/ * Apart from the above required attributions, neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // Maintainer: joaander #include "TwoStepBD.h" #include "saruprng.h" #ifdef ENABLE_MPI #include "HOOMDMPI.h" #endif #include <boost/python.hpp> using namespace boost::python; using namespace std; /*! \file TwoStepBD.h \brief Contains code for the TwoStepBD class */ /*! \param sysdef SystemDefinition this method will act on. Must not be NULL. \param group The group of particles this integration method is to work on \param T Temperature set point as a function of time \param seed Random seed to use in generating random numbers \param use_lambda If true, gamma=lambda*diameter, otherwise use a per-type gamma via setGamma() \param lambda Scale factor to convert diameter to gamma */ TwoStepBD::TwoStepBD(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<ParticleGroup> group, boost::shared_ptr<Variant> T, unsigned int seed, bool use_lambda, Scalar lambda) : TwoStepLangevinBase(sysdef, group, T, seed, use_lambda, lambda) { m_exec_conf->msg->notice(5) << "Constructing TwoStepBD" << endl; } TwoStepBD::~TwoStepBD() { m_exec_conf->msg->notice(5) << "Destroying TwoStepBD" << endl; } /*! \param timestep Current time step \post Particle positions are moved forward to timestep+1 The integration method here is from the book "The Langevin and Generalised Langevin Approach to the Dynamics of Atomic, Polymeric and Colloidal Systems", chapter 6. */ void TwoStepBD::integrateStepOne(unsigned int timestep) { unsigned int group_size = m_group->getNumMembers(); // profile this step if (m_prof) m_prof->push("BD step 1"); // grab some initial variables const Scalar currentTemp = m_T->getValue(timestep); const unsigned int D = Scalar(m_sysdef->getNDimensions()); const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce(); ArrayHandle<Scalar4> h_vel(m_pdata->getVelocities(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<int3> h_image(m_pdata->getImages(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_net_force(net_force, access_location::host, access_mode::read); ArrayHandle<Scalar> h_gamma(m_gamma, access_location::host, access_mode::read); ArrayHandle<Scalar> h_diameter(m_pdata->getDiameters(), access_location::host, access_mode::read); /////////////// if (m_aniso) { ArrayHandle<Scalar4> h_orien(m_pdata->getOrientationArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_torque(m_pdata->getNetTorqueArray(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar3> h_inertia(m_pdata->getMomentsOfInertiaArray(), access_location::host, access_mode::read); ArrayHandle<Scalar3> h_angmom(m_pdata->getAltAngularMomentumArray(), access_location::host, access_mode::read); } /////////////// const BoxDim& box = m_pdata->getBox(); // initialize the RNG Saru saru(m_seed, timestep, 0xffaabb); // perform the first half step // r(t+deltaT) = r(t) + (Fc(t) + Fr)*deltaT/gamma // v(t+deltaT) = random distribution consistent with T for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { unsigned int j = m_group->getMemberIndex(group_idx); // compute the random force Scalar rx = saru.s<Scalar>(-1,1); Scalar ry = saru.s<Scalar>(-1,1); Scalar rz = saru.s<Scalar>(-1,1); Scalar gamma; if (m_use_lambda) gamma = m_lambda*h_diameter.data[j]; else { unsigned int type = __scalar_as_int(h_pos.data[j].w); gamma = h_gamma.data[type]; } // compute the bd force (the extra factor of 3 is because <rx^2> is 1/3 in the uniform -1,1 distribution // it is not the dimensionality of the system Scalar coeff = fast::sqrt(Scalar(3.0)*Scalar(2.0)*gamma*currentTemp/m_deltaT); Scalar Fr_x = rx*coeff; Scalar Fr_y = ry*coeff; Scalar Fr_z = rz*coeff; if (D < 3) Fr_z = Scalar(0.0); // update position h_pos.data[j].x += (h_net_force.data[j].x + Fr_x) * m_deltaT / gamma; h_pos.data[j].y += (h_net_force.data[j].y + Fr_y) * m_deltaT / gamma; h_pos.data[j].z += (h_net_force.data[j].z + Fr_z) * m_deltaT / gamma; // particles may have been moved slightly outside the box by the above steps, wrap them back into place box.wrap(h_pos.data[j], h_image.data[j]); // draw a new random velocity for particle j Scalar mass = h_vel.data[j].w; Scalar sigma = fast::sqrt(currentTemp/mass); h_vel.data[j].x = gaussian_rng(saru, sigma); h_vel.data[j].y = gaussian_rng(saru, sigma); if (D > 2) h_vel.data[j].z = gaussian_rng(saru, sigma); else h_vel.data[j].z = 0; /////////////// Scalar coeff_r = fast::sqrt(Scalar(2.0)*gamma_r*currentTemp/m_deltaT); Scalar tau_rz = gaussian_rng(saru, sigma); Scalar gamma_r; // gamma_r needs initialization // if (m_use_lambda) // gamma = m_lambda*h_diameter.data[j]; // else // { // unsigned int type = __scalar_as_int(h_pos.data[j].w); // gamma = h_gamma.data[type]; // } if (D < 3) { // h_orien.data[j].x += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].x + tau_r) ; // h_orien.data[j].y += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].y + tau_r) ; // h_orien.data[j].z += Scalar(1.0 / 2.0) * m_deltaT / gamma_r * (h_torque.data[j].z + tau_r) ; vec3<Scalar> axis (0, 0, 1); Scalar theta = (h_torque.data[j].z + tau_r) / gamma_r; quat<Scalar> omega = fromAxisAngle(axis, theta); quat<Scalar> q (h_orien.data[j]); q += Scalar(0.5) * m_deltaT * q * omega; // renormalize (improves stability) q = q*(Scalar(1.0)/slow::sqrt(norm2(q))); h_orien.data[j].x = q.x; h_orien.data[j].y = q.y; h_orien.data[j].z = q.z; h_orien.data[j].w = q.w; } /////////////// } // done profiling if (m_prof) m_prof->pop(); } /*! \param timestep Current time step */ void TwoStepBD::integrateStepTwo(unsigned int timestep) { // there is no step 2 in Brownian dynamics. } void export_TwoStepBD() { class_<TwoStepBD, boost::shared_ptr<TwoStepBD>, bases<TwoStepLangevinBase>, boost::noncopyable> ("TwoStepBD", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<ParticleGroup>, boost::shared_ptr<Variant>, unsigned int, bool, Scalar >()) ; } <|endoftext|>
<commit_before>#include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> // for PositionJointInterface #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> class Arcsys2HW : public hardware_interface::RobotHW { public: Arcsys2HW(); void read(); void write(); ros::Time getTime() const; ros::Duration getPeriod() const; private: static constexpr std::size_t JOINT_COUNT {6}; hardware_interface::JointStateInterface joint_state_interface_; hardware_interface::PositionJointInterface joint_position_interface_; hardware_interface::VelocityJointInterface joint_velocity_interface_; double pos_[JOINT_COUNT]; double vel_[JOINT_COUNT]; double eff_[JOINT_COUNT]; double cmd_[JOINT_COUNT]; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); Arcsys2HW robot {}; controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline Arcsys2HW::Arcsys2HW() : joint_state_interface_ {}, joint_position_interface_ {}, joint_velocity_interface_ {}, cmd_ {}, pos_ {}, vel_ {}, eff_ {} { // [input] connect and register the joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos_[0], &vel_[0], &eff_[0]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos_[1], &vel_[1], &eff_[1]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos_[2], &vel_[2], &eff_[2]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos_[3], &vel_[3], &eff_[3]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos_[4], &vel_[4], &eff_[4]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos_[5], &vel_[5], &eff_[5]}); registerInterface(&joint_state_interface_); // [output] connect and register the joint position interface joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("rail_to_shaft_joint"), &cmd_[0]}); joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("shaft_to_arm0_joint"), &cmd_[1]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm0_to_arm1_joint"), &cmd_[2]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm1_to_arm2_joint"), &cmd_[3]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm2_to_effector_base_joint"), &cmd_[4]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("effector_base_to_effector_end_joint"), &cmd_[5]}); registerInterface(&joint_velocity_interface_); registerInterface(&joint_position_interface_); } inline void Arcsys2HW::read() { for (std::size_t i {0}; i < 2; i++) { static double pos_vel_cntr[2] {0.0, 0.0}; vel_[i] = cmd_[i]; pos_[i] = pos_vel_cntr[i] += cmd_[i] * getPeriod().toSec(); } for (std::size_t i {2}; i < 6; i++) pos_[i] = cmd_[i]; } inline void Arcsys2HW::write() { } inline ros::Time Arcsys2HW::getTime() const { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() const { return ros::Duration(0.01); } <commit_msg>Optimize posision calculate on velocity controller<commit_after>#include <string> #include <utility> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <hardware_interface/joint_command_interface.h> // for PositionJointInterface #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> class Arcsys2HW : public hardware_interface::RobotHW { public: Arcsys2HW(); void read(); void write(); ros::Time getTime() const; ros::Duration getPeriod() const; private: static constexpr std::size_t JOINT_COUNT {6}; hardware_interface::JointStateInterface joint_state_interface_; hardware_interface::PositionJointInterface joint_position_interface_; hardware_interface::VelocityJointInterface joint_velocity_interface_; double pos_[JOINT_COUNT]; double vel_[JOINT_COUNT]; double eff_[JOINT_COUNT]; double cmd_[JOINT_COUNT]; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); Arcsys2HW robot {}; controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline Arcsys2HW::Arcsys2HW() : joint_state_interface_ {}, joint_position_interface_ {}, joint_velocity_interface_ {}, cmd_ {}, pos_ {}, vel_ {}, eff_ {} { // [input] connect and register the joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos_[0], &vel_[0], &eff_[0]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos_[1], &vel_[1], &eff_[1]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos_[2], &vel_[2], &eff_[2]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos_[3], &vel_[3], &eff_[3]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos_[4], &vel_[4], &eff_[4]}); joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos_[5], &vel_[5], &eff_[5]}); registerInterface(&joint_state_interface_); // [output] connect and register the joint position interface joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("rail_to_shaft_joint"), &cmd_[0]}); joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("shaft_to_arm0_joint"), &cmd_[1]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm0_to_arm1_joint"), &cmd_[2]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm1_to_arm2_joint"), &cmd_[3]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm2_to_effector_base_joint"), &cmd_[4]}); joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("effector_base_to_effector_end_joint"), &cmd_[5]}); registerInterface(&joint_velocity_interface_); registerInterface(&joint_position_interface_); } inline void Arcsys2HW::read() { for (std::size_t i {0}; i < 2; i++) { vel_[i] = cmd_[i]; pos_[i] += cmd_[i] * getPeriod().toSec(); } for (std::size_t i {2}; i < 6; i++) pos_[i] = cmd_[i]; } inline void Arcsys2HW::write() { } inline ros::Time Arcsys2HW::getTime() const { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() const { return ros::Duration(0.01); } <|endoftext|>
<commit_before>// $Id$ AliEmcalClusTrackMatcherTask* AddTaskEmcalClusTrackMatcher( const char *nTracks = "Tracks", const char *nClusters = "CaloClusters", Double_t maxDist = 0.1 ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalClusTrackMatcher", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskEmcalClusTrackMatcher", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- TString name(Form("ClusTrackMatcher_%s_%s",nTracks,nClusters)); AliEmcalClusTrackMatcherTask* matcher = new AliEmcalClusTrackMatcherTask(name); matcher->SetTracksName(nTracks); matcher->SetClusName(nClusters); matcher->SetMaxDistance(maxDist); matcher->SetAnaType(AliAnalysisTaskEmcal::kEMCAL); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(matcher); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ; mgr->ConnectInput (matcher, 0, cinput1 ); return matcher; } <commit_msg>new default names<commit_after>// $Id$ AliEmcalClusTrackMatcherTask* AddTaskEmcalClusTrackMatcher( const char *nTracks = "EmcalTracks", const char *nClusters = "EmcalClusters", Double_t maxDist = 0.1 ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalClusTrackMatcher", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskEmcalClusTrackMatcher", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- TString name(Form("ClusTrackMatcher_%s_%s",nTracks,nClusters)); AliEmcalClusTrackMatcherTask* matcher = new AliEmcalClusTrackMatcherTask(name); matcher->SetTracksName(nTracks); matcher->SetClusName(nClusters); matcher->SetMaxDistance(maxDist); matcher->SetAnaType(AliAnalysisTaskEmcal::kEMCAL); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(matcher); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ; mgr->ConnectInput (matcher, 0, cinput1 ); return matcher; } <|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 <stdio.h> #include "bin/dartutils.h" #include "bin/file.h" #include "bin/platform.h" #include "platform/assert.h" #include "vm/benchmark_test.h" #include "vm/dart.h" #include "vm/unit_test.h" // TODO(iposva, asiva): This is a placeholder for the real unittest framework. namespace dart { // Defined in vm/os_thread_win.cc extern bool private_flag_windows_run_tls_destructors; // vm_snapshot_data_buffer points to a snapshot for the vm isolate if we // link in a snapshot otherwise it is initialized to NULL. extern const uint8_t* bin::vm_snapshot_data; extern const uint8_t* bin::vm_snapshot_instructions; // Only run tests that match the filter string. The default does not match any // tests. static const char* const kNone = "No Test or Benchmarks"; static const char* const kList = "List all Tests and Benchmarks"; static const char* const kAllBenchmarks = "All Benchmarks"; static const char* run_filter = kNone; static int run_matches = 0; void TestCase::Run() { fprintf(stdout, "Running test: %s\n", name()); (*run_)(); fprintf(stdout, "Done: %s\n", name()); } void RawTestCase::Run() { fprintf(stdout, "Running test: %s\n", name()); (*run_)(); fprintf(stdout, "Done: %s\n", name()); } void TestCaseBase::RunTest() { if (strcmp(run_filter, this->name()) == 0) { this->Run(); run_matches++; } else if (run_filter == kList) { fprintf(stdout, "%s\n", this->name()); run_matches++; } } void Benchmark::RunBenchmark() { if ((run_filter == kAllBenchmarks) || (strcmp(run_filter, this->name()) == 0)) { this->Run(); OS::Print("%s(%s): %" Pd64 "\n", this->name(), this->score_kind(), this->score()); run_matches++; } else if (run_filter == kList) { fprintf(stdout, "%s\n", this->name()); run_matches++; } } static void PrintUsage() { fprintf(stderr, "run_vm_tests [--list | --benchmarks | " "<test name> | <benchmark name>]\n"); fprintf(stderr, "run_vm_tests [vm-flags ...] <test name>\n"); fprintf(stderr, "run_vm_tests [vm-flags ...] <benchmark name>\n"); } static int Main(int argc, const char** argv) { // Flags being passed to the Dart VM. int dart_argc = 0; const char** dart_argv = NULL; if (argc < 2) { // Bad parameter count. PrintUsage(); return 1; } else if (argc == 2) { if (strcmp(argv[1], "--list") == 0) { run_filter = kList; // List all tests and benchmarks and exit without initializing the VM. TestCaseBase::RunAll(); Benchmark::RunAll(argv[0]); TestCaseBase::RunAllRaw(); fflush(stdout); return 0; } else if (strcmp(argv[1], "--benchmarks") == 0) { run_filter = kAllBenchmarks; } else { run_filter = argv[1]; } } else { // Last argument is the test name, the rest are vm flags. run_filter = argv[argc - 1]; // Remove the first value (executable) from the arguments and // exclude the last argument which is the test name. dart_argc = argc - 2; dart_argv = &argv[1]; } bool set_vm_flags_success = Flags::ProcessCommandLineFlags(dart_argc, dart_argv); ASSERT(set_vm_flags_success); const char* err_msg = Dart::InitOnce( dart::bin::vm_snapshot_data, dart::bin::vm_snapshot_instructions, NULL, NULL, NULL, dart::bin::DartUtils::OpenFile, dart::bin::DartUtils::ReadFile, dart::bin::DartUtils::WriteFile, dart::bin::DartUtils::CloseFile, NULL, NULL); ASSERT(err_msg == NULL); // Apply the filter to all registered tests. TestCaseBase::RunAll(); // Apply the filter to all registered benchmarks. Benchmark::RunAll(argv[0]); err_msg = Dart::Cleanup(); ASSERT(err_msg == NULL); TestCaseBase::RunAllRaw(); // Print a warning message if no tests or benchmarks were matched. if (run_matches == 0) { fprintf(stderr, "No tests matched: %s\n", run_filter); return 1; } if (DynamicAssertionHelper::failed()) { return 255; } return 0; } } // namespace dart int main(int argc, const char** argv) { dart::bin::Platform::Exit(dart::Main(argc, argv)); } <commit_msg>Removed instances of fprintf in run_vm_tests and replaced them with OS::Print/PrintErr.<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 <stdio.h> #include "bin/dartutils.h" #include "bin/file.h" #include "bin/platform.h" #include "platform/assert.h" #include "vm/benchmark_test.h" #include "vm/dart.h" #include "vm/unit_test.h" // TODO(iposva, asiva): This is a placeholder for the real unittest framework. namespace dart { // Defined in vm/os_thread_win.cc extern bool private_flag_windows_run_tls_destructors; // vm_snapshot_data_buffer points to a snapshot for the vm isolate if we // link in a snapshot otherwise it is initialized to NULL. extern const uint8_t* bin::vm_snapshot_data; extern const uint8_t* bin::vm_snapshot_instructions; // Only run tests that match the filter string. The default does not match any // tests. static const char* const kNone = "No Test or Benchmarks"; static const char* const kList = "List all Tests and Benchmarks"; static const char* const kAllBenchmarks = "All Benchmarks"; static const char* run_filter = kNone; static int run_matches = 0; void TestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void RawTestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void TestCaseBase::RunTest() { if (strcmp(run_filter, this->name()) == 0) { this->Run(); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } void Benchmark::RunBenchmark() { if ((run_filter == kAllBenchmarks) || (strcmp(run_filter, this->name()) == 0)) { this->Run(); OS::Print("%s(%s): %" Pd64 "\n", this->name(), this->score_kind(), this->score()); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } static void PrintUsage() { OS::PrintErr( "run_vm_tests [--list | --benchmarks | " "<test name> | <benchmark name>]\n"); OS::PrintErr("run_vm_tests [vm-flags ...] <test name>\n"); OS::PrintErr("run_vm_tests [vm-flags ...] <benchmark name>\n"); } static int Main(int argc, const char** argv) { // Flags being passed to the Dart VM. int dart_argc = 0; const char** dart_argv = NULL; if (argc < 2) { // Bad parameter count. PrintUsage(); return 1; } else if (argc == 2) { if (strcmp(argv[1], "--list") == 0) { run_filter = kList; // List all tests and benchmarks and exit without initializing the VM. TestCaseBase::RunAll(); Benchmark::RunAll(argv[0]); TestCaseBase::RunAllRaw(); fflush(stdout); return 0; } else if (strcmp(argv[1], "--benchmarks") == 0) { run_filter = kAllBenchmarks; } else { run_filter = argv[1]; } } else { // Last argument is the test name, the rest are vm flags. run_filter = argv[argc - 1]; // Remove the first value (executable) from the arguments and // exclude the last argument which is the test name. dart_argc = argc - 2; dart_argv = &argv[1]; } bool set_vm_flags_success = Flags::ProcessCommandLineFlags(dart_argc, dart_argv); ASSERT(set_vm_flags_success); const char* err_msg = Dart::InitOnce( dart::bin::vm_snapshot_data, dart::bin::vm_snapshot_instructions, NULL, NULL, NULL, dart::bin::DartUtils::OpenFile, dart::bin::DartUtils::ReadFile, dart::bin::DartUtils::WriteFile, dart::bin::DartUtils::CloseFile, NULL, NULL); ASSERT(err_msg == NULL); // Apply the filter to all registered tests. TestCaseBase::RunAll(); // Apply the filter to all registered benchmarks. Benchmark::RunAll(argv[0]); err_msg = Dart::Cleanup(); ASSERT(err_msg == NULL); TestCaseBase::RunAllRaw(); // Print a warning message if no tests or benchmarks were matched. if (run_matches == 0) { OS::PrintErr("No tests matched: %s\n", run_filter); return 1; } if (DynamicAssertionHelper::failed()) { return 255; } return 0; } } // namespace dart int main(int argc, const char** argv) { dart::bin::Platform::Exit(dart::Main(argc, argv)); } <|endoftext|>
<commit_before> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/geometry/half_space_intersection.hpp" #include "openMVG/sfm/sfm.hpp" #include "openMVG/sfm/sfm_data_filters_frustum.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/types.hpp" #include <fstream> #include <iomanip> namespace openMVG { namespace sfm { using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::geometry::halfPlane; // Constructor Frustum_Filter::Frustum_Filter(const SfM_Data & sfm_data, const double zNear, const double zFar, const NearFarPlanesT & z_near_z_far) { z_near_z_far_perView = z_near_z_far; //-- Init Z_Near & Z_Far for all valid views init_z_near_z_far_depth(sfm_data, zNear, zFar); const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); _bTruncated = (zNear != -1. && zFar != -1.) || bComputed_Z; initFrustum(sfm_data); } // Init a frustum for each valid views of the SfM scene void Frustum_Filter::initFrustum(const SfM_Data & sfm_data) { for (NearFarPlanesT::const_iterator it = z_near_z_far_perView.begin(); it != z_near_z_far_perView.end(); ++it) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second.get()->getType())) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (cam == NULL) continue; if (!_bTruncated) // use infinite frustum { const Frustum f( cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center()); frustum_perView[view->id_view] = f; } else // use truncated frustum with defined Near and Far planes { const Frustum f(cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center(), it->second.first, it->second.second); frustum_perView[view->id_view] = f; } } } Pair_Set Frustum_Filter::getFrustumIntersectionPairs() const { Pair_Set pairs; // List active view Id std::vector<IndexT> viewIds; viewIds.reserve(z_near_z_far_perView.size()); std::transform(z_near_z_far_perView.begin(), z_near_z_far_perView.end(), std::back_inserter(viewIds), stl::RetrieveKey()); C_Progress_display my_progress_bar( viewIds.size() * (viewIds.size()-1)/2, std::cout, "\nCompute frustum intersection\n"); // Exhaustive comparison (use the fact that the intersect function is symmetric) #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < (int)viewIds.size(); ++i) { for (size_t j = i+1; j < viewIds.size(); ++j) { if (frustum_perView.at(viewIds[i]).intersect(frustum_perView.at(viewIds[j]))) { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { pairs.insert(std::make_pair(viewIds[i], viewIds[j])); } } // Progress bar update #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { ++my_progress_bar; } } } return pairs; } // Export defined frustum in PLY file for viewing bool Frustum_Filter::export_Ply(const std::string & filename) const { std::ofstream of(filename.c_str()); if (!of.is_open()) return false; // Vertex count evaluation // Faces count evaluation size_t vertex_count = 0; size_t face_count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) { vertex_count += 5; face_count += 5; // 4 triangles + 1 quad } else // truncated { vertex_count += 8; face_count += 6; // 6 quads } } of << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1); of << "ply" << '\n' << "format ascii 1.0" << '\n' << "element vertex " << vertex_count << '\n' << "property double x" << '\n' << "property double y" << '\n' << "property double z" << '\n' << "element face " << face_count << '\n' << "property list uchar int vertex_index" << '\n' << "end_header" << '\n'; // Export frustums points for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { const std::vector<Vec3> & points = it->second.frustum_points(); for (size_t i=0; i < points.size(); ++i) of << points[i].transpose() << '\n'; } // Export frustums faces IndexT count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) // infinite frustum: drawn normalized cone: 4 faces { of << "3 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << '\n' << "3 " << count + 0 << ' ' << count + 2 << ' ' << count + 3 << '\n' << "3 " << count + 0 << ' ' << count + 3 << ' ' << count + 4 << '\n' << "3 " << count + 0 << ' ' << count + 4 << ' ' << count + 1 << '\n' << "4 " << count + 1 << ' ' << count + 2 << ' ' << count + 3 << ' ' << count + 4 << '\n'; count += 5; } else // truncated frustum: 6 faces { of << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << ' ' << count + 3 << '\n' << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 5 << ' ' << count + 4 << '\n' << "4 " << count + 1 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 2 << '\n' << "4 " << count + 3 << ' ' << count + 7 << ' ' << count + 6 << ' ' << count + 2 << '\n' << "4 " << count + 0 << ' ' << count + 4 << ' ' << count + 7 << ' ' << count + 3 << '\n' << "4 " << count + 4 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 7 << '\n'; count += 8; } } of.flush(); bool bOk = of.good(); of.close(); return bOk; } void Frustum_Filter::init_z_near_z_far_depth(const SfM_Data & sfm_data, const double zNear, const double zFar) { // If z_near & z_far are -1 and structure if not empty, // compute the values for each camera and the structure const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); if (bComputed_Z) // Compute the near & far planes from the structure and view observations { for (Landmarks::const_iterator itL = sfm_data.GetLandmarks().begin(); itL != sfm_data.GetLandmarks().end(); ++itL) { const Landmark & landmark = itL->second; const Vec3 & X = landmark.X; for (Observations::const_iterator iterO = landmark.obs.begin(); iterO != landmark.obs.end(); ++iterO) { const IndexT id_view = iterO->first; const View * view = sfm_data.GetViews().at(id_view).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const Pose3 pose = sfm_data.GetPoseOrDie(view); const double z = pose.depth(X); NearFarPlanesT::iterator itZ = z_near_z_far_perView.find(id_view); if (itZ != z_near_z_far_perView.end()) { if ( z < itZ->second.first) itZ->second.first = z; else if ( z > itZ->second.second) itZ->second.second = z; } else z_near_z_far_perView[id_view] = std::make_pair(z,z); } } } else { // Init the same near & far limit for all the valid views for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * view = it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; if (z_near_z_far_perView.find(view->id_view) == z_near_z_far_perView.end()) z_near_z_far_perView[view->id_view] = std::make_pair(zNear, zFar); } } } } // namespace sfm } // namespace openMVG <commit_msg>[sfm] Allow passing z_near/z_far for each view to Frustum_Filter #743<commit_after> // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/geometry/half_space_intersection.hpp" #include "openMVG/sfm/sfm.hpp" #include "openMVG/sfm/sfm_data_filters_frustum.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/types.hpp" #include <fstream> #include <iomanip> namespace openMVG { namespace sfm { using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::geometry::halfPlane; // Constructor Frustum_Filter::Frustum_Filter ( const SfM_Data & sfm_data, const double zNear, const double zFar, const NearFarPlanesT & z_near_z_far ) { z_near_z_far_perView = z_near_z_far; //-- Init Z_Near & Z_Far for all valid views init_z_near_z_far_depth(sfm_data, zNear, zFar); const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); _bTruncated = (zNear != -1. && zFar != -1.) || bComputed_Z; initFrustum(sfm_data); } // Init a frustum for each valid views of the SfM scene void Frustum_Filter::initFrustum ( const SfM_Data & sfm_data ) { for (NearFarPlanesT::const_iterator it = z_near_z_far_perView.begin(); it != z_near_z_far_perView.end(); ++it) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second.get()->getType())) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (cam == NULL) continue; if (!_bTruncated) // use infinite frustum { const Frustum f( cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center()); frustum_perView[view->id_view] = f; } else // use truncated frustum with defined Near and Far planes { const Frustum f(cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center(), it->second.first, it->second.second); frustum_perView[view->id_view] = f; } } } Pair_Set Frustum_Filter::getFrustumIntersectionPairs() const { Pair_Set pairs; // List active view Id std::vector<IndexT> viewIds; viewIds.reserve(z_near_z_far_perView.size()); std::transform(z_near_z_far_perView.begin(), z_near_z_far_perView.end(), std::back_inserter(viewIds), stl::RetrieveKey()); C_Progress_display my_progress_bar( viewIds.size() * (viewIds.size()-1)/2, std::cout, "\nCompute frustum intersection\n"); // Exhaustive comparison (use the fact that the intersect function is symmetric) #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < (int)viewIds.size(); ++i) { for (size_t j = i+1; j < viewIds.size(); ++j) { if (frustum_perView.at(viewIds[i]).intersect(frustum_perView.at(viewIds[j]))) { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { pairs.insert(std::make_pair(viewIds[i], viewIds[j])); } } // Progress bar update #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { ++my_progress_bar; } } } return pairs; } // Export defined frustum in PLY file for viewing bool Frustum_Filter::export_Ply ( const std::string & filename ) const { std::ofstream of(filename.c_str()); if (!of.is_open()) return false; // Vertex count evaluation // Faces count evaluation size_t vertex_count = 0; size_t face_count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) { vertex_count += 5; face_count += 5; // 4 triangles + 1 quad } else // truncated { vertex_count += 8; face_count += 6; // 6 quads } } of << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1); of << "ply" << '\n' << "format ascii 1.0" << '\n' << "element vertex " << vertex_count << '\n' << "property double x" << '\n' << "property double y" << '\n' << "property double z" << '\n' << "element face " << face_count << '\n' << "property list uchar int vertex_index" << '\n' << "end_header" << '\n'; // Export frustums points for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { const std::vector<Vec3> & points = it->second.frustum_points(); for (size_t i=0; i < points.size(); ++i) of << points[i].transpose() << '\n'; } // Export frustums faces IndexT count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) // infinite frustum: drawn normalized cone: 4 faces { of << "3 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << '\n' << "3 " << count + 0 << ' ' << count + 2 << ' ' << count + 3 << '\n' << "3 " << count + 0 << ' ' << count + 3 << ' ' << count + 4 << '\n' << "3 " << count + 0 << ' ' << count + 4 << ' ' << count + 1 << '\n' << "4 " << count + 1 << ' ' << count + 2 << ' ' << count + 3 << ' ' << count + 4 << '\n'; count += 5; } else // truncated frustum: 6 faces { of << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << ' ' << count + 3 << '\n' << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 5 << ' ' << count + 4 << '\n' << "4 " << count + 1 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 2 << '\n' << "4 " << count + 3 << ' ' << count + 7 << ' ' << count + 6 << ' ' << count + 2 << '\n' << "4 " << count + 0 << ' ' << count + 4 << ' ' << count + 7 << ' ' << count + 3 << '\n' << "4 " << count + 4 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 7 << '\n'; count += 8; } } of.flush(); bool bOk = of.good(); of.close(); return bOk; } void Frustum_Filter::init_z_near_z_far_depth ( const SfM_Data & sfm_data, const double zNear, const double zFar ) { // If z_near & z_far are -1 and structure if not empty, // compute the values for each camera and the structure const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); if (bComputed_Z) // Compute the near & far planes from the structure and view observations { for (Landmarks::const_iterator itL = sfm_data.GetLandmarks().begin(); itL != sfm_data.GetLandmarks().end(); ++itL) { const Landmark & landmark = itL->second; const Vec3 & X = landmark.X; for (Observations::const_iterator iterO = landmark.obs.begin(); iterO != landmark.obs.end(); ++iterO) { const IndexT id_view = iterO->first; const View * view = sfm_data.GetViews().at(id_view).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const Pose3 pose = sfm_data.GetPoseOrDie(view); const double z = pose.depth(X); NearFarPlanesT::iterator itZ = z_near_z_far_perView.find(id_view); if (itZ != z_near_z_far_perView.end()) { if ( z < itZ->second.first) itZ->second.first = z; else if ( z > itZ->second.second) itZ->second.second = z; } else z_near_z_far_perView[id_view] = std::make_pair(z,z); } } } else { // Init the same near & far limit for all the valid views for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * view = it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; if (z_near_z_far_perView.find(view->id_view) == z_near_z_far_perView.end()) z_near_z_far_perView[view->id_view] = std::make_pair(zNear, zFar); } } } } // namespace sfm } // namespace openMVG <|endoftext|>
<commit_before>// // main.cpp // afj-interpreter // // Created by Martin Kiesel on 17/02/16. // Copyright © 2016 Martin Kiesel. All rights reserved. // #include <iostream> #include <sys/stat.h> #include "lib/Interpreter/Interpreter.cpp" using namespace std; const char* VERSION = "2.0.0"; void showHelp (char *s); void showExamples (char *s); bool validateArguments (string &input_file, const string &input_stream, const string &stream_file, string *out_file, bool *overwrite_out_file, const string &print_option); bool fileExists (const string &file_name); int main (int argc, char *argv[]) { char get_opt; string source_code, stream_file, input_stream, print_option, out_file; bool overwrite_out_file = false; while((get_opt = getopt(argc, argv, "hvei:s:f:p:o:x")) != -1) { switch(get_opt) { case 'h': showHelp(argv[0]); return 0; case 'v': cout << "Current version is " << VERSION << endl; return 0; case 'e': showExamples(argv[0]); return 0; case 'i': source_code = strdup(optarg); break; case 's': input_stream = strdup(optarg); break; case 'f': stream_file = strdup(optarg); break; case 'p': print_option = strdup(optarg); break; case 'o': out_file = strdup(optarg); break; case 'x': overwrite_out_file = true; break; default: showHelp(argv[0]); break; } } if (!validateArguments(source_code, input_stream, stream_file, &out_file, &overwrite_out_file, print_option)) { return 1; } Interpreter Interpreter(source_code, input_stream, stream_file, out_file, print_option); if (Interpreter.bracketsPairCheck()) { Interpreter.run(); Interpreter.writeOutputToFile(); Interpreter.print(); } return 0; } void showHelp(char *s) { cout << "Usage: " << s << " [-option] [argument]" << endl; cout << "option: " << "-h show help" << endl; cout << " " << "-v show version infomation" << endl; cout << " " << "-e show examples" << endl; cout << " " << "-i input file (source code file) / default \"source.afj\"" << endl; cout << " " << "-s byte stream enclosed in \" ex: \"myStream\"" << endl; cout << " " << "-f file with input stream (binary file)" << endl; cout << " " << "-p hex (default) | str | hexstr | strhex / print to console" << endl; cout << " " << "-o \"file name\" where output is saved as binary data" << endl; cout << " " << "-x do not ask to overwrite output file (DOES OVERWRITE FILE)" << endl; cout << endl; cout << "example: " << s << endl; cout << "example: " << s << " -i source.afj -s \"hello world!\" -p hex" << endl; cout << "example: " << s << " -i source.afj -f stream.bin -p hexstr" << endl; cout << "example: " << s << " -i source.afj -o myoutfile.bin" << endl; cout << "See more examples using -e option." << endl; } void showExamples(char *s) { cout << "Lets assume source code is saved in \"./source.afj\", our input stream of bytes is in binary file \"./stream.bin\" and file we write to is \"out.bin\"." << endl; cout << "Showing examples for " << s << " program:" << endl; cout << s << " -i source.afj -s \"ABCDE\" -o out.bin" << endl; cout << s << " -i source.afj -s \"ABCDE\" -o out.bin -x" << endl; cout << s << " -i source.afj -f stream.bin -o out.bin -x" << endl; cout << s << " -i source.afj -f stream.bin -p hexstr" << endl; cout << s << " -i source.afj -f stream.bin -p str -o out.bin -x" << endl; } inline bool fileExists (const string& file_name) { struct stat buffer; return (stat (file_name.c_str(), &buffer) == 0); } bool validateArguments (string &source_code, const string &input_stream, const string &stream_file, string *out_file, bool *overwrite_out_file, const string &print_option) { string _out_file = *out_file; if (source_code.empty()) { cerr << "Input file (source file) not specified. Please use -i option... trying \"source.afj\"." << endl; source_code = "source.afj"; } if (!fileExists(source_code)) { cerr << "File \"" << source_code << "\" does not exist." << endl; return false; } if (input_stream.empty() && stream_file.empty()) { cout << "Input stream of bytes (or file) not defined by user, please use either -s or -f option. \nUsing '0x00' (NULL) for all \"R\" instructions." << endl; } if (!stream_file.empty() && !fileExists(stream_file)) { cerr << "File \"" << stream_file << "\" does not exist." << endl; return false; } if (!_out_file.empty() && !*overwrite_out_file && fileExists(_out_file)) { char yes_no = NULL; cout << "File \"" << _out_file << "\" already exist (use option -x to make this question disappear in future), do you want to overwrite?" << endl; do { cout << "[y/n]" << endl; cin >> yes_no; } while(!cin.fail() && yes_no != 'y' && yes_no != 'n'); if (yes_no == 'y') { *overwrite_out_file = true; cout << "File \"" << _out_file << "\" will be overwritten." << endl; } else { cout << "Program continues without writing any data to file \"" << _out_file << "\"." << endl; *out_file = _out_file.erase(); } } if (!print_option.empty() && !(!print_option.compare("hex") || !print_option.compare("str") || !print_option.compare("hexstr"))) { cout << "Printing option is unrecognized, using default printing method (hex)." << endl; } return true; }<commit_msg>getopt missing argument for option now terminates program<commit_after>// // main.cpp // afj-interpreter // // Created by Martin Kiesel on 17/02/16. // Copyright © 2016 Martin Kiesel. All rights reserved. // #include <iostream> #include <sys/stat.h> #include <unistd.h> #include "lib/Interpreter/Interpreter.cpp" using namespace std; const char* VERSION = "2.0.0"; void showHelp (char *s); void showExamples (char *s); bool validateArguments (string &input_file, const string &input_stream, const string &stream_file, string *out_file, bool *overwrite_out_file, const string &print_option); bool fileExists (const string &file_name); int main (int argc, char *argv[]) { char get_opt; string source_code, stream_file, input_stream, print_option, out_file; bool overwrite_out_file = false; while((get_opt = getopt(argc, argv, "hvei:s:f:p:o:x")) != -1) { switch(get_opt) { case '?': return 0; case 'h': showHelp(argv[0]); return 0; case 'v': cout << "Current version is " << VERSION << endl; return 0; case 'e': showExamples(argv[0]); return 0; case 'i': source_code = strdup(optarg); break; case 's': input_stream = strdup(optarg); break; case 'f': stream_file = strdup(optarg); break; case 'p': print_option = strdup(optarg); break; case 'o': out_file = strdup(optarg); break; case 'x': overwrite_out_file = true; break; default: showHelp(argv[0]); break; } } if (!validateArguments(source_code, input_stream, stream_file, &out_file, &overwrite_out_file, print_option)) { return 1; } Interpreter Interpreter(source_code, input_stream, stream_file, out_file, print_option); if (Interpreter.bracketsPairCheck()) { Interpreter.run(); Interpreter.writeOutputToFile(); Interpreter.print(); } return 0; } void showHelp(char *s) { cout << "Usage: " << s << " [-option] [argument]" << endl; cout << "option: " << "-h show help" << endl; cout << " " << "-v show version infomation" << endl; cout << " " << "-e show examples" << endl; cout << " " << "-i input file (source code file) / default \"source.afj\"" << endl; cout << " " << "-s byte stream enclosed in \" ex: \"myStream\"" << endl; cout << " " << "-f file with input stream (binary file)" << endl; cout << " " << "-p hex (default) | str | hexstr | strhex / print to console" << endl; cout << " " << "-o \"file name\" where output is saved as binary data" << endl; cout << " " << "-x do not ask to overwrite output file (DOES OVERWRITE FILE)" << endl; cout << endl; cout << "example: " << s << endl; cout << "example: " << s << " -i source.afj -s \"hello world!\" -p hex" << endl; cout << "example: " << s << " -i source.afj -f stream.bin -p hexstr" << endl; cout << "example: " << s << " -i source.afj -o myoutfile.bin" << endl; cout << "See more examples using -e option." << endl; } void showExamples(char *s) { cout << "Lets assume source code is saved in \"./source.afj\", our input stream of bytes is in binary file \"./stream.bin\" and file we write to is \"out.bin\"." << endl; cout << "Showing examples for " << s << " program:" << endl; cout << s << " -i source.afj -s \"ABCDE\" -o out.bin" << endl; cout << s << " -i source.afj -s \"ABCDE\" -o out.bin -x" << endl; cout << s << " -i source.afj -f stream.bin -o out.bin -x" << endl; cout << s << " -i source.afj -f stream.bin -p hexstr" << endl; cout << s << " -i source.afj -f stream.bin -p str -o out.bin -x" << endl; } inline bool fileExists (const string& file_name) { struct stat buffer; return (stat (file_name.c_str(), &buffer) == 0); } bool validateArguments (string &source_code, const string &input_stream, const string &stream_file, string *out_file, bool *overwrite_out_file, const string &print_option) { string _out_file = *out_file; if (source_code.empty()) { cerr << "Input file (source file) not specified. Please use -i option... trying \"source.afj\"." << endl; source_code = "source.afj"; } if (!fileExists(source_code)) { cerr << "File \"" << source_code << "\" does not exist." << endl; return false; } if (input_stream.empty() && stream_file.empty()) { cout << "Input stream of bytes (or file) not defined by user, please use either -s or -f option. \nUsing '0x00' (NULL) for all \"R\" instructions." << endl; } if (!stream_file.empty() && !fileExists(stream_file)) { cerr << "File \"" << stream_file << "\" does not exist." << endl; return false; } if (!_out_file.empty() && !*overwrite_out_file && fileExists(_out_file)) { char yes_no = NULL; cout << "File \"" << _out_file << "\" already exist (use option -x to make this question disappear in future), do you want to overwrite?" << endl; do { cout << "[y/n]" << endl; cin >> yes_no; } while(!cin.fail() && yes_no != 'y' && yes_no != 'n'); if (yes_no == 'y') { *overwrite_out_file = true; cout << "File \"" << _out_file << "\" will be overwritten." << endl; } else { cout << "Program continues without writing any data to file \"" << _out_file << "\"." << endl; *out_file = _out_file.erase(); } } if (!print_option.empty() && !(!print_option.compare("hex") || !print_option.compare("str") || !print_option.compare("hexstr"))) { cout << "Printing option is unrecognized, using default printing method (hex)." << endl; } return true; }<|endoftext|>
<commit_before><commit_msg>Filter search results by type and keyword in Template Manager.<commit_after><|endoftext|>
<commit_before>#include "discord.h" #include "system.h" #include "../logger.h" #include "../util.h" #include "../config.h" #include <sleepy_discord/sleepy_discord.h> #include <random> namespace shanghai { namespace system { namespace { const std::string HELP_TEXT = R"(/help Show this help /info Print system information /server Show server list /ch <server_id> Show channel list /dice [<max>] [<times>] Nondeterministic dice roll )"; struct DiscordConfig { std::string DefaultReply = ""; }; } // namespace class Discord::MyClient : public SleepyDiscord::DiscordClient { public: // コンストラクタ MyClient(const DiscordConfig &conf, const std::string &token, char numOfThreads) : SleepyDiscord::DiscordClient(token, numOfThreads), m_conf(conf) {} virtual ~MyClient() = default; private: DiscordConfig m_conf; // 非決定論的乱数生成器 (連打禁止) std::random_device m_rng; // コマンドとして処理出来たら true bool ExecuteCommand(SleepyDiscord::Snowflake<SleepyDiscord::Channel> ch, std::vector<std::string> args) { if (args.size() == 0) { return false; } if (args.at(0) == "/help") { sendMessage(ch, HELP_TEXT); return true; } else if (args.at(0) == "/info") { auto &sys_info = system::Get().sys_info; system::SysInfoData data = sys_info.Get(); std::string msg = util::Format( "Build Type: {0}\n" "Branch: {1}\n" "Commit: {2}\n" "White: {3}\n" "Black: {4}", { data.build_type, data.git_branch, data.git_hash, std::to_string(data.white), std::to_string(data.black) }); sendMessage(ch, msg); return true; } else if (args.at(0) == "/server") { std::vector<SleepyDiscord::Server> resp = getServers(); std::string msg = util::Format("{0} Server(s)", {std::to_string(resp.size())}); for (const auto &server : resp) { msg += '\n'; msg += server.ID; msg += ' '; msg += server.name; } sendMessage(ch, msg); return true; } else if (args.at(0) == "/ch") { if (args.size() < 2) { sendMessage(ch, "Argument error."); return true; } std::vector<SleepyDiscord::Channel> resp = getServerChannels(args.at(1)); std::string msg = util::Format("Channel(s)", {std::to_string(resp.size())}); for (const auto &ch : resp) { if (ch.type != SleepyDiscord::Channel::ChannelType::SERVER_TEXT) { continue; } msg += '\n'; msg += ch.ID; msg += ' '; msg += ch.name; } sendMessage(ch, msg); return true; } else if (args.at(0) == "/dice") { const uint64_t DICE_MAX = 1ULL << 56; const uint64_t COUNT_MAX = 100; // d * c < U64 // <=> d < U64 / c static_assert( DICE_MAX < std::numeric_limits<uint64_t>::max() / COUNT_MAX); uint64_t d = 6; uint64_t count = 1; bool error = false; if (args.size() >= 2) { try { d = util::to_uint64(args.at(1), 1, DICE_MAX); } catch(...){ error = true; } } if (args.size() >= 3) { try { count = util::to_uint64(args.at(2), 1, COUNT_MAX); } catch(...){ error = true; } } if (error) { std::string msg = util::Format( "1 <= DICE <= {0}\n" "1 <= COUNT <= {1}", {std::to_string(DICE_MAX), std::to_string(COUNT_MAX)}); sendMessage(ch, msg); return true; } std::string seq = ""; uint64_t sum = 0; for (uint64_t i = 0; i < count; i++) { std::uniform_int_distribution<uint64_t> dist(1, d); uint64_t r = dist(m_rng); sum += r; if (seq.size() != 0) { seq += ", "; } seq += std::to_string(r); } std::string msg; if (count == 1) { msg = std::to_string(sum); } else { msg = util::Format("{0}\n({1})", {std::to_string(sum), seq}); } sendMessage(ch, msg); return true; } else { return false; } } protected: void onReady(SleepyDiscord::Ready ready) override { logger.Log(LogLevel::Info, "[Discord] Ready"); { const SleepyDiscord::User &user = ready.user; const std::string &id = user.ID; logger.Log(LogLevel::Info, "[Discord] user %s %s bot:%s", id.c_str(), user.username.c_str(), user.bot ? "Yes" : "No"); } } void onMessage(SleepyDiscord::Message message) override { // ミラーマッチ対策として bot には反応しないようにする if (message.author.bot) { return; } logger.Log(LogLevel::Info, "[Discord] Message"); logger.Log(LogLevel::Info, "[Discord] %s", message.content.c_str()); // メンション時のみでフィルタ if (message.isMentioned(getID())) { // 半角スペースで区切ってメンションを削除 // 例: <@!123456789> std::vector<std::string> tokens = util::Split( message.content, ' ', true); auto result = std::remove_if(tokens.begin(), tokens.end(), [](const std::string &s) { return s.find("<") == 0 && s.rfind(">") == s.size() - 1; }); tokens.erase(result, tokens.end()); // コマンドとして実行 // できなかったらデフォルト返信 if (!ExecuteCommand(message.channelID, tokens)) { std::string msg = m_conf.DefaultReply; msg += "\n(Help command: /help)"; sendMessage(message.channelID, msg); } } } void onError(SleepyDiscord::ErrorCode errorCode, const std::string errorMessage) override { logger.Log(LogLevel::Error, "[Discord] %s", errorMessage.c_str()); } }; Discord::Discord() { logger.Log(LogLevel::Info, "Initialize Discord..."); bool enabled = config.GetBool({"Discord", "Enabled"}); std::string token = config.GetStr({"Discord", "Token"}); if (enabled) { DiscordConfig dconf; dconf.DefaultReply = config.GetStr({"Discord", "DefaultReply"}); m_client = std::make_unique<MyClient>( dconf, token, SleepyDiscord::USE_RUN_THREAD); m_thread = std::thread([this]() { try { m_client->run(); } catch (std::exception &e) { logger.Log(LogLevel::Error, "Discord thread error: %s", e.what()); } }); logger.Log(LogLevel::Info, "Initialize Discord OK"); } else { logger.Log(LogLevel::Info, "Initialize Discord OK (Disabled)"); } } Discord::~Discord() { logger.Log(LogLevel::Info, "Finalize Discord..."); if (m_client != nullptr) { logger.Log(LogLevel::Info, "Quit asio..."); logger.Flush(); m_client->quit(); logger.Log(LogLevel::Info, "Join discord thread..."); logger.Flush(); m_thread.join(); } logger.Log(LogLevel::Info, "Finalize Discord OK"); } } // namespace system } // namespace shanghai <commit_msg>/haipai 配牌機能<commit_after>#include "discord.h" #include "system.h" #include "../logger.h" #include "../util.h" #include "../config.h" #include <sleepy_discord/sleepy_discord.h> #include <random> namespace shanghai { namespace system { namespace { const std::string HELP_TEXT = R"(/help Show this help /info Print system information /server Show server list /ch <server_id> Show channel list /dice [<max>] [<times>] Nondeterministic dice roll /haipai Deal piles (MT19937) )"; struct DiscordConfig { std::string DefaultReply = ""; }; } // namespace class Discord::MyClient : public SleepyDiscord::DiscordClient { public: // コンストラクタ MyClient(const DiscordConfig &conf, const std::string &token, char numOfThreads) : SleepyDiscord::DiscordClient(token, numOfThreads), m_conf(conf) {} virtual ~MyClient() = default; private: DiscordConfig m_conf; // 非決定論的乱数生成器 (連打禁止) std::random_device m_rng; // コマンドとして処理出来たら true bool ExecuteCommand(SleepyDiscord::Snowflake<SleepyDiscord::Channel> ch, std::vector<std::string> args) { if (args.size() == 0) { return false; } if (args.at(0) == "/help") { sendMessage(ch, HELP_TEXT); return true; } else if (args.at(0) == "/info") { auto &sys_info = system::Get().sys_info; system::SysInfoData data = sys_info.Get(); std::string msg = util::Format( "Build Type: {0}\n" "Branch: {1}\n" "Commit: {2}\n" "White: {3}\n" "Black: {4}", { data.build_type, data.git_branch, data.git_hash, std::to_string(data.white), std::to_string(data.black) }); sendMessage(ch, msg); return true; } else if (args.at(0) == "/server") { std::vector<SleepyDiscord::Server> resp = getServers(); std::string msg = util::Format("{0} Server(s)", {std::to_string(resp.size())}); for (const auto &server : resp) { msg += '\n'; msg += server.ID; msg += ' '; msg += server.name; } sendMessage(ch, msg); return true; } else if (args.at(0) == "/ch") { if (args.size() < 2) { sendMessage(ch, "Argument error."); return true; } std::vector<SleepyDiscord::Channel> resp = getServerChannels(args.at(1)); std::string msg = util::Format("Channel(s)", {std::to_string(resp.size())}); for (const auto &ch : resp) { if (ch.type != SleepyDiscord::Channel::ChannelType::SERVER_TEXT) { continue; } msg += '\n'; msg += ch.ID; msg += ' '; msg += ch.name; } sendMessage(ch, msg); return true; } else if (args.at(0) == "/dice") { const uint64_t DICE_MAX = 1ULL << 56; const uint64_t COUNT_MAX = 100; // d * c < U64 // <=> d < U64 / c static_assert( DICE_MAX < std::numeric_limits<uint64_t>::max() / COUNT_MAX); uint64_t d = 6; uint64_t count = 1; bool error = false; if (args.size() >= 2) { try { d = util::to_uint64(args.at(1), 1, DICE_MAX); } catch(...){ error = true; } } if (args.size() >= 3) { try { count = util::to_uint64(args.at(2), 1, COUNT_MAX); } catch(...){ error = true; } } if (error) { std::string msg = util::Format( "1 <= DICE <= {0}\n" "1 <= COUNT <= {1}", {std::to_string(DICE_MAX), std::to_string(COUNT_MAX)}); sendMessage(ch, msg); return true; } std::string seq = ""; uint64_t sum = 0; for (uint64_t i = 0; i < count; i++) { std::uniform_int_distribution<uint64_t> dist(1, d); uint64_t r = dist(m_rng); sum += r; if (seq.size() != 0) { seq += ", "; } seq += std::to_string(r); } std::string msg; if (count == 1) { msg = std::to_string(sum); } else { msg = util::Format("{0}\n({1})", {std::to_string(sum), seq}); } sendMessage(ch, msg); return true; } else if (args.at(0) == "/haipai") { // 文字コード順だと // 🀀🀁🀂🀃🀄🀅🀆🀇🀈🀉🀊🀋🀌🀍🀏🀏🀐🀑🀒🀓🀕🀕🀖🀗🀘🀙🀚🀛🀜🀝🀞🀟🀠🀡 // になってしまう const char RES[] = u8"🀇🀈🀉🀊🀋🀌🀍🀏🀏🀙🀚🀛🀜🀝🀞🀟🀠🀡🀐🀑🀒🀓🀕🀕🀖🀗🀘🀀🀁🀂🀃🀆🀅🀄"; // sizeof(emoji_hai) == 4 static_assert(sizeof(RES) == 4 * 34 + 1); std::array<int, 136> deck; for (int i = 0; i < 34; i++) { deck[i * 4 + 0] = deck[i * 4 + 1] = deck[i * 4 + 2] = deck[i * 4 + 3] = i; } std::mt19937 engine(m_rng()); std::shuffle(deck.begin(), deck.end(), engine); std::sort(deck.begin(), deck.begin() + 14); std::string msg; for (int i = 0; i < 14; i++) { int x = deck.at(i); msg += std::string(RES, x * 4, 4); } sendMessage(ch, msg); return true; } else { return false; } } protected: void onReady(SleepyDiscord::Ready ready) override { logger.Log(LogLevel::Info, "[Discord] Ready"); { const SleepyDiscord::User &user = ready.user; const std::string &id = user.ID; logger.Log(LogLevel::Info, "[Discord] user %s %s bot:%s", id.c_str(), user.username.c_str(), user.bot ? "Yes" : "No"); } } void onMessage(SleepyDiscord::Message message) override { // ミラーマッチ対策として bot には反応しないようにする if (message.author.bot) { return; } logger.Log(LogLevel::Info, "[Discord] Message"); logger.Log(LogLevel::Info, "[Discord] %s", message.content.c_str()); // メンション時のみでフィルタ if (message.isMentioned(getID())) { // 半角スペースで区切ってメンションを削除 // 例: <@!123456789> std::vector<std::string> tokens = util::Split( message.content, ' ', true); auto result = std::remove_if(tokens.begin(), tokens.end(), [](const std::string &s) { return s.find("<") == 0 && s.rfind(">") == s.size() - 1; }); tokens.erase(result, tokens.end()); // コマンドとして実行 // できなかったらデフォルト返信 if (!ExecuteCommand(message.channelID, tokens)) { std::string msg = m_conf.DefaultReply; msg += "\n(Help command: /help)"; sendMessage(message.channelID, msg); } } } void onError(SleepyDiscord::ErrorCode errorCode, const std::string errorMessage) override { logger.Log(LogLevel::Error, "[Discord] %s", errorMessage.c_str()); } }; Discord::Discord() { logger.Log(LogLevel::Info, "Initialize Discord..."); bool enabled = config.GetBool({"Discord", "Enabled"}); std::string token = config.GetStr({"Discord", "Token"}); if (enabled) { DiscordConfig dconf; dconf.DefaultReply = config.GetStr({"Discord", "DefaultReply"}); m_client = std::make_unique<MyClient>( dconf, token, SleepyDiscord::USE_RUN_THREAD); m_thread = std::thread([this]() { try { m_client->run(); } catch (std::exception &e) { logger.Log(LogLevel::Error, "Discord thread error: %s", e.what()); } }); logger.Log(LogLevel::Info, "Initialize Discord OK"); } else { logger.Log(LogLevel::Info, "Initialize Discord OK (Disabled)"); } } Discord::~Discord() { logger.Log(LogLevel::Info, "Finalize Discord..."); if (m_client != nullptr) { logger.Log(LogLevel::Info, "Quit asio..."); logger.Flush(); m_client->quit(); logger.Log(LogLevel::Info, "Join discord thread..."); logger.Flush(); m_thread.join(); } logger.Log(LogLevel::Info, "Finalize Discord OK"); } } // namespace system } // namespace shanghai <|endoftext|>
<commit_before>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " with index " << childSegment->getArrayIndex() << " and start position " << childSegment->getStartPosition() << " and sequence " << childSegment->getSequence()->getName() << " has length " << childSegment->getLength() << " but parent with index " << bottomSegment->getArrayIndex() << " and start position " << bottomSegment->getStartPosition() << " in sequence " << bottomSegment->getSequence()->getName() << " has length " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { stringstream ss; ss << "Parent / child index mismatch:\n" << genome->getName() << "[" << bottomSegment->getArrayIndex() << "]" << " links to " << childGenome->getName() << "[" << childIndex << "] but \n" << childGenome->getName() << "[" << childSegment->getArrayIndex() << "] links to " << genome->getName() << "[" << childSegment->getParentIndex() << "]"; throw hal_exception(ss.str()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index out of range"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } if (paralogyIndex == topSegment->getArrayIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has paralogy index " << topSegment->getNextParalogyIndex() << " which isn't allowed"; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } } <commit_msg>make parse index out of bounds error message more verbose<commit_after>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <sstream> #include <deque> #include <vector> #include <iostream> #include "halValidate.h" #include "hal.h" using namespace std; using namespace hal; // current implementation is poor and hacky. should fix up to // use iterators to properly scan the segments. void hal::validateBottomSegment(const BottomSegment* bottomSegment) { const Genome* genome = bottomSegment->getGenome(); hal_index_t index = bottomSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Bottom segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (bottomSegment->getLength() < 1) { stringstream ss; ss << "Bottom segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } hal_size_t numChildren = bottomSegment->getNumChildren(); for (hal_size_t child = 0; child < numChildren; ++child) { const Genome* childGenome = genome->getChild(child); const hal_index_t childIndex = bottomSegment->getChildIndex(child); if (childGenome != NULL && childIndex != NULL_INDEX) { if (childIndex >= (hal_index_t)childGenome->getNumTopSegments()) { stringstream ss; ss << "Child " << child << " index " <<childIndex << " of segment " << bottomSegment->getArrayIndex() << " out of range in genome " << childGenome->getName(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr topSegmentIteratr = childGenome->getTopSegmentIterator(childIndex); const TopSegment* childSegment = topSegmentIteratr->getTopSegment(); if (childSegment->getLength() != bottomSegment->getLength()) { stringstream ss; ss << "Child " << child << " with index " << childSegment->getArrayIndex() << " and start position " << childSegment->getStartPosition() << " and sequence " << childSegment->getSequence()->getName() << " has length " << childSegment->getLength() << " but parent with index " << bottomSegment->getArrayIndex() << " and start position " << bottomSegment->getStartPosition() << " in sequence " << bottomSegment->getSequence()->getName() << " has length " << bottomSegment->getLength(); throw hal_exception(ss.str()); } if (childSegment->getNextParalogyIndex() == NULL_INDEX && childSegment->getParentIndex() != bottomSegment->getArrayIndex()) { stringstream ss; ss << "Parent / child index mismatch:\n" << genome->getName() << "[" << bottomSegment->getArrayIndex() << "]" << " links to " << childGenome->getName() << "[" << childIndex << "] but \n" << childGenome->getName() << "[" << childSegment->getArrayIndex() << "] links to " << genome->getName() << "[" << childSegment->getParentIndex() << "]"; throw hal_exception(ss.str()); } if (childSegment->getParentReversed() != bottomSegment->getChildReversed(child)) { throw hal_exception("parent / child reversal mismatch (parent=" + genome->getName() + " child=" + childGenome->getName()); } } } const hal_index_t parseIndex = bottomSegment->getTopParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getParent() != NULL) { stringstream ss; ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumTopSegments()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " greater than the number of top segments, " << (hal_index_t)genome->getNumTopSegments(); throw hal_exception(ss.str()); } TopSegmentIteratorConstPtr parseIterator = genome->getTopSegmentIterator(parseIndex); const TopSegment* parseSegment = parseIterator->getTopSegment(); hal_offset_t parseOffset = bottomSegment->getTopParseOffset(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset, " << parseOffset << ", greater than the length of the segment, " << parseSegment->getLength(); throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != bottomSegment->getStartPosition()) { throw hal_exception("parse index broken in bottom segment in genome " + genome->getName()); } } } void hal::validateTopSegment(const TopSegment* topSegment) { const Genome* genome = topSegment->getGenome(); hal_index_t index = topSegment->getArrayIndex(); if (index < 0 || index >= (hal_index_t)genome->getSequenceLength()) { stringstream ss; ss << "Segment out of range " << index << " in genome " << genome->getName(); throw hal_exception(ss.str()); } if (topSegment->getLength() < 1) { stringstream ss; ss << "Top segment " << index << " in genome " << genome->getName() << " has length 0 which is not currently supported"; throw hal_exception(ss.str()); } const Genome* parentGenome = genome->getParent(); const hal_index_t parentIndex = topSegment->getParentIndex(); if (parentGenome != NULL && parentIndex != NULL_INDEX) { if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments()) { stringstream ss; ss << "Parent index " << parentIndex << " of segment " << topSegment->getArrayIndex() << " out of range in genome " << parentGenome->getName(); throw hal_exception(ss.str()); } BottomSegmentIteratorConstPtr bottomSegmentIterator = parentGenome->getBottomSegmentIterator(parentIndex); const BottomSegment* parentSegment = bottomSegmentIterator->getBottomSegment(); if (topSegment->getLength() != parentSegment->getLength()) { stringstream ss; ss << "Parent length of segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has length " << parentSegment->getLength() << " which does not match " << topSegment->getLength(); throw hal_exception(ss.str()); } } const hal_index_t parseIndex = topSegment->getBottomParseIndex(); if (parseIndex == NULL_INDEX) { if (genome->getNumChildren() != 0) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has null parse index"; throw hal_exception(ss.str()); } } else { if (parseIndex >= (hal_index_t)genome->getNumBottomSegments()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse index " << parseIndex << " which is out of range since genome has " << genome->getNumBottomSegments() << " bottom segments"; throw hal_exception(ss.str()); } hal_offset_t parseOffset = topSegment->getBottomParseOffset(); BottomSegmentIteratorConstPtr bottomSegmentIterator = genome->getBottomSegmentIterator(parseIndex); const BottomSegment* parseSegment = bottomSegmentIterator->getBottomSegment(); if (parseOffset >= parseSegment->getLength()) { stringstream ss; ss << "Top Segment " << topSegment->getArrayIndex() << " in genome " << genome->getName() << " has parse offset out of range"; throw hal_exception(ss.str()); } if ((hal_index_t)parseOffset + parseSegment->getStartPosition() != topSegment->getStartPosition()) { throw hal_exception("parse index broken in top segment in genome " + genome->getName()); } } const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex(); if (paralogyIndex != NULL_INDEX) { TopSegmentIteratorConstPtr pti = genome->getTopSegmentIterator(paralogyIndex); if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has parent index " << topSegment->getParentIndex() << ", but next paraglog " << topSegment->getNextParalogyIndex() << " has parent Index " << pti->getTopSegment()->getParentIndex() << ". Paralogous top segments must share same parent."; throw hal_exception(ss.str()); } if (paralogyIndex == topSegment->getArrayIndex()) { stringstream ss; ss << "Top segment " << topSegment->getArrayIndex() << " has paralogy index " << topSegment->getNextParalogyIndex() << " which isn't allowed"; throw hal_exception(ss.str()); } } } void hal::validateSequence(const Sequence* sequence) { // Verify that the DNA sequence doesn't contain funny characters DNAIteratorConstPtr dnaIt = sequence->getDNAIterator(); hal_size_t length = sequence->getSequenceLength(); for (hal_size_t i = 0; i < length; ++i) { char c = dnaIt->getChar(); if (isNucleotide(c) == false) { stringstream ss; ss << "Non-nucleotide character discoverd at position " << i << " of sequence " << sequence->getName() << ": " << c; throw hal_exception(ss.str()); } } // Check the top segments if (sequence->getGenome()->getParent() != NULL) { hal_size_t totalTopLength = 0; TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator(); hal_size_t numTopSegments = sequence->getNumTopSegments(); for (hal_size_t i = 0; i < numTopSegments; ++i) { const TopSegment* topSegment = topIt->getTopSegment(); validateTopSegment(topSegment); totalTopLength += topSegment->getLength(); topIt->toRight(); } if (totalTopLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its top segments add up to " << totalTopLength; throw hal_exception(ss.str()); } } // Check the bottom segments if (sequence->getGenome()->getNumChildren() > 0) { hal_size_t totalBottomLength = 0; BottomSegmentIteratorConstPtr bottomIt = sequence->getBottomSegmentIterator(); hal_size_t numBottomSegments = sequence->getNumBottomSegments(); for (hal_size_t i = 0; i < numBottomSegments; ++i) { const BottomSegment* bottomSegment = bottomIt->getBottomSegment(); validateBottomSegment(bottomSegment); totalBottomLength += bottomSegment->getLength(); bottomIt->toRight(); } if (totalBottomLength != length) { stringstream ss; ss << "Sequence " << sequence->getName() << " has length " << length << " but its bottom segments add up to " << totalBottomLength; throw hal_exception(ss.str()); } } } void hal::validateDuplications(const Genome* genome) { const Genome* parent = genome->getParent(); if (parent == NULL) { return; } TopSegmentIteratorConstPtr topIt = genome->getTopSegmentIterator(); TopSegmentIteratorConstPtr endIt = genome->getTopSegmentEndIterator(); vector<unsigned char> pcount(parent->getNumBottomSegments(), 0); for (; topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { if (pcount[topIt->getTopSegment()->getParentIndex()] < 250) { ++pcount[topIt->getTopSegment()->getParentIndex()]; } } } for (topIt = genome->getTopSegmentIterator(); topIt != endIt; topIt->toRight()) { if (topIt->hasParent()) { size_t count = pcount[topIt->getTopSegment()->getParentIndex()]; assert(count > 0); { if (topIt->hasNextParalogy() == false && count > 1) { stringstream ss; ss << "Top Segment " << topIt->getTopSegment()->getArrayIndex() << " in genome " << genome->getName() << " is not marked as a" << " duplication but it shares its parent " << topIt->getTopSegment()->getArrayIndex() << " with at least " << count - 1 << " other segments in the same genome"; throw hal_exception(ss.str()); } } } } } void hal::validateGenome(const Genome* genome) { // first we check the sequence coverage hal_size_t totalTop = 0; hal_size_t totalBottom = 0; hal_size_t totalLength = 0; SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEnd = genome->getSequenceEndIterator(); for (; seqIt != seqEnd; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); validateSequence(sequence); totalTop += sequence->getNumTopSegments(); totalBottom += sequence->getNumBottomSegments(); totalLength += sequence->getSequenceLength(); // make sure it doesn't overlap any other sequences; if (sequence->getSequenceLength() > 0) { const Sequence* s1 = genome->getSequenceBySite(sequence->getStartPosition()); if (s1 == NULL || s1->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } const Sequence* s2 = genome->getSequenceBySite(sequence->getStartPosition() + sequence->getSequenceLength() - 1); if (s2 == NULL || s2->getName() != sequence->getName()) { stringstream ss; ss << "Sequence " << sequence->getName() << " has a bad overlap in " << genome->getName(); throw hal_exception(ss.str()); } } } hal_size_t genomeLength = genome->getSequenceLength(); hal_size_t genomeTop = genome->getNumTopSegments(); hal_size_t genomeBottom = genome->getNumBottomSegments(); if (genomeLength != totalLength) { stringstream ss; ss << "Problem: genome has length " << genomeLength << "But sequences total " << totalLength; throw hal_exception(ss.str()); } if (genomeTop != totalTop) { stringstream ss; ss << "Problem: genome has " << genomeTop << " top segments but " << "sequences have " << totalTop << " top segments"; throw ss.str(); } if (genomeBottom != totalBottom) { stringstream ss; ss << "Problem: genome has " << genomeBottom << " bottom segments but " << "sequences have " << totalBottom << " bottom segments"; throw hal_exception(ss.str()); } if (genomeLength > 0 && genomeTop == 0 && genomeBottom == 0) { stringstream ss; ss << "Problem: genome " << genome->getName() << " has length " << genomeLength << "but no segments"; throw hal_exception(ss.str()); } validateDuplications(genome); } void hal::validateAlignment(AlignmentConstPtr alignment) { deque<string> bfQueue; bfQueue.push_back(alignment->getRootName()); while (bfQueue.empty() == false) { string name = bfQueue.back(); bfQueue.pop_back(); if (name.empty() == false) { const Genome* genome = alignment->openGenome(name); if (genome == NULL) { throw hal_exception("Failure to open genome " + name); } validateGenome(genome); vector<string> childNames = alignment->getChildNames(name); for (size_t i = 0; i < childNames.size(); ++i) { bfQueue.push_front(childNames[i]); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: table.hxx,v $ * * $Revision: 1.22 $ * * last change: $Author: vg $ $Date: 2002-10-30 09:34:14 $ * * 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 _DBA_CORE_TABLE_HXX_ #define _DBA_CORE_TABLE_HXX_ #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_ #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XIndexesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_ #include <com/sun/star/sdbcx/XRename.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_ #include <com/sun/star/sdbcx/XAlterTable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase7.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _DBA_CORE_DATASETTINGS_HXX_ #include "datasettings.hxx" #endif #ifndef _DBA_COREAPI_COLUMN_HXX_ #include <column.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef CONNECTIVITY_TABLEHELPER_HXX #include <connectivity/TTableHelper.hxx> #endif #ifndef _DBA_CORE_CONFIGURATIONFLUSHABLE_HXX_ #include "configurationflushable.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif namespace dbaccess { typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection; //========================================================================== //= OTables //========================================================================== class ODBTable; typedef ::comphelper::OIdPropertyArrayUsageHelper< ODBTable > ODBTable_PROP; typedef ::connectivity::OTableHelper OTable_Base; typedef ::connectivity::sdbcx::OTableDescriptor_BASE OTable_Linux; class ODBTable :public ODataSettings_Base ,public ODBTable_PROP ,public OTable_Base ,public OConfigurationFlushable ,public IColumnFactory { protected: ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xDriverColumns; using OTable_Linux::rBHelper; // <properties> sal_Int32 m_nPrivileges; // </properties> virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const; virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // OConfigurationFlushable virtual void flush_NoBroadcast_NoCommit(); // IColumnFactory virtual OColumn* createColumn(const ::rtl::OUString& _rName) const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject(); /** creates the column collection for the table @param _rNames The column names. */ virtual ::connectivity::sdbcx::OCollection* createColumns(const ::connectivity::TStringVector& _rNames); /** creates the key collection for the table @param _rNames The key names. */ virtual ::connectivity::sdbcx::OCollection* createKeys(const ::connectivity::TStringVector& _rNames); /** creates the index collection for the table @param _rNames The index names. */ virtual ::connectivity::sdbcx::OCollection* createIndexes(const ::connectivity::TStringVector& _rNames); // OComponentHelper virtual void SAL_CALL disposing(void); public: /** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR> @param _rxConn the connection the table belongs to @param _rxTable the table from the driver can be null @param _rCatalog the name of the catalog the table belongs to. May be empty. @param _rSchema the name of the schema the table belongs to. May be empty. @param _rName the name of the table @param _rType the type of the table, as supplied by the driver @param _rDesc the description of the table, as supplied by the driver */ ODBTable(connectivity::sdbcx::OCollection* _pTables,const ::utl::OConfigurationNode& _rTableConfig, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName, const ::rtl::OUString& _rType, const ::rtl::OUString& _rDesc) throw(::com::sun::star::sdbc::SQLException); ODBTable(connectivity::sdbcx::OCollection* _pTables,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn) throw(::com::sun::star::sdbc::SQLException); virtual ~ODBTable(); // ODescriptor virtual void construct(); //XInterface DECLARE_XINTERFACE() //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId(); // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // com::sun::star::beans::XPropertySet // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const; // ::com::sun::star::sdbcx::XRename, virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // ::com::sun::star::sdbcx::XAlterTable, virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // com::sun::star::lang::XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); virtual void refreshColumns(); }; } #endif // _DBA_CORE_TABLE_HXX_ <commit_msg>#100000# removed obsole declaration<commit_after>/************************************************************************* * * $RCSfile: table.hxx,v $ * * $Revision: 1.23 $ * * last change: $Author: vg $ $Date: 2002-10-30 14:58:43 $ * * 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 _DBA_CORE_TABLE_HXX_ #define _DBA_CORE_TABLE_HXX_ #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_ #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XIndexesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XKeysSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_ #include <com/sun/star/sdbcx/XRename.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_ #include <com/sun/star/sdbcx/XAlterTable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase7.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef _DBA_CORE_DATASETTINGS_HXX_ #include "datasettings.hxx" #endif #ifndef _DBA_COREAPI_COLUMN_HXX_ #include <column.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef CONNECTIVITY_TABLEHELPER_HXX #include <connectivity/TTableHelper.hxx> #endif #ifndef _DBA_CORE_CONFIGURATIONFLUSHABLE_HXX_ #include "configurationflushable.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif namespace dbaccess { typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection; //========================================================================== //= OTables //========================================================================== class ODBTable; typedef ::comphelper::OIdPropertyArrayUsageHelper< ODBTable > ODBTable_PROP; typedef ::connectivity::OTableHelper OTable_Base; typedef ::connectivity::sdbcx::OTableDescriptor_BASE OTable_Linux; class ODBTable :public ODataSettings_Base ,public ODBTable_PROP ,public OTable_Base ,public OConfigurationFlushable ,public IColumnFactory { protected: ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xDriverColumns; // <properties> sal_Int32 m_nPrivileges; // </properties> virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const; virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // OConfigurationFlushable virtual void flush_NoBroadcast_NoCommit(); // IColumnFactory virtual OColumn* createColumn(const ::rtl::OUString& _rName) const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject(); /** creates the column collection for the table @param _rNames The column names. */ virtual ::connectivity::sdbcx::OCollection* createColumns(const ::connectivity::TStringVector& _rNames); /** creates the key collection for the table @param _rNames The key names. */ virtual ::connectivity::sdbcx::OCollection* createKeys(const ::connectivity::TStringVector& _rNames); /** creates the index collection for the table @param _rNames The index names. */ virtual ::connectivity::sdbcx::OCollection* createIndexes(const ::connectivity::TStringVector& _rNames); // OComponentHelper virtual void SAL_CALL disposing(void); public: /** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR> @param _rxConn the connection the table belongs to @param _rxTable the table from the driver can be null @param _rCatalog the name of the catalog the table belongs to. May be empty. @param _rSchema the name of the schema the table belongs to. May be empty. @param _rName the name of the table @param _rType the type of the table, as supplied by the driver @param _rDesc the description of the table, as supplied by the driver */ ODBTable(connectivity::sdbcx::OCollection* _pTables,const ::utl::OConfigurationNode& _rTableConfig, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName, const ::rtl::OUString& _rType, const ::rtl::OUString& _rDesc) throw(::com::sun::star::sdbc::SQLException); ODBTable(connectivity::sdbcx::OCollection* _pTables,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn) throw(::com::sun::star::sdbc::SQLException); virtual ~ODBTable(); // ODescriptor virtual void construct(); //XInterface DECLARE_XINTERFACE() //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId(); // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // com::sun::star::beans::XPropertySet // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const; // ::com::sun::star::sdbcx::XRename, virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // ::com::sun::star::sdbcx::XAlterTable, virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // com::sun::star::lang::XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); virtual void refreshColumns(); }; } #endif // _DBA_CORE_TABLE_HXX_ <|endoftext|>
<commit_before>#include "asio_tcp_connection.h" #include "halley/support/logger.h" #include "halley/text/halleystring.h" #include "halley/text/string_converter.h" #include "halley/net/connection/network_packet.h" using namespace Halley; AsioTCPConnection::AsioTCPConnection(asio::io_service& service, TCPSocket socket) : service(service) , socket(std::move(socket)) , status(ConnectionStatus::Connected) {} AsioTCPConnection::AsioTCPConnection(asio::io_service& service, String host, int port) : service(service) , socket(service) , status(ConnectionStatus::Connecting) { resolver = std::make_unique<asio::ip::tcp::resolver>(service); resolver->async_resolve(host.cppStr(), toString(port).cppStr(), [=] (const boost::system::error_code& ec, asio::ip::tcp::resolver::results_type result) { if (ec) { Logger::logError("Error trying to connect to " + host + ":" + toString(port) + ": " + ec.message()); } else { for (auto& r: result) { boost::system::error_code ec2; socket.connect(r, ec2); if (!ec2) { Logger::logDev("Connected to " + host + ":" + toString(port)); status = ConnectionStatus::Connected; break; } } if (status != ConnectionStatus::Connected) { Logger::logError("Error trying to connect to " + host + ":" + toString(port) + "."); status = ConnectionStatus::Closing; } } }); service.poll(); } AsioTCPConnection::~AsioTCPConnection() { AsioTCPConnection::close(); } void AsioTCPConnection::update() { if (status == ConnectionStatus::Closing) { close(); } if (status == ConnectionStatus::Connected) { { std::unique_lock<std::mutex> lock(mutex); needsPoll = false; tryReceive(); trySend(); } if (!socket.is_open()) { close(); } } } void AsioTCPConnection::close() { std::unique_lock<std::mutex> lock(mutex); resolver.reset(); if (status != ConnectionStatus::Closed) { Logger::logInfo("Disconnected"); try { if (!socket.is_open()) { socket.shutdown(TCPSocket::shutdown_both); socket.close(); } } catch (std::exception& e) { Logger::logException(e); } catch (...) { Logger::logError(String("Unknown error closing TCP connection")); } needsPoll = false; status = ConnectionStatus::Closed; } } ConnectionStatus AsioTCPConnection::getStatus() const { return status; } void AsioTCPConnection::send(OutboundNetworkPacket&& packet) { packet.addHeader(uint32_t(packet.getSize())); auto bytes = packet.getBytes(); auto bs = Bytes(bytes.size_bytes()); memcpy(bs.data(), bytes.data(), bytes.size()); std::unique_lock<std::mutex> lock(mutex); if (status == ConnectionStatus::Connected) { sendQueue.emplace_back(std::move(bs)); if (sendQueue.size() == 1) { trySend(); } } } bool AsioTCPConnection::receive(InboundNetworkPacket& packet) { std::unique_lock<std::mutex> lock(mutex); if (receiveQueue.size() >= sizeof(uint32_t) && status == ConnectionStatus::Connected) { const uint32_t size = *reinterpret_cast<uint32_t*>(receiveQueue.data()); if (size > 128 * 1024 * 1024) { Logger::logError("Invalid packet size."); close(); } const auto packetSize = sizeof(uint32_t) + size; if (receiveQueue.size() >= packetSize) { packet = InboundNetworkPacket(gsl::as_bytes(gsl::span<Byte>(receiveQueue.data(), packetSize))); uint32_t size2; packet.extractHeader(size2); receiveQueue.erase(receiveQueue.begin(), receiveQueue.begin() + packetSize); return true; } } return false; } bool AsioTCPConnection::needsPolling() const { return needsPoll; } void AsioTCPConnection::trySend() { if (!sendQueue.empty() && status == ConnectionStatus::Connected) { needsPoll = true; sendingQueue.emplace_back(std::move(sendQueue.front())); sendQueue.pop_front(); auto& toSend = sendingQueue.back(); socket.async_write_some(asio::buffer(toSend.data(), toSend.size()), [=] (const boost::system::error_code& ec, size_t bytesWritten) { if (ec) { Logger::logError("Error sending data on TCP socket: " + ec.message()); close(); } else { auto& front = sendingQueue.front(); if (bytesWritten == front.size()) { sendingQueue.pop_front(); } else { front.erase(front.begin(), front.begin() + bytesWritten); } trySend(); } }); } } void AsioTCPConnection::tryReceive() { if (!reading && status == ConnectionStatus::Connected) { needsPoll = true; reading = true; if (receiveBuffer.size() < 4096) { receiveBuffer.resize(4096); } socket.async_read_some(asio::mutable_buffer(receiveBuffer.data(), receiveBuffer.size()), [=] (const boost::system::error_code& ec, size_t nBytesReceived) { reading = false; if (ec) { // retry on would_block and try_again errors, close connection on any other errors if (ec.value() == asio::error::would_block || ec.value() == asio::error::try_again) { tryReceive(); } else { Logger::logError("Error reading data on TCP socket: " + ec.message()); close(); } } else { size_t curQueueSize = receiveQueue.size(); receiveQueue.resize(curQueueSize + nBytesReceived); memcpy(receiveQueue.data() + curQueueSize, receiveBuffer.data(), nBytesReceived); if (nBytesReceived == 4096) { tryReceive(); } } }); } } <commit_msg>Fix race condition<commit_after>#include "asio_tcp_connection.h" #include "halley/support/logger.h" #include "halley/text/halleystring.h" #include "halley/text/string_converter.h" #include "halley/net/connection/network_packet.h" using namespace Halley; AsioTCPConnection::AsioTCPConnection(asio::io_service& service, TCPSocket socket) : service(service) , socket(std::move(socket)) , status(ConnectionStatus::Connected) {} AsioTCPConnection::AsioTCPConnection(asio::io_service& service, String host, int port) : service(service) , socket(service) , status(ConnectionStatus::Connecting) { resolver = std::make_unique<asio::ip::tcp::resolver>(service); resolver->async_resolve(host.cppStr(), toString(port).cppStr(), [=] (const boost::system::error_code& ec, asio::ip::tcp::resolver::results_type result) { if (ec) { Logger::logError("Error trying to connect to " + host + ":" + toString(port) + ": " + ec.message()); } else { for (auto& r: result) { boost::system::error_code ec2; socket.connect(r, ec2); if (!ec2) { Logger::logDev("Connected to " + host + ":" + toString(port)); status = ConnectionStatus::Connected; break; } } if (status != ConnectionStatus::Connected) { Logger::logError("Error trying to connect to " + host + ":" + toString(port) + "."); status = ConnectionStatus::Closing; } } }); service.poll(); } AsioTCPConnection::~AsioTCPConnection() { AsioTCPConnection::close(); } void AsioTCPConnection::update() { if (status == ConnectionStatus::Closing) { close(); } if (status == ConnectionStatus::Connected) { { std::unique_lock<std::mutex> lock(mutex); needsPoll = false; tryReceive(); trySend(); } if (!socket.is_open()) { close(); } } } void AsioTCPConnection::close() { std::unique_lock<std::mutex> lock(mutex); resolver.reset(); if (status != ConnectionStatus::Closed) { Logger::logInfo("Disconnected"); try { if (!socket.is_open()) { socket.shutdown(TCPSocket::shutdown_both); socket.close(); } } catch (std::exception& e) { Logger::logException(e); } catch (...) { Logger::logError(String("Unknown error closing TCP connection")); } needsPoll = false; status = ConnectionStatus::Closed; } } ConnectionStatus AsioTCPConnection::getStatus() const { return status; } void AsioTCPConnection::send(OutboundNetworkPacket&& packet) { packet.addHeader(uint32_t(packet.getSize())); auto bytes = packet.getBytes(); auto bs = Bytes(bytes.size_bytes()); memcpy(bs.data(), bytes.data(), bytes.size()); std::unique_lock<std::mutex> lock(mutex); if (status == ConnectionStatus::Connected) { sendQueue.emplace_back(std::move(bs)); if (sendQueue.size() == 1) { trySend(); } } } bool AsioTCPConnection::receive(InboundNetworkPacket& packet) { std::unique_lock<std::mutex> lock(mutex); if (receiveQueue.size() >= sizeof(uint32_t) && status == ConnectionStatus::Connected) { const uint32_t size = *reinterpret_cast<uint32_t*>(receiveQueue.data()); if (size > 128 * 1024 * 1024) { Logger::logError("Invalid packet size."); close(); } const auto packetSize = sizeof(uint32_t) + size; if (receiveQueue.size() >= packetSize) { packet = InboundNetworkPacket(gsl::as_bytes(gsl::span<Byte>(receiveQueue.data(), packetSize))); uint32_t size2; packet.extractHeader(size2); receiveQueue.erase(receiveQueue.begin(), receiveQueue.begin() + packetSize); return true; } } return false; } bool AsioTCPConnection::needsPolling() const { return needsPoll; } void AsioTCPConnection::trySend() { if (!sendQueue.empty() && status == ConnectionStatus::Connected) { needsPoll = true; sendingQueue.emplace_back(std::move(sendQueue.front())); sendQueue.pop_front(); auto& toSend = sendingQueue.back(); socket.async_write_some(asio::buffer(toSend.data(), toSend.size()), [=] (const boost::system::error_code& ec, size_t bytesWritten) { if (ec) { Logger::logError("Error sending data on TCP socket: " + ec.message()); close(); } else { auto& front = sendingQueue.front(); if (bytesWritten == front.size()) { sendingQueue.pop_front(); } else { front.erase(front.begin(), front.begin() + bytesWritten); } std::unique_lock<std::mutex> lock(mutex); trySend(); } }); } } void AsioTCPConnection::tryReceive() { if (!reading && status == ConnectionStatus::Connected) { needsPoll = true; reading = true; if (receiveBuffer.size() < 4096) { receiveBuffer.resize(4096); } socket.async_read_some(asio::mutable_buffer(receiveBuffer.data(), receiveBuffer.size()), [=] (const boost::system::error_code& ec, size_t nBytesReceived) { reading = false; if (ec) { // retry on would_block and try_again errors, close connection on any other errors if (ec.value() == asio::error::would_block || ec.value() == asio::error::try_again) { tryReceive(); } else { Logger::logError("Error reading data on TCP socket: " + ec.message()); close(); } } else { size_t curQueueSize = receiveQueue.size(); receiveQueue.resize(curQueueSize + nBytesReceived); memcpy(receiveQueue.data() + curQueueSize, receiveBuffer.data(), nBytesReceived); if (nBytesReceived == 4096) { tryReceive(); } } }); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basevcseditorfactory.h" #include "vcsbaseeditor.h" #include <texteditor/texteditoractionhandler.h> #include <texteditor/texteditorsettings.h> #include <QCoreApplication> #include <QStringList> /*! \class VcsBase::BaseVCSEditorFactory \brief The BaseVCSEditorFactory class is the base class for editor factories creating instances of VcsBaseEditor subclasses. \sa VcsBase::VcsBaseEditorWidget */ namespace VcsBase { namespace Internal { class BaseVcsEditorFactoryPrivate { public: BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t); const VcsBaseEditorParameters *m_type; }; BaseVcsEditorFactoryPrivate::BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t) : m_type(t) { } } // namespace Internal BaseVcsEditorFactory::BaseVcsEditorFactory(const VcsBaseEditorParameters *t) : d(new Internal::BaseVcsEditorFactoryPrivate(t)) { setId(t->id); setDisplayName(QCoreApplication::translate("VCS", t->displayName)); addMimeType(t->mimeType); new TextEditor::TextEditorActionHandler(this, t->context); } BaseVcsEditorFactory::~BaseVcsEditorFactory() { delete d; } Core::IEditor *BaseVcsEditorFactory::createEditor(QWidget *parent) { VcsBaseEditorWidget *vcsEditor = createVcsBaseEditor(d->m_type, parent); vcsEditor->setMimeType(mimeTypes().front()); // Wire font settings and set initial values connect(TextEditor::TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)), vcsEditor, SLOT(setFontSettings(TextEditor::FontSettings))); vcsEditor->setFontSettings(TextEditor::TextEditorSettings::fontSettings()); return vcsEditor->editor(); } } // namespace VcsBase <commit_msg>VcsBaseEditor: Use standard method for getting editor settings updates<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basevcseditorfactory.h" #include "vcsbaseeditor.h" #include <texteditor/texteditoractionhandler.h> #include <texteditor/texteditorsettings.h> #include <QCoreApplication> #include <QStringList> /*! \class VcsBase::BaseVCSEditorFactory \brief The BaseVCSEditorFactory class is the base class for editor factories creating instances of VcsBaseEditor subclasses. \sa VcsBase::VcsBaseEditorWidget */ namespace VcsBase { namespace Internal { class BaseVcsEditorFactoryPrivate { public: BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t); const VcsBaseEditorParameters *m_type; }; BaseVcsEditorFactoryPrivate::BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t) : m_type(t) { } } // namespace Internal BaseVcsEditorFactory::BaseVcsEditorFactory(const VcsBaseEditorParameters *t) : d(new Internal::BaseVcsEditorFactoryPrivate(t)) { setId(t->id); setDisplayName(QCoreApplication::translate("VCS", t->displayName)); addMimeType(t->mimeType); new TextEditor::TextEditorActionHandler(this, t->context); } BaseVcsEditorFactory::~BaseVcsEditorFactory() { delete d; } Core::IEditor *BaseVcsEditorFactory::createEditor(QWidget *parent) { VcsBaseEditorWidget *vcsEditor = createVcsBaseEditor(d->m_type, parent); vcsEditor->setMimeType(mimeTypes().front()); TextEditor::TextEditorSettings::initializeEditor(vcsEditor); return vcsEditor->editor(); } } // namespace VcsBase <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_key_event_plugin.h" #include "flutter/shell/platform/linux/fl_plugin_registrar_private.h" #include "flutter/shell/platform/linux/fl_renderer_x11.h" #include "flutter/shell/platform/linux/fl_text_input_plugin.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h" #include <gdk/gdkx.h> static constexpr int kMicrosecondsPerMillisecond = 1000; struct _FlView { GtkWidget parent_instance; // Project being run. FlDartProject* project; // Rendering output. FlRendererX11* renderer; // Engine running @project. FlEngine* engine; // Pointer button state recorded for sending status updates. int64_t button_state; // Flutter system channel handlers. FlKeyEventPlugin* key_event_plugin; FlTextInputPlugin* text_input_plugin; }; enum { PROP_FLUTTER_PROJECT = 1, PROP_LAST }; static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlView, fl_view, GTK_TYPE_WIDGET, G_IMPLEMENT_INTERFACE(fl_plugin_registry_get_type(), fl_view_plugin_registry_iface_init)) // Converts a GDK button event into a Flutter event and sends it to the engine. static gboolean fl_view_send_pointer_button_event(FlView* self, GdkEventButton* event) { int64_t button; switch (event->button) { case 1: button = kFlutterPointerButtonMousePrimary; break; case 2: button = kFlutterPointerButtonMouseMiddle; break; case 3: button = kFlutterPointerButtonMouseSecondary; break; default: return FALSE; } int old_button_state = self->button_state; FlutterPointerPhase phase; if (event->type == GDK_BUTTON_PRESS) { // Drop the event if Flutter already thinks the button is down. if ((self->button_state & button) != 0) return FALSE; self->button_state ^= button; phase = old_button_state == 0 ? kDown : kMove; } else if (event->type == GDK_BUTTON_RELEASE) { // Drop the event if Flutter already thinks the button is up. if ((self->button_state & button) == 0) return FALSE; self->button_state ^= button; phase = self->button_state == 0 ? kUp : kMove; } if (self->engine == nullptr) return FALSE; fl_engine_send_mouse_pointer_event(self->engine, phase, event->time * kMicrosecondsPerMillisecond, event->x, event->y, self->button_state); return TRUE; } // Implements FlPluginRegistry::get_registrar_for_plugin. static FlPluginRegistrar* fl_view_get_registrar_for_plugin( FlPluginRegistry* registry, const gchar* name) { FlView* self = FL_VIEW(registry); return fl_plugin_registrar_new(self, fl_engine_get_binary_messenger(self->engine)); } static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface) { iface->get_registrar_for_plugin = fl_view_get_registrar_for_plugin; } static void fl_view_constructed(GObject* object) { FlView* self = FL_VIEW(object); self->renderer = fl_renderer_x11_new(); self->engine = fl_engine_new(self->project, FL_RENDERER(self->renderer)); // Create system channel handlers. FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(self->engine); self->key_event_plugin = fl_key_event_plugin_new(messenger); self->text_input_plugin = fl_text_input_plugin_new(messenger); } static void fl_view_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case PROP_FLUTTER_PROJECT: g_set_object(&self->project, static_cast<FlDartProject*>(g_value_get_object(value))); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case PROP_FLUTTER_PROJECT: g_value_set_object(value, self->project); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_dispose(GObject* object) { FlView* self = FL_VIEW(object); g_clear_object(&self->project); g_clear_object(&self->renderer); g_clear_object(&self->engine); g_clear_object(&self->key_event_plugin); g_clear_object(&self->text_input_plugin); G_OBJECT_CLASS(fl_view_parent_class)->dispose(object); } // Implements GtkWidget::realize. static void fl_view_realize(GtkWidget* widget) { FlView* self = FL_VIEW(widget); gtk_widget_set_realized(widget, TRUE); GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); GdkWindowAttr window_attributes; window_attributes.window_type = GDK_WINDOW_CHILD; window_attributes.x = allocation.x; window_attributes.y = allocation.y; window_attributes.width = allocation.width; window_attributes.height = allocation.height; window_attributes.wclass = GDK_INPUT_OUTPUT; window_attributes.visual = gtk_widget_get_visual(widget); window_attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK | GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK; gint window_attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL; GdkWindow* window = gdk_window_new(gtk_widget_get_parent_window(widget), &window_attributes, window_attributes_mask); gtk_widget_register_window(widget, window); gtk_widget_set_window(widget, window); Window xid = gdk_x11_window_get_xid(gtk_widget_get_window(GTK_WIDGET(self))); fl_renderer_x11_set_xid(self->renderer, xid); g_autoptr(GError) error = nullptr; if (!fl_engine_start(self->engine, &error)) g_warning("Failed to start Flutter engine: %s", error->message); } // Implements GtkWidget::size-allocate. static void fl_view_size_allocate(GtkWidget* widget, GtkAllocation* allocation) { FlView* self = FL_VIEW(widget); gtk_widget_set_allocation(widget, allocation); if (gtk_widget_get_realized(widget) && gtk_widget_get_has_window(widget)) { gdk_window_move_resize(gtk_widget_get_window(widget), allocation->x, allocation->y, allocation->width, allocation->height); } // TODO(robert-ancell): This pixel ratio won't work on hidpi displays. fl_engine_send_window_metrics_event(self->engine, allocation->width, allocation->height, 1); } // Implements GtkWidget::button_press_event. static gboolean fl_view_button_press_event(GtkWidget* widget, GdkEventButton* event) { FlView* self = FL_VIEW(widget); // Flutter doesn't handle double and triple click events. if (event->type == GDK_DOUBLE_BUTTON_PRESS || event->type == GDK_TRIPLE_BUTTON_PRESS) return FALSE; return fl_view_send_pointer_button_event(self, event); } // Implements GtkWidget::button_release_event. static gboolean fl_view_button_release_event(GtkWidget* widget, GdkEventButton* event) { FlView* self = FL_VIEW(widget); return fl_view_send_pointer_button_event(self, event); } // Implements GtkWidget::motion_notify_event. static gboolean fl_view_motion_notify_event(GtkWidget* widget, GdkEventMotion* event) { FlView* self = FL_VIEW(widget); if (self->engine == nullptr) return FALSE; fl_engine_send_mouse_pointer_event(self->engine, self->button_state != 0 ? kMove : kHover, event->time * kMicrosecondsPerMillisecond, event->x, event->y, self->button_state); return TRUE; } // Implements GtkWidget::key_press_event. static gboolean fl_view_key_press_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); if (fl_text_input_plugin_filter_keypress(self->text_input_plugin, event)) return TRUE; fl_key_event_plugin_send_key_event(self->key_event_plugin, event); return TRUE; } // Implements GtkWidget::key_release_event. static gboolean fl_view_key_release_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); if (fl_text_input_plugin_filter_keypress(self->text_input_plugin, event)) return TRUE; fl_key_event_plugin_send_key_event(self->key_event_plugin, event); return TRUE; } static void fl_view_class_init(FlViewClass* klass) { G_OBJECT_CLASS(klass)->constructed = fl_view_constructed; G_OBJECT_CLASS(klass)->set_property = fl_view_set_property; G_OBJECT_CLASS(klass)->get_property = fl_view_get_property; G_OBJECT_CLASS(klass)->dispose = fl_view_dispose; GTK_WIDGET_CLASS(klass)->realize = fl_view_realize; GTK_WIDGET_CLASS(klass)->size_allocate = fl_view_size_allocate; GTK_WIDGET_CLASS(klass)->button_press_event = fl_view_button_press_event; GTK_WIDGET_CLASS(klass)->button_release_event = fl_view_button_release_event; GTK_WIDGET_CLASS(klass)->motion_notify_event = fl_view_motion_notify_event; GTK_WIDGET_CLASS(klass)->key_press_event = fl_view_key_press_event; GTK_WIDGET_CLASS(klass)->key_release_event = fl_view_key_release_event; g_object_class_install_property( G_OBJECT_CLASS(klass), PROP_FLUTTER_PROJECT, g_param_spec_object( "flutter-project", "flutter-project", "Flutter project in use", fl_dart_project_get_type(), static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS))); } static void fl_view_init(FlView* self) { gtk_widget_set_can_focus(GTK_WIDGET(self), TRUE); } G_MODULE_EXPORT FlView* fl_view_new(FlDartProject* project) { return static_cast<FlView*>( g_object_new(fl_view_get_type(), "flutter-project", project, nullptr)); } G_MODULE_EXPORT FlEngine* fl_view_get_engine(FlView* view) { g_return_val_if_fail(FL_IS_VIEW(view), nullptr); return view->engine; } <commit_msg>Support window scaling (#18891)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/fl_key_event_plugin.h" #include "flutter/shell/platform/linux/fl_plugin_registrar_private.h" #include "flutter/shell/platform/linux/fl_renderer_x11.h" #include "flutter/shell/platform/linux/fl_text_input_plugin.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registry.h" #include <gdk/gdkx.h> static constexpr int kMicrosecondsPerMillisecond = 1000; struct _FlView { GtkWidget parent_instance; // Project being run. FlDartProject* project; // Rendering output. FlRendererX11* renderer; // Engine running @project. FlEngine* engine; // Pointer button state recorded for sending status updates. int64_t button_state; // Flutter system channel handlers. FlKeyEventPlugin* key_event_plugin; FlTextInputPlugin* text_input_plugin; }; enum { PROP_FLUTTER_PROJECT = 1, PROP_LAST }; static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface); G_DEFINE_TYPE_WITH_CODE( FlView, fl_view, GTK_TYPE_WIDGET, G_IMPLEMENT_INTERFACE(fl_plugin_registry_get_type(), fl_view_plugin_registry_iface_init)) // Converts a GDK button event into a Flutter event and sends it to the engine. static gboolean fl_view_send_pointer_button_event(FlView* self, GdkEventButton* event) { int64_t button; switch (event->button) { case 1: button = kFlutterPointerButtonMousePrimary; break; case 2: button = kFlutterPointerButtonMouseMiddle; break; case 3: button = kFlutterPointerButtonMouseSecondary; break; default: return FALSE; } int old_button_state = self->button_state; FlutterPointerPhase phase; if (event->type == GDK_BUTTON_PRESS) { // Drop the event if Flutter already thinks the button is down. if ((self->button_state & button) != 0) return FALSE; self->button_state ^= button; phase = old_button_state == 0 ? kDown : kMove; } else if (event->type == GDK_BUTTON_RELEASE) { // Drop the event if Flutter already thinks the button is up. if ((self->button_state & button) == 0) return FALSE; self->button_state ^= button; phase = self->button_state == 0 ? kUp : kMove; } if (self->engine == nullptr) return FALSE; gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_mouse_pointer_event( self->engine, phase, event->time * kMicrosecondsPerMillisecond, event->x * scale_factor, event->y * scale_factor, self->button_state); return TRUE; } // Updates the engine with the current window metrics. static void fl_view_send_window_metrics(FlView* self) { GtkAllocation allocation; gtk_widget_get_allocation(GTK_WIDGET(self), &allocation); gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_window_metrics_event( self->engine, allocation.width * scale_factor, allocation.height * scale_factor, scale_factor); } // Implements FlPluginRegistry::get_registrar_for_plugin. static FlPluginRegistrar* fl_view_get_registrar_for_plugin( FlPluginRegistry* registry, const gchar* name) { FlView* self = FL_VIEW(registry); return fl_plugin_registrar_new(self, fl_engine_get_binary_messenger(self->engine)); } static void fl_view_plugin_registry_iface_init( FlPluginRegistryInterface* iface) { iface->get_registrar_for_plugin = fl_view_get_registrar_for_plugin; } static void fl_view_constructed(GObject* object) { FlView* self = FL_VIEW(object); self->renderer = fl_renderer_x11_new(); self->engine = fl_engine_new(self->project, FL_RENDERER(self->renderer)); // Create system channel handlers. FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(self->engine); self->key_event_plugin = fl_key_event_plugin_new(messenger); self->text_input_plugin = fl_text_input_plugin_new(messenger); } static void fl_view_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case PROP_FLUTTER_PROJECT: g_set_object(&self->project, static_cast<FlDartProject*>(g_value_get_object(value))); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { FlView* self = FL_VIEW(object); switch (prop_id) { case PROP_FLUTTER_PROJECT: g_value_set_object(value, self->project); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } static void fl_view_notify(GObject* object, GParamSpec* pspec) { FlView* self = FL_VIEW(object); if (strcmp(pspec->name, "scale-factor") == 0) { fl_view_send_window_metrics(self); } if (G_OBJECT_CLASS(fl_view_parent_class)->notify != nullptr) G_OBJECT_CLASS(fl_view_parent_class)->notify(object, pspec); } static void fl_view_dispose(GObject* object) { FlView* self = FL_VIEW(object); g_clear_object(&self->project); g_clear_object(&self->renderer); g_clear_object(&self->engine); g_clear_object(&self->key_event_plugin); g_clear_object(&self->text_input_plugin); G_OBJECT_CLASS(fl_view_parent_class)->dispose(object); } // Implements GtkWidget::realize. static void fl_view_realize(GtkWidget* widget) { FlView* self = FL_VIEW(widget); gtk_widget_set_realized(widget, TRUE); GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); GdkWindowAttr window_attributes; window_attributes.window_type = GDK_WINDOW_CHILD; window_attributes.x = allocation.x; window_attributes.y = allocation.y; window_attributes.width = allocation.width; window_attributes.height = allocation.height; window_attributes.wclass = GDK_INPUT_OUTPUT; window_attributes.visual = gtk_widget_get_visual(widget); window_attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK | GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK; gint window_attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL; GdkWindow* window = gdk_window_new(gtk_widget_get_parent_window(widget), &window_attributes, window_attributes_mask); gtk_widget_register_window(widget, window); gtk_widget_set_window(widget, window); Window xid = gdk_x11_window_get_xid(gtk_widget_get_window(GTK_WIDGET(self))); fl_renderer_x11_set_xid(self->renderer, xid); g_autoptr(GError) error = nullptr; if (!fl_engine_start(self->engine, &error)) g_warning("Failed to start Flutter engine: %s", error->message); } // Implements GtkWidget::size-allocate. static void fl_view_size_allocate(GtkWidget* widget, GtkAllocation* allocation) { FlView* self = FL_VIEW(widget); gtk_widget_set_allocation(widget, allocation); if (gtk_widget_get_realized(widget) && gtk_widget_get_has_window(widget)) { gdk_window_move_resize(gtk_widget_get_window(widget), allocation->x, allocation->y, allocation->width, allocation->height); } fl_view_send_window_metrics(self); } // Implements GtkWidget::button_press_event. static gboolean fl_view_button_press_event(GtkWidget* widget, GdkEventButton* event) { FlView* self = FL_VIEW(widget); // Flutter doesn't handle double and triple click events. if (event->type == GDK_DOUBLE_BUTTON_PRESS || event->type == GDK_TRIPLE_BUTTON_PRESS) return FALSE; return fl_view_send_pointer_button_event(self, event); } // Implements GtkWidget::button_release_event. static gboolean fl_view_button_release_event(GtkWidget* widget, GdkEventButton* event) { FlView* self = FL_VIEW(widget); return fl_view_send_pointer_button_event(self, event); } // Implements GtkWidget::motion_notify_event. static gboolean fl_view_motion_notify_event(GtkWidget* widget, GdkEventMotion* event) { FlView* self = FL_VIEW(widget); if (self->engine == nullptr) return FALSE; gint scale_factor = gtk_widget_get_scale_factor(GTK_WIDGET(self)); fl_engine_send_mouse_pointer_event( self->engine, self->button_state != 0 ? kMove : kHover, event->time * kMicrosecondsPerMillisecond, event->x * scale_factor, event->y * scale_factor, self->button_state); return TRUE; } // Implements GtkWidget::key_press_event. static gboolean fl_view_key_press_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); if (fl_text_input_plugin_filter_keypress(self->text_input_plugin, event)) return TRUE; fl_key_event_plugin_send_key_event(self->key_event_plugin, event); return TRUE; } // Implements GtkWidget::key_release_event. static gboolean fl_view_key_release_event(GtkWidget* widget, GdkEventKey* event) { FlView* self = FL_VIEW(widget); if (fl_text_input_plugin_filter_keypress(self->text_input_plugin, event)) return TRUE; fl_key_event_plugin_send_key_event(self->key_event_plugin, event); return TRUE; } static void fl_view_class_init(FlViewClass* klass) { G_OBJECT_CLASS(klass)->constructed = fl_view_constructed; G_OBJECT_CLASS(klass)->set_property = fl_view_set_property; G_OBJECT_CLASS(klass)->get_property = fl_view_get_property; G_OBJECT_CLASS(klass)->notify = fl_view_notify; G_OBJECT_CLASS(klass)->dispose = fl_view_dispose; GTK_WIDGET_CLASS(klass)->realize = fl_view_realize; GTK_WIDGET_CLASS(klass)->size_allocate = fl_view_size_allocate; GTK_WIDGET_CLASS(klass)->button_press_event = fl_view_button_press_event; GTK_WIDGET_CLASS(klass)->button_release_event = fl_view_button_release_event; GTK_WIDGET_CLASS(klass)->motion_notify_event = fl_view_motion_notify_event; GTK_WIDGET_CLASS(klass)->key_press_event = fl_view_key_press_event; GTK_WIDGET_CLASS(klass)->key_release_event = fl_view_key_release_event; g_object_class_install_property( G_OBJECT_CLASS(klass), PROP_FLUTTER_PROJECT, g_param_spec_object( "flutter-project", "flutter-project", "Flutter project in use", fl_dart_project_get_type(), static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS))); } static void fl_view_init(FlView* self) { gtk_widget_set_can_focus(GTK_WIDGET(self), TRUE); } G_MODULE_EXPORT FlView* fl_view_new(FlDartProject* project) { return static_cast<FlView*>( g_object_new(fl_view_get_type(), "flutter-project", project, nullptr)); } G_MODULE_EXPORT FlEngine* fl_view_get_engine(FlView* view) { g_return_val_if_fail(FL_IS_VIEW(view), nullptr); return view->engine; } <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/message.hpp> #include <qimessaging/datastream.hpp> #include <iostream> #include <boost/atomic.hpp> #include <qi/log.hpp> #include <cassert> namespace qi { const unsigned int messageMagic = 0x42adde42; unsigned int newMessageId() { static boost::atomic_uint32_t id(0); id++; return id; } Message::Message() { _header = new qi::Message::MessageHeader(); memset(_header, 0, sizeof(MessageHeader)); _header->id = newMessageId(); _header->magic = messageMagic; _buffer = new qi::Buffer(); _withBuffer = false; } Message::Message(Buffer *buf) { _header = new qi::Message::MessageHeader(); memset(_header, 0, sizeof(MessageHeader)); _header->id = newMessageId(); _header->magic = messageMagic; _buffer = buf; _withBuffer = true; } Message::~Message() { if (!_withBuffer) delete _buffer; } std::ostream& operator<<(std::ostream& os, const qi::Message& msg) { os << "message {" << "size=" << msg.size() << ", id=" << msg.id() << ", type=" << msg.type() << ", serv=" << msg.service() << ", path=" << msg.path() << ", func=" << msg.function() << "}"; return os; } size_t Message::size() const { return _buffer->size(); } void Message::setId(uint32_t id) { _header->id = id; } unsigned int Message::id() const { return _header->id; } void Message::setType(uint32_t type) { _header->type = type; } unsigned int Message::type() const { return _header->type; } void Message::setService(uint32_t service) { _header->service = service; } unsigned int Message::service() const { return _header->service; } void Message::setPath(uint32_t path) { _header->path = path; } unsigned int Message::path() const { return _header->path; } void Message::setFunction(uint32_t function) { _header->function = function; } unsigned int Message::function() const { return _header->function; } qi::Buffer *Message::buffer() const { return _buffer; } // write header into msg before send. bool Message::complete() { if (type() == qi::Message::Type_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (type is None)" << std::endl; assert(type() != qi::Message::Type_None); return false; } if (service() == qi::Message::Service_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (service is 0)" << std::endl; assert(service() != qi::Message::Service_None); return false; } if (path() == qi::Message::Path_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (path is 0)" << std::endl; assert(service() != qi::Message::Service_None); return false; } _header->size = _buffer->size(); _buffer->prepend(_header, sizeof(MessageHeader)); return true; } void Message::buildReplyFrom(const Message &call) { setId(call.id()); setType(qi::Message::Type_Reply); setService(call.service()); setPath(call.path()); setFunction(call.function()); } void Message::buildForwardFrom(const Message &msg) { setType(msg.type()); setService(msg.service()); setPath(msg.path()); setFunction(msg.function()); } } <commit_msg>Fix assertion.<commit_after>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/message.hpp> #include <qimessaging/datastream.hpp> #include <iostream> #include <boost/atomic.hpp> #include <qi/log.hpp> #include <cassert> namespace qi { const unsigned int messageMagic = 0x42adde42; unsigned int newMessageId() { static boost::atomic_uint32_t id(0); id++; return id; } Message::Message() { _header = new qi::Message::MessageHeader(); memset(_header, 0, sizeof(MessageHeader)); _header->id = newMessageId(); _header->magic = messageMagic; _buffer = new qi::Buffer(); _withBuffer = false; } Message::Message(Buffer *buf) { _header = new qi::Message::MessageHeader(); memset(_header, 0, sizeof(MessageHeader)); _header->id = newMessageId(); _header->magic = messageMagic; _buffer = buf; _withBuffer = true; } Message::~Message() { if (!_withBuffer) delete _buffer; } std::ostream& operator<<(std::ostream& os, const qi::Message& msg) { os << "message {" << "size=" << msg.size() << ", id=" << msg.id() << ", type=" << msg.type() << ", serv=" << msg.service() << ", path=" << msg.path() << ", func=" << msg.function() << "}"; return os; } size_t Message::size() const { return _buffer->size(); } void Message::setId(uint32_t id) { _header->id = id; } unsigned int Message::id() const { return _header->id; } void Message::setType(uint32_t type) { _header->type = type; } unsigned int Message::type() const { return _header->type; } void Message::setService(uint32_t service) { _header->service = service; } unsigned int Message::service() const { return _header->service; } void Message::setPath(uint32_t path) { _header->path = path; } unsigned int Message::path() const { return _header->path; } void Message::setFunction(uint32_t function) { _header->function = function; } unsigned int Message::function() const { return _header->function; } qi::Buffer *Message::buffer() const { return _buffer; } // write header into msg before send. bool Message::complete() { if (type() == qi::Message::Type_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (type is None)" << std::endl; assert(type() != qi::Message::Type_None); return false; } if (service() == qi::Message::Service_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (service is 0)" << std::endl; assert(service() != qi::Message::Service_None); return false; } if (path() == qi::Message::Path_None) { qiLogError("qimessaging.TransportSocket") << "Message dropped (path is 0)" << std::endl; assert(path() != qi::Message::Path_None); return false; } _header->size = _buffer->size(); _buffer->prepend(_header, sizeof(MessageHeader)); return true; } void Message::buildReplyFrom(const Message &call) { setId(call.id()); setType(qi::Message::Type_Reply); setService(call.service()); setPath(call.path()); setFunction(call.function()); } void Message::buildForwardFrom(const Message &msg) { setType(msg.type()); setService(msg.service()); setPath(msg.path()); setFunction(msg.function()); } } <|endoftext|>
<commit_before>extern "C" { #include <sys/systm.h> #include <sys/un.h> #include <sys/kpi_socket.h> errno_t sock_nointerrupt(socket_t so, int on); } #include "base.hpp" #include "Client.hpp" #include "Config.hpp" #include "IOLockWrapper.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { struct sockaddr_un sockaddr_; bool sockaddr_available_ = false; IOLock* lock_ = NULL; void releaseSocket(socket_t& socket) { sock_shutdown(socket, SHUT_RDWR); sock_close(socket); } bool makeSocket(socket_t& socket) { int error = sock_socket(PF_LOCAL, SOCK_STREAM, 0, NULL, NULL, &socket); if (error) { printf("[KeyRemap4MacBook ERROR] sock_socket failed(%d)\n", error); return false; } // ---------------------------------------- struct timeval tv; tv.tv_sec = KeyRemap4MacBook_client::TIMEOUT_SECOND; tv.tv_usec = KeyRemap4MacBook_client::TIMEOUT_MICROSECOND; error = sock_setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } error = sock_setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } return true; error: releaseSocket(socket); printf("KeyRemap4MacBook_client makeSocket failed(%d)\n", error); return false; } bool connectSocket(socket_t& socket) { if (! sockaddr_available_) return false; errno_t error = sock_connect(socket, reinterpret_cast<const sockaddr*>(&sockaddr_), 0); if (error) { #if 0 // the connection failure is no problem because a server does not start at login window. printf("[KeyRemap4MacBook ERROR] sock_connect failed(%d)\n", error); #endif return false; } error = sock_nointerrupt(socket, TRUE); if (error) { printf("[KeyRemap4MacBook ERROR] sock_nointerrupt failed(%d)\n", error); return false; } return true; } } void KeyRemap4MacBook_client::initialize(void) { lock_ = IOLockWrapper::alloc(); refreshSockAddr(); } void KeyRemap4MacBook_client::terminate(void) { if (lock_) { IOLockWrapper::free(lock_); } } void KeyRemap4MacBook_client::refreshSockAddr(void) { if (! lock_) return; IOLockWrapper::ScopedLock lk(lock_); if (config.socket_path[0] == '\0') { sockaddr_available_ = false; } else { sockaddr_available_ = true; memset(&sockaddr_, 0, sizeof(sockaddr_)); sockaddr_.sun_len = sizeof(sockaddr_); sockaddr_.sun_family = AF_UNIX; strlcpy(sockaddr_.sun_path, config.socket_path, sizeof(sockaddr_.sun_path) - 8); } } int KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::RequestType type, void* request, uint32_t requestsize, void* reply, uint32_t replysize) { if (! lock_) { return EIO; } IOLockWrapper::ScopedLock lk(lock_); if (type == KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE) { if (config.general_hide_statusmessage) { if (! request) return 0; char* p = reinterpret_cast<KeyRemap4MacBook_bridge::StatusMessage::Request*>(request)->message; if (p[0] != '\0') { return 0; } } } // ------------------------------------------------------------ int result = 0; int error = 0; socket_t socket; bool isMakeSocket = false; if (! makeSocket(socket)) { result = EIO; goto finish; } isMakeSocket = true; if (! connectSocket(socket)) { result = EIO; goto finish; } // ---------------------------------------- struct msghdr msg; memset(&msg, 0, sizeof(msg)); struct iovec aiov[3]; size_t iolen; aiov[0].iov_base = reinterpret_cast<caddr_t>(&type); aiov[0].iov_len = sizeof(type); if (requestsize <= 0) { msg.msg_iovlen = 1; } else { aiov[1].iov_base = reinterpret_cast<caddr_t>(&requestsize); aiov[1].iov_len = sizeof(requestsize); aiov[2].iov_base = reinterpret_cast<caddr_t>(request); aiov[2].iov_len = requestsize; msg.msg_iovlen = 3; } msg.msg_iov = aiov; error = sock_send(socket, &msg, 0, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_send failed(%d)\n", error); result = error; goto finish; } // ---------------------------------------- if (replysize > 0) { memset(&msg, 0, sizeof(msg)); uint32_t status = -1; aiov[0].iov_base = reinterpret_cast<caddr_t>(&status); aiov[0].iov_len = sizeof(status); aiov[1].iov_base = reinterpret_cast<caddr_t>(reply); aiov[1].iov_len = replysize; msg.msg_iov = aiov; msg.msg_iovlen = 2; error = sock_receive(socket, &msg, MSG_WAITALL, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_receive failed(%d)\n", error); result = error; goto finish; } } finish: if (isMakeSocket) { releaseSocket(socket); } if (result) { printf("KeyRemap4MacBook_client::sendmsg error result (%d)\n", result); } return result; } } <commit_msg>update sendmsg to use static variable<commit_after>extern "C" { #include <sys/systm.h> #include <sys/un.h> #include <sys/kpi_socket.h> errno_t sock_nointerrupt(socket_t so, int on); } #include "base.hpp" #include "Client.hpp" #include "Config.hpp" #include "IOLockWrapper.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { struct sockaddr_un sockaddr_; bool sockaddr_available_ = false; IOLock* lock_ = NULL; void releaseSocket(socket_t& socket) { sock_shutdown(socket, SHUT_RDWR); sock_close(socket); } bool makeSocket(socket_t& socket) { int error = sock_socket(PF_LOCAL, SOCK_STREAM, 0, NULL, NULL, &socket); if (error) { printf("[KeyRemap4MacBook ERROR] sock_socket failed(%d)\n", error); return false; } // ---------------------------------------- struct timeval tv; tv.tv_sec = KeyRemap4MacBook_client::TIMEOUT_SECOND; tv.tv_usec = KeyRemap4MacBook_client::TIMEOUT_MICROSECOND; error = sock_setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } error = sock_setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } return true; error: releaseSocket(socket); printf("KeyRemap4MacBook_client makeSocket failed(%d)\n", error); return false; } bool connectSocket(socket_t& socket) { if (! sockaddr_available_) return false; errno_t error = sock_connect(socket, reinterpret_cast<const sockaddr*>(&sockaddr_), 0); if (error) { #if 0 // the connection failure is no problem because a server does not start at login window. printf("[KeyRemap4MacBook ERROR] sock_connect failed(%d)\n", error); #endif return false; } error = sock_nointerrupt(socket, TRUE); if (error) { printf("[KeyRemap4MacBook ERROR] sock_nointerrupt failed(%d)\n", error); return false; } return true; } } void KeyRemap4MacBook_client::initialize(void) { lock_ = IOLockWrapper::alloc(); refreshSockAddr(); } void KeyRemap4MacBook_client::terminate(void) { if (lock_) { IOLockWrapper::free(lock_); } } void KeyRemap4MacBook_client::refreshSockAddr(void) { if (! lock_) return; IOLockWrapper::ScopedLock lk(lock_); if (config.socket_path[0] == '\0') { sockaddr_available_ = false; } else { sockaddr_available_ = true; memset(&sockaddr_, 0, sizeof(sockaddr_)); sockaddr_.sun_len = sizeof(sockaddr_); sockaddr_.sun_family = AF_UNIX; strlcpy(sockaddr_.sun_path, config.socket_path, sizeof(sockaddr_.sun_path) - 8); } } int KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::RequestType type, void* request, uint32_t requestsize, void* reply, uint32_t replysize) { if (! lock_) { return EIO; } IOLockWrapper::ScopedLock lk(lock_); if (type == KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE) { if (config.general_hide_statusmessage) { if (! request) return 0; char* p = reinterpret_cast<KeyRemap4MacBook_bridge::StatusMessage::Request*>(request)->message; if (p[0] != '\0') { return 0; } } } // ------------------------------------------------------------ int result = 0; int error = 0; socket_t socket; bool isMakeSocket = false; if (! makeSocket(socket)) { result = EIO; goto finish; } isMakeSocket = true; if (! connectSocket(socket)) { result = EIO; goto finish; } // ---------------------------------------- // We can use static variable, because this function uses lock at the beginning. static struct msghdr msg; memset(&msg, 0, sizeof(msg)); static struct iovec aiov[3]; size_t iolen; aiov[0].iov_base = reinterpret_cast<caddr_t>(&type); aiov[0].iov_len = sizeof(type); if (requestsize <= 0) { msg.msg_iovlen = 1; } else { aiov[1].iov_base = reinterpret_cast<caddr_t>(&requestsize); aiov[1].iov_len = sizeof(requestsize); aiov[2].iov_base = reinterpret_cast<caddr_t>(request); aiov[2].iov_len = requestsize; msg.msg_iovlen = 3; } msg.msg_iov = aiov; error = sock_send(socket, &msg, 0, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_send failed(%d)\n", error); result = error; goto finish; } // ---------------------------------------- if (replysize > 0) { memset(&msg, 0, sizeof(msg)); uint32_t status = -1; aiov[0].iov_base = reinterpret_cast<caddr_t>(&status); aiov[0].iov_len = sizeof(status); aiov[1].iov_base = reinterpret_cast<caddr_t>(reply); aiov[1].iov_len = replysize; msg.msg_iov = aiov; msg.msg_iovlen = 2; error = sock_receive(socket, &msg, MSG_WAITALL, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_receive failed(%d)\n", error); result = error; goto finish; } } finish: if (isMakeSocket) { releaseSocket(socket); } if (result) { printf("KeyRemap4MacBook_client::sendmsg error result (%d)\n", result); } return result; } } <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/sysctl.h> #include "Config.hpp" #include "version.hpp" #include "Client.hpp" #include "FlagStatus.hpp" #include "RemapClass.hpp" #include "RemapFunc/PointingRelativeToScroll.hpp" #include "util/CommonData.hpp" namespace org_pqrs_KeyRemap4MacBook { int Config::debug = 0; int Config::debug_pointing = 0; int Config::debug_devel = 0; int Config::initialized = 0; int Config::do_reset = 0; int Config::do_reload_xml = 0; int Config::do_reload_only_config = 0; char Config::socket_path[SOCKET_PATH_MAX]; int Config::essential_config_[BRIDGE_ESSENTIAL_CONFIG_INDEX__END__] = { #include "../bridge/config/output/include.bridge_essential_config_index.cpp" }; const int Config::essential_config_default_[BRIDGE_ESSENTIAL_CONFIG_INDEX__END__] = { #include "../bridge/config/output/include.bridge_essential_config_index.cpp" }; namespace { int do_reset_handler SYSCTL_HANDLER_ARGS { IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock()); if (! lk_eventlock) return EAGAIN; int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reset == 1) { Config::load_essential_config_default(); RemapClassManager::clear_xml(); Config::do_reset = 0; Config::initialized = 0; } } return error; } int do_reload_xml_handler SYSCTL_HANDLER_ARGS { IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock()); if (! lk_eventlock) return EAGAIN; Config::initialized = 0; int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reload_xml == 1) { Config::load_essential_config(); if (RemapClassManager::reload_xml()) { Config::do_reload_xml = 0; Config::initialized = 1; } else { Config::do_reload_xml = -1; } } } return error; } int do_reload_only_config_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reload_only_config == 1) { Config::load_essential_config(); if (RemapClassManager::reload_xml()) { Config::do_reload_only_config = 0; } else { Config::do_reload_only_config = -1; } } } return error; } int socket_path_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_string(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { KeyRemap4MacBook_client::refreshSockAddr(); } return error; } int refresh_remapfunc_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { FlagStatus::lock_clear(); FlagStatus::sticky_clear(); RemapClassManager::refresh(); RemapFunc::PointingRelativeToScroll::cancelScroll(); // StatusMessageWindowParameter { static int last_parameter_statuswindow_alpha_font = -1; static int last_parameter_statuswindow_alpha_background = -1; static int last_parameter_statuswindow_posx_adjustment = 0; static int last_parameter_statuswindow_posy_adjustment = 0; int alpha_font = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_alpha_font); int alpha_background = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_alpha_background); int posx_adjustment = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_posx_adjustment); int posy_adjustment = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_posy_adjustment); if (last_parameter_statuswindow_alpha_font != alpha_font || last_parameter_statuswindow_alpha_background != alpha_background || last_parameter_statuswindow_posx_adjustment != posx_adjustment || last_parameter_statuswindow_posy_adjustment != posy_adjustment) { last_parameter_statuswindow_alpha_font = alpha_font; last_parameter_statuswindow_alpha_background = alpha_background; last_parameter_statuswindow_posx_adjustment = posx_adjustment; last_parameter_statuswindow_posy_adjustment = posy_adjustment; KeyRemap4MacBook_bridge::StatusMessageWindowParameter::Request request(alpha_font, alpha_background, posx_adjustment, posy_adjustment); KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE_WINDOW_PARAMETER, &request, sizeof(request), NULL, 0); } } } return 0; } } // ---------------------------------------------------------------------- // SYSCTL staff // http://developer.apple.com/documentation/Darwin/Conceptual/KernelProgramming/boundaries/chapter_14_section_7.html#//apple_ref/doc/uid/TP30000905-CH217-TPXREF116 SYSCTL_DECL(_keyremap4macbook); SYSCTL_NODE(, OID_AUTO, keyremap4macbook, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_general); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, general, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_remap); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, remap, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_option); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, option, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_repeat); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, repeat, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_pointing); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, pointing, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_parameter); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, parameter, CTLFLAG_RW, 0, ""); SYSCTL_DECL(_keyremap4macbook_passthrough); SYSCTL_NODE(_keyremap4macbook, OID_AUTO, passthrough, CTLFLAG_RW, 0, ""); // ---------------------------------------- SYSCTL_INT (_keyremap4macbook, OID_AUTO, initialized, CTLTYPE_INT, &(Config::initialized), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug_pointing, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug_pointing), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug_devel, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug_devel), 0, ""); SYSCTL_STRING(_keyremap4macbook, OID_AUTO, version, CTLFLAG_RD, config_version, 0, ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reset, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reset), 0, do_reset_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reload_xml, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reload_xml), 0, do_reload_xml_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reload_only_config, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reload_only_config), 0, do_reload_only_config_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, socket_path, CTLTYPE_STRING | CTLFLAG_RW, Config::socket_path, sizeof(Config::socket_path), socket_path_handler, "A", ""); // ---------------------------------------------------------------------- void Config::initialize(void) { socket_path[0] = '\0'; } void Config::terminate(void) {} void Config::sysctl_register(void) { sysctl_register_oid(&sysctl__keyremap4macbook); sysctl_register_oid(&sysctl__keyremap4macbook_general); sysctl_register_oid(&sysctl__keyremap4macbook_remap); sysctl_register_oid(&sysctl__keyremap4macbook_option); sysctl_register_oid(&sysctl__keyremap4macbook_repeat); sysctl_register_oid(&sysctl__keyremap4macbook_pointing); sysctl_register_oid(&sysctl__keyremap4macbook_parameter); sysctl_register_oid(&sysctl__keyremap4macbook_passthrough); // ---------------------------------------- sysctl_register_oid(&sysctl__keyremap4macbook_socket_path); sysctl_register_oid(&sysctl__keyremap4macbook_debug); sysctl_register_oid(&sysctl__keyremap4macbook_debug_pointing); sysctl_register_oid(&sysctl__keyremap4macbook_debug_devel); sysctl_register_oid(&sysctl__keyremap4macbook_version); sysctl_register_oid(&sysctl__keyremap4macbook_initialized); sysctl_register_oid(&sysctl__keyremap4macbook_do_reset); sysctl_register_oid(&sysctl__keyremap4macbook_do_reload_xml); sysctl_register_oid(&sysctl__keyremap4macbook_do_reload_only_config); } void Config::sysctl_unregister(void) { sysctl_unregister_oid(&sysctl__keyremap4macbook); sysctl_unregister_oid(&sysctl__keyremap4macbook_general); sysctl_unregister_oid(&sysctl__keyremap4macbook_remap); sysctl_unregister_oid(&sysctl__keyremap4macbook_option); sysctl_unregister_oid(&sysctl__keyremap4macbook_repeat); sysctl_unregister_oid(&sysctl__keyremap4macbook_pointing); sysctl_unregister_oid(&sysctl__keyremap4macbook_parameter); sysctl_unregister_oid(&sysctl__keyremap4macbook_passthrough); // ---------------------------------------- sysctl_unregister_oid(&sysctl__keyremap4macbook_socket_path); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug_pointing); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug_devel); sysctl_unregister_oid(&sysctl__keyremap4macbook_version); sysctl_unregister_oid(&sysctl__keyremap4macbook_initialized); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reset); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reload_xml); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reload_only_config); } void Config::load_essential_config_default(void) { for (int i = 0; i < BRIDGE_ESSENTIAL_CONFIG_INDEX__END__; ++i) { essential_config_[i] = essential_config_default_[i]; } } void Config::load_essential_config(void) { KeyRemap4MacBook_bridge::GetEssentialConfig::Reply reply; time_t timeout_second = 3; int error = KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_GET_ESSENTIAL_CONFIG, NULL, 0, &reply, sizeof(reply), timeout_second, 0); if (error) { IOLOG_ERROR("do_reload_xml GetEssentialConfig sendmsg failed. (%d)\n", error); return; } for (size_t i = 0; i < sizeof(reply.value) / sizeof(reply.value[0]); ++i) { essential_config_[i] = reply.value[i]; } } } <commit_msg>update kext<commit_after>#include <sys/types.h> #include <sys/sysctl.h> #include "Config.hpp" #include "version.hpp" #include "Client.hpp" #include "FlagStatus.hpp" #include "RemapClass.hpp" #include "RemapFunc/PointingRelativeToScroll.hpp" #include "util/CommonData.hpp" namespace org_pqrs_KeyRemap4MacBook { int Config::debug = 0; int Config::debug_pointing = 0; int Config::debug_devel = 0; int Config::initialized = 0; int Config::do_reset = 0; int Config::do_reload_xml = 0; int Config::do_reload_only_config = 0; char Config::socket_path[SOCKET_PATH_MAX]; int Config::essential_config_[BRIDGE_ESSENTIAL_CONFIG_INDEX__END__] = { #include "../bridge/config/output/include.bridge_essential_config_index.cpp" }; const int Config::essential_config_default_[BRIDGE_ESSENTIAL_CONFIG_INDEX__END__] = { #include "../bridge/config/output/include.bridge_essential_config_index.cpp" }; namespace { int do_reset_handler SYSCTL_HANDLER_ARGS { IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock()); if (! lk_eventlock) return EAGAIN; int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reset == 1) { Config::load_essential_config_default(); RemapClassManager::clear_xml(); Config::do_reset = 0; Config::initialized = 0; } } return error; } int do_reload_xml_handler SYSCTL_HANDLER_ARGS { IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock()); if (! lk_eventlock) return EAGAIN; Config::initialized = 0; int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reload_xml == 1) { Config::load_essential_config(); if (RemapClassManager::reload_xml()) { Config::do_reload_xml = 0; Config::initialized = 1; } else { Config::do_reload_xml = -1; } } } return error; } int do_reload_only_config_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { if (Config::do_reload_only_config == 1) { Config::load_essential_config(); if (RemapClassManager::reload_xml()) { Config::do_reload_only_config = 0; } else { Config::do_reload_only_config = -1; } } } return error; } int socket_path_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_string(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { KeyRemap4MacBook_client::refreshSockAddr(); } return error; } int refresh_remapfunc_handler SYSCTL_HANDLER_ARGS { int error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req); if (! error && req->newptr) { FlagStatus::lock_clear(); FlagStatus::sticky_clear(); RemapClassManager::refresh(); RemapFunc::PointingRelativeToScroll::cancelScroll(); // StatusMessageWindowParameter { static int last_parameter_statuswindow_alpha_font = -1; static int last_parameter_statuswindow_alpha_background = -1; static int last_parameter_statuswindow_posx_adjustment = 0; static int last_parameter_statuswindow_posy_adjustment = 0; int alpha_font = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_alpha_font); int alpha_background = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_alpha_background); int posx_adjustment = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_posx_adjustment); int posy_adjustment = Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_parameter_statuswindow_posy_adjustment); if (last_parameter_statuswindow_alpha_font != alpha_font || last_parameter_statuswindow_alpha_background != alpha_background || last_parameter_statuswindow_posx_adjustment != posx_adjustment || last_parameter_statuswindow_posy_adjustment != posy_adjustment) { last_parameter_statuswindow_alpha_font = alpha_font; last_parameter_statuswindow_alpha_background = alpha_background; last_parameter_statuswindow_posx_adjustment = posx_adjustment; last_parameter_statuswindow_posy_adjustment = posy_adjustment; KeyRemap4MacBook_bridge::StatusMessageWindowParameter::Request request(alpha_font, alpha_background, posx_adjustment, posy_adjustment); KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE_WINDOW_PARAMETER, &request, sizeof(request), NULL, 0); } } } return 0; } } // ---------------------------------------------------------------------- // SYSCTL staff // http://developer.apple.com/documentation/Darwin/Conceptual/KernelProgramming/boundaries/chapter_14_section_7.html#//apple_ref/doc/uid/TP30000905-CH217-TPXREF116 SYSCTL_DECL(_keyremap4macbook); SYSCTL_NODE(, OID_AUTO, keyremap4macbook, CTLFLAG_RW, 0, ""); // ---------------------------------------- SYSCTL_INT (_keyremap4macbook, OID_AUTO, initialized, CTLTYPE_INT, &(Config::initialized), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug_pointing, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug_pointing), 0, ""); SYSCTL_INT (_keyremap4macbook, OID_AUTO, debug_devel, CTLTYPE_INT | CTLFLAG_RW, &(Config::debug_devel), 0, ""); SYSCTL_STRING(_keyremap4macbook, OID_AUTO, version, CTLFLAG_RD, config_version, 0, ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reset, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reset), 0, do_reset_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reload_xml, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reload_xml), 0, do_reload_xml_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, do_reload_only_config, CTLTYPE_INT | CTLFLAG_RW, &(Config::do_reload_only_config), 0, do_reload_only_config_handler, "I", ""); SYSCTL_PROC (_keyremap4macbook, OID_AUTO, socket_path, CTLTYPE_STRING | CTLFLAG_RW, Config::socket_path, sizeof(Config::socket_path), socket_path_handler, "A", ""); // ---------------------------------------------------------------------- void Config::initialize(void) { socket_path[0] = '\0'; } void Config::terminate(void) {} void Config::sysctl_register(void) { sysctl_register_oid(&sysctl__keyremap4macbook); sysctl_register_oid(&sysctl__keyremap4macbook_socket_path); sysctl_register_oid(&sysctl__keyremap4macbook_debug); sysctl_register_oid(&sysctl__keyremap4macbook_debug_pointing); sysctl_register_oid(&sysctl__keyremap4macbook_debug_devel); sysctl_register_oid(&sysctl__keyremap4macbook_version); sysctl_register_oid(&sysctl__keyremap4macbook_initialized); sysctl_register_oid(&sysctl__keyremap4macbook_do_reset); sysctl_register_oid(&sysctl__keyremap4macbook_do_reload_xml); sysctl_register_oid(&sysctl__keyremap4macbook_do_reload_only_config); } void Config::sysctl_unregister(void) { sysctl_unregister_oid(&sysctl__keyremap4macbook); sysctl_unregister_oid(&sysctl__keyremap4macbook_socket_path); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug_pointing); sysctl_unregister_oid(&sysctl__keyremap4macbook_debug_devel); sysctl_unregister_oid(&sysctl__keyremap4macbook_version); sysctl_unregister_oid(&sysctl__keyremap4macbook_initialized); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reset); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reload_xml); sysctl_unregister_oid(&sysctl__keyremap4macbook_do_reload_only_config); } void Config::load_essential_config_default(void) { for (int i = 0; i < BRIDGE_ESSENTIAL_CONFIG_INDEX__END__; ++i) { essential_config_[i] = essential_config_default_[i]; } } void Config::load_essential_config(void) { KeyRemap4MacBook_bridge::GetEssentialConfig::Reply reply; time_t timeout_second = 3; int error = KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_GET_ESSENTIAL_CONFIG, NULL, 0, &reply, sizeof(reply), timeout_second, 0); if (error) { IOLOG_ERROR("do_reload_xml GetEssentialConfig sendmsg failed. (%d)\n", error); return; } for (size_t i = 0; i < sizeof(reply.value) / sizeof(reply.value[0]); ++i) { essential_config_[i] = reply.value[i]; } } } <|endoftext|>
<commit_before>#include <unistd.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <signal.h> #include <sys/signalfd.h> #include <sys/eventfd.h> #include <pthread.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdint> #include <memory> using namespace std; volatile bool stop = false; void* thread_start(void* args) { int evfd = reinterpret_cast<uint64_t>(args); while(!stop) { sleep(5); uint64_t value = 5; write(evfd, &value, sizeof(value)); } return nullptr; } int main(int argc, char *argv[]) { printf("=======================================================================\n"); printf(" *****event processing demonstration, process id: [%d]*****\n", getpid()); printf(" **send SIGUSR1 to this process:\n"); printf(" while true; do kill -s SIGUSR1 %d 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf(" **connect to port 8080:\n"); printf(" while true; do nc localhost 8080 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf("=======================================================================\n"); struct FDDeleter { void operator()(int* pfd) const { close(*pfd); } }; constexpr int MAX_EVENTS = 10; struct epoll_event ev, events[MAX_EVENTS]; auto epollfd = epoll_create1(EPOLL_CLOEXEC); if(-1 == epollfd) { printf("failed to create epoll file descriptor\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> managed_epollfd(&epollfd); // create a notify between two threads // potentially mimic Event on Windows platform auto evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if(-1 == evfd) { printf("failed to create event file descriptor\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> managed_evfd(&evfd); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = evfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &ev)) { printf("failed to event file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a timer firing every 5 seconds auto timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC | TFD_NONBLOCK); if(-1 == timerfd) { printf("failed to create file descriptor for timer\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> managed_timerfd(&timerfd); struct itimerspec timerspec; memset(&timerspec, 0, sizeof(timerspec)); timerspec.it_interval.tv_sec = 5; timerspec.it_value.tv_sec = 2; if(-1 == timerfd_settime(timerfd, 0, &timerspec, nullptr)) { printf("failed to start timer\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = timerfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev)) { printf("failed to add timer file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add signal SIGINT & SIGUSR1 sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, nullptr); auto sigfd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC); if(-1 == sigfd) { printf("failed to create file descriptor for signal\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> managed_sigfd(&sigfd); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sigfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sigfd, &ev)) { printf("failed to add signal file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add standard input file descriptor auto flags = fcntl(STDIN_FILENO, F_GETFL); flags |= O_NONBLOCK; if(-1 == fcntl(STDIN_FILENO, F_SETFL, flags)) { printf("failed to set NONBLOCK on standard input file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = STDIN_FILENO; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev)) { printf("failed to add stardard input file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a listening socket to monitor auto sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if(-1 == sockfd) { printf("failed to create listening socket\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> managed_sockfd(&sockfd); int enable = 1; if(-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))) { printf("failed to set socket option\n"); return EXIT_FAILURE; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(8080); if(-1 == bind(sockfd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) { printf("failed to bind listening socket\n"); return EXIT_FAILURE; } constexpr int BACKLOG = 10; if(-1 == listen(sockfd, BACKLOG)) { printf("failed to listening socket\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sockfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev)) { printf("failed to add listening socket file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // IMPORTANT! // create another thread here so that SIGUSR1 will also be blocked in new thread pthread_t thread; if(pthread_create(&thread, nullptr, thread_start, reinterpret_cast<void*>(evfd)) == -1) { printf("failed to create a new thread\n"); return EXIT_FAILURE; } // start event loop while(!stop) { auto nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); for(auto i = 0; i < nfds; ++i) { if(timerfd == events[i].data.fd) { uint64_t value; read(timerfd, &value, sizeof(value)); printf("timer event received, value: %lld\n", value); } else if(sigfd == events[i].data.fd) { struct signalfd_siginfo fdsi; read(sigfd, &fdsi, sizeof(fdsi)); if(SIGINT == fdsi.ssi_signo) { printf("SIGINT received, exit event loop\n"); stop = true; } else { printf("signal event received, sender pid: %d, signal no: %d\n", fdsi.ssi_pid, fdsi.ssi_signo); } } else if(evfd == events[i].data.fd) { uint64_t value; read(evfd, &value, sizeof(value)); printf("thread event received, value: %lld\n", value); } else if(STDIN_FILENO == events[i].data.fd) { constexpr int BUF_SIZE = 10; char buf[BUF_SIZE]; auto n = read(STDIN_FILENO, buf, sizeof(buf)); memset(buf + n, 0, sizeof(buf) - n); buf[sizeof(buf)-1] = '\0'; printf("standard input ready event received, value: %s", buf); } else if(sockfd == events[i].data.fd) { auto cfd = accept(sockfd, nullptr, nullptr); unique_ptr<int, FDDeleter> managed_cfd(&cfd); printf("client connection event received, connection closed\n"); } else { printf("unknown event received\n"); } } if(-1 == nfds) { printf("error on epoll waiting or interrupted, exit event loop\n"); stop = true; } } pthread_join(thread, nullptr); return EXIT_SUCCESS; } <commit_msg>resource management<commit_after>#include <unistd.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <signal.h> #include <sys/signalfd.h> #include <sys/eventfd.h> #include <pthread.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdint> #include <memory> using namespace std; volatile bool stop = false; void* thread_start(void* args) { int evfd = reinterpret_cast<uint64_t>(args); while(!stop) { sleep(5); uint64_t value = 5; write(evfd, &value, sizeof(value)); } return nullptr; } int main(int argc, char *argv[]) { printf("=======================================================================\n"); printf(" *****event processing demonstration, process id: [%d]*****\n", getpid()); printf(" **send SIGUSR1 to this process:\n"); printf(" while true; do kill -s SIGUSR1 %d 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf(" **connect to port 8080:\n"); printf(" while true; do nc localhost 8080 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf("=======================================================================\n"); struct FDDeleter { void operator()(int* pfd) const { close(*pfd); } }; constexpr int MAX_EVENTS = 10; struct epoll_event ev, events[MAX_EVENTS]; auto epollfd = epoll_create1(EPOLL_CLOEXEC); if(-1 == epollfd) { printf("failed to create epoll file descriptor\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> raii_epollfd(&epollfd); // create a notify between two threads // potentially mimic Event on Windows platform auto evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if(-1 == evfd) { printf("failed to create event file descriptor\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> raii_evfd(&evfd); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = evfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &ev)) { printf("failed to event file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a timer firing every 5 seconds auto timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC | TFD_NONBLOCK); if(-1 == timerfd) { printf("failed to create file descriptor for timer\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> raii_timerfd(&timerfd); struct itimerspec timerspec; memset(&timerspec, 0, sizeof(timerspec)); timerspec.it_interval.tv_sec = 5; timerspec.it_value.tv_sec = 2; if(-1 == timerfd_settime(timerfd, 0, &timerspec, nullptr)) { printf("failed to start timer\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = timerfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev)) { printf("failed to add timer file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add signal SIGINT & SIGUSR1 sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, nullptr); auto sigfd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC); if(-1 == sigfd) { printf("failed to create file descriptor for signal\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> raii_sigfd(&sigfd); memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sigfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sigfd, &ev)) { printf("failed to add signal file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add standard input file descriptor auto flags = fcntl(STDIN_FILENO, F_GETFL); flags |= O_NONBLOCK; if(-1 == fcntl(STDIN_FILENO, F_SETFL, flags)) { printf("failed to set NONBLOCK on standard input file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = STDIN_FILENO; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev)) { printf("failed to add stardard input file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a listening socket to monitor auto sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if(-1 == sockfd) { printf("failed to create listening socket\n"); return EXIT_FAILURE; } unique_ptr<int, FDDeleter> raii_sockfd(&sockfd); int enable = 1; if(-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))) { printf("failed to set socket option\n"); return EXIT_FAILURE; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(8080); if(-1 == bind(sockfd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) { printf("failed to bind listening socket\n"); return EXIT_FAILURE; } constexpr int BACKLOG = 10; if(-1 == listen(sockfd, BACKLOG)) { printf("failed to listening socket\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sockfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev)) { printf("failed to add listening socket file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // IMPORTANT! // create another thread here so that SIGUSR1 will also be blocked in new thread pthread_t thread; if(pthread_create(&thread, nullptr, thread_start, reinterpret_cast<void*>(evfd)) == -1) { printf("failed to create a new thread\n"); return EXIT_FAILURE; } // start event loop while(!stop) { auto nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); for(auto i = 0; i < nfds; ++i) { if(timerfd == events[i].data.fd) { uint64_t value; read(timerfd, &value, sizeof(value)); printf("timer event received, value: %lld\n", value); } else if(sigfd == events[i].data.fd) { struct signalfd_siginfo fdsi; read(sigfd, &fdsi, sizeof(fdsi)); if(SIGINT == fdsi.ssi_signo) { printf("SIGINT received, exit event loop\n"); stop = true; } else { printf("signal event received, sender pid: %d, signal no: %d\n", fdsi.ssi_pid, fdsi.ssi_signo); } } else if(evfd == events[i].data.fd) { uint64_t value; read(evfd, &value, sizeof(value)); printf("thread event received, value: %lld\n", value); } else if(STDIN_FILENO == events[i].data.fd) { constexpr int BUF_SIZE = 10; char buf[BUF_SIZE]; auto n = read(STDIN_FILENO, buf, sizeof(buf)); memset(buf + n, 0, sizeof(buf) - n); buf[sizeof(buf)-1] = '\0'; printf("standard input ready event received, value: %s", buf); } else if(sockfd == events[i].data.fd) { auto cfd = accept(sockfd, nullptr, nullptr); unique_ptr<int, FDDeleter> raii_cfd(&cfd); printf("client connection event received, connection closed\n"); } else { printf("unknown event received\n"); } } if(-1 == nfds) { printf("error on epoll waiting or interrupted, exit event loop\n"); stop = true; } } pthread_join(thread, nullptr); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "tablet.hpp" #include "../core-impl.hpp" #include "../wm.hpp" #include "input-manager.hpp" #include <signal-definitions.hpp> #include <linux/input-event-codes.h> extern "C" { #include <wlr/types/wlr_tablet_v2.h> } /* --------------------- Tablet tool implementation ------------------------- */ wf::tablet_tool_t::tablet_tool_t(wlr_tablet_tool *tool, wlr_tablet_v2_tablet *tablet) { this->tablet_v2 = tablet; /* Initialize tool_v2 */ this->tool = tool; this->tool->data = this; auto& core = wf::get_core_impl(); this->tool_v2 = wlr_tablet_tool_create(core.protocols.tablet_v2, core.get_current_seat(), tool); /* Free memory when the tool is destroyed */ this->on_destroy.set_callback([=] (void*) { delete this; }); this->on_destroy.connect(&tool->events.destroy); /* Ungrab surface, and update focused surface if a surface is unmapped, * we don't want to end up with a reference to unfocused or a destroyed * surface. */ on_surface_map_state_changed = [=] (signal_data_t *data) { auto ev = static_cast<_surface_map_state_changed_signal*> (data); if (!ev->surface->is_mapped() && ev->surface == this->grabbed_surface) this->grabbed_surface = nullptr; update_tool_position(); }; wf::get_core().connect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().connect_signal("_surface_unmapped", &on_surface_map_state_changed); /* Just pass cursor set requests to core, but translate them to * regular pointer set requests */ on_set_cursor.set_callback([=] (void *data) { auto ev = static_cast<wlr_tablet_v2_event_cursor*> (data); wlr_seat_pointer_request_set_cursor_event pev; pev.surface = ev->surface; pev.hotspot_x = ev->hotspot_x; pev.hotspot_y = ev->hotspot_y; pev.serial = ev->serial; pev.seat_client = ev->seat_client; wf::get_core_impl().input->cursor->set_cursor(&pev); }); on_set_cursor.connect(&tool_v2->events.set_cursor); } wf::tablet_tool_t::~tablet_tool_t() { wf::get_core().disconnect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().disconnect_signal("_surface_unmapped", &on_surface_map_state_changed); tool->data = NULL; } void wf::tablet_tool_t::update_tool_position() { if (!is_active) return; auto& core = wf::get_core_impl(); auto& input = core.input; auto gc = core.get_cursor_position(); /* XXX: tablet input works only with programs, Wayfire itself doesn't do * anything useful with it */ if (core.input->input_grabbed()) return; /* Figure out what surface is under the tool */ wf_pointf local; // local to the surface wf::surface_interface_t *surface = nullptr; if (this->grabbed_surface) { surface = this->grabbed_surface; local = get_surface_relative_coords(surface, gc); } else { surface = input->input_surface_at(gc, local); } set_focus(surface); /* If focus is a wlr surface, send position */ wlr_surface *next_focus = surface ? surface->priv->wsurface : nullptr; if (next_focus) wlr_tablet_v2_tablet_tool_notify_motion(tool_v2, local.x, local.y); } void wf::tablet_tool_t::set_focus(wf::surface_interface_t *surface) { /* Unfocus old surface */ if (surface != this->proximity_surface && this->proximity_surface) { wlr_tablet_v2_tablet_tool_notify_proximity_out(tool_v2); this->proximity_surface = nullptr; } /* Set the new focus, if it is a wlr surface */ wlr_surface *next_focus = surface ? surface->priv->wsurface : nullptr; if (next_focus && wlr_surface_accepts_tablet_v2(tablet_v2, next_focus)) { this->proximity_surface = surface; wlr_tablet_v2_tablet_tool_notify_proximity_in( tool_v2, tablet_v2, next_focus); } } void wf::tablet_tool_t::passthrough_axis(wlr_event_tablet_tool_axis *ev) { if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_PRESSURE) wlr_tablet_v2_tablet_tool_notify_pressure(tool_v2, ev->pressure); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_DISTANCE) wlr_tablet_v2_tablet_tool_notify_distance(tool_v2, ev->distance); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_ROTATION) wlr_tablet_v2_tablet_tool_notify_rotation(tool_v2, ev->rotation); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_SLIDER) wlr_tablet_v2_tablet_tool_notify_slider(tool_v2, ev->slider); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_WHEEL) wlr_tablet_v2_tablet_tool_notify_wheel(tool_v2, ev->wheel_delta, 0); /* Update tilt, use old values if no new values are provided */ if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_X) tilt_x = ev->tilt_x; if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_Y) tilt_y = ev->tilt_y; if (ev->updated_axes & (WLR_TABLET_TOOL_AXIS_TILT_X | WLR_TABLET_TOOL_AXIS_TILT_Y)) { wlr_tablet_v2_tablet_tool_notify_tilt(tool_v2, tilt_x, tilt_y); } } void wf::tablet_tool_t::handle_tip(wlr_event_tablet_tool_tip *ev) { /* Nothing to do without a proximity surface */ if (!this->proximity_surface) return; if (ev->state == WLR_TABLET_TOOL_TIP_DOWN) { wlr_send_tablet_v2_tablet_tool_down(tool_v2); this->grabbed_surface = this->proximity_surface; /* Try to focus the view under the tool */ auto view = dynamic_cast<wf::view_interface_t*> ( this->proximity_surface->get_main_surface()); if (view) { wf::get_core().focus_output(view->get_output()); wm_focus_request data; data.surface = this->proximity_surface; view->get_output()->emit_signal("wm-focus-request", &data); } } else { wlr_send_tablet_v2_tablet_tool_up(tool_v2); this->grabbed_surface = nullptr; } } void wf::tablet_tool_t::handle_button(wlr_event_tablet_tool_button *ev) { wlr_tablet_v2_tablet_tool_notify_button(tool_v2, (zwp_tablet_pad_v2_button_state)ev->button, (zwp_tablet_pad_v2_button_state)ev->state); } void wf::tablet_tool_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { set_focus(nullptr); is_active = false; } else { is_active = true; update_tool_position(); } } /* ----------------------- Tablet implementation ---------------------------- */ wf::tablet_t::tablet_t(wlr_cursor *cursor, wlr_input_device *dev) : wf_input_device_internal(dev) { this->handle = dev->tablet; this->handle->data = this; this->cursor = cursor; auto& core = wf::get_core_impl(); tablet_v2 = wlr_tablet_create(core.protocols.tablet_v2, core.get_current_seat(), dev); wlr_cursor_attach_input_device(cursor, dev); } wf::tablet_t::~tablet_t() { this->handle->data = NULL; } wf::tablet_tool_t *wf::tablet_t::ensure_tool(wlr_tablet_tool *tool) { if (tool->data == NULL) new wf::tablet_tool_t(tool, tablet_v2); return (wf::tablet_tool_t*) tool->data; } void wf::tablet_t::handle_tip(wlr_event_tablet_tool_tip *ev) { auto& input = wf::get_core_impl().input; if (input->input_grabbed()) { /* Simulate buttons, in case some application started moving */ if (input->active_grab->callbacks.pointer.button) { uint32_t state = ev->state == WLR_TABLET_TOOL_TIP_DOWN ? WLR_BUTTON_PRESSED : WLR_BUTTON_RELEASED; input->active_grab->callbacks.pointer.button(BTN_LEFT, state); } return; } auto tool = ensure_tool(ev->tool); tool->handle_tip(ev); } void wf::tablet_t::handle_axis(wlr_event_tablet_tool_axis *ev) { auto& input = wf::get_core_impl().input; /* Update cursor position */ switch(ev->tool->type) { case WLR_TABLET_TOOL_TYPE_MOUSE: wlr_cursor_move(cursor, ev->device, ev->dx, ev->dy); break; default: double x = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_X) ? ev->x : NAN; double y = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_Y) ? ev->y : NAN; wlr_cursor_warp_absolute(cursor, ev->device, x, y); } if (input->input_grabbed()) { /* Simulate movement */ if (input->active_grab->callbacks.pointer.motion) { auto gc = wf::get_core().get_cursor_position(); input->active_grab->callbacks.pointer.motion(gc.x, gc.y); } return; } /* Update focus */ auto tool = ensure_tool(ev->tool); tool->update_tool_position(); tool->passthrough_axis(ev); } void wf::tablet_t::handle_button(wlr_event_tablet_tool_button *ev) { /* Pass to the tool */ ensure_tool(ev->tool)->handle_button(ev); } void wf::tablet_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { ensure_tool(ev->tool)->handle_proximity(ev); /* Show appropriate cursor */ if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { wf::get_core().set_cursor("default"); } else { wf::get_core().set_cursor("crosshair"); } } <commit_msg>tablet: do not set cursor on inactive tools<commit_after>#include "tablet.hpp" #include "../core-impl.hpp" #include "../wm.hpp" #include "input-manager.hpp" #include <signal-definitions.hpp> #include <linux/input-event-codes.h> extern "C" { #include <wlr/types/wlr_tablet_v2.h> } /* --------------------- Tablet tool implementation ------------------------- */ wf::tablet_tool_t::tablet_tool_t(wlr_tablet_tool *tool, wlr_tablet_v2_tablet *tablet) { this->tablet_v2 = tablet; /* Initialize tool_v2 */ this->tool = tool; this->tool->data = this; auto& core = wf::get_core_impl(); this->tool_v2 = wlr_tablet_tool_create(core.protocols.tablet_v2, core.get_current_seat(), tool); /* Free memory when the tool is destroyed */ this->on_destroy.set_callback([=] (void*) { delete this; }); this->on_destroy.connect(&tool->events.destroy); /* Ungrab surface, and update focused surface if a surface is unmapped, * we don't want to end up with a reference to unfocused or a destroyed * surface. */ on_surface_map_state_changed = [=] (signal_data_t *data) { auto ev = static_cast<_surface_map_state_changed_signal*> (data); if (!ev->surface->is_mapped() && ev->surface == this->grabbed_surface) this->grabbed_surface = nullptr; update_tool_position(); }; wf::get_core().connect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().connect_signal("_surface_unmapped", &on_surface_map_state_changed); /* Just pass cursor set requests to core, but translate them to * regular pointer set requests */ on_set_cursor.set_callback([=] (void *data) { if (!this->is_active) return; auto ev = static_cast<wlr_tablet_v2_event_cursor*> (data); wlr_seat_pointer_request_set_cursor_event pev; pev.surface = ev->surface; pev.hotspot_x = ev->hotspot_x; pev.hotspot_y = ev->hotspot_y; pev.serial = ev->serial; pev.seat_client = ev->seat_client; wf::get_core_impl().input->cursor->set_cursor(&pev); }); on_set_cursor.connect(&tool_v2->events.set_cursor); } wf::tablet_tool_t::~tablet_tool_t() { wf::get_core().disconnect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().disconnect_signal("_surface_unmapped", &on_surface_map_state_changed); tool->data = NULL; } void wf::tablet_tool_t::update_tool_position() { if (!is_active) return; auto& core = wf::get_core_impl(); auto& input = core.input; auto gc = core.get_cursor_position(); /* XXX: tablet input works only with programs, Wayfire itself doesn't do * anything useful with it */ if (core.input->input_grabbed()) return; /* Figure out what surface is under the tool */ wf_pointf local; // local to the surface wf::surface_interface_t *surface = nullptr; if (this->grabbed_surface) { surface = this->grabbed_surface; local = get_surface_relative_coords(surface, gc); } else { surface = input->input_surface_at(gc, local); } set_focus(surface); /* If focus is a wlr surface, send position */ wlr_surface *next_focus = surface ? surface->priv->wsurface : nullptr; if (next_focus) wlr_tablet_v2_tablet_tool_notify_motion(tool_v2, local.x, local.y); } void wf::tablet_tool_t::set_focus(wf::surface_interface_t *surface) { /* Unfocus old surface */ if (surface != this->proximity_surface && this->proximity_surface) { wlr_tablet_v2_tablet_tool_notify_proximity_out(tool_v2); this->proximity_surface = nullptr; } /* Set the new focus, if it is a wlr surface */ wlr_surface *next_focus = surface ? surface->priv->wsurface : nullptr; if (next_focus && wlr_surface_accepts_tablet_v2(tablet_v2, next_focus)) { this->proximity_surface = surface; wlr_tablet_v2_tablet_tool_notify_proximity_in( tool_v2, tablet_v2, next_focus); } } void wf::tablet_tool_t::passthrough_axis(wlr_event_tablet_tool_axis *ev) { if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_PRESSURE) wlr_tablet_v2_tablet_tool_notify_pressure(tool_v2, ev->pressure); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_DISTANCE) wlr_tablet_v2_tablet_tool_notify_distance(tool_v2, ev->distance); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_ROTATION) wlr_tablet_v2_tablet_tool_notify_rotation(tool_v2, ev->rotation); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_SLIDER) wlr_tablet_v2_tablet_tool_notify_slider(tool_v2, ev->slider); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_WHEEL) wlr_tablet_v2_tablet_tool_notify_wheel(tool_v2, ev->wheel_delta, 0); /* Update tilt, use old values if no new values are provided */ if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_X) tilt_x = ev->tilt_x; if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_Y) tilt_y = ev->tilt_y; if (ev->updated_axes & (WLR_TABLET_TOOL_AXIS_TILT_X | WLR_TABLET_TOOL_AXIS_TILT_Y)) { wlr_tablet_v2_tablet_tool_notify_tilt(tool_v2, tilt_x, tilt_y); } } void wf::tablet_tool_t::handle_tip(wlr_event_tablet_tool_tip *ev) { /* Nothing to do without a proximity surface */ if (!this->proximity_surface) return; if (ev->state == WLR_TABLET_TOOL_TIP_DOWN) { wlr_send_tablet_v2_tablet_tool_down(tool_v2); this->grabbed_surface = this->proximity_surface; /* Try to focus the view under the tool */ auto view = dynamic_cast<wf::view_interface_t*> ( this->proximity_surface->get_main_surface()); if (view) { wf::get_core().focus_output(view->get_output()); wm_focus_request data; data.surface = this->proximity_surface; view->get_output()->emit_signal("wm-focus-request", &data); } } else { wlr_send_tablet_v2_tablet_tool_up(tool_v2); this->grabbed_surface = nullptr; } } void wf::tablet_tool_t::handle_button(wlr_event_tablet_tool_button *ev) { wlr_tablet_v2_tablet_tool_notify_button(tool_v2, (zwp_tablet_pad_v2_button_state)ev->button, (zwp_tablet_pad_v2_button_state)ev->state); } void wf::tablet_tool_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { set_focus(nullptr); is_active = false; } else { is_active = true; update_tool_position(); } } /* ----------------------- Tablet implementation ---------------------------- */ wf::tablet_t::tablet_t(wlr_cursor *cursor, wlr_input_device *dev) : wf_input_device_internal(dev) { this->handle = dev->tablet; this->handle->data = this; this->cursor = cursor; auto& core = wf::get_core_impl(); tablet_v2 = wlr_tablet_create(core.protocols.tablet_v2, core.get_current_seat(), dev); wlr_cursor_attach_input_device(cursor, dev); } wf::tablet_t::~tablet_t() { this->handle->data = NULL; } wf::tablet_tool_t *wf::tablet_t::ensure_tool(wlr_tablet_tool *tool) { if (tool->data == NULL) new wf::tablet_tool_t(tool, tablet_v2); return (wf::tablet_tool_t*) tool->data; } void wf::tablet_t::handle_tip(wlr_event_tablet_tool_tip *ev) { auto& input = wf::get_core_impl().input; if (input->input_grabbed()) { /* Simulate buttons, in case some application started moving */ if (input->active_grab->callbacks.pointer.button) { uint32_t state = ev->state == WLR_TABLET_TOOL_TIP_DOWN ? WLR_BUTTON_PRESSED : WLR_BUTTON_RELEASED; input->active_grab->callbacks.pointer.button(BTN_LEFT, state); } return; } auto tool = ensure_tool(ev->tool); tool->handle_tip(ev); } void wf::tablet_t::handle_axis(wlr_event_tablet_tool_axis *ev) { auto& input = wf::get_core_impl().input; /* Update cursor position */ switch(ev->tool->type) { case WLR_TABLET_TOOL_TYPE_MOUSE: wlr_cursor_move(cursor, ev->device, ev->dx, ev->dy); break; default: double x = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_X) ? ev->x : NAN; double y = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_Y) ? ev->y : NAN; wlr_cursor_warp_absolute(cursor, ev->device, x, y); } if (input->input_grabbed()) { /* Simulate movement */ if (input->active_grab->callbacks.pointer.motion) { auto gc = wf::get_core().get_cursor_position(); input->active_grab->callbacks.pointer.motion(gc.x, gc.y); } return; } /* Update focus */ auto tool = ensure_tool(ev->tool); tool->update_tool_position(); tool->passthrough_axis(ev); } void wf::tablet_t::handle_button(wlr_event_tablet_tool_button *ev) { /* Pass to the tool */ ensure_tool(ev->tool)->handle_button(ev); } void wf::tablet_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { ensure_tool(ev->tool)->handle_proximity(ev); /* Show appropriate cursor */ if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { wf::get_core().set_cursor("default"); } else { wf::get_core().set_cursor("crosshair"); } } <|endoftext|>
<commit_before>#include <cppunit/Portability.h> #include <cppunit/Exception.h> #include <cppunit/Protector.h> #include <cppunit/TestCase.h> #include <cppunit/TestResult.h> #include <stdexcept> #if CPPUNIT_USE_TYPEINFO_NAME # include <typeinfo> #endif CPPUNIT_NS_BEGIN /*! \brief Functor to call test case method (Implementation). * * Implementation detail. */ class TestCaseMethodFunctor : public Functor { public: typedef void (TestCase::*Method)(); TestCaseMethodFunctor( TestCase *target, Method method ) : m_target( target ) , m_method( method ) { } bool operator()() const { (m_target->*m_method)(); return true; } private: // disable copying TestCaseMethodFunctor( const TestCaseMethodFunctor& ); // disable copying TestCaseMethodFunctor& operator=( const TestCaseMethodFunctor& ); TestCase *m_target; Method m_method; }; /** Constructs a test case. * \param name the name of the TestCase. **/ TestCase::TestCase( const std::string &name ) : m_name(name) { } /// Run the test and catch any exceptions that are triggered by it void TestCase::run( TestResult *result ) { result->startTest(this); /* try { setUp(); try { runTest(); } catch ( Exception &e ) { Exception *copy = e.clone(); result->addFailure( this, copy ); } catch ( std::exception &e ) { result->addError( this, new Exception( Message( "uncaught std::exception", e.what() ) ) ); } catch (...) { Exception *e = new Exception( Message( "uncaught unknown exception" ) ); result->addError( this, e ); } try { tearDown(); } catch (...) { result->addError( this, new Exception( Message( "tearDown() failed" ) ) ); } } catch (...) { result->addError( this, new Exception( Message( "setUp() failed" ) ) ); } */ if ( result->protect( TestCaseMethodFunctor( this, &TestCase::setUp ), this, "setUp() failed" ) ) { result->protect( TestCaseMethodFunctor( this, &TestCase::runTest ), this ); } result->protect( TestCaseMethodFunctor( this, &TestCase::tearDown ), this, "tearDown() failed" ); result->endTest( this ); } /// All the work for runTest is deferred to subclasses void TestCase::runTest() { } /** Constructs a test case for a suite. * \deprecated This constructor was used by fixture when TestFixture did not exist. * Have your fixture inherits TestFixture instead of TestCase. * \internal * This TestCase was intended for use by the TestCaller and should not * be used by a test case for which run() is called. **/ TestCase::TestCase() : m_name( "" ) { } /// Destructs a test case TestCase::~TestCase() { } /// Returns the name of the test case std::string TestCase::getName() const { return m_name; } CPPUNIT_NS_END <commit_msg>-Werror,-Wbind-to-temporary-copy<commit_after>#include <cppunit/Portability.h> #include <cppunit/Exception.h> #include <cppunit/Protector.h> #include <cppunit/TestCase.h> #include <cppunit/TestResult.h> #include <stdexcept> #if CPPUNIT_USE_TYPEINFO_NAME # include <typeinfo> #endif CPPUNIT_NS_BEGIN /*! \brief Functor to call test case method (Implementation). * * Implementation detail. */ class TestCaseMethodFunctor : public Functor { public: typedef void (TestCase::*Method)(); TestCaseMethodFunctor( TestCase *target, Method method ) : m_target( target ) , m_method( method ) { } bool operator()() const { (m_target->*m_method)(); return true; } private: TestCase *m_target; Method m_method; }; /** Constructs a test case. * \param name the name of the TestCase. **/ TestCase::TestCase( const std::string &name ) : m_name(name) { } /// Run the test and catch any exceptions that are triggered by it void TestCase::run( TestResult *result ) { result->startTest(this); /* try { setUp(); try { runTest(); } catch ( Exception &e ) { Exception *copy = e.clone(); result->addFailure( this, copy ); } catch ( std::exception &e ) { result->addError( this, new Exception( Message( "uncaught std::exception", e.what() ) ) ); } catch (...) { Exception *e = new Exception( Message( "uncaught unknown exception" ) ); result->addError( this, e ); } try { tearDown(); } catch (...) { result->addError( this, new Exception( Message( "tearDown() failed" ) ) ); } } catch (...) { result->addError( this, new Exception( Message( "setUp() failed" ) ) ); } */ if ( result->protect( TestCaseMethodFunctor( this, &TestCase::setUp ), this, "setUp() failed" ) ) { result->protect( TestCaseMethodFunctor( this, &TestCase::runTest ), this ); } result->protect( TestCaseMethodFunctor( this, &TestCase::tearDown ), this, "tearDown() failed" ); result->endTest( this ); } /// All the work for runTest is deferred to subclasses void TestCase::runTest() { } /** Constructs a test case for a suite. * \deprecated This constructor was used by fixture when TestFixture did not exist. * Have your fixture inherits TestFixture instead of TestCase. * \internal * This TestCase was intended for use by the TestCaller and should not * be used by a test case for which run() is called. **/ TestCase::TestCase() : m_name( "" ) { } /// Destructs a test case TestCase::~TestCase() { } /// Returns the name of the test case std::string TestCase::getName() const { return m_name; } CPPUNIT_NS_END <|endoftext|>
<commit_before>#ifndef MAINWINDOW_HPP_ #define MAINWINDOW_HPP_ #include <QtCore/QtGlobal> #include <QtCore/QVector> #include <QtSerialPort/QSerialPort> #include <QtWidgets/QMainWindow> #include <QtWidgets/QSpinBox> #include <QtWidgets/QPushButton> #include <QtWidgets/QBoxLayout> #include <qwt/qwt_plot.h> #include <qwt/qwt_plot_curve.h> #include <qwt/qwt_point_data.h> namespace Ui { class GlowneOkno; } class GlowneOkno : public QMainWindow { Q_OBJECT public: explicit GlowneOkno(QWidget* parent = nullptr); ~GlowneOkno(); bool wyslijRozkaz(const char* rozkaz); private: void setupRS(void); void setupOkno(void); void setupCzasTemperatura(void); void setupTemperatura(void); void setupWyslij(void); void setupZatrzymajGrzanie(void); void setupReset(void); void setupWykresChwilowy(void); void setupWykresDlugookresowy(void); void setupRozklad(void); bool obsluzBladRS(QSerialPort::SerialPortError kod_bledu); private: Ui::GlowneOkno *ui; QWidget* okno_; QVBoxLayout* glownyRozmieszczacz_; QHBoxLayout* wiersze_; unsigned iloscWierszy_; QSerialPort *rs232_; QSpinBox* zadanaTemperatura_; QPushButton* wyslij_; QPushButton* zatrzymajGrzanie_; QPushButton* reset_; QVector <double>* czasChwilowy_; QVector <double>* temperaturaChwilowa_; QVector <double>* czasDlugookresowy_; QVector <double>* temperaturaDlugookresowa_; QwtPlot* wykresChwilowy_; QwtPlot* wykresDlugookresowy_; QwtPlotCurve* danePomiaroweWykresChwilowy_; QwtPlotCurve* danePomiaroweWykresDlugookresowy_; public slots: void ustawTemperature(void); void zatrzymajGrzanie(void); void odbierzDane(void); void zrestartujUrzadenie(void); }; #endif <commit_msg>Porządki w klasie (najpierw deklarowane są prywatne pola i metody, a dopiero potem publiczne metody).<commit_after>#ifndef MAINWINDOW_HPP_ #define MAINWINDOW_HPP_ #include <QtCore/QtGlobal> #include <QtCore/QVector> #include <QtSerialPort/QSerialPort> #include <QtWidgets/QMainWindow> #include <QtWidgets/QSpinBox> #include <QtWidgets/QPushButton> #include <QtWidgets/QBoxLayout> #include <qwt/qwt_plot.h> #include <qwt/qwt_plot_curve.h> #include <qwt/qwt_point_data.h> namespace Ui { class GlowneOkno; } class GlowneOkno : public QMainWindow { Q_OBJECT private: Ui::GlowneOkno *ui; QWidget* okno_; QVBoxLayout* glownyRozmieszczacz_; QHBoxLayout* wiersze_; unsigned iloscWierszy_; QSerialPort *rs232_; QSpinBox* zadanaTemperatura_; QPushButton* wyslij_; QPushButton* zatrzymajGrzanie_; QPushButton* reset_; QVector <double>* czasChwilowy_; QVector <double>* temperaturaChwilowa_; QVector <double>* czasDlugookresowy_; QVector <double>* temperaturaDlugookresowa_; QwtPlot* wykresChwilowy_; QwtPlot* wykresDlugookresowy_; QwtPlotCurve* danePomiaroweWykresChwilowy_; QwtPlotCurve* danePomiaroweWykresDlugookresowy_; void setupRS(void); void setupOkno(void); void setupCzasTemperatura(void); void setupTemperatura(void); void setupWyslij(void); void setupZatrzymajGrzanie(void); void setupReset(void); void setupWykresChwilowy(void); void setupWykresDlugookresowy(void); void setupRozklad(void); bool obsluzBladRS(QSerialPort::SerialPortError kod_bledu); public: explicit GlowneOkno(QWidget* parent = nullptr); ~GlowneOkno(); bool wyslijRozkaz(const char* rozkaz); public slots: void ustawTemperature(void); void zatrzymajGrzanie(void); void odbierzDane(void); void zrestartujUrzadenie(void); }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <psapi.h> #include "skia/ext/bitmap_platform_device_win.h" #include "skia/ext/platform_canvas.h" namespace skia { // Crash on failure. #define CHECK(condition) if (!(condition)) __debugbreak(); // Crashes the process. This is called when a bitmap allocation fails, and this // function tries to determine why it might have failed, and crash on different // lines. This allows us to see in crash dumps the most likely reason for the // failure. It takes the size of the bitmap we were trying to allocate as its // arguments so we can check that as well. // // Note that in a sandboxed renderer this function crashes when trying to // call GetProcessMemoryInfo() because it tries to load psapi.dll, which // is fine but gives you a very hard to read crash dump. __declspec(noinline) void CrashForBitmapAllocationFailure(int w, int h) { // If the bitmap is ginormous, then we probably can't allocate it. // We use 64M pixels = 256MB @ 4 bytes per pixel. const __int64 kGinormousBitmapPxl = 64000000; CHECK(static_cast<__int64>(w) * static_cast<__int64>(h) < kGinormousBitmapPxl); // The maximum number of GDI objects per process is 10K. If we're very close // to that, it's probably the problem. const int kLotsOfGDIObjs = 9990; CHECK(GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS) < kLotsOfGDIObjs); // If we're using a crazy amount of virtual address space, then maybe there // isn't enough for our bitmap. const __int64 kLotsOfMem = 1500000000; // 1.5GB. PROCESS_MEMORY_COUNTERS pmc; if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) CHECK(pmc.PagefileUsage < kLotsOfMem); // Everything else. CHECK(0); } // Crashes the process. This is called when a bitmap allocation fails but // unlike its cousin CrashForBitmapAllocationFailure() it tries to detect if // the issue was a non-valid shared bitmap handle. __declspec(noinline) void CrashIfInvalidSection(HANDLE shared_section) { DWORD handle_info = 0; CHECK(::GetHandleInformation(shared_section, &handle_info) == TRUE); } PlatformCanvas::PlatformCanvas() : SkCanvas() { } PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque) : SkCanvas() { bool initialized = initialize(width, height, is_opaque, NULL); if (!initialized) CrashForBitmapAllocationFailure(width, height); } PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque, HANDLE shared_section) : SkCanvas() { bool initialized = initialize(width, height, is_opaque, shared_section); if (!initialized) { CrashIfInvalidSection(shared_section); CrashForBitmapAllocationFailure(width, height); } } PlatformCanvas::~PlatformCanvas() { } bool PlatformCanvas::initialize(int width, int height, bool is_opaque, HANDLE shared_section) { SkDevice* device = BitmapPlatformDevice::create(width, height, is_opaque, shared_section); if (!device) return false; setDevice(device); device->unref(); // was created with refcount 1, and setDevice also refs return true; } HDC PlatformCanvas::beginPlatformPaint() { return getTopPlatformDevice().getBitmapDC(); } void PlatformCanvas::endPlatformPaint() { // we don't clear the DC here since it will be likely to be used again // flushing will be done in onAccessBitmap } SkDevice* PlatformCanvas::createDevice(SkBitmap::Config config, int width, int height, bool is_opaque, bool isForLayer) { SkASSERT(config == SkBitmap::kARGB_8888_Config); return BitmapPlatformDevice::create(width, height, is_opaque, NULL); } } // namespace skia <commit_msg>Enhance the post-mortem information provided by CrashForBitmapAllocationFailure. <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 <windows.h> #include <psapi.h> #include "skia/ext/bitmap_platform_device_win.h" #include "skia/ext/platform_canvas.h" namespace skia { // Disable optimizations during crash analysis. #pragma optimize("", off) // Crash on failure. #define CHECK(condition) if (!(condition)) __debugbreak(); // Crashes the process. This is called when a bitmap allocation fails, and this // function tries to determine why it might have failed, and crash on different // lines. This allows us to see in crash dumps the most likely reason for the // failure. It takes the size of the bitmap we were trying to allocate as its // arguments so we can check that as well. // // Note that in a sandboxed renderer this function crashes when trying to // call GetProcessMemoryInfo() because it tries to load psapi.dll, which // is fine but gives you a very hard to read crash dump. void CrashForBitmapAllocationFailure(int w, int h) { // Store the extended error info in a place easy to find at debug time. struct { unsigned int last_error; unsigned int diag_error; } extended_error_info; extended_error_info.last_error = GetLastError(); extended_error_info.diag_error = 0; // If the bitmap is ginormous, then we probably can't allocate it. // We use 64M pixels = 256MB @ 4 bytes per pixel. const __int64 kGinormousBitmapPxl = 64000000; CHECK(static_cast<__int64>(w) * static_cast<__int64>(h) < kGinormousBitmapPxl); // The maximum number of GDI objects per process is 10K. If we're very close // to that, it's probably the problem. const unsigned int kLotsOfGDIObjects = 9990; unsigned int num_gdi_objects = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); if (num_gdi_objects == 0) { extended_error_info.diag_error = GetLastError(); CHECK(0); } CHECK(num_gdi_objects < kLotsOfGDIObjects); // If we're using a crazy amount of virtual address space, then maybe there // isn't enough for our bitmap. const SIZE_T kLotsOfMem = 1500000000; // 1.5GB. PROCESS_MEMORY_COUNTERS pmc; if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) { extended_error_info.diag_error = GetLastError(); CHECK(0); } CHECK(pmc.PagefileUsage < kLotsOfMem); // Everything else. CHECK(0); } // Crashes the process. This is called when a bitmap allocation fails but // unlike its cousin CrashForBitmapAllocationFailure() it tries to detect if // the issue was a non-valid shared bitmap handle. void CrashIfInvalidSection(HANDLE shared_section) { DWORD handle_info = 0; CHECK(::GetHandleInformation(shared_section, &handle_info) == TRUE); } // Restore the optimization options. #pragma optimize("", on) PlatformCanvas::PlatformCanvas() : SkCanvas() { } PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque) : SkCanvas() { bool initialized = initialize(width, height, is_opaque, NULL); if (!initialized) CrashForBitmapAllocationFailure(width, height); } PlatformCanvas::PlatformCanvas(int width, int height, bool is_opaque, HANDLE shared_section) : SkCanvas() { bool initialized = initialize(width, height, is_opaque, shared_section); if (!initialized) { CrashIfInvalidSection(shared_section); CrashForBitmapAllocationFailure(width, height); } } PlatformCanvas::~PlatformCanvas() { } bool PlatformCanvas::initialize(int width, int height, bool is_opaque, HANDLE shared_section) { SkDevice* device = BitmapPlatformDevice::create(width, height, is_opaque, shared_section); if (!device) return false; setDevice(device); device->unref(); // was created with refcount 1, and setDevice also refs return true; } HDC PlatformCanvas::beginPlatformPaint() { return getTopPlatformDevice().getBitmapDC(); } void PlatformCanvas::endPlatformPaint() { // we don't clear the DC here since it will be likely to be used again // flushing will be done in onAccessBitmap } SkDevice* PlatformCanvas::createDevice(SkBitmap::Config config, int width, int height, bool is_opaque, bool isForLayer) { SkASSERT(config == SkBitmap::kARGB_8888_Config); return BitmapPlatformDevice::create(width, height, is_opaque, NULL); } } // namespace skia <|endoftext|>
<commit_before>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #ifndef CLOVER_UTIL_COMPAT_HPP #define CLOVER_UTIL_COMPAT_HPP #include <new> #include <cstring> #include <cstdlib> #include <string> #include <stdint.h> namespace clover { namespace compat { // XXX - For cases where we can't rely on STL... I.e. the // interface between code compiled as C++98 and C++11 // source. Get rid of this as soon as everything can be // compiled as C++11. template<typename T> class vector { protected: static T * alloc(int n, const T *q, int m) { T *p = reinterpret_cast<T *>(std::malloc(n * sizeof(T))); for (int i = 0; i < m; ++i) new(&p[i]) T(q[i]); return p; } static void free(int n, T *p) { for (int i = 0; i < n; ++i) p[i].~T(); std::free(p); } public: typedef T *iterator; typedef const T *const_iterator; typedef T value_type; typedef T &reference; typedef const T &const_reference; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; vector() : p(NULL), _size(0), _capacity(0) { } vector(const vector &v) : p(alloc(v._size, v.p, v._size)), _size(v._size), _capacity(v._size) { } vector(const_iterator p, size_type n) : p(alloc(n, p, n)), _size(n), _capacity(n) { } template<typename C> vector(const C &v) : p(alloc(v.size(), &*v.begin(), v.size())), _size(v.size()) , _capacity(v.size()) { } ~vector() { free(_size, p); } vector & operator=(const vector &v) { free(_size, p); p = alloc(v._size, v.p, v._size); _size = v._size; _capacity = v._size; return *this; } void reserve(size_type n) { if (_capacity < n) { T *q = alloc(n, p, _size); free(_size, p); p = q; _capacity = n; } } void resize(size_type n, T x = T()) { if (n <= _size) { for (size_type i = n; i < _size; ++i) p[i].~T(); } else { reserve(n); for (size_type i = _size; i < n; ++i) new(&p[i]) T(x); } _size = n; } void push_back(const T &x) { reserve(_size + 1); new(&p[_size]) T(x); ++_size; } size_type size() const { return _size; } size_type capacity() const { return _capacity; } iterator begin() { return p; } const_iterator begin() const { return p; } iterator end() { return p + _size; } const_iterator end() const { return p + _size; } reference operator[](size_type i) { return p[i]; } const_reference operator[](size_type i) const { return p[i]; } private: iterator p; size_type _size; size_type _capacity; }; template<typename T> class vector_ref { public: typedef T *iterator; typedef const T *const_iterator; typedef T value_type; typedef T &reference; typedef const T &const_reference; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; vector_ref(iterator p, size_type n) : p(p), n(n) { } template<typename C> vector_ref(C &v) : p(&*v.begin()), n(v.size()) { } size_type size() const { return n; } iterator begin() { return p; } const_iterator begin() const { return p; } iterator end() { return p + n; } const_iterator end() const { return p + n; } reference operator[](int i) { return p[i]; } const_reference operator[](int i) const { return p[i]; } private: iterator p; size_type n; }; class istream { public: typedef vector_ref<const unsigned char> buffer_t; class error { public: virtual ~error() {} }; istream(const buffer_t &buf) : buf(buf), offset(0) {} void read(char *p, size_t n) { if (offset + n > buf.size()) throw error(); std::memcpy(p, buf.begin() + offset, n); offset += n; } private: const buffer_t &buf; size_t offset; }; class ostream { public: typedef vector<unsigned char> buffer_t; ostream(buffer_t &buf) : buf(buf), offset(buf.size()) {} void write(const char *p, size_t n) { buf.resize(offset + n); std::memcpy(buf.begin() + offset, p, n); offset += n; } private: buffer_t &buf; size_t offset; }; class string : public vector<char> { public: string() : vector() { } string(const char *p) : vector(p, std::strlen(p)) { } template<typename C> string(const C &v) : vector(v) { } operator std::string() const { return std::string(begin(), end()); } const char * c_str() const { return begin(); } const char * find(const string &s) const { for (size_t i = 0; i + s.size() < size(); ++i) { if (!std::memcmp(begin() + i, s.begin(), s.size())) return begin() + i; } return end(); } }; template<typename T> bool operator==(const vector_ref<T> &a, const vector_ref<T> &b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) return false; return true; } class exception { public: exception() {} virtual ~exception(); virtual const char *what() const; }; class runtime_error : public exception { public: runtime_error(const string &what) : _what(what) {} virtual const char *what() const; protected: string _what; }; } } #endif <commit_msg>clover/util: Implement compat::string using aggregation instead of inheritance.<commit_after>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #ifndef CLOVER_UTIL_COMPAT_HPP #define CLOVER_UTIL_COMPAT_HPP #include <new> #include <cstring> #include <cstdlib> #include <string> #include <stdint.h> namespace clover { namespace compat { // XXX - For cases where we can't rely on STL... I.e. the // interface between code compiled as C++98 and C++11 // source. Get rid of this as soon as everything can be // compiled as C++11. template<typename T> class vector { protected: static T * alloc(int n, const T *q, int m) { T *p = reinterpret_cast<T *>(std::malloc(n * sizeof(T))); for (int i = 0; i < m; ++i) new(&p[i]) T(q[i]); return p; } static void free(int n, T *p) { for (int i = 0; i < n; ++i) p[i].~T(); std::free(p); } public: typedef T *iterator; typedef const T *const_iterator; typedef T value_type; typedef T &reference; typedef const T &const_reference; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; vector() : p(NULL), _size(0), _capacity(0) { } vector(const vector &v) : p(alloc(v._size, v.p, v._size)), _size(v._size), _capacity(v._size) { } vector(const_iterator p, size_type n) : p(alloc(n, p, n)), _size(n), _capacity(n) { } template<typename C> vector(const C &v) : p(alloc(v.size(), &*v.begin(), v.size())), _size(v.size()) , _capacity(v.size()) { } ~vector() { free(_size, p); } vector & operator=(const vector &v) { free(_size, p); p = alloc(v._size, v.p, v._size); _size = v._size; _capacity = v._size; return *this; } void reserve(size_type n) { if (_capacity < n) { T *q = alloc(n, p, _size); free(_size, p); p = q; _capacity = n; } } void resize(size_type n, T x = T()) { if (n <= _size) { for (size_type i = n; i < _size; ++i) p[i].~T(); } else { reserve(n); for (size_type i = _size; i < n; ++i) new(&p[i]) T(x); } _size = n; } void push_back(const T &x) { reserve(_size + 1); new(&p[_size]) T(x); ++_size; } size_type size() const { return _size; } size_type capacity() const { return _capacity; } iterator begin() { return p; } const_iterator begin() const { return p; } iterator end() { return p + _size; } const_iterator end() const { return p + _size; } reference operator[](size_type i) { return p[i]; } const_reference operator[](size_type i) const { return p[i]; } private: iterator p; size_type _size; size_type _capacity; }; template<typename T> class vector_ref { public: typedef T *iterator; typedef const T *const_iterator; typedef T value_type; typedef T &reference; typedef const T &const_reference; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; vector_ref(iterator p, size_type n) : p(p), n(n) { } template<typename C> vector_ref(C &v) : p(&*v.begin()), n(v.size()) { } size_type size() const { return n; } iterator begin() { return p; } const_iterator begin() const { return p; } iterator end() { return p + n; } const_iterator end() const { return p + n; } reference operator[](int i) { return p[i]; } const_reference operator[](int i) const { return p[i]; } private: iterator p; size_type n; }; class istream { public: typedef vector_ref<const unsigned char> buffer_t; class error { public: virtual ~error() {} }; istream(const buffer_t &buf) : buf(buf), offset(0) {} void read(char *p, size_t n) { if (offset + n > buf.size()) throw error(); std::memcpy(p, buf.begin() + offset, n); offset += n; } private: const buffer_t &buf; size_t offset; }; class ostream { public: typedef vector<unsigned char> buffer_t; ostream(buffer_t &buf) : buf(buf), offset(buf.size()) {} void write(const char *p, size_t n) { buf.resize(offset + n); std::memcpy(buf.begin() + offset, p, n); offset += n; } private: buffer_t &buf; size_t offset; }; class string { public: typedef char *iterator; typedef const char *const_iterator; typedef char value_type; typedef char &reference; typedef const char &const_reference; typedef std::ptrdiff_t difference_type; typedef std::size_t size_type; string() : v() { } string(const char *p) : v(p, std::strlen(p)) { } template<typename C> string(const C &v) : v(v) { } operator std::string() const { return std::string(v.begin(), v.end()); } void reserve(size_type n) { v.reserve(n); } void resize(size_type n, char x = char()) { v.resize(n, x); } void push_back(char x) { v.push_back(x); } size_type size() const { return v.size(); } size_type capacity() const { return v.capacity(); } iterator begin() { return v.begin(); } const_iterator begin() const { return v.begin(); } iterator end() { return v.end(); } const_iterator end() const { return v.end(); } reference operator[](size_type i) { return v[i]; } const_reference operator[](size_type i) const { return v[i]; } const char * c_str() const { return begin(); } const char * find(const string &s) const { for (size_t i = 0; i + s.size() < size(); ++i) { if (!std::memcmp(begin() + i, s.begin(), s.size())) return begin() + i; } return end(); } private: mutable vector<char> v; }; template<typename T> bool operator==(const vector_ref<T> &a, const vector_ref<T> &b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) return false; return true; } class exception { public: exception() {} virtual ~exception(); virtual const char *what() const; }; class runtime_error : public exception { public: runtime_error(const string &what) : _what(what) {} virtual const char *what() const; protected: string _what; }; } } #endif <|endoftext|>
<commit_before> #include <stdio.h> #include <windows.h> typedef unsigned int uint; typedef unsigned long long qword; const uint g_PageFlag0 = 0x1000; const uint g_PageMask0 = 0x1000-1; uint g_PageFlag = g_PageFlag0; uint g_PageMask = g_PageMask0; #pragma comment(lib, "advapi32.lib") void InitLargePages( void ) { HANDLE hToken = 0; LUID luid; TOKEN_PRIVILEGES tp; OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken ); LookupPrivilegeValue( NULL, "SeLockMemoryPrivilege", &luid ); tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(tp), 0, 0 ); CloseHandle(hToken); uint size = 0x1000; typedef uint (__stdcall *GetLPMP)( void ); GetLPMP LPM = (GetLPMP)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),"GetLargePageMinimum"); if( LPM ) size = LPM(); if( (size==0) || ((size&(size-1))!=0) ) size=0x1000; g_PageMask = size-1; g_PageFlag = g_PageFlag0; if( size>0x1000 ) g_PageFlag |= 0x20000000; } template< class T > T* VAlloc( qword size ) { void* r; size *= sizeof(T); qword s = (size+g_PageMask) & (~qword(g_PageMask)); Retry: #ifndef MY_CPU_64BIT if( s>=(qword(1)<<32) ) r=0; else #endif r = VirtualAlloc(0, s, g_PageFlag, PAGE_READWRITE ); if( (r==0) && (g_PageMask!=g_PageMask0) ) { g_PageFlag = g_PageFlag0; g_PageMask = g_PageMask0; s = size; goto Retry; } return (T*)r; } template< class T > void VFree( T* p ) { VirtualFree( p, 0, MEM_RELEASE ); } int main( void ) { InitLargePages(); uint* p = VAlloc<uint>( 1<<20 ); printf( "p=%08X Flags=%08X\n", p, g_PageFlag ); } <commit_msg>LargePages.cpp: final version<commit_after>#include <windows.h> const DWORD g_PageFlag0 = 0x1000; const uint64_t g_PageMask0 = 0x1000-1; DWORD g_PageFlag = g_PageFlag0; uint64_t g_PageMask = g_PageMask0; #pragma comment(lib, "advapi32.lib") void InitLargePages() { HANDLE hToken = 0; LUID luid; TOKEN_PRIVILEGES tp; OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken); LookupPrivilegeValue (NULL, "SeLockMemoryPrivilege", &luid); tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges (hToken, FALSE, &tp, sizeof(tp), 0, 0); CloseHandle(hToken); uint64_t size = 0x1000; typedef SIZE_T (__stdcall *GetLPMP)(); GetLPMP LPM = (GetLPMP)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),"GetLargePageMinimum"); if (LPM) size = LPM(); if (size==0 || (size&(size-1))!=0) size=0x1000; g_PageMask = size-1; g_PageFlag = g_PageFlag0; if (size>0x1000) g_PageFlag |= 0x20000000; } template< class T > T* VAlloc (uint64_t size) { size *= sizeof(T); uint64_t s = (size+g_PageMask) & (~g_PageMask); if (s > size_t(-1)) { return 0; } void* r = 0; if (size > g_PageMask) { r = VirtualAlloc(0, s, g_PageFlag, PAGE_READWRITE); // alloc using 2 MB pages only if the size is no less than one page } if (r==0) { printf("LargePage allocation failed\n"); s = (size+g_PageMask0) & (~g_PageMask0); r = VirtualAlloc(0, size, g_PageFlag0, PAGE_READWRITE); // alloc using 4 KB pages, if preceding attempt failed } return (T*)r; } template< class T > void VFree( T* p ) { VirtualFree(p, 0, MEM_RELEASE); } <|endoftext|>
<commit_before>#include "grabber.h" #include "main.h" #include <X11/extensions/XTest.h> #include <X11/Xutil.h> Grabber::Grabber() { current.grab = false; current.suspend = false; current.all = false; current.xi = false; current.pointer = false; get_button(); wm_state = XInternAtom(dpy, "WM_STATE", False); xinput = init_xi(); init(ROOT, 0); cursor = XCreateFontCursor(dpy, XC_double_arrow); } Grabber::~Grabber() { XFreeCursor(dpy, cursor); } bool Grabber::init_xi() { xi_devs_n = 0; int nMajor, nFEV, nFER; if (!XQueryExtension(dpy,INAME,&nMajor,&nFEV,&nFER)) return false; int i, n; XDeviceInfo *devs; devs = XListInputDevices(dpy, &n); if (!devs) return false; xi_devs = new XiDevice *[n]; for (i=0; i<n; ++i) { XDeviceInfo *dev = devs + i; if (dev->use == 0 || dev->use == IsXKeyboard || dev->use == IsXPointer) continue; bool has_button = false; for (int j = 0; j < dev->num_classes; j++) if (dev->inputclassinfo[j].c_class == ButtonClass) has_button = true; if (!has_button) continue; if (verbosity >= 1) printf("Opening Device %s...\n", dev->name); XiDevice *xi_dev = new XiDevice; xi_dev->dev = XOpenDevice(dpy, dev->id); if (!xi_dev) { delete xi_dev; continue; } DeviceButtonPress(xi_dev->dev, xi_dev->button_down, xi_dev->button_events[0]); DeviceButtonRelease(xi_dev->dev, xi_dev->button_up, xi_dev->button_events[1]); xi_dev->button_events_n = 2; xi_devs[xi_devs_n++] = xi_dev; } return xi_devs_n; } bool Grabber::is_button_up(int type) { for (int i = 0; i < xi_devs_n; i++) if (type == xi_devs[i]->button_up) return true; return false; } bool Grabber::is_button_down(int type) { for (int i = 0; i < xi_devs_n; i++) if (type == xi_devs[i]->button_down) return true; return false; } // Fuck Xlib bool Grabber::has_wm_state(Window w) { Atom actual_type_return; int actual_format_return; unsigned long nitems_return; unsigned long bytes_after_return; unsigned char *prop_return; if (Success != XGetWindowProperty(dpy, w, wm_state, 0, 2, False, AnyPropertyType, &actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &prop_return)) return false; XFree(prop_return); return nitems_return; } // Calls create on top-level windows, i.e. windows that have th wm_state property. void Grabber::init(Window w, int depth) { depth++; // I have no clue why this is needed, but just querying the whole tree // prevents EnterNotifies from being generated. Weird. // update 2/12/08: Disappeared. Leaving the code here in case this // comes back // 2/15/08: put it back in for release. You never know. if (depth > 2) return; unsigned int n; Window dummyw1, dummyw2, *ch; XQueryTree(dpy, w, &dummyw1, &dummyw2, &ch, &n); for (unsigned int i = 0; i != n; i++) { if (!has_wm_state(ch[i])) init(ch[i], depth); else create(ch[i]); } XFree(ch); } #define ENSURE(p) while (!(p)) { printf("Grab failed, retrying...\n"); usleep(10000); } void Grabber::set(State s) { Goal old_goal = goal(current); Goal new_goal = goal(s); current = s; if (old_goal == new_goal) return; if (old_goal == BUTTON) { for (int i = 0; i < xi_devs_n; i++) XUngrabDeviceButton(dpy, xi_devs[i]->dev, button, state, NULL, ROOT); XUngrabButton(dpy, button, state, ROOT); } if (old_goal == ALL) XUngrabButton(dpy, AnyButton, AnyModifier, ROOT); if (old_goal == XI) for (int i = 0; i < xi_devs_n; i++) XUngrabDeviceButton(dpy, xi_devs[i]->dev, AnyButton, AnyModifier, NULL, ROOT); if (old_goal == POINTER) { XUngrabPointer(dpy, CurrentTime); } if (new_goal == BUTTON) { ENSURE(XGrabButton(dpy, button, state, ROOT, False, ButtonMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None)) for (int i = 0; i < xi_devs_n; i++) ENSURE(!xinput || !XGrabDeviceButton(dpy, xi_devs[i]->dev, button, state, NULL, ROOT, False, xi_devs[i]->button_events_n, xi_devs[i]->button_events, GrabModeAsync, GrabModeAsync)) } if (new_goal == ALL) ENSURE(XGrabButton(dpy, AnyButton, AnyModifier, ROOT, False, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None)) if (new_goal == XI) for (int i = 0; i < xi_devs_n; i++) ENSURE(!xinput || XGrabDeviceButton(dpy, xi_devs[i]->dev, AnyButton, AnyModifier, NULL, ROOT, False, xi_devs[i]->button_events_n, xi_devs[i]->button_events, GrabModeAsync, GrabModeAsync)) if (new_goal == POINTER) { while (XGrabPointer(dpy, ROOT, False, PointerMotionMask|ButtonMotionMask|ButtonPressMask|ButtonReleaseMask, GrabModeAsync, GrabModeAsync, ROOT, cursor, CurrentTime) != GrabSuccess) usleep(10000); } } #undef ENSURE void Grabber::get_button() { Ref<ButtonInfo> ref(prefs().button); button = ref->button; state = ref->state; } void Grabber::fake_button(int b) { suspend(); XTestFakeButtonEvent(dpy, b, True, CurrentTime); XTestFakeButtonEvent(dpy, b, False, CurrentTime); clear_mods(); restore(); } void Grabber::ignore(int b) { XAllowEvents(dpy, ReplayPointer, CurrentTime); clear_mods(); State s = current; s.all = false; set(s); } std::string Grabber::get_wm_state(Window w) { XClassHint ch; if (!XGetClassHint(dpy, w, &ch)) return ""; std::string ans = ch.res_name; XFree(ch.res_name); XFree(ch.res_class); return ans; } void Grabber::create(Window w) { XSetWindowAttributes attr; attr.event_mask = EnterWindowMask; XChangeWindowAttributes(dpy, w, CWEventMask, &attr); } <commit_msg>stupid bug<commit_after>#include "grabber.h" #include "main.h" #include <X11/extensions/XTest.h> #include <X11/Xutil.h> Grabber::Grabber() { current.grab = false; current.suspend = false; current.all = false; current.xi = false; current.pointer = false; get_button(); wm_state = XInternAtom(dpy, "WM_STATE", False); xinput = init_xi(); init(ROOT, 0); cursor = XCreateFontCursor(dpy, XC_double_arrow); } Grabber::~Grabber() { XFreeCursor(dpy, cursor); } bool Grabber::init_xi() { xi_devs_n = 0; int nMajor, nFEV, nFER; if (!XQueryExtension(dpy,INAME,&nMajor,&nFEV,&nFER)) return false; int i, n; XDeviceInfo *devs; devs = XListInputDevices(dpy, &n); if (!devs) return false; xi_devs = new XiDevice *[n]; for (i=0; i<n; ++i) { XDeviceInfo *dev = devs + i; if (dev->use == 0 || dev->use == IsXKeyboard || dev->use == IsXPointer) continue; bool has_button = false; for (int j = 0; j < dev->num_classes; j++) if (dev->inputclassinfo[j].c_class == ButtonClass) has_button = true; if (!has_button) continue; if (verbosity >= 1) printf("Opening Device %s...\n", dev->name); XiDevice *xi_dev = new XiDevice; xi_dev->dev = XOpenDevice(dpy, dev->id); if (!xi_dev) { delete xi_dev; continue; } DeviceButtonPress(xi_dev->dev, xi_dev->button_down, xi_dev->button_events[0]); DeviceButtonRelease(xi_dev->dev, xi_dev->button_up, xi_dev->button_events[1]); xi_dev->button_events_n = 2; xi_devs[xi_devs_n++] = xi_dev; } return xi_devs_n; } bool Grabber::is_button_up(int type) { for (int i = 0; i < xi_devs_n; i++) if (type == xi_devs[i]->button_up) return true; return false; } bool Grabber::is_button_down(int type) { for (int i = 0; i < xi_devs_n; i++) if (type == xi_devs[i]->button_down) return true; return false; } // Fuck Xlib bool Grabber::has_wm_state(Window w) { Atom actual_type_return; int actual_format_return; unsigned long nitems_return; unsigned long bytes_after_return; unsigned char *prop_return; if (Success != XGetWindowProperty(dpy, w, wm_state, 0, 2, False, AnyPropertyType, &actual_type_return, &actual_format_return, &nitems_return, &bytes_after_return, &prop_return)) return false; XFree(prop_return); return nitems_return; } // Calls create on top-level windows, i.e. windows that have th wm_state property. void Grabber::init(Window w, int depth) { depth++; // I have no clue why this is needed, but just querying the whole tree // prevents EnterNotifies from being generated. Weird. // update 2/12/08: Disappeared. Leaving the code here in case this // comes back // 2/15/08: put it back in for release. You never know. if (depth > 2) return; unsigned int n; Window dummyw1, dummyw2, *ch; XQueryTree(dpy, w, &dummyw1, &dummyw2, &ch, &n); for (unsigned int i = 0; i != n; i++) { if (!has_wm_state(ch[i])) init(ch[i], depth); else create(ch[i]); } XFree(ch); } #define ENSURE(p) while (!(p)) { printf("Grab failed, retrying...\n"); usleep(10000); } void Grabber::set(State s) { Goal old_goal = goal(current); Goal new_goal = goal(s); current = s; if (old_goal == new_goal) return; if (old_goal == BUTTON) { for (int i = 0; i < xi_devs_n; i++) XUngrabDeviceButton(dpy, xi_devs[i]->dev, button, state, NULL, ROOT); XUngrabButton(dpy, button, state, ROOT); } if (old_goal == ALL) XUngrabButton(dpy, AnyButton, AnyModifier, ROOT); if (old_goal == XI) for (int i = 0; i < xi_devs_n; i++) XUngrabDeviceButton(dpy, xi_devs[i]->dev, AnyButton, AnyModifier, NULL, ROOT); if (old_goal == POINTER) { XUngrabPointer(dpy, CurrentTime); } if (new_goal == BUTTON) { ENSURE(XGrabButton(dpy, button, state, ROOT, False, ButtonMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None)) for (int i = 0; i < xi_devs_n; i++) ENSURE(!xinput || !XGrabDeviceButton(dpy, xi_devs[i]->dev, button, state, NULL, ROOT, False, xi_devs[i]->button_events_n, xi_devs[i]->button_events, GrabModeAsync, GrabModeAsync)) } if (new_goal == ALL) ENSURE(XGrabButton(dpy, AnyButton, AnyModifier, ROOT, False, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None)) if (new_goal == XI) for (int i = 0; i < xi_devs_n; i++) ENSURE(!xinput || !XGrabDeviceButton(dpy, xi_devs[i]->dev, AnyButton, AnyModifier, NULL, ROOT, False, xi_devs[i]->button_events_n, xi_devs[i]->button_events, GrabModeAsync, GrabModeAsync)) if (new_goal == POINTER) { while (XGrabPointer(dpy, ROOT, False, PointerMotionMask|ButtonMotionMask|ButtonPressMask|ButtonReleaseMask, GrabModeAsync, GrabModeAsync, ROOT, cursor, CurrentTime) != GrabSuccess) usleep(10000); } } #undef ENSURE void Grabber::get_button() { Ref<ButtonInfo> ref(prefs().button); button = ref->button; state = ref->state; } void Grabber::fake_button(int b) { suspend(); XTestFakeButtonEvent(dpy, b, True, CurrentTime); XTestFakeButtonEvent(dpy, b, False, CurrentTime); clear_mods(); restore(); } void Grabber::ignore(int b) { XAllowEvents(dpy, ReplayPointer, CurrentTime); clear_mods(); State s = current; s.all = false; set(s); } std::string Grabber::get_wm_state(Window w) { XClassHint ch; if (!XGetClassHint(dpy, w, &ch)) return ""; std::string ans = ch.res_name; XFree(ch.res_name); XFree(ch.res_class); return ans; } void Grabber::create(Window w) { XSetWindowAttributes attr; attr.event_mask = EnterWindowMask; XChangeWindowAttributes(dpy, w, CWEventMask, &attr); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fileos2.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-02 13:04:22 $ * * 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 INCLUDED_STORE_FILEOS2_HXX #define INCLUDED_STORE_FILEOS2_HXX #define INCL_DOS #define INCL_DOSERRORS #include <os2.h> typedef HFILE HSTORE; /*======================================================================== * * File I/O (inline) implementation. * *======================================================================*/ /* * __store_errcode_map. */ static const __store_errcode_mapping_st __store_errcode_map[] = { { NO_ERROR, store_E_None }, { ERROR_FILE_NOT_FOUND, store_E_NotExists }, { ERROR_PATH_NOT_FOUND, store_E_NotExists }, { ERROR_ACCESS_DENIED, store_E_AccessViolation }, { ERROR_SHARING_VIOLATION, store_E_AccessViolation }, { ERROR_LOCK_VIOLATION, store_E_LockingViolation }, { ERROR_INVALID_ACCESS, store_E_InvalidAccess }, { ERROR_INVALID_HANDLE, store_E_InvalidHandle }, { ERROR_INVALID_PARAMETER, store_E_InvalidParameter }, { ERROR_FILENAME_EXCED_RANGE, store_E_NameTooLong }, { ERROR_TOO_MANY_OPEN_FILES, store_E_NoMoreFiles } }; /* * __store_errno. */ inline sal_Int32 __store_errno (void) { return (sal_Int32)errno; } /* * __store_malign (unsupported). */ inline sal_uInt32 __store_malign (void) { return (sal_uInt32)(-1); } /* * __store_fmap (readonly, unsupported). */ inline HSTORE __store_fmap (HSTORE hFile) { return ((HSTORE)0); } /* * __store_funmap. */ inline void __store_funmap (HSTORE hMap) { } /* * __store_mmap (readonly, unsupported). */ inline sal_uInt8* __store_mmap (HSTORE h, sal_uInt32 k, sal_uInt32 n) { return (sal_uInt8*)NULL; } /* * __store_munmap (unsupported). */ inline void __store_munmap (sal_uInt8 *p, sal_uInt32 n) { } /* * __store_fopen. */ inline storeError __store_fopen ( const sal_Char *pszName, sal_uInt32 nMode, HSTORE &rhFile) { // Initialize [out] param. rhFile = 0; // Access mode. sal_uInt32 nAccessMode = OPEN_ACCESS_READONLY; if (nMode & store_File_OpenWrite) nAccessMode = OPEN_ACCESS_READWRITE; if (nAccessMode == OPEN_ACCESS_READONLY) { nMode |= store_File_OpenNoCreate; nMode &= ~store_File_OpenTruncate; } // Share mode. sal_uInt32 nShareMode = OPEN_SHARE_DENYNONE; if (nMode & store_File_OpenWrite) nShareMode = OPEN_SHARE_DENYWRITE; // Open action. sal_uInt32 nOpenAction = 0, nDoneAction = 0; if (!(nMode & store_File_OpenNoCreate)) nOpenAction = OPEN_ACTION_CREATE_IF_NEW; // Open always. else nOpenAction = OPEN_ACTION_FAIL_IF_NEW; // Open existing. if (nMode & store_File_OpenTruncate) nOpenAction |= OPEN_ACTION_REPLACE_IF_EXISTS; else nOpenAction |= OPEN_ACTION_OPEN_IF_EXISTS; // Create file handle. APIRET result = ::DosOpen ( (PSZ)pszName, &rhFile, &nDoneAction, 0L, FILE_NORMAL, nOpenAction, nAccessMode | nShareMode | OPEN_FLAGS_NOINHERIT, 0L); // Check result. if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fread. */ inline storeError __store_fread ( HSTORE h, sal_uInt32 offset, void *p, sal_uInt32 n, sal_uInt32 &k) { APIRET result; if ((result = ::DosSetFilePtr (h, (long)offset, FILE_BEGIN, &k)) != 0) return ERROR_FROM_NATIVE(result); if ((result = ::DosRead (h, p, n, &k)) != 0) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fwrite. */ inline storeError __store_fwrite ( HSTORE h, sal_uInt32 offset, const void *p, sal_uInt32 n, sal_uInt32 &k) { APIRET result; if ((result = ::DosSetFilePtr (h, (long)offset, FILE_BEGIN, &k)) != 0) return ERROR_FROM_NATIVE(result); if ((result = ::DosWrite (h, (PVOID)p, n, &k)) != 0) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fseek. */ inline storeError __store_fseek (HSTORE h, sal_uInt32 n) { sal_uInt32 k = 0; APIRET result = ::DosSetFilePtr (h, (long)n, FILE_BEGIN, &k); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fsize. */ inline storeError __store_fsize (HSTORE h, sal_uInt32 &k) { APIRET result = ::DosSetFilePtr (h, 0L, FILE_END, &k); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_ftrunc. */ inline storeError __store_ftrunc (HSTORE h, sal_uInt32 n) { APIRET result = ::DosSetFileSize (h, n); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fsync. */ inline storeError __store_fsync (HSTORE h) { APIRET result = ::DosResetBuffer (h); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fclose. */ inline storeError __store_fclose (HSTORE h) { APIRET result = ::DosClose (h); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } #endif /* INCLUDED_STORE_FILEOS2_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.5.8); FILE MERGED 2008/03/31 15:27:47 rt 1.5.8.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: fileos2.hxx,v $ * $Revision: 1.6 $ * * 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 INCLUDED_STORE_FILEOS2_HXX #define INCLUDED_STORE_FILEOS2_HXX #define INCL_DOS #define INCL_DOSERRORS #include <os2.h> typedef HFILE HSTORE; /*======================================================================== * * File I/O (inline) implementation. * *======================================================================*/ /* * __store_errcode_map. */ static const __store_errcode_mapping_st __store_errcode_map[] = { { NO_ERROR, store_E_None }, { ERROR_FILE_NOT_FOUND, store_E_NotExists }, { ERROR_PATH_NOT_FOUND, store_E_NotExists }, { ERROR_ACCESS_DENIED, store_E_AccessViolation }, { ERROR_SHARING_VIOLATION, store_E_AccessViolation }, { ERROR_LOCK_VIOLATION, store_E_LockingViolation }, { ERROR_INVALID_ACCESS, store_E_InvalidAccess }, { ERROR_INVALID_HANDLE, store_E_InvalidHandle }, { ERROR_INVALID_PARAMETER, store_E_InvalidParameter }, { ERROR_FILENAME_EXCED_RANGE, store_E_NameTooLong }, { ERROR_TOO_MANY_OPEN_FILES, store_E_NoMoreFiles } }; /* * __store_errno. */ inline sal_Int32 __store_errno (void) { return (sal_Int32)errno; } /* * __store_malign (unsupported). */ inline sal_uInt32 __store_malign (void) { return (sal_uInt32)(-1); } /* * __store_fmap (readonly, unsupported). */ inline HSTORE __store_fmap (HSTORE hFile) { return ((HSTORE)0); } /* * __store_funmap. */ inline void __store_funmap (HSTORE hMap) { } /* * __store_mmap (readonly, unsupported). */ inline sal_uInt8* __store_mmap (HSTORE h, sal_uInt32 k, sal_uInt32 n) { return (sal_uInt8*)NULL; } /* * __store_munmap (unsupported). */ inline void __store_munmap (sal_uInt8 *p, sal_uInt32 n) { } /* * __store_fopen. */ inline storeError __store_fopen ( const sal_Char *pszName, sal_uInt32 nMode, HSTORE &rhFile) { // Initialize [out] param. rhFile = 0; // Access mode. sal_uInt32 nAccessMode = OPEN_ACCESS_READONLY; if (nMode & store_File_OpenWrite) nAccessMode = OPEN_ACCESS_READWRITE; if (nAccessMode == OPEN_ACCESS_READONLY) { nMode |= store_File_OpenNoCreate; nMode &= ~store_File_OpenTruncate; } // Share mode. sal_uInt32 nShareMode = OPEN_SHARE_DENYNONE; if (nMode & store_File_OpenWrite) nShareMode = OPEN_SHARE_DENYWRITE; // Open action. sal_uInt32 nOpenAction = 0, nDoneAction = 0; if (!(nMode & store_File_OpenNoCreate)) nOpenAction = OPEN_ACTION_CREATE_IF_NEW; // Open always. else nOpenAction = OPEN_ACTION_FAIL_IF_NEW; // Open existing. if (nMode & store_File_OpenTruncate) nOpenAction |= OPEN_ACTION_REPLACE_IF_EXISTS; else nOpenAction |= OPEN_ACTION_OPEN_IF_EXISTS; // Create file handle. APIRET result = ::DosOpen ( (PSZ)pszName, &rhFile, &nDoneAction, 0L, FILE_NORMAL, nOpenAction, nAccessMode | nShareMode | OPEN_FLAGS_NOINHERIT, 0L); // Check result. if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fread. */ inline storeError __store_fread ( HSTORE h, sal_uInt32 offset, void *p, sal_uInt32 n, sal_uInt32 &k) { APIRET result; if ((result = ::DosSetFilePtr (h, (long)offset, FILE_BEGIN, &k)) != 0) return ERROR_FROM_NATIVE(result); if ((result = ::DosRead (h, p, n, &k)) != 0) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fwrite. */ inline storeError __store_fwrite ( HSTORE h, sal_uInt32 offset, const void *p, sal_uInt32 n, sal_uInt32 &k) { APIRET result; if ((result = ::DosSetFilePtr (h, (long)offset, FILE_BEGIN, &k)) != 0) return ERROR_FROM_NATIVE(result); if ((result = ::DosWrite (h, (PVOID)p, n, &k)) != 0) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fseek. */ inline storeError __store_fseek (HSTORE h, sal_uInt32 n) { sal_uInt32 k = 0; APIRET result = ::DosSetFilePtr (h, (long)n, FILE_BEGIN, &k); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fsize. */ inline storeError __store_fsize (HSTORE h, sal_uInt32 &k) { APIRET result = ::DosSetFilePtr (h, 0L, FILE_END, &k); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_ftrunc. */ inline storeError __store_ftrunc (HSTORE h, sal_uInt32 n) { APIRET result = ::DosSetFileSize (h, n); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fsync. */ inline storeError __store_fsync (HSTORE h) { APIRET result = ::DosResetBuffer (h); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } /* * __store_fclose. */ inline storeError __store_fclose (HSTORE h) { APIRET result = ::DosClose (h); if (result) return ERROR_FROM_NATIVE(result); else return store_E_None; } #endif /* INCLUDED_STORE_FILEOS2_HXX */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fileunx.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2003-08-18 14:47:42 $ * * 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 INCLUDED_STORE_FILEUNX_HXX #define INCLUDED_STORE_FILEUNX_HXX #define _USE_UNIX98 /* _XOPEN_SOURCE=500 */ #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #if defined(FREEBSD) || defined(NETBSD) || defined(MACOSX) #define EDEADLOCK EDEADLK #endif /* FREEBSD || NETBSD || MACOSX */ typedef int HSTORE; /*======================================================================== * * File I/O (inline) implementation. * *======================================================================*/ /* * __store_errcode_map. */ static const __store_errcode_mapping_st __store_errcode_map[] = { { 0, store_E_None }, { ENOENT, store_E_NotExists }, { EACCES, store_E_AccessViolation }, { EPERM, store_E_AccessViolation }, { EAGAIN, store_E_LockingViolation }, #if defined(EDEADLOCK) { EDEADLOCK, store_E_LockingViolation }, #endif /* EDEADLOCK */ { EBADF, store_E_InvalidHandle }, { EINVAL, store_E_InvalidParameter }, }; /* * __store_errno. */ inline sal_Int32 __store_errno (void) { return (sal_Int32)errno; } /* * __store_malign. */ #if defined(FREEBSD) || defined(LINUX) || defined(MACOSX) inline sal_uInt32 __store_malign (void) { return (sal_uInt32)::getpagesize(); } #elif defined(IRIX) || defined(SOLARIS) inline sal_uInt32 __store_malign (void) { return (sal_uInt32)::sysconf (_SC_PAGESIZE); } #else inline sal_uInt32 __store_malign (void) { return (sal_uInt32)(-1); } #endif /* FREEBSD || IRIX || LINUX || SOLARIS || MACOSX*/ /* * __store_fmap (readonly). */ inline HSTORE __store_fmap (HSTORE hFile) { // Avoid hMap = dup (hFile); may result in EMFILE. return hFile; } /* * __store_funmap. */ inline void __store_funmap (HSTORE hMap) { // Nothing to do, see '__store_fmap()'. } /* * __store_mmap (readonly, shared). */ inline sal_uInt8* __store_mmap (HSTORE h, sal_uInt32 k, sal_uInt32 n) { void * p = ::mmap (NULL, (size_t)n, PROT_READ, MAP_SHARED, h, (off_t)k); return ((p != MAP_FAILED) ? (sal_uInt8*)p : 0); } /* * __store_munmap. */ inline void __store_munmap (sal_uInt8 *p, sal_uInt32 n) { ::munmap ((char *)p, (size_t)n); } /* * __store_fopen. */ inline storeError __store_fopen ( const sal_Char *pszName, sal_uInt32 nMode, HSTORE &rhFile) { // Access mode. int nAccessMode = O_RDONLY; if (nMode & store_File_OpenWrite) nAccessMode = O_RDWR; if (nAccessMode == O_RDONLY) nMode |= store_File_OpenNoCreate; if ((!(nMode & store_File_OpenNoCreate)) && (!(nAccessMode == O_RDONLY))) nAccessMode |= O_CREAT; if (nMode & store_File_OpenTruncate) nAccessMode |= O_TRUNC; // Share mode. int nShareMode = S_IREAD | S_IROTH | S_IRGRP; if (nMode & store_File_OpenWrite) nShareMode |= (S_IWRITE | S_IWOTH | S_IWGRP); // Create file handle. if ((rhFile = ::open (pszName, nAccessMode, nShareMode)) < 0) { rhFile = 0; return ERROR_FROM_NATIVE(errno); } #ifdef SOLARIS /* see workaround comment below */ /* * Workaround for SunOS <= 5.7: * * 'mmap()' fails on posix (advisory) locked (F_SETLK) NFS file handles. * Using non-posix F_SHARE / F_UNSHARE instead. */ // Acquire (advisory) Share Access (Multiple Reader | Single Writer) struct fshare share; if (nMode & store_File_OpenWrite) { share.f_access = F_RWACC; /* Request own read and write access */ share.f_deny = F_RWDNY; /* Deny other's read and write access */ } else { share.f_access = F_RDACC; /* Request own read-only access */ share.f_deny = F_WRDNY; /* Deny other's write access */ } share.f_id = 0; if (::fcntl (rhFile, F_SHARE, &share) < 0) { // Save original result. storeError result; if ((errno == EACCES) || (errno == EAGAIN)) result = store_E_LockingViolation; else result = ERROR_FROM_NATIVE(errno); // Close file handle. ::close (rhFile); rhFile = 0; // Finish. return (result); } #else /* POSIX */ // Acquire (advisory) Lock (Multiple Reader | Single Writer) struct flock lock; if (nMode & store_File_OpenWrite) lock.l_type = F_WRLCK; else lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (::fcntl (rhFile, F_SETLK, &lock) < 0) { // Save original result. storeError result; if ((errno == EACCES) || (errno == EAGAIN)) result = store_E_LockingViolation; else result = ERROR_FROM_NATIVE(errno); // Close file handle. ::close (rhFile); rhFile = 0; // Finish. return (result); } #endif /* SOLARIS || POSIX */ int nFlags = ::fcntl (rhFile, F_GETFD, 0); if (!(nFlags < 0)) { // Set close-on-exec flag. nFlags |= FD_CLOEXEC; ::fcntl (rhFile, F_SETFD, nFlags); } return store_E_None; } /* * __store_fread. */ inline storeError __store_fread ( HSTORE h, sal_uInt32 offset, void *p, sal_uInt32 n, sal_uInt32 &k) { #if defined(LINUX) || defined(SOLARIS) k = (sal_uInt32)::pread (h, (char*)p, (size_t)n, (off_t)offset); if ((k == (sal_uInt32)(-1)) && (errno == EOVERFLOW)) { /* * Workaround for 'pread()' failure at end-of-file: * * Some 'pread()'s fail with EOVERFLOW when reading at (or past) * end-of-file, different from 'lseek() + read()' behaviour. * Returning '0 bytes read' and 'store_E_None' instead. */ k = 0; } #else /* LINUX || SOLARIS */ if (::lseek (h, (off_t)offset, SEEK_SET) < 0) return ERROR_FROM_NATIVE(errno); k = (sal_uInt32)::read (h, (char *)p, (size_t)n); #endif /* LINUX || SOLARIS */ if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_fwrite. */ inline storeError __store_fwrite ( HSTORE h, sal_uInt32 offset, const void *p, sal_uInt32 n, sal_uInt32 &k) { #if defined(LINUX) || defined(SOLARIS) k = (sal_uInt32)::pwrite (h, (char*)p, (size_t)n, (off_t)offset); #else /* LINUX || SOLARIS */ if (::lseek (h, (off_t)offset, SEEK_SET) < 0) return ERROR_FROM_NATIVE(errno); k = (sal_uInt32)::write (h, (char *)p, (size_t)n); #endif /* LINUX || SOLARIS */ if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_fsize. */ inline storeError __store_fsize (HSTORE h, sal_uInt32 &k) { k = (sal_uInt32)::lseek (h, (off_t)0, SEEK_END); if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_ftrunc. */ inline storeError __store_ftrunc (HSTORE h, sal_uInt32 n) { if (::ftruncate (h, (off_t)n) < 0) { // Save original result. storeError result = ERROR_FROM_NATIVE(errno); // Check against current size. Fail upon 'shrink'. sal_uInt32 k = (sal_uInt32)::lseek (h, (off_t)0, SEEK_END); if (k == (sal_uInt32)(-1)) return (result); if ((0 <= n) && (n <= k)) return (result); // Try 'expand' via 'lseek()' and 'write()'. if (::lseek (h, (off_t)(n - 1), SEEK_SET) < 0) return (result); if (::write (h, (char*)"", (size_t)1) < 0) return (result); } return store_E_None; } /* * __store_fsync. */ inline void __store_fsync (HSTORE h) { ::fsync (h); } /* * __store_fclose. */ inline void __store_fclose (HSTORE h) { #ifdef SOLARIS /* see comment in __store_fopen() */ // Release (advisory) Share Access (Multiple Reader | Single Writer) struct fshare share; share.f_access = 0; share.f_deny = 0; share.f_id = 0; ::fcntl (h, F_UNSHARE, &share); #else /* POSIX */ // Release (advisory) Lock (Multiple Reader | Single Writer) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; ::fcntl (h, F_SETLK, &lock); #endif /* SOLARIS || POSIX */ // Close file handle. ::close (h); } #endif /* INCLUDED_STORE_FILEUNX_HXX */ <commit_msg>INTEGRATION: CWS mhu05 (1.3.32); FILE MERGED 2004/12/09 18:03:24 mhu 1.3.32.1: #i38646# Disabled internal commit (sync) to disk (STORE_FEATURE_COMMIT). Improved propagation of errors from fsync() and close() calls.<commit_after>/************************************************************************* * * $RCSfile: fileunx.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2004-12-23 11:32:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_STORE_FILEUNX_HXX #define INCLUDED_STORE_FILEUNX_HXX #define _USE_UNIX98 /* _XOPEN_SOURCE=500 */ #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #if defined(FREEBSD) || defined(NETBSD) || defined(MACOSX) #define EDEADLOCK EDEADLK #endif /* FREEBSD || NETBSD || MACOSX */ typedef int HSTORE; /*======================================================================== * * File I/O (inline) implementation. * *======================================================================*/ /* * __store_errcode_map. */ static const __store_errcode_mapping_st __store_errcode_map[] = { { 0, store_E_None }, { ENOENT, store_E_NotExists }, { EACCES, store_E_AccessViolation }, { EPERM, store_E_AccessViolation }, { EAGAIN, store_E_LockingViolation }, #if defined(EDEADLOCK) { EDEADLOCK, store_E_LockingViolation }, #endif /* EDEADLOCK */ { EBADF, store_E_InvalidHandle }, { EINVAL, store_E_InvalidParameter }, { ENOSPC, store_E_OutOfSpace }, }; /* * __store_errno. */ inline sal_Int32 __store_errno (void) { return (sal_Int32)errno; } /* * __store_malign. */ #if defined(FREEBSD) || defined(LINUX) || defined(MACOSX) inline sal_uInt32 __store_malign (void) { return (sal_uInt32)::getpagesize(); } #elif defined(IRIX) || defined(SOLARIS) inline sal_uInt32 __store_malign (void) { return (sal_uInt32)::sysconf (_SC_PAGESIZE); } #else inline sal_uInt32 __store_malign (void) { return (sal_uInt32)(-1); } #endif /* FREEBSD || IRIX || LINUX || SOLARIS || MACOSX*/ /* * __store_fmap (readonly). */ inline HSTORE __store_fmap (HSTORE hFile) { // Avoid hMap = dup (hFile); may result in EMFILE. return hFile; } /* * __store_funmap. */ inline void __store_funmap (HSTORE hMap) { // Nothing to do, see '__store_fmap()'. } /* * __store_mmap (readonly, shared). */ inline sal_uInt8* __store_mmap (HSTORE h, sal_uInt32 k, sal_uInt32 n) { void * p = ::mmap (NULL, (size_t)n, PROT_READ, MAP_SHARED, h, (off_t)k); return ((p != MAP_FAILED) ? (sal_uInt8*)p : 0); } /* * __store_munmap. */ inline void __store_munmap (sal_uInt8 *p, sal_uInt32 n) { (void)::munmap ((char *)p, (size_t)n); } /* * __store_fopen. */ inline storeError __store_fopen ( const sal_Char *pszName, sal_uInt32 nMode, HSTORE &rhFile) { // Access mode. int nAccessMode = O_RDONLY; if (nMode & store_File_OpenWrite) nAccessMode = O_RDWR; if (nAccessMode == O_RDONLY) nMode |= store_File_OpenNoCreate; if ((!(nMode & store_File_OpenNoCreate)) && (!(nAccessMode == O_RDONLY))) nAccessMode |= O_CREAT; if (nMode & store_File_OpenTruncate) nAccessMode |= O_TRUNC; // Share mode. int nShareMode = S_IREAD | S_IROTH | S_IRGRP; if (nMode & store_File_OpenWrite) nShareMode |= (S_IWRITE | S_IWOTH | S_IWGRP); // Create file handle. if ((rhFile = ::open (pszName, nAccessMode, nShareMode)) < 0) { rhFile = 0; return ERROR_FROM_NATIVE(errno); } #ifdef SOLARIS /* see workaround comment below */ /* * Workaround for SunOS <= 5.7: * * 'mmap()' fails on posix (advisory) locked (F_SETLK) NFS file handles. * Using non-posix F_SHARE / F_UNSHARE instead. */ // Acquire (advisory) Share Access (Multiple Reader | Single Writer) struct fshare share; if (nMode & store_File_OpenWrite) { share.f_access = F_RWACC; /* Request own read and write access */ share.f_deny = F_RWDNY; /* Deny other's read and write access */ } else { share.f_access = F_RDACC; /* Request own read-only access */ share.f_deny = F_WRDNY; /* Deny other's write access */ } share.f_id = 0; if (::fcntl (rhFile, F_SHARE, &share) < 0) { // Save original result. storeError result; if ((errno == EACCES) || (errno == EAGAIN)) result = store_E_LockingViolation; else result = ERROR_FROM_NATIVE(errno); // Close file handle. (void)::close (rhFile); rhFile = 0; // Finish. return (result); } #else /* POSIX */ // Acquire (advisory) Lock (Multiple Reader | Single Writer) struct flock lock; if (nMode & store_File_OpenWrite) lock.l_type = F_WRLCK; else lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (::fcntl (rhFile, F_SETLK, &lock) < 0) { // Save original result. storeError result; if ((errno == EACCES) || (errno == EAGAIN)) result = store_E_LockingViolation; else result = ERROR_FROM_NATIVE(errno); // Close file handle. (void)::close (rhFile); rhFile = 0; // Finish. return (result); } #endif /* SOLARIS || POSIX */ int nFlags = ::fcntl (rhFile, F_GETFD, 0); if (!(nFlags < 0)) { // Set close-on-exec flag. nFlags |= FD_CLOEXEC; (void)::fcntl (rhFile, F_SETFD, nFlags); } return store_E_None; } /* * __store_fread. */ inline storeError __store_fread ( HSTORE h, sal_uInt32 offset, void *p, sal_uInt32 n, sal_uInt32 &k) { #if defined(LINUX) || defined(SOLARIS) k = (sal_uInt32)::pread (h, (char*)p, (size_t)n, (off_t)offset); if ((k == (sal_uInt32)(-1)) && (errno == EOVERFLOW)) { /* * Workaround for 'pread()' failure at end-of-file: * * Some 'pread()'s fail with EOVERFLOW when reading at (or past) * end-of-file, different from 'lseek() + read()' behaviour. * Returning '0 bytes read' and 'store_E_None' instead. */ k = 0; } #else /* LINUX || SOLARIS */ if (::lseek (h, (off_t)offset, SEEK_SET) < 0) return ERROR_FROM_NATIVE(errno); k = (sal_uInt32)::read (h, (char *)p, (size_t)n); #endif /* LINUX || SOLARIS */ if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_fwrite. */ inline storeError __store_fwrite ( HSTORE h, sal_uInt32 offset, const void *p, sal_uInt32 n, sal_uInt32 &k) { #if defined(LINUX) || defined(SOLARIS) k = (sal_uInt32)::pwrite (h, (char*)p, (size_t)n, (off_t)offset); #else /* LINUX || SOLARIS */ if (::lseek (h, (off_t)offset, SEEK_SET) < 0) return ERROR_FROM_NATIVE(errno); k = (sal_uInt32)::write (h, (char *)p, (size_t)n); #endif /* LINUX || SOLARIS */ if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_fsize. */ inline storeError __store_fsize (HSTORE h, sal_uInt32 &k) { k = (sal_uInt32)::lseek (h, (off_t)0, SEEK_END); if (k == (sal_uInt32)(-1)) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_ftrunc. */ inline storeError __store_ftrunc (HSTORE h, sal_uInt32 n) { if (::ftruncate (h, (off_t)n) < 0) { // Save original result. storeError result = ERROR_FROM_NATIVE(errno); // Check against current size. Fail upon 'shrink'. sal_uInt32 k = (sal_uInt32)::lseek (h, (off_t)0, SEEK_END); if (k == (sal_uInt32)(-1)) return (result); if ((0 <= n) && (n <= k)) return (result); // Try 'expand' via 'lseek()' and 'write()'. if (::lseek (h, (off_t)(n - 1), SEEK_SET) < 0) return (result); if (::write (h, (char*)"", (size_t)1) < 0) return (result); } return store_E_None; } /* * __store_fsync. */ inline storeError __store_fsync (HSTORE h) { if (::fsync (h) == -1) return ERROR_FROM_NATIVE(errno); else return store_E_None; } /* * __store_fclose. */ inline storeError __store_fclose (HSTORE h) { #ifdef SOLARIS /* see comment in __store_fopen() */ // Release (advisory) Share Access (Multiple Reader | Single Writer) struct fshare share; share.f_access = 0; share.f_deny = 0; share.f_id = 0; (void)::fcntl (h, F_UNSHARE, &share); #else /* POSIX */ // Release (advisory) Lock (Multiple Reader | Single Writer) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; (void)::fcntl (h, F_SETLK, &lock); #endif /* SOLARIS || POSIX */ // Close file handle. if (::close (h) == -1) return ERROR_FROM_NATIVE(errno); else return store_E_None; } #endif /* INCLUDED_STORE_FILEUNX_HXX */ <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ #include "datasource_cache.hpp" #include <algorithm> #include <stdexcept> #include <boost/filesystem/operations.hpp> namespace mapnik { using namespace std; using namespace boost; datasource_cache::datasource_cache() { if (lt_dlinit()) throw; } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<string,ref_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; datasource_p datasource_cache::create(const Parameters& params) { datasource *ds=0; try { std::string type=params.get("type"); map<string,ref_ptr<PluginInfo> >::iterator itr=plugins_.find(type); if (itr!=plugins_.end()) { if (itr->second->handle()) { create_ds* create_datasource = (create_ds*) lt_dlsym(itr->second->handle(), "create"); if (!create_datasource) { std::cerr << "Cannot load symbols: " << lt_dlerror() << std::endl; } else { ds=create_datasource(params); } } else { std::cerr << "Cannot load library: " << " "<< lt_dlerror() << std::endl; } } std::cout<<"datasource="<<ds<<" type="<<type<<std::endl; } catch (datasource_exception& ex) { std::cerr<<ex.what()<<std::endl; } catch (...) { std::cerr<<"exception caught "<<std::endl; } return ref_ptr<datasource,datasource_delete>(ds); } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,ref_ptr<PluginInfo>(new PluginInfo(type,module)))).second; } void datasource_cache::register_datasources(const std::string& str) { Lock lock(&mutex_); filesystem::path path(str); filesystem::directory_iterator end_itr; if (exists(path)) { for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { if (!is_directory( *itr )) { std::string file_name(str+"/"+itr->leaf()); if (file_name=="." || file_name=="..") continue; std::string::size_type len=file_name.size(); if (len>3 && file_name[len-1]=='o' && file_name[len-2]=='s') { lt_dlhandle module=lt_dlopenext(file_name.c_str()); if (module) { datasource_name* ds_name = (datasource_name*) lt_dlsym(module, "datasource_name"); if (ds_name && insert(ds_name(),module)) { std::cout<<"registered datasource : "<<ds_name()<<std::endl; registered_=true; } } else { std::cerr<<lt_dlerror()<<std::endl; } } } } } } } <commit_msg>try to dlopen any file in datasources dir<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ #include "datasource_cache.hpp" #include <algorithm> #include <stdexcept> #include <boost/filesystem/operations.hpp> namespace mapnik { using namespace std; using namespace boost; datasource_cache::datasource_cache() { if (lt_dlinit()) throw; } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<string,ref_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; datasource_p datasource_cache::create(const Parameters& params) { datasource *ds=0; try { std::string type=params.get("type"); map<string,ref_ptr<PluginInfo> >::iterator itr=plugins_.find(type); if (itr!=plugins_.end()) { if (itr->second->handle()) { create_ds* create_datasource = (create_ds*) lt_dlsym(itr->second->handle(), "create"); if (!create_datasource) { std::cerr << "Cannot load symbols: " << lt_dlerror() << std::endl; } else { ds=create_datasource(params); } } else { std::cerr << "Cannot load library: " << " "<< lt_dlerror() << std::endl; } } std::cout<<"datasource="<<ds<<" type="<<type<<std::endl; } catch (datasource_exception& ex) { std::cerr<<ex.what()<<std::endl; } catch (...) { std::cerr<<"exception caught "<<std::endl; } return ref_ptr<datasource,datasource_delete>(ds); } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,ref_ptr<PluginInfo>(new PluginInfo(type,module)))).second; } void datasource_cache::register_datasources(const std::string& str) { Lock lock(&mutex_); filesystem::path path(str); filesystem::directory_iterator end_itr; if (exists(path)) { for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { if (!is_directory( *itr )) { std::string file_name(str+"/"+itr->leaf()); lt_dlhandle module=lt_dlopenext(file_name.c_str()); if (module) { datasource_name* ds_name = (datasource_name*) lt_dlsym(module, "datasource_name"); if (ds_name && insert(ds_name(),module)) { std::cout<<"registered datasource : "<<ds_name()<<std::endl; registered_=true; } } else { std::cerr<<lt_dlerror()<<std::endl; } } } } } } <|endoftext|>
<commit_before>// // EnttecDevice.cpp // // Created by Soso Limited. // // #include "EnttecDevice.h" #include "cinder/app/App.h" #include "cinder/Log.h" using namespace ci; using namespace ci::app; using namespace std; using namespace dmx; namespace { const auto EnttecDeviceDummyBaudRate = 56000; const auto StartOfMessage = 0x7E; const auto EndOfMessage = 0xE7; const auto DataStartCode = 0x00; enum MessageLabel { // ReprogramFirmware = 1, // ProgramFlashPage = 2, GetWidgetParameters = 3, SetWidgetParameters = 4, ReceivedDMXPacket = 5, OutputOnlySendDMXPacket = 6, SendRMDPacket = 7, ReceiveDMXOnChange = 8, ReceivedDMXChangeOfStatePacket = 9, GetWidgetSerialNumber = 10, SendRDMDiscovery = 11 }; uint8_t leastSignificantByte(int value) { return value & 0xFF; } uint8_t mostSignificantByte(int value) { return (value >> 8) & 0xFF; } int combinedNumber(uint8_t lsb, uint8_t msb) { return (msb << 8) + lsb; } } // namespace EnttecDevice::EnttecDevice(const std::string &device_name, int device_fps) { _target_frame_time = std::chrono::milliseconds(1000 / device_fps); _message_body.assign(512, 0); connect(device_name); } EnttecDevice::~EnttecDevice() { stopLoop(); // For now, turn out the lights as the previous implementation did so. // In future, perhaps it is better to let the user specify what to do. fillBuffer(0); writeData(); closeConnection(); } void EnttecDevice::closeConnection() { stopLoop(); if (_serial) { std::lock_guard<std::mutex> lock(_data_mutex); CI_LOG_I("Shutting down serial connection: " << _serial->getDevice().getPath()); _serial->flush(); _serial.reset(); } } void EnttecDevice::startLoop() { _do_loop = true; _loop_thread = std::thread(&EnttecDevice::dataSendLoop, this); } void EnttecDevice::stopLoop() { _do_loop = false; if (_loop_thread.joinable()) { _loop_thread.join(); } } bool EnttecDevice::connect(const std::string &device_name) { closeConnection(); try { std::lock_guard<std::mutex> lock(_data_mutex); const Serial::Device dev = Serial::findDeviceByNameContains(device_name); _serial = Serial::create(dev, EnttecDeviceDummyBaudRate); _serial->flush(); // Drain serial. auto old_stuff = std::vector<uint8_t>(); old_stuff.resize(_serial->getNumBytesAvailable()); _serial->readAvailableBytes(old_stuff.data(), old_stuff.size()); return true; } catch(const std::exception &exc) { CI_LOG_E("Error initializing DMX device: " << exc.what()); return false; } } void EnttecDevice::dataSendLoop() { ci::ThreadSetup thread_setup; CI_LOG_I("Starting DMX loop."); auto before = std::chrono::high_resolution_clock::now(); while (_do_loop) { writeData(); auto after = std::chrono::high_resolution_clock::now(); auto actual_frame_time = after - before; before = after; std::this_thread::sleep_for(_target_frame_time - actual_frame_time); } CI_LOG_I("Exiting DMX loop."); } void EnttecDevice::applySettings(const dmx::EnttecDevice::Settings &settings) { std::lock_guard<std::mutex> lock(_data_mutex); const auto message = std::array<uint8_t, 8> { StartOfMessage, MessageLabel::SetWidgetParameters, leastSignificantByte(0), // no user settings to pass through mostSignificantByte(0), settings.break_time, settings.mark_after_break_time, settings.device_fps, EndOfMessage }; _target_frame_time = std::chrono::milliseconds(1000 / settings.device_fps); _serial->writeBytes(message.data(), message.size()); } std::future<EnttecDevice::Settings> EnttecDevice::loadSettings() const { return std::async(std::launch::async, [this] () { std::lock_guard<std::mutex> lock(_data_mutex); const auto message = std::array<uint8_t, 5> { StartOfMessage, MessageLabel::GetWidgetParameters, leastSignificantByte(0), mostSignificantByte(0), EndOfMessage }; if (_serial) { _serial->writeBytes(message.data(), message.size()); auto response = std::vector<uint8_t>(); auto response_is_valid = [&response] { if (! response.empty()) { return response.back() == EndOfMessage; } return false; }; while (! response_is_valid()) { auto byte = _serial->readByte(); if (byte == StartOfMessage) { response = { byte }; } else { response.push_back(byte); } CI_LOG_D((int)byte); } const auto message_body_start = 4; // start, type, data lsb, data msb // skip two bytes (lsb, msb of message size) const auto firmware_index_lsb = message_body_start; const auto firmware_index_msb = message_body_start + 1; const auto break_time_index = message_body_start + 2; const auto mark_after_break_time_index = message_body_start + 3; const auto device_fps_index = message_body_start + 4; auto firmware_number = combinedNumber(response[firmware_index_lsb], response[firmware_index_msb]); auto settings = Settings { firmware_number, response[break_time_index], response[mark_after_break_time_index], response[device_fps_index] }; return settings; } else { CI_LOG_W("Not connected via serial, returning empty settings."); return Settings{ 0, 0, 0, 0 }; } }); } void EnttecDevice::writeData() { std::lock_guard<std::mutex> lock(_data_mutex); if (_serial) { const auto data_size = _message_body.size() + 1; // account for data start code const auto header = std::array<uint8_t, 5> { StartOfMessage, MessageLabel::OutputOnlySendDMXPacket, leastSignificantByte(data_size), mostSignificantByte(data_size), DataStartCode }; _serial->writeBytes(header.data(), header.size()); _serial->writeBytes(_message_body.data(), _message_body.size()); _serial->writeByte(EndOfMessage); } } void EnttecDevice::bufferData(const uint8_t *data, size_t size) { std::lock_guard<std::mutex> lock(_data_mutex); size = std::min(size, _message_body.size()); std::memcpy(_message_body.data(), data, size); } void EnttecDevice::fillBuffer(uint8_t value) { std::lock_guard<std::mutex> lock(_data_mutex); std::memset(_message_body.data(), value, _message_body.size()); } namespace dmx { std::ostream& operator << (std::ostream& os, const EnttecDevice::Settings& settings) { os << "Firmware version: " << settings.firmware_number; os << ", Break time: " << (int)settings.break_time; os << ", Mark after break time: " << (int)settings.mark_after_break_time; os << ", Device fps: " << (int)settings.device_fps; return os; } }<commit_msg>Notes on number of bytes specified in message.<commit_after>// // EnttecDevice.cpp // // Created by Soso Limited. // // #include "EnttecDevice.h" #include "cinder/app/App.h" #include "cinder/Log.h" using namespace ci; using namespace ci::app; using namespace std; using namespace dmx; namespace { const auto EnttecDeviceDummyBaudRate = 56000; const auto StartOfMessage = 0x7E; const auto EndOfMessage = 0xE7; const auto DataStartCode = 0x00; enum MessageLabel { // ReprogramFirmware = 1, // ProgramFlashPage = 2, GetWidgetParameters = 3, SetWidgetParameters = 4, ReceivedDMXPacket = 5, OutputOnlySendDMXPacket = 6, SendRMDPacket = 7, ReceiveDMXOnChange = 8, ReceivedDMXChangeOfStatePacket = 9, GetWidgetSerialNumber = 10, SendRDMDiscovery = 11 }; uint8_t leastSignificantByte(int value) { return value & 0xFF; } uint8_t mostSignificantByte(int value) { return (value >> 8) & 0xFF; } int combinedNumber(uint8_t lsb, uint8_t msb) { return (msb << 8) + lsb; } } // namespace EnttecDevice::EnttecDevice(const std::string &device_name, int device_fps) { _target_frame_time = std::chrono::milliseconds(1000 / device_fps); _message_body.assign(512, 0); connect(device_name); } EnttecDevice::~EnttecDevice() { stopLoop(); // For now, turn out the lights as the previous implementation did so. // In future, perhaps it is better to let the user specify what to do. fillBuffer(0); writeData(); closeConnection(); } void EnttecDevice::closeConnection() { stopLoop(); if (_serial) { std::lock_guard<std::mutex> lock(_data_mutex); CI_LOG_I("Shutting down serial connection: " << _serial->getDevice().getPath()); _serial->flush(); _serial.reset(); } } void EnttecDevice::startLoop() { _do_loop = true; _loop_thread = std::thread(&EnttecDevice::dataSendLoop, this); } void EnttecDevice::stopLoop() { _do_loop = false; if (_loop_thread.joinable()) { _loop_thread.join(); } } bool EnttecDevice::connect(const std::string &device_name) { closeConnection(); try { std::lock_guard<std::mutex> lock(_data_mutex); const Serial::Device dev = Serial::findDeviceByNameContains(device_name); _serial = Serial::create(dev, EnttecDeviceDummyBaudRate); _serial->flush(); // Drain serial. auto old_stuff = std::vector<uint8_t>(); old_stuff.resize(_serial->getNumBytesAvailable()); _serial->readAvailableBytes(old_stuff.data(), old_stuff.size()); return true; } catch(const std::exception &exc) { CI_LOG_E("Error initializing DMX device: " << exc.what()); return false; } } void EnttecDevice::dataSendLoop() { ci::ThreadSetup thread_setup; CI_LOG_I("Starting DMX loop."); auto before = std::chrono::high_resolution_clock::now(); while (_do_loop) { writeData(); auto after = std::chrono::high_resolution_clock::now(); auto actual_frame_time = after - before; before = after; std::this_thread::sleep_for(_target_frame_time - actual_frame_time); } CI_LOG_I("Exiting DMX loop."); } void EnttecDevice::applySettings(const dmx::EnttecDevice::Settings &settings) { std::lock_guard<std::mutex> lock(_data_mutex); const auto message = std::array<uint8_t, 8> { StartOfMessage, MessageLabel::SetWidgetParameters, leastSignificantByte(0), // no user settings to pass through mostSignificantByte(0), settings.break_time, settings.mark_after_break_time, settings.device_fps, EndOfMessage }; _target_frame_time = std::chrono::milliseconds(1000 / settings.device_fps); _serial->writeBytes(message.data(), message.size()); } std::future<EnttecDevice::Settings> EnttecDevice::loadSettings() const { return std::async(std::launch::async, [this] () { std::lock_guard<std::mutex> lock(_data_mutex); const auto message = std::array<uint8_t, 5> { StartOfMessage, MessageLabel::GetWidgetParameters, leastSignificantByte(0), mostSignificantByte(0), EndOfMessage }; if (_serial) { _serial->writeBytes(message.data(), message.size()); auto response = std::vector<uint8_t>(); auto response_is_valid = [&response] { if (! response.empty()) { return response.back() == EndOfMessage; } return false; }; while (! response_is_valid()) { auto byte = _serial->readByte(); if (byte == StartOfMessage) { response = { byte }; } else { response.push_back(byte); } CI_LOG_D((int)byte); } const auto message_body_start = 4; // start, type, data lsb, data msb // skip two bytes (lsb, msb of message size, it seems) const auto firmware_index_lsb = message_body_start; const auto firmware_index_msb = message_body_start + 1; const auto break_time_index = message_body_start + 2; const auto mark_after_break_time_index = message_body_start + 3; const auto device_fps_index = message_body_start + 4; auto firmware_number = combinedNumber(response[firmware_index_lsb], response[firmware_index_msb]); auto settings = Settings { firmware_number, response[break_time_index], response[mark_after_break_time_index], response[device_fps_index] }; return settings; } else { CI_LOG_W("Not connected via serial, returning empty settings."); return Settings{ 0, 0, 0, 0 }; } }); } void EnttecDevice::writeData() { std::lock_guard<std::mutex> lock(_data_mutex); if (_serial) { // May need to include 2 or 3 more bytes in data size so it represents complete message size. (label, lsb, msb) // The documentation suggests otherwise, but the Mk2 sends back undocumented bytes when querying settings. // If we seem to be missing the last handful of channels of data when testing the full 512 channels, this could be why. const auto data_size = _message_body.size() + 1; // account for data start code const auto header = std::array<uint8_t, 5> { StartOfMessage, MessageLabel::OutputOnlySendDMXPacket, leastSignificantByte(data_size), mostSignificantByte(data_size), DataStartCode }; _serial->writeBytes(header.data(), header.size()); _serial->writeBytes(_message_body.data(), _message_body.size()); _serial->writeByte(EndOfMessage); } } void EnttecDevice::bufferData(const uint8_t *data, size_t size) { std::lock_guard<std::mutex> lock(_data_mutex); size = std::min(size, _message_body.size()); std::memcpy(_message_body.data(), data, size); } void EnttecDevice::fillBuffer(uint8_t value) { std::lock_guard<std::mutex> lock(_data_mutex); std::memset(_message_body.data(), value, _message_body.size()); } namespace dmx { std::ostream& operator << (std::ostream& os, const EnttecDevice::Settings& settings) { os << "Firmware version: " << settings.firmware_number; os << ", Break time: " << (int)settings.break_time; os << ", Mark after break time: " << (int)settings.mark_after_break_time; os << ", Device fps: " << (int)settings.device_fps; return os; } }<|endoftext|>
<commit_before>#include "musiclrcmanager.h" #include <QFile> #include <QFontDatabase> #include <QDebug> MusicLRCManager::MusicLRCManager(QWidget *parent) : QLabel(parent) { m_intervalCount = 0.0f; m_linearGradient.setStart(0, 10);//The starting point coordinates filled m_linearGradient.setFinalStop(0, 40);//The coordinates of the end filling //A linear gradient mask filling m_maskLinearGradient.setStart(0, 10); m_maskLinearGradient.setFinalStop(0, 40); //Set the font m_font.setFamily("Times New Roman"); m_font.setBold(true); //Set the timer m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), SLOT(setTimeOut())); m_lrcMaskWidth = 0; m_lrcMaskWidthInterval = 0; m_transparent = 100; } MusicLRCManager::~MusicLRCManager() { delete m_timer; } void MusicLRCManager::startTimerClock() { m_timer->start(30); } void MusicLRCManager::setLrcFontSize(LrcSizeTable size) { m_font.setPointSize(size); update(); } void MusicLRCManager::setFontFamily(int index) { QStringList family = QFontDatabase().families(QFontDatabase::Any); if(index >= family.count()) index = 0; m_font.setFamily(family[index]); } void MusicLRCManager::setFontType(int type) { if(type == 1) {m_font.setBold(true); m_font.setItalic(false);} else if(type == 2) {m_font.setBold(false); m_font.setItalic(true);} else if(type == 3) {m_font.setBold(true); m_font.setItalic(true);} else {m_font.setBold(false);m_font.setItalic(false);} } void MusicLRCManager::startLrcMask(qint64 intervaltime) { /*Open the mask, need to specify the current lyrics start with the interval between the end of,Here set every 30 msec update a mask width, because if too frequent updates,The CPU occupancy rate will increase, and if the time interval is too large, then the animation is not smooth */ m_intervalCount = 0.0f; m_geometry.setX(QFontMetrics(m_font).width(text())); qreal count = intervaltime / m_speedLeve; m_lrcMaskWidthInterval = m_geometry.x() / count; m_lrcMaskWidth = 0; m_timer->start(30); } void MusicLRCManager::stopLrcMask() { m_timer->stop(); update(); } void MusicLRCManager::setLinearGradientColor(QColor color) { //The first parameter coordinates relative to the US, the area above, //calculated in accordance with the proportion of color.setAlpha(m_transparent*2.55); m_linearGradient.setColorAt(0.1, color); m_linearGradient.setColorAt(0.5, QColor(114, 232, 255,m_transparent*2.55)); m_linearGradient.setColorAt(0.9, color); update(); } void MusicLRCManager::setMaskLinearGradientColor(QColor color) { color.setAlpha(m_transparent*2.55); m_maskLinearGradient.setColorAt(0.1, color); m_maskLinearGradient.setColorAt(0.5, QColor(255, 72, 16,m_transparent*2.55)); m_maskLinearGradient.setColorAt(0.9, color); } void MusicLRCManager::setTimeOut() { //At a fixed period of time covered length increases. m_lrcMaskWidth += m_lrcMaskWidthInterval; update(); } void MusicLRCManager::setText(const QString &str) { m_geometry.setX(QFontMetrics(m_font).width(str)); QLabel::setText(str); } <commit_msg>fix index out of range for set family[468303]<commit_after>#include "musiclrcmanager.h" #include <QFile> #include <QFontDatabase> #include <QDebug> MusicLRCManager::MusicLRCManager(QWidget *parent) : QLabel(parent) { m_intervalCount = 0.0f; m_linearGradient.setStart(0, 10);//The starting point coordinates filled m_linearGradient.setFinalStop(0, 40);//The coordinates of the end filling //A linear gradient mask filling m_maskLinearGradient.setStart(0, 10); m_maskLinearGradient.setFinalStop(0, 40); //Set the font m_font.setFamily("Times New Roman"); m_font.setBold(true); //Set the timer m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), SLOT(setTimeOut())); m_lrcMaskWidth = 0; m_lrcMaskWidthInterval = 0; m_transparent = 100; } MusicLRCManager::~MusicLRCManager() { delete m_timer; } void MusicLRCManager::startTimerClock() { m_timer->start(30); } void MusicLRCManager::setLrcFontSize(LrcSizeTable size) { m_font.setPointSize(size); update(); } void MusicLRCManager::setFontFamily(int index) { if(index < 0) return; QStringList family = QFontDatabase().families(QFontDatabase::Any); if(index >= family.count()) index = 0; m_font.setFamily(family[index]); } void MusicLRCManager::setFontType(int type) { if(type == 1) {m_font.setBold(true); m_font.setItalic(false);} else if(type == 2) {m_font.setBold(false); m_font.setItalic(true);} else if(type == 3) {m_font.setBold(true); m_font.setItalic(true);} else {m_font.setBold(false);m_font.setItalic(false);} } void MusicLRCManager::startLrcMask(qint64 intervaltime) { /*Open the mask, need to specify the current lyrics start with the interval between the end of,Here set every 30 msec update a mask width, because if too frequent updates,The CPU occupancy rate will increase, and if the time interval is too large, then the animation is not smooth */ m_intervalCount = 0.0f; m_geometry.setX(QFontMetrics(m_font).width(text())); qreal count = intervaltime / m_speedLeve; m_lrcMaskWidthInterval = m_geometry.x() / count; m_lrcMaskWidth = 0; m_timer->start(30); } void MusicLRCManager::stopLrcMask() { m_timer->stop(); update(); } void MusicLRCManager::setLinearGradientColor(QColor color) { //The first parameter coordinates relative to the US, the area above, //calculated in accordance with the proportion of color.setAlpha(m_transparent*2.55); m_linearGradient.setColorAt(0.1, color); m_linearGradient.setColorAt(0.5, QColor(114, 232, 255,m_transparent*2.55)); m_linearGradient.setColorAt(0.9, color); update(); } void MusicLRCManager::setMaskLinearGradientColor(QColor color) { color.setAlpha(m_transparent*2.55); m_maskLinearGradient.setColorAt(0.1, color); m_maskLinearGradient.setColorAt(0.5, QColor(255, 72, 16,m_transparent*2.55)); m_maskLinearGradient.setColorAt(0.9, color); } void MusicLRCManager::setTimeOut() { //At a fixed period of time covered length increases. m_lrcMaskWidth += m_lrcMaskWidthInterval; update(); } void MusicLRCManager::setText(const QString &str) { m_geometry.setX(QFontMetrics(m_font).width(str)); QLabel::setText(str); } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <signal.h> #include "bochs.h" #include "gui/bitmaps/floppya.h" #include "gui/bitmaps/floppyb.h" #include "gui/bitmaps/mouse.h" #include "gui/bitmaps/reset.h" #include "gui/bitmaps/power.h" #include "gui/bitmaps/snapshot.h" #include "gui/bitmaps/configbutton.h" #include "gui/bitmaps/cdromd.h" #if BX_WITH_MACOS # include <Disks.h> #endif bx_gui_c bx_gui; #define BX_GUI_THIS bx_gui. #define LOG_THIS BX_GUI_THIS bx_gui_c::bx_gui_c(void) { put("GUI"); // Init in specific_init settype(GUILOG); } void bx_gui_c::init(int argc, char **argv, unsigned tilewidth, unsigned tileheight) { specific_init(&bx_gui, argc, argv, tilewidth, tileheight, BX_HEADER_BAR_Y); // Define some bitmaps to use in the headerbar BX_GUI_THIS floppyA_bmap_id = create_bitmap(bx_floppya_bmap, BX_FLOPPYA_BMAP_X, BX_FLOPPYA_BMAP_Y); BX_GUI_THIS floppyA_eject_bmap_id = create_bitmap(bx_floppya_eject_bmap, BX_FLOPPYA_BMAP_X, BX_FLOPPYA_BMAP_Y); BX_GUI_THIS floppyB_bmap_id = create_bitmap(bx_floppyb_bmap, BX_FLOPPYB_BMAP_X, BX_FLOPPYB_BMAP_Y); BX_GUI_THIS floppyB_eject_bmap_id = create_bitmap(bx_floppyb_eject_bmap, BX_FLOPPYB_BMAP_X, BX_FLOPPYB_BMAP_Y); BX_GUI_THIS cdromD_bmap_id = create_bitmap(bx_cdromd_bmap, BX_CDROMD_BMAP_X, BX_CDROMD_BMAP_Y); BX_GUI_THIS cdromD_eject_bmap_id = create_bitmap(bx_cdromd_eject_bmap, BX_CDROMD_BMAP_X, BX_CDROMD_BMAP_Y); BX_GUI_THIS mouse_bmap_id = create_bitmap(bx_mouse_bmap, BX_MOUSE_BMAP_X, BX_MOUSE_BMAP_Y); BX_GUI_THIS nomouse_bmap_id = create_bitmap(bx_nomouse_bmap, BX_MOUSE_BMAP_X, BX_MOUSE_BMAP_Y); BX_GUI_THIS power_bmap_id = create_bitmap(bx_power_bmap, BX_POWER_BMAP_X, BX_POWER_BMAP_Y); BX_GUI_THIS reset_bmap_id = create_bitmap(bx_reset_bmap, BX_RESET_BMAP_X, BX_RESET_BMAP_Y); BX_GUI_THIS snapshot_bmap_id = create_bitmap(bx_snapshot_bmap, BX_SNAPSHOT_BMAP_X, BX_SNAPSHOT_BMAP_Y); BX_GUI_THIS config_bmap_id = create_bitmap(bx_config_bmap, BX_SNAPSHOT_BMAP_X, BX_SNAPSHOT_BMAP_Y); // Add the initial bitmaps to the headerbar, and enable callback routine, for use // when that bitmap is clicked on // Floppy A: BX_GUI_THIS floppyA_status = bx_devices.floppy->get_media_status(0); if (BX_GUI_THIS floppyA_status) BX_GUI_THIS floppyA_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyA_bmap_id, BX_GRAVITY_LEFT, floppyA_handler); else BX_GUI_THIS floppyA_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyA_eject_bmap_id, BX_GRAVITY_LEFT, floppyA_handler); // Floppy B: BX_GUI_THIS floppyB_status = bx_devices.floppy->get_media_status(1); if (BX_GUI_THIS floppyB_status) BX_GUI_THIS floppyB_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyB_bmap_id, BX_GRAVITY_LEFT, floppyB_handler); else BX_GUI_THIS floppyB_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyB_eject_bmap_id, BX_GRAVITY_LEFT, floppyB_handler); // CDROM BX_GUI_THIS cdromD_status = bx_devices.hard_drive->get_cd_media_status() && bx_options.cdromd.Opresent->get (); if (BX_GUI_THIS cdromD_status) BX_GUI_THIS cdromD_hbar_id = headerbar_bitmap(BX_GUI_THIS cdromD_bmap_id, BX_GRAVITY_LEFT, cdromD_handler); else BX_GUI_THIS cdromD_hbar_id = headerbar_bitmap(BX_GUI_THIS cdromD_eject_bmap_id, BX_GRAVITY_LEFT, cdromD_handler); // Mouse button if (bx_options.Omouse_enabled->get ()) BX_GUI_THIS mouse_hbar_id = headerbar_bitmap(BX_GUI_THIS mouse_bmap_id, BX_GRAVITY_LEFT, toggle_mouse_enable); else BX_GUI_THIS mouse_hbar_id = headerbar_bitmap(BX_GUI_THIS nomouse_bmap_id, BX_GRAVITY_LEFT, toggle_mouse_enable); // Power button BX_GUI_THIS power_hbar_id = headerbar_bitmap(BX_GUI_THIS power_bmap_id, BX_GRAVITY_RIGHT, power_handler); // Reset button BX_GUI_THIS reset_hbar_id = headerbar_bitmap(BX_GUI_THIS reset_bmap_id, BX_GRAVITY_RIGHT, reset_handler); // Snapshot button BX_GUI_THIS snapshot_hbar_id = headerbar_bitmap(BX_GUI_THIS snapshot_bmap_id, BX_GRAVITY_RIGHT, snapshot_handler); // Configure button BX_GUI_THIS config_hbar_id = headerbar_bitmap(BX_GUI_THIS config_bmap_id, BX_GRAVITY_RIGHT, config_handler); show_headerbar(); } void bx_gui_c::update_floppy_status_buttons (void) { BX_GUI_THIS floppyA_status = bx_devices.floppy->get_media_status (0) && bx_options.floppya.Oinitial_status->get (); BX_GUI_THIS floppyB_status = bx_devices.floppy->get_media_status (1) && bx_options.floppyb.Oinitial_status->get (); BX_GUI_THIS cdromD_status = bx_devices.hard_drive->get_cd_media_status() && bx_options.cdromd.Opresent->get (); if (BX_GUI_THIS floppyA_status) replace_bitmap(BX_GUI_THIS floppyA_hbar_id, BX_GUI_THIS floppyA_bmap_id); else { #if BX_WITH_MACOS // If we are using the Mac floppy driver, eject the disk // from the floppy drive. This doesn't work in MacOS X. if (!strcmp(bx_options.floppya.Opath->get (), SuperDrive)) DiskEject(1); #endif replace_bitmap(BX_GUI_THIS floppyA_hbar_id, BX_GUI_THIS floppyA_eject_bmap_id); } if (BX_GUI_THIS floppyB_status) replace_bitmap(BX_GUI_THIS floppyB_hbar_id, BX_GUI_THIS floppyB_bmap_id); else { #if BX_WITH_MACOS // If we are using the Mac floppy driver, eject the disk // from the floppy drive. This doesn't work in MacOS X. if (!strcmp(bx_options.floppyb.Opath->get (), SuperDrive)) DiskEject(1); #endif replace_bitmap(BX_GUI_THIS floppyB_hbar_id, BX_GUI_THIS floppyB_eject_bmap_id); } if (BX_GUI_THIS cdromD_status) replace_bitmap(BX_GUI_THIS cdromD_hbar_id, BX_GUI_THIS cdromD_bmap_id); else { replace_bitmap(BX_GUI_THIS cdromD_hbar_id, BX_GUI_THIS cdromD_eject_bmap_id); } } void bx_gui_c::floppyA_handler(void) { BX_GUI_THIS floppyA_status = !BX_GUI_THIS floppyA_status; bx_devices.floppy->set_media_status(0, BX_GUI_THIS floppyA_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::floppyB_handler(void) { BX_GUI_THIS floppyB_status = !BX_GUI_THIS floppyB_status; bx_devices.floppy->set_media_status(1, BX_GUI_THIS floppyB_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::cdromD_handler(void) { BX_GUI_THIS cdromD_status = bx_devices.hard_drive->set_cd_media_status(!BX_GUI_THIS cdromD_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::reset_handler(void) { BX_INFO(( "system RESET callback." )); bx_pc_system.ResetSignal( PCS_SET ); /* XXX is this right? */ for (int i=0; i<BX_SMP_PROCESSORS; i++) BX_CPU(i)->reset(BX_RESET_HARDWARE); } void bx_gui_c::power_handler(void) { // the user pressed power button, so there's no doubt they want bochs // to quit. Change panics to fatal for the GUI and then do a panic. LOG_THIS setonoff(LOGLEV_PANIC, ACT_FATAL); BX_PANIC (("POWER button turned off.")); // shouldn't reach this point, but if you do, QUIT!!! fprintf (stderr, "Bochs is exiting because you pressed the power button.\n"); ::exit (1); } void bx_gui_c::snapshot_handler(void) { Bit8u* text_snapshot = NULL; unsigned line_addr, txHeight, txWidth; FILE *OUTPUT; bx_vga.get_text_snapshot(&text_snapshot, &txHeight, &txWidth); if (txHeight > 0) { OUTPUT = fopen("snapshot.txt", "w"); for (unsigned i=0; i<txHeight; i++) { line_addr = i * txWidth * 2; for (unsigned j=0; j<(txWidth*2); j+=2) { if (OUTPUT) fputc(text_snapshot[line_addr+j], OUTPUT); } fprintf(OUTPUT, "\n"); } fclose(OUTPUT); } else { BX_INFO(( "# SNAPSHOT callback (graphics mode unimplemented)." )); } } void bx_gui_c::config_handler(void) { #if BX_USE_CONTROL_PANEL bx_control_panel (BX_CPANEL_RUNTIME); #else BX_INFO(( "# CONFIG callback (unimplemented)." )); #endif } void bx_gui_c::toggle_mouse_enable(void) { int old = bx_options.Omouse_enabled->get (); BX_DEBUG (("toggle mouse_enabled, now %d", !old)); bx_options.Omouse_enabled->set (!old); } void bx_gui_c::mouse_enabled_changed (Boolean val) { // This is only called when SIM->get_init_done is 1. Note that VAL // is the new value of mouse_enabled, which may not match the old // value which is still in bx_options.Omouse_enabled->get (). BX_DEBUG (("replacing the mouse bitmaps")); if (val) replace_bitmap(BX_GUI_THIS mouse_hbar_id, BX_GUI_THIS mouse_bmap_id); else replace_bitmap(BX_GUI_THIS mouse_hbar_id, BX_GUI_THIS nomouse_bmap_id); // give the GUI a chance to respond to the event. Most guis will hide // the native mouse cursor and do something to trap the mouse inside the // bochs VGA display window. mouse_enabled_changed_specific (val); } void bx_gui_c::init_signal_handlers () { #if BX_GUI_SIGHANDLER Bit32u mask = get_sighandler_mask (); for (Bit32u sig=0; sig<32; sig++) { if (mask & (1<<sig)) signal (sig, bx_signal_handler); } #endif } <commit_msg>- snapshot_handler() prepared for copying text to clipboard - copy text to clipboard added for WIN32<commit_after>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <signal.h> #include "bochs.h" #include "gui/bitmaps/floppya.h" #include "gui/bitmaps/floppyb.h" #include "gui/bitmaps/mouse.h" #include "gui/bitmaps/reset.h" #include "gui/bitmaps/power.h" #include "gui/bitmaps/snapshot.h" #include "gui/bitmaps/configbutton.h" #include "gui/bitmaps/cdromd.h" #if BX_WITH_MACOS # include <Disks.h> #endif bx_gui_c bx_gui; #define BX_GUI_THIS bx_gui. #define LOG_THIS BX_GUI_THIS bx_gui_c::bx_gui_c(void) { put("GUI"); // Init in specific_init settype(GUILOG); } void bx_gui_c::init(int argc, char **argv, unsigned tilewidth, unsigned tileheight) { specific_init(&bx_gui, argc, argv, tilewidth, tileheight, BX_HEADER_BAR_Y); // Define some bitmaps to use in the headerbar BX_GUI_THIS floppyA_bmap_id = create_bitmap(bx_floppya_bmap, BX_FLOPPYA_BMAP_X, BX_FLOPPYA_BMAP_Y); BX_GUI_THIS floppyA_eject_bmap_id = create_bitmap(bx_floppya_eject_bmap, BX_FLOPPYA_BMAP_X, BX_FLOPPYA_BMAP_Y); BX_GUI_THIS floppyB_bmap_id = create_bitmap(bx_floppyb_bmap, BX_FLOPPYB_BMAP_X, BX_FLOPPYB_BMAP_Y); BX_GUI_THIS floppyB_eject_bmap_id = create_bitmap(bx_floppyb_eject_bmap, BX_FLOPPYB_BMAP_X, BX_FLOPPYB_BMAP_Y); BX_GUI_THIS cdromD_bmap_id = create_bitmap(bx_cdromd_bmap, BX_CDROMD_BMAP_X, BX_CDROMD_BMAP_Y); BX_GUI_THIS cdromD_eject_bmap_id = create_bitmap(bx_cdromd_eject_bmap, BX_CDROMD_BMAP_X, BX_CDROMD_BMAP_Y); BX_GUI_THIS mouse_bmap_id = create_bitmap(bx_mouse_bmap, BX_MOUSE_BMAP_X, BX_MOUSE_BMAP_Y); BX_GUI_THIS nomouse_bmap_id = create_bitmap(bx_nomouse_bmap, BX_MOUSE_BMAP_X, BX_MOUSE_BMAP_Y); BX_GUI_THIS power_bmap_id = create_bitmap(bx_power_bmap, BX_POWER_BMAP_X, BX_POWER_BMAP_Y); BX_GUI_THIS reset_bmap_id = create_bitmap(bx_reset_bmap, BX_RESET_BMAP_X, BX_RESET_BMAP_Y); BX_GUI_THIS snapshot_bmap_id = create_bitmap(bx_snapshot_bmap, BX_SNAPSHOT_BMAP_X, BX_SNAPSHOT_BMAP_Y); BX_GUI_THIS config_bmap_id = create_bitmap(bx_config_bmap, BX_SNAPSHOT_BMAP_X, BX_SNAPSHOT_BMAP_Y); // Add the initial bitmaps to the headerbar, and enable callback routine, for use // when that bitmap is clicked on // Floppy A: BX_GUI_THIS floppyA_status = bx_devices.floppy->get_media_status(0); if (BX_GUI_THIS floppyA_status) BX_GUI_THIS floppyA_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyA_bmap_id, BX_GRAVITY_LEFT, floppyA_handler); else BX_GUI_THIS floppyA_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyA_eject_bmap_id, BX_GRAVITY_LEFT, floppyA_handler); // Floppy B: BX_GUI_THIS floppyB_status = bx_devices.floppy->get_media_status(1); if (BX_GUI_THIS floppyB_status) BX_GUI_THIS floppyB_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyB_bmap_id, BX_GRAVITY_LEFT, floppyB_handler); else BX_GUI_THIS floppyB_hbar_id = headerbar_bitmap(BX_GUI_THIS floppyB_eject_bmap_id, BX_GRAVITY_LEFT, floppyB_handler); // CDROM BX_GUI_THIS cdromD_status = bx_devices.hard_drive->get_cd_media_status() && bx_options.cdromd.Opresent->get (); if (BX_GUI_THIS cdromD_status) BX_GUI_THIS cdromD_hbar_id = headerbar_bitmap(BX_GUI_THIS cdromD_bmap_id, BX_GRAVITY_LEFT, cdromD_handler); else BX_GUI_THIS cdromD_hbar_id = headerbar_bitmap(BX_GUI_THIS cdromD_eject_bmap_id, BX_GRAVITY_LEFT, cdromD_handler); // Mouse button if (bx_options.Omouse_enabled->get ()) BX_GUI_THIS mouse_hbar_id = headerbar_bitmap(BX_GUI_THIS mouse_bmap_id, BX_GRAVITY_LEFT, toggle_mouse_enable); else BX_GUI_THIS mouse_hbar_id = headerbar_bitmap(BX_GUI_THIS nomouse_bmap_id, BX_GRAVITY_LEFT, toggle_mouse_enable); // Power button BX_GUI_THIS power_hbar_id = headerbar_bitmap(BX_GUI_THIS power_bmap_id, BX_GRAVITY_RIGHT, power_handler); // Reset button BX_GUI_THIS reset_hbar_id = headerbar_bitmap(BX_GUI_THIS reset_bmap_id, BX_GRAVITY_RIGHT, reset_handler); // Snapshot button BX_GUI_THIS snapshot_hbar_id = headerbar_bitmap(BX_GUI_THIS snapshot_bmap_id, BX_GRAVITY_RIGHT, snapshot_handler); // Configure button BX_GUI_THIS config_hbar_id = headerbar_bitmap(BX_GUI_THIS config_bmap_id, BX_GRAVITY_RIGHT, config_handler); show_headerbar(); } void bx_gui_c::update_floppy_status_buttons (void) { BX_GUI_THIS floppyA_status = bx_devices.floppy->get_media_status (0) && bx_options.floppya.Oinitial_status->get (); BX_GUI_THIS floppyB_status = bx_devices.floppy->get_media_status (1) && bx_options.floppyb.Oinitial_status->get (); BX_GUI_THIS cdromD_status = bx_devices.hard_drive->get_cd_media_status() && bx_options.cdromd.Opresent->get (); if (BX_GUI_THIS floppyA_status) replace_bitmap(BX_GUI_THIS floppyA_hbar_id, BX_GUI_THIS floppyA_bmap_id); else { #if BX_WITH_MACOS // If we are using the Mac floppy driver, eject the disk // from the floppy drive. This doesn't work in MacOS X. if (!strcmp(bx_options.floppya.Opath->get (), SuperDrive)) DiskEject(1); #endif replace_bitmap(BX_GUI_THIS floppyA_hbar_id, BX_GUI_THIS floppyA_eject_bmap_id); } if (BX_GUI_THIS floppyB_status) replace_bitmap(BX_GUI_THIS floppyB_hbar_id, BX_GUI_THIS floppyB_bmap_id); else { #if BX_WITH_MACOS // If we are using the Mac floppy driver, eject the disk // from the floppy drive. This doesn't work in MacOS X. if (!strcmp(bx_options.floppyb.Opath->get (), SuperDrive)) DiskEject(1); #endif replace_bitmap(BX_GUI_THIS floppyB_hbar_id, BX_GUI_THIS floppyB_eject_bmap_id); } if (BX_GUI_THIS cdromD_status) replace_bitmap(BX_GUI_THIS cdromD_hbar_id, BX_GUI_THIS cdromD_bmap_id); else { replace_bitmap(BX_GUI_THIS cdromD_hbar_id, BX_GUI_THIS cdromD_eject_bmap_id); } } void bx_gui_c::floppyA_handler(void) { BX_GUI_THIS floppyA_status = !BX_GUI_THIS floppyA_status; bx_devices.floppy->set_media_status(0, BX_GUI_THIS floppyA_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::floppyB_handler(void) { BX_GUI_THIS floppyB_status = !BX_GUI_THIS floppyB_status; bx_devices.floppy->set_media_status(1, BX_GUI_THIS floppyB_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::cdromD_handler(void) { BX_GUI_THIS cdromD_status = bx_devices.hard_drive->set_cd_media_status(!BX_GUI_THIS cdromD_status); BX_GUI_THIS update_floppy_status_buttons (); } void bx_gui_c::reset_handler(void) { BX_INFO(( "system RESET callback." )); bx_pc_system.ResetSignal( PCS_SET ); /* XXX is this right? */ for (int i=0; i<BX_SMP_PROCESSORS; i++) BX_CPU(i)->reset(BX_RESET_HARDWARE); } void bx_gui_c::power_handler(void) { // the user pressed power button, so there's no doubt they want bochs // to quit. Change panics to fatal for the GUI and then do a panic. LOG_THIS setonoff(LOGLEV_PANIC, ACT_FATAL); BX_PANIC (("POWER button turned off.")); // shouldn't reach this point, but if you do, QUIT!!! fprintf (stderr, "Bochs is exiting because you pressed the power button.\n"); ::exit (1); } void bx_gui_c::snapshot_handler(void) { Bit8u* text_snapshot = NULL; char *snapshot_txt; unsigned line_addr, txt_addr, txHeight, txWidth; #ifdef WIN32 HANDLE hMem; #else FILE *OUTPUT; #endif bx_vga.get_text_snapshot(&text_snapshot, &txHeight, &txWidth); if (txHeight > 0) { snapshot_txt = (char*) malloc(txHeight*(txWidth+2)+1); txt_addr = 0; for (unsigned i=0; i<txHeight; i++) { line_addr = i * txWidth * 2; for (unsigned j=0; j<(txWidth*2); j+=2) { snapshot_txt[txt_addr] = text_snapshot[line_addr+j]; txt_addr++; } #ifdef WIN32 snapshot_txt[txt_addr] = 13; txt_addr++; #endif snapshot_txt[txt_addr] = 10; txt_addr++; } snapshot_txt[txt_addr] = 0; #ifdef WIN32 if (OpenClipboard(NULL)) { hMem = GlobalAlloc(GMEM_ZEROINIT, txHeight*(txWidth+2)+1); EmptyClipboard(); lstrcpy((char *)hMem, snapshot_txt); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); GlobalFree(hMem); } #else OUTPUT = fopen("snapshot.txt", "w"); fwrite(snapshot_txt, 1, strlen(snapshot_txt), OUTPUT); fclose(OUTPUT); #endif free(snapshot_txt); } else { BX_INFO(( "# SNAPSHOT callback (graphics mode unimplemented)." )); } } void bx_gui_c::config_handler(void) { #if BX_USE_CONTROL_PANEL bx_control_panel (BX_CPANEL_RUNTIME); #else BX_INFO(( "# CONFIG callback (unimplemented)." )); #endif } void bx_gui_c::toggle_mouse_enable(void) { int old = bx_options.Omouse_enabled->get (); BX_DEBUG (("toggle mouse_enabled, now %d", !old)); bx_options.Omouse_enabled->set (!old); } void bx_gui_c::mouse_enabled_changed (Boolean val) { // This is only called when SIM->get_init_done is 1. Note that VAL // is the new value of mouse_enabled, which may not match the old // value which is still in bx_options.Omouse_enabled->get (). BX_DEBUG (("replacing the mouse bitmaps")); if (val) replace_bitmap(BX_GUI_THIS mouse_hbar_id, BX_GUI_THIS mouse_bmap_id); else replace_bitmap(BX_GUI_THIS mouse_hbar_id, BX_GUI_THIS nomouse_bmap_id); // give the GUI a chance to respond to the event. Most guis will hide // the native mouse cursor and do something to trap the mouse inside the // bochs VGA display window. mouse_enabled_changed_specific (val); } void bx_gui_c::init_signal_handlers () { #if BX_GUI_SIGHANDLER Bit32u mask = get_sighandler_mask (); for (Bit32u sig=0; sig<32; sig++) { if (mask & (1<<sig)) signal (sig, bx_signal_handler); } #endif } <|endoftext|>
<commit_before>// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess // 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. // // 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 matrix_storage.cpp * * \brief Definitions. * */ #include "matrix_storage.hpp" namespace sddk { template <typename T> void matrix_storage<T, matrix_storage_t::slab>::set_num_extra(int n__, int idx0__, memory_pool* mp__) { PROFILE("sddk::matrix_storage::set_num_extra"); auto& comm_col = gvp_->comm_ortho_fft(); /* this is how n columns of the matrix will be distributed between columns of the MPI grid */ spl_num_col_ = splindex<splindex_t::block>(n__, comm_col.size(), comm_col.rank()); T* ptr{nullptr}; T* ptr_d{nullptr}; int ncol{0}; /* trivial case */ if (!is_remapped()) { assert(num_rows_loc_ == gvp_->gvec_count_fft()); ncol = n__; ptr = prime_.at(memory_t::host, 0, idx0__); if (prime_.on_device()) { ptr_d = prime_.at(memory_t::device, 0, idx0__); } } else { /* maximum local number of matrix columns */ ncol = splindex_base<int>::block_size(n__, comm_col.size()); /* upper limit for the size of swapped extra matrix */ size_t sz = gvp_->gvec_count_fft() * ncol; /* reallocate buffers if necessary */ if (extra_buf_.size() < sz) { utils::timer t1("sddk::matrix_storage::set_num_extra|alloc"); if (mp__) { send_recv_buf_ = mdarray<T, 1>(*mp__, sz, "matrix_storage.send_recv_buf_"); extra_buf_ = mdarray<T, 1>(*mp__, sz, "matrix_storage.extra_buf_"); } else { send_recv_buf_ = mdarray<T, 1>(sz, memory_t::host, "matrix_storage.send_recv_buf_"); extra_buf_ = mdarray<T, 1>(sz, memory_t::host, "matrix_storage.extra_buf_"); } } ptr = extra_buf_.at(memory_t::host); } /* create the extra storage */ extra_ = mdarray<T, 2>(ptr, ptr_d, gvp_->gvec_count_fft(), ncol, "matrix_storage.extra_"); } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_from(const dmatrix<T>& mtrx__, int irow0__) { PROFILE("sddk::matrix_storage::remap_from"); auto& comm = mtrx__.blacs_grid().comm(); /* cache cartesian ranks */ mdarray<int, 2> cart_rank(mtrx__.blacs_grid().num_ranks_row(), mtrx__.blacs_grid().num_ranks_col()); for (int i = 0; i < mtrx__.blacs_grid().num_ranks_col(); i++) { for (int j = 0; j < mtrx__.blacs_grid().num_ranks_row(); j++) { cart_rank(j, i) = mtrx__.blacs_grid().cart_rank(j, i); } } if (send_recv_buf_.size() < prime_.size()) { send_recv_buf_ = mdarray<T, 1>(prime_.size(), memory_t::host, "matrix_storage::send_recv_buf_"); } block_data_descriptor rd(comm.size()); rd.counts[comm.rank()] = num_rows_loc(); comm.allgather(rd.counts.data(), comm.rank(), 1); rd.calc_offsets(); block_data_descriptor sd(comm.size()); /* global index of column */ int j0 = 0; /* actual number of columns in the submatrix */ int ncol = num_cols_; splindex<splindex_t::block_cyclic> spl_col_begin(j0, mtrx__.num_ranks_col(), mtrx__.rank_col(), mtrx__.bs_col()); splindex<splindex_t::block_cyclic> spl_col_end(j0 + ncol, mtrx__.num_ranks_col(), mtrx__.rank_col(), mtrx__.bs_col()); int local_size_col = spl_col_end.local_size() - spl_col_begin.local_size(); for (int rank_row = 0; rank_row < comm.size(); rank_row++) { if (!rd.counts[rank_row]) { continue; } /* global index of column */ int i0 = rd.offsets[rank_row]; /* actual number of rows in the submatrix */ int nrow = rd.counts[rank_row]; assert(nrow != 0); splindex<splindex_t::block_cyclic> spl_row_begin(irow0__ + i0, mtrx__.num_ranks_row(), mtrx__.rank_row(), mtrx__.bs_row()); splindex<splindex_t::block_cyclic> spl_row_end(irow0__ + i0 + nrow, mtrx__.num_ranks_row(), mtrx__.rank_row(), mtrx__.bs_row()); int local_size_row = spl_row_end.local_size() - spl_row_begin.local_size(); mdarray<T, 1> buf(local_size_row * local_size_col); /* fetch elements of sub-matrix matrix */ if (local_size_row) { for (int j = 0; j < local_size_col; j++) { std::memcpy(&buf[local_size_row * j], &mtrx__(spl_row_begin.local_size(), spl_col_begin.local_size() + j), local_size_row * sizeof(T)); } } sd.counts[comm.rank()] = local_size_row * local_size_col; comm.allgather(sd.counts.data(), comm.rank(), 1); sd.calc_offsets(); /* collect buffers submatrix */ T* send_buf = (buf.size() == 0) ? nullptr : &buf[0]; T* recv_buf = (send_recv_buf_.size() == 0) ? nullptr : &send_recv_buf_[0]; comm.gather(send_buf, recv_buf, sd.counts.data(), sd.offsets.data(), rank_row); if (comm.rank() == rank_row) { /* unpack data */ std::vector<int> counts(comm.size(), 0); for (int jcol = 0; jcol < ncol; jcol++) { auto pos_jcol = mtrx__.spl_col().location(j0 + jcol); for (int irow = 0; irow < nrow; irow++) { auto pos_irow = mtrx__.spl_row().location(irow0__ + i0 + irow); int rank = cart_rank(pos_irow.rank, pos_jcol.rank); prime_(irow, jcol) = send_recv_buf_[sd.offsets[rank] + counts[rank]]; counts[rank]++; } } for (int rank = 0; rank < comm.size(); rank++) { assert(sd.counts[rank] == counts[rank]); } } } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_backward(int n__, int idx0__) { PROFILE("sddk::matrix_storage::remap_backward"); /* trivial case when extra storage mirrors the prime storage */ if (!is_remapped()) { return; } auto& comm_col = gvp_->comm_ortho_fft(); auto& row_distr = gvp_->gvec_fft_slab(); assert(n__ == spl_num_col_.global_index_size()); /* local number of columns */ int n_loc = spl_num_col_.local_size(); /* reorder sending blocks */ #pragma omp parallel for for (int i = 0; i < n_loc; i++) { for (int j = 0; j < comm_col.size(); j++) { int offset = row_distr.offsets[j]; int count = row_distr.counts[j]; if (count) { std::memcpy(&send_recv_buf_[offset * n_loc + count * i], &extra_(offset, i), count * sizeof(T)); } } } /* send and recieve dimensions */ block_data_descriptor sd(comm_col.size()), rd(comm_col.size()); for (int j = 0; j < comm_col.size(); j++) { sd.counts[j] = spl_num_col_.local_size(comm_col.rank()) * row_distr.counts[j]; rd.counts[j] = spl_num_col_.local_size(j) * row_distr.counts[comm_col.rank()]; } sd.calc_offsets(); rd.calc_offsets(); T* recv_buf = (num_rows_loc_ == 0) ? nullptr : prime_.at(memory_t::host, 0, idx0__); utils::timer t1("sddk::matrix_storage::remap_backward|mpi"); comm_col.alltoall(send_recv_buf_.at(memory_t::host), sd.counts.data(), sd.offsets.data(), recv_buf, rd.counts.data(), rd.offsets.data()); t1.stop(); /* move data back to device */ if (prime_.on_device()) { prime_.copy_to(memory_t::device, idx0__ * num_rows_loc(), n__ * num_rows_loc()); } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_forward(int n__, int idx0__, memory_pool* mp__) { PROFILE("sddk::matrix_storage::remap_forward"); set_num_extra(n__, idx0__, mp__); /* trivial case when extra storage mirrors the prime storage */ if (!is_remapped()) { return; } auto& row_distr = gvp_->gvec_fft_slab(); auto& comm_col = gvp_->comm_ortho_fft(); /* local number of columns */ int n_loc = spl_num_col_.local_size(); /* send and recieve dimensions */ block_data_descriptor sd(comm_col.size()), rd(comm_col.size()); for (int j = 0; j < comm_col.size(); j++) { sd.counts[j] = spl_num_col_.local_size(j) * row_distr.counts[comm_col.rank()]; rd.counts[j] = spl_num_col_.local_size(comm_col.rank()) * row_distr.counts[j]; } sd.calc_offsets(); rd.calc_offsets(); T* send_buf = (num_rows_loc_ == 0) ? nullptr : prime_.at(memory_t::host, 0, idx0__); utils::timer t1("sddk::matrix_storage::remap_forward|mpi"); comm_col.alltoall(send_buf, sd.counts.data(), sd.offsets.data(), send_recv_buf_.at(memory_t::host), rd.counts.data(), rd.offsets.data()); t1.stop(); /* reorder recieved blocks */ #pragma omp parallel for for (int i = 0; i < n_loc; i++) { for (int j = 0; j < comm_col.size(); j++) { int offset = row_distr.offsets[j]; int count = row_distr.counts[j]; if (count) { std::memcpy(&extra_(offset, i), &send_recv_buf_[offset * n_loc + count * i], count * sizeof(T)); } } } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::scale(memory_t mem__, int i0__, int n__, double beta__) { if (is_host_memory(mem__)) { for (int i = 0; i < n__; i++) { for (int j = 0; j < num_rows_loc(); j++) { prime(j, i0__ + i) *= beta__; } } } else { #if defined(__GPU) scale_matrix_elements_gpu((acc_complex_double_t*)prime().at(mem__, 0, i0__), prime().ld(), num_rows_loc(), n__, beta__); #endif } } template <typename T> double_complex matrix_storage<T, matrix_storage_t::slab>::checksum(device_t pu__, int i0__, int n__) { double_complex cs(0, 0); switch (pu__) { case device_t::CPU: { for (int i = 0; i < n__; i++) { for (int j = 0; j < num_rows_loc(); j++) { cs += prime(j, i0__ + i); } } break; } case device_t::GPU: { mdarray<double_complex, 1> cs1(n__, memory_t::host, "checksum"); cs1.allocate(memory_t::device).zero(memory_t::device); #if defined(__GPU) add_checksum_gpu(prime().at(memory_t::device, 0, i0__), num_rows_loc(), n__, cs1.at(memory_t::device)); cs1.copy_to(memory_t::host); cs = cs1.checksum(); #endif break; } } return cs; } // insantiate required types template class matrix_storage<double, matrix_storage_t::slab>; template class matrix_storage<double_complex, matrix_storage_t::slab>; } // namespace sddk <commit_msg>matrix_storage<double,...>::add_checksum is missing but required...<commit_after>// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess // 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. // // 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 matrix_storage.cpp * * \brief Definitions. * */ #include "matrix_storage.hpp" namespace sddk { template <typename T> void matrix_storage<T, matrix_storage_t::slab>::set_num_extra(int n__, int idx0__, memory_pool* mp__) { PROFILE("sddk::matrix_storage::set_num_extra"); auto& comm_col = gvp_->comm_ortho_fft(); /* this is how n columns of the matrix will be distributed between columns of the MPI grid */ spl_num_col_ = splindex<splindex_t::block>(n__, comm_col.size(), comm_col.rank()); T* ptr{nullptr}; T* ptr_d{nullptr}; int ncol{0}; /* trivial case */ if (!is_remapped()) { assert(num_rows_loc_ == gvp_->gvec_count_fft()); ncol = n__; ptr = prime_.at(memory_t::host, 0, idx0__); if (prime_.on_device()) { ptr_d = prime_.at(memory_t::device, 0, idx0__); } } else { /* maximum local number of matrix columns */ ncol = splindex_base<int>::block_size(n__, comm_col.size()); /* upper limit for the size of swapped extra matrix */ size_t sz = gvp_->gvec_count_fft() * ncol; /* reallocate buffers if necessary */ if (extra_buf_.size() < sz) { utils::timer t1("sddk::matrix_storage::set_num_extra|alloc"); if (mp__) { send_recv_buf_ = mdarray<T, 1>(*mp__, sz, "matrix_storage.send_recv_buf_"); extra_buf_ = mdarray<T, 1>(*mp__, sz, "matrix_storage.extra_buf_"); } else { send_recv_buf_ = mdarray<T, 1>(sz, memory_t::host, "matrix_storage.send_recv_buf_"); extra_buf_ = mdarray<T, 1>(sz, memory_t::host, "matrix_storage.extra_buf_"); } } ptr = extra_buf_.at(memory_t::host); } /* create the extra storage */ extra_ = mdarray<T, 2>(ptr, ptr_d, gvp_->gvec_count_fft(), ncol, "matrix_storage.extra_"); } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_from(const dmatrix<T>& mtrx__, int irow0__) { PROFILE("sddk::matrix_storage::remap_from"); auto& comm = mtrx__.blacs_grid().comm(); /* cache cartesian ranks */ mdarray<int, 2> cart_rank(mtrx__.blacs_grid().num_ranks_row(), mtrx__.blacs_grid().num_ranks_col()); for (int i = 0; i < mtrx__.blacs_grid().num_ranks_col(); i++) { for (int j = 0; j < mtrx__.blacs_grid().num_ranks_row(); j++) { cart_rank(j, i) = mtrx__.blacs_grid().cart_rank(j, i); } } if (send_recv_buf_.size() < prime_.size()) { send_recv_buf_ = mdarray<T, 1>(prime_.size(), memory_t::host, "matrix_storage::send_recv_buf_"); } block_data_descriptor rd(comm.size()); rd.counts[comm.rank()] = num_rows_loc(); comm.allgather(rd.counts.data(), comm.rank(), 1); rd.calc_offsets(); block_data_descriptor sd(comm.size()); /* global index of column */ int j0 = 0; /* actual number of columns in the submatrix */ int ncol = num_cols_; splindex<splindex_t::block_cyclic> spl_col_begin(j0, mtrx__.num_ranks_col(), mtrx__.rank_col(), mtrx__.bs_col()); splindex<splindex_t::block_cyclic> spl_col_end(j0 + ncol, mtrx__.num_ranks_col(), mtrx__.rank_col(), mtrx__.bs_col()); int local_size_col = spl_col_end.local_size() - spl_col_begin.local_size(); for (int rank_row = 0; rank_row < comm.size(); rank_row++) { if (!rd.counts[rank_row]) { continue; } /* global index of column */ int i0 = rd.offsets[rank_row]; /* actual number of rows in the submatrix */ int nrow = rd.counts[rank_row]; assert(nrow != 0); splindex<splindex_t::block_cyclic> spl_row_begin(irow0__ + i0, mtrx__.num_ranks_row(), mtrx__.rank_row(), mtrx__.bs_row()); splindex<splindex_t::block_cyclic> spl_row_end(irow0__ + i0 + nrow, mtrx__.num_ranks_row(), mtrx__.rank_row(), mtrx__.bs_row()); int local_size_row = spl_row_end.local_size() - spl_row_begin.local_size(); mdarray<T, 1> buf(local_size_row * local_size_col); /* fetch elements of sub-matrix matrix */ if (local_size_row) { for (int j = 0; j < local_size_col; j++) { std::memcpy(&buf[local_size_row * j], &mtrx__(spl_row_begin.local_size(), spl_col_begin.local_size() + j), local_size_row * sizeof(T)); } } sd.counts[comm.rank()] = local_size_row * local_size_col; comm.allgather(sd.counts.data(), comm.rank(), 1); sd.calc_offsets(); /* collect buffers submatrix */ T* send_buf = (buf.size() == 0) ? nullptr : &buf[0]; T* recv_buf = (send_recv_buf_.size() == 0) ? nullptr : &send_recv_buf_[0]; comm.gather(send_buf, recv_buf, sd.counts.data(), sd.offsets.data(), rank_row); if (comm.rank() == rank_row) { /* unpack data */ std::vector<int> counts(comm.size(), 0); for (int jcol = 0; jcol < ncol; jcol++) { auto pos_jcol = mtrx__.spl_col().location(j0 + jcol); for (int irow = 0; irow < nrow; irow++) { auto pos_irow = mtrx__.spl_row().location(irow0__ + i0 + irow); int rank = cart_rank(pos_irow.rank, pos_jcol.rank); prime_(irow, jcol) = send_recv_buf_[sd.offsets[rank] + counts[rank]]; counts[rank]++; } } for (int rank = 0; rank < comm.size(); rank++) { assert(sd.counts[rank] == counts[rank]); } } } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_backward(int n__, int idx0__) { PROFILE("sddk::matrix_storage::remap_backward"); /* trivial case when extra storage mirrors the prime storage */ if (!is_remapped()) { return; } auto& comm_col = gvp_->comm_ortho_fft(); auto& row_distr = gvp_->gvec_fft_slab(); assert(n__ == spl_num_col_.global_index_size()); /* local number of columns */ int n_loc = spl_num_col_.local_size(); /* reorder sending blocks */ #pragma omp parallel for for (int i = 0; i < n_loc; i++) { for (int j = 0; j < comm_col.size(); j++) { int offset = row_distr.offsets[j]; int count = row_distr.counts[j]; if (count) { std::memcpy(&send_recv_buf_[offset * n_loc + count * i], &extra_(offset, i), count * sizeof(T)); } } } /* send and recieve dimensions */ block_data_descriptor sd(comm_col.size()), rd(comm_col.size()); for (int j = 0; j < comm_col.size(); j++) { sd.counts[j] = spl_num_col_.local_size(comm_col.rank()) * row_distr.counts[j]; rd.counts[j] = spl_num_col_.local_size(j) * row_distr.counts[comm_col.rank()]; } sd.calc_offsets(); rd.calc_offsets(); T* recv_buf = (num_rows_loc_ == 0) ? nullptr : prime_.at(memory_t::host, 0, idx0__); utils::timer t1("sddk::matrix_storage::remap_backward|mpi"); comm_col.alltoall(send_recv_buf_.at(memory_t::host), sd.counts.data(), sd.offsets.data(), recv_buf, rd.counts.data(), rd.offsets.data()); t1.stop(); /* move data back to device */ if (prime_.on_device()) { prime_.copy_to(memory_t::device, idx0__ * num_rows_loc(), n__ * num_rows_loc()); } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::remap_forward(int n__, int idx0__, memory_pool* mp__) { PROFILE("sddk::matrix_storage::remap_forward"); set_num_extra(n__, idx0__, mp__); /* trivial case when extra storage mirrors the prime storage */ if (!is_remapped()) { return; } auto& row_distr = gvp_->gvec_fft_slab(); auto& comm_col = gvp_->comm_ortho_fft(); /* local number of columns */ int n_loc = spl_num_col_.local_size(); /* send and recieve dimensions */ block_data_descriptor sd(comm_col.size()), rd(comm_col.size()); for (int j = 0; j < comm_col.size(); j++) { sd.counts[j] = spl_num_col_.local_size(j) * row_distr.counts[comm_col.rank()]; rd.counts[j] = spl_num_col_.local_size(comm_col.rank()) * row_distr.counts[j]; } sd.calc_offsets(); rd.calc_offsets(); T* send_buf = (num_rows_loc_ == 0) ? nullptr : prime_.at(memory_t::host, 0, idx0__); utils::timer t1("sddk::matrix_storage::remap_forward|mpi"); comm_col.alltoall(send_buf, sd.counts.data(), sd.offsets.data(), send_recv_buf_.at(memory_t::host), rd.counts.data(), rd.offsets.data()); t1.stop(); /* reorder recieved blocks */ #pragma omp parallel for for (int i = 0; i < n_loc; i++) { for (int j = 0; j < comm_col.size(); j++) { int offset = row_distr.offsets[j]; int count = row_distr.counts[j]; if (count) { std::memcpy(&extra_(offset, i), &send_recv_buf_[offset * n_loc + count * i], count * sizeof(T)); } } } } template <typename T> void matrix_storage<T, matrix_storage_t::slab>::scale(memory_t mem__, int i0__, int n__, double beta__) { if (is_host_memory(mem__)) { for (int i = 0; i < n__; i++) { for (int j = 0; j < num_rows_loc(); j++) { prime(j, i0__ + i) *= beta__; } } } else { #if defined(__GPU) scale_matrix_elements_gpu((acc_complex_double_t*)prime().at(mem__, 0, i0__), prime().ld(), num_rows_loc(), n__, beta__); #endif } } template <> double_complex matrix_storage<std::complex<double>, matrix_storage_t::slab>::checksum(device_t pu__, int i0__, int n__) { double_complex cs(0, 0); switch (pu__) { case device_t::CPU: { for (int i = 0; i < n__; i++) { for (int j = 0; j < num_rows_loc(); j++) { cs += prime(j, i0__ + i); } } break; } case device_t::GPU: { mdarray<double_complex, 1> cs1(n__, memory_t::host, "checksum"); cs1.allocate(memory_t::device).zero(memory_t::device); #if defined(__GPU) add_checksum_gpu(prime().at(memory_t::device, 0, i0__), num_rows_loc(), n__, cs1.at(memory_t::device)); cs1.copy_to(memory_t::host); cs = cs1.checksum(); #endif break; } } return cs; } template <> double_complex matrix_storage<double, matrix_storage_t::slab>::checksum(device_t, int, int) { TERMINATE("matrix_storage<double, ..>::checksum is not implemented for double\n"); return 0; } // instantiate required types template class matrix_storage<double, matrix_storage_t::slab>; template class matrix_storage<double_complex, matrix_storage_t::slab>; } // namespace sddk <|endoftext|>
<commit_before>//===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a pass that expands pseudo instructions into target // instructions to allow proper scheduling, if-conversion, other late // optimizations, or simply the encoding of the instructions. // //===----------------------------------------------------------------------===// #include "X86.h" #include "X86FrameLowering.h" #include "X86InstrBuilder.h" #include "X86InstrInfo.h" #include "X86MachineFunctionInfo.h" #include "X86Subtarget.h" #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved. #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/IR/GlobalValue.h" using namespace llvm; #define DEBUG_TYPE "x86-pseudo" namespace { class X86ExpandPseudo : public MachineFunctionPass { public: static char ID; X86ExpandPseudo() : MachineFunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addPreservedID(MachineLoopInfoID); AU.addPreservedID(MachineDominatorsID); MachineFunctionPass::getAnalysisUsage(AU); } const X86Subtarget *STI; const X86InstrInfo *TII; const X86RegisterInfo *TRI; const X86FrameLowering *X86FrameLowering; bool runOnMachineFunction(MachineFunction &Fn) override; const char *getPassName() const override { return "X86 pseudo instruction expansion pass"; } private: bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI); bool ExpandMBB(MachineBasicBlock &MBB); }; char X86ExpandPseudo::ID = 0; } // End anonymous namespace. /// If \p MBBI is a pseudo instruction, this method expands /// it to the corresponding (sequence of) actual instruction(s). /// \returns true if \p MBBI has been expanded. bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) { MachineInstr &MI = *MBBI; unsigned Opcode = MI.getOpcode(); DebugLoc DL = MBBI->getDebugLoc(); switch (Opcode) { default: return false; case X86::TCRETURNdi: case X86::TCRETURNri: case X86::TCRETURNmi: case X86::TCRETURNdi64: case X86::TCRETURNri64: case X86::TCRETURNmi64: { bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64; MachineOperand &JumpTarget = MBBI->getOperand(0); MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1); assert(StackAdjust.isImm() && "Expecting immediate value."); // Adjust stack pointer. int StackAdj = StackAdjust.getImm(); if (StackAdj) { bool Is64Bit = STI->is64Bit(); // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); bool UseLEAForSP = X86FrameLowering->useLEAForSPInProlog(*MBB.getParent()); unsigned StackPtr = TRI->getStackRegister(); // Check for possible merge with preceding ADD instruction. StackAdj += X86FrameLowering::mergeSPUpdates(MBB, MBBI, StackPtr, true); X86FrameLowering::emitSPUpdate(MBB, MBBI, StackPtr, StackAdj, Is64Bit, Uses64BitFramePtr, UseLEAForSP, *TII, *TRI); } // Jump to label or value in register. bool IsWin64 = STI->isTargetWin64(); if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdi64) { unsigned Op = (Opcode == X86::TCRETURNdi) ? X86::TAILJMPd : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); if (JumpTarget.isGlobal()) MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), JumpTarget.getTargetFlags()); else { assert(JumpTarget.isSymbol()); MIB.addExternalSymbol(JumpTarget.getSymbolName(), JumpTarget.getTargetFlags()); } } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) { unsigned Op = (Opcode == X86::TCRETURNmi) ? X86::TAILJMPm : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); for (unsigned i = 0; i != 5; ++i) MIB.addOperand(MBBI->getOperand(i)); } else if (Opcode == X86::TCRETURNri64) { BuildMI(MBB, MBBI, DL, TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64)) .addReg(JumpTarget.getReg(), RegState::Kill); } else { BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr)) .addReg(JumpTarget.getReg(), RegState::Kill); } MachineInstr *NewMI = std::prev(MBBI); NewMI->copyImplicitOps(*MBBI->getParent()->getParent(), MBBI); // Delete the pseudo instruction TCRETURN. MBB.erase(MBBI); return true; } case X86::EH_RETURN: case X86::EH_RETURN64: { MachineOperand &DestAddr = MBBI->getOperand(0); assert(DestAddr.isReg() && "Offset should be in register!"); const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); unsigned StackPtr = TRI->getStackRegister(); BuildMI(MBB, MBBI, DL, TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr) .addReg(DestAddr.getReg()); // The EH_RETURN pseudo is really removed during the MC Lowering. return true; } } llvm_unreachable("Previous switch has a fallthrough?"); } /// Expand all pseudo instructions contained in \p MBB. /// \returns true if any expansion occurred for \p MBB. bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) { bool Modified = false; // MBBI may be invalidated by the expansion. MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); while (MBBI != E) { MachineBasicBlock::iterator NMBBI = std::next(MBBI); Modified |= ExpandMI(MBB, MBBI); MBBI = NMBBI; } return Modified; } bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) { STI = &static_cast<const X86Subtarget &>(MF.getSubtarget()); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); X86FrameLowering = STI->getFrameLowering(); bool Modified = false; for (MachineBasicBlock &MBB : MF) Modified |= ExpandMBB(MBB); return Modified; } /// Returns an instance of the pseudo instruction expansion pass. FunctionPass *llvm::createX86ExpandPseudoPass() { return new X86ExpandPseudo(); } <commit_msg>[X86] Fix a variable name for r237977 so that it works with every compilers.<commit_after>//===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a pass that expands pseudo instructions into target // instructions to allow proper scheduling, if-conversion, other late // optimizations, or simply the encoding of the instructions. // //===----------------------------------------------------------------------===// #include "X86.h" #include "X86FrameLowering.h" #include "X86InstrBuilder.h" #include "X86InstrInfo.h" #include "X86MachineFunctionInfo.h" #include "X86Subtarget.h" #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved. #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/IR/GlobalValue.h" using namespace llvm; #define DEBUG_TYPE "x86-pseudo" namespace { class X86ExpandPseudo : public MachineFunctionPass { public: static char ID; X86ExpandPseudo() : MachineFunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addPreservedID(MachineLoopInfoID); AU.addPreservedID(MachineDominatorsID); MachineFunctionPass::getAnalysisUsage(AU); } const X86Subtarget *STI; const X86InstrInfo *TII; const X86RegisterInfo *TRI; const X86FrameLowering *X86FL; bool runOnMachineFunction(MachineFunction &Fn) override; const char *getPassName() const override { return "X86 pseudo instruction expansion pass"; } private: bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI); bool ExpandMBB(MachineBasicBlock &MBB); }; char X86ExpandPseudo::ID = 0; } // End anonymous namespace. /// If \p MBBI is a pseudo instruction, this method expands /// it to the corresponding (sequence of) actual instruction(s). /// \returns true if \p MBBI has been expanded. bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) { MachineInstr &MI = *MBBI; unsigned Opcode = MI.getOpcode(); DebugLoc DL = MBBI->getDebugLoc(); switch (Opcode) { default: return false; case X86::TCRETURNdi: case X86::TCRETURNri: case X86::TCRETURNmi: case X86::TCRETURNdi64: case X86::TCRETURNri64: case X86::TCRETURNmi64: { bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64; MachineOperand &JumpTarget = MBBI->getOperand(0); MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1); assert(StackAdjust.isImm() && "Expecting immediate value."); // Adjust stack pointer. int StackAdj = StackAdjust.getImm(); if (StackAdj) { bool Is64Bit = STI->is64Bit(); // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); bool UseLEAForSP = X86FL->useLEAForSPInProlog(*MBB.getParent()); unsigned StackPtr = TRI->getStackRegister(); // Check for possible merge with preceding ADD instruction. StackAdj += X86FrameLowering::mergeSPUpdates(MBB, MBBI, StackPtr, true); X86FrameLowering::emitSPUpdate(MBB, MBBI, StackPtr, StackAdj, Is64Bit, Uses64BitFramePtr, UseLEAForSP, *TII, *TRI); } // Jump to label or value in register. bool IsWin64 = STI->isTargetWin64(); if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdi64) { unsigned Op = (Opcode == X86::TCRETURNdi) ? X86::TAILJMPd : (IsWin64 ? X86::TAILJMPd64_REX : X86::TAILJMPd64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); if (JumpTarget.isGlobal()) MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), JumpTarget.getTargetFlags()); else { assert(JumpTarget.isSymbol()); MIB.addExternalSymbol(JumpTarget.getSymbolName(), JumpTarget.getTargetFlags()); } } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) { unsigned Op = (Opcode == X86::TCRETURNmi) ? X86::TAILJMPm : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64); MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op)); for (unsigned i = 0; i != 5; ++i) MIB.addOperand(MBBI->getOperand(i)); } else if (Opcode == X86::TCRETURNri64) { BuildMI(MBB, MBBI, DL, TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64)) .addReg(JumpTarget.getReg(), RegState::Kill); } else { BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr)) .addReg(JumpTarget.getReg(), RegState::Kill); } MachineInstr *NewMI = std::prev(MBBI); NewMI->copyImplicitOps(*MBBI->getParent()->getParent(), MBBI); // Delete the pseudo instruction TCRETURN. MBB.erase(MBBI); return true; } case X86::EH_RETURN: case X86::EH_RETURN64: { MachineOperand &DestAddr = MBBI->getOperand(0); assert(DestAddr.isReg() && "Offset should be in register!"); const bool Uses64BitFramePtr = STI->isTarget64BitLP64() || STI->isTargetNaCl64(); unsigned StackPtr = TRI->getStackRegister(); BuildMI(MBB, MBBI, DL, TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr) .addReg(DestAddr.getReg()); // The EH_RETURN pseudo is really removed during the MC Lowering. return true; } } llvm_unreachable("Previous switch has a fallthrough?"); } /// Expand all pseudo instructions contained in \p MBB. /// \returns true if any expansion occurred for \p MBB. bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) { bool Modified = false; // MBBI may be invalidated by the expansion. MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end(); while (MBBI != E) { MachineBasicBlock::iterator NMBBI = std::next(MBBI); Modified |= ExpandMI(MBB, MBBI); MBBI = NMBBI; } return Modified; } bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) { STI = &static_cast<const X86Subtarget &>(MF.getSubtarget()); TII = STI->getInstrInfo(); TRI = STI->getRegisterInfo(); X86FL = STI->getFrameLowering(); bool Modified = false; for (MachineBasicBlock &MBB : MF) Modified |= ExpandMBB(MBB); return Modified; } /// Returns an instance of the pseudo instruction expansion pass. FunctionPass *llvm::createX86ExpandPseudoPass() { return new X86ExpandPseudo(); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This application is open source and may be redistributed and/or modified under * the terms of the GNU Public License (GPL) version 1.0 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 * OpenSceneGraph Public License for more details. */ #include "PhotoArchive.h" #include <osg/GLU> #include <osg/Notify> #include <osgDB/ReadFile> #include <Producer/RenderSurface> #include <fstream> const std::string FILE_IDENTIFER("osgphotoalbum photo archive"); class GraphicsContext { public: GraphicsContext() { rs = new Producer::RenderSurface; rs->setWindowRectangle(0,0,1,1); rs->useBorder(false); rs->useConfigEventThread(false); rs->realize(); std::cout<<"Realized window"<<std::endl; } virtual ~GraphicsContext() { } private: Producer::ref_ptr<Producer::RenderSurface> rs; }; PhotoArchive::PhotoArchive(const std::string& filename) { readPhotoIndex(filename); } bool PhotoArchive::readPhotoIndex(const std::string& filename) { std::ifstream in(filename.c_str()); char* fileIndentifier = new char [FILE_IDENTIFER.size()]; in.read(fileIndentifier,FILE_IDENTIFER.size()); if (FILE_IDENTIFER!=fileIndentifier) return false; unsigned int numPhotos; in.read((char*)&numPhotos,sizeof(numPhotos)); _photoIndex.resize(numPhotos); in.read((char*)&_photoIndex.front(),sizeof(PhotoHeader)*numPhotos); // success record filename. _archiveFileName = filename; return true; } void PhotoArchive::getImageFileNameList(FileNameList& filenameList) { for(PhotoIndexList::const_iterator itr=_photoIndex.begin(); itr!=_photoIndex.end(); ++itr) { filenameList.push_back(std::string(itr->filename)); } } osg::Image* PhotoArchive::readImage(const std::string& filename, unsigned int target_s, unsigned target_t, float& original_s, float& original_t) { for(PhotoIndexList::const_iterator itr=_photoIndex.begin(); itr!=_photoIndex.end(); ++itr) { if (filename==itr->filename) { const PhotoHeader& photoHeader = *itr; if (target_s <= photoHeader.thumbnail_s && target_t <= photoHeader.thumbnail_t && photoHeader.thumbnail_position != 0) { std::ifstream in(_archiveFileName.c_str(),std::ios::in | std::ios::binary); // find image in.seekg(photoHeader.thumbnail_position); // read image header ImageHeader imageHeader; in.read((char*)&imageHeader,sizeof(ImageHeader)); unsigned char* data = new unsigned char[imageHeader.size]; in.read((char*)data,imageHeader.size); osg::Image* image = new osg::Image; image->setImage(photoHeader.thumbnail_s,photoHeader.thumbnail_t,1, imageHeader.pixelFormat,imageHeader.pixelFormat,imageHeader.type, data,osg::Image::USE_NEW_DELETE); original_s = photoHeader.original_s; original_t = photoHeader.original_t; return image; } if (photoHeader.fullsize_s && photoHeader.fullsize_t && photoHeader.fullsize_position != 0) { std::ifstream in(_archiveFileName.c_str(),std::ios::in | std::ios::binary); // find image in.seekg(photoHeader.fullsize_position); // read image header ImageHeader imageHeader; in.read((char*)&imageHeader,sizeof(ImageHeader)); unsigned char* data = new unsigned char[imageHeader.size]; in.read((char*)data,imageHeader.size); osg::Image* image = new osg::Image; image->setImage(photoHeader.fullsize_s,photoHeader.fullsize_t,1, imageHeader.pixelFormat,imageHeader.pixelFormat,imageHeader.type, data,osg::Image::USE_NEW_DELETE); original_s = photoHeader.original_s; original_t = photoHeader.original_t; return image; } } } return NULL; } void PhotoArchive::buildArchive(const std::string& filename, const FileNameList& imageList, unsigned int thumbnailSize, unsigned int maximumSize, bool /*compressed*/) { PhotoIndexList photoIndex; photoIndex.reserve(imageList.size()); for(FileNameList::const_iterator fitr=imageList.begin(); fitr!=imageList.end(); ++fitr) { PhotoHeader header; // set name strncpy(header.filename,fitr->c_str(),255); header.filename[255]=0; header.thumbnail_s = thumbnailSize; header.thumbnail_t = thumbnailSize; header.thumbnail_position = 0; header.fullsize_s = thumbnailSize; header.fullsize_t = thumbnailSize; header.fullsize_position = 0; photoIndex.push_back(header); } std::cout<<"Building photo archive containing "<<photoIndex.size()<<" pictures"<<std::endl; // create a graphics context so we can do data operations GraphicsContext context; // open up the archive for writing to std::ofstream out(filename.c_str(), std::ios::out | std::ios::binary); // write out file indentifier. out.write(FILE_IDENTIFER.c_str(),FILE_IDENTIFER.size()); unsigned int numPhotos = photoIndex.size(); out.write((char*)&numPhotos,sizeof(unsigned int)); // write the photo index to ensure we can the correct amount of space // available. unsigned int startOfPhotoIndex = out.tellp(); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); unsigned int photoCount=1; for(PhotoIndexList::iterator pitr=photoIndex.begin(); pitr!=photoIndex.end(); ++pitr,++photoCount) { PhotoHeader& photoHeader = *pitr; std::cout<<"Processng image "<<photoCount<<" of "<< photoIndex.size()<<" filename="<< photoHeader.filename << std::endl; std::cout<<" reading image...";std::cout.flush(); osg::ref_ptr<osg::Image> image = osgDB::readImageFile(photoHeader.filename); std::cout<<"done."<< std::endl; photoHeader.original_s = image->s(); photoHeader.original_t = image->t(); { std::cout<<" creating thumbnail image..."; // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(thumbnailSize,image->getPixelFormat(),image->getDataType(),image->getPacking())* thumbnailSize; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,image->getPacking()); glPixelStorei(GL_UNPACK_ALIGNMENT,image->getPacking()); GLint status = gluScaleImage(image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), thumbnailSize, thumbnailSize, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } // now set up the photo header. photoHeader.thumbnail_s = thumbnailSize; photoHeader.thumbnail_t = thumbnailSize; photoHeader.thumbnail_position = (unsigned int)out.tellp(); // set up image header ImageHeader imageHeader; imageHeader.s = thumbnailSize; imageHeader.t = thumbnailSize; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; // write out image header and image data. out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } { std::cout<<" creating fullsize image...";std::cout.flush(); photoHeader.fullsize_s = osg::minimum((unsigned int)image->s(),maximumSize); photoHeader.fullsize_t = osg::minimum((unsigned int)image->t(),maximumSize); photoHeader.fullsize_position = (unsigned int)out.tellp(); // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(photoHeader.fullsize_s,image->getPixelFormat(),image->getDataType(),image->getPacking())* photoHeader.fullsize_t; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,image->getPacking()); glPixelStorei(GL_UNPACK_ALIGNMENT,image->getPacking()); GLint status = gluScaleImage(image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), photoHeader.fullsize_s, photoHeader.fullsize_t, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } ImageHeader imageHeader; imageHeader.s = photoHeader.fullsize_s; imageHeader.t = photoHeader.fullsize_t; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); //out.write((char*)image->data(),imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } } // rewrite photo index now it has the correct sizes set out.seekp(startOfPhotoIndex); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); } <commit_msg>Fixed typo.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This application is open source and may be redistributed and/or modified under * the terms of the GNU Public License (GPL) version 1.0 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 * OpenSceneGraph Public License for more details. */ #include "PhotoArchive.h" #include <osg/GLU> #include <osg/Notify> #include <osgDB/ReadFile> #include <Producer/RenderSurface> #include <fstream> const std::string FILE_IDENTIFER("osgphotoalbum photo archive"); class GraphicsContext { public: GraphicsContext() { rs = new Producer::RenderSurface; rs->setWindowRectangle(0,0,1,1); rs->useBorder(false); rs->useConfigEventThread(false); rs->realize(); std::cout<<"Realized window"<<std::endl; } virtual ~GraphicsContext() { } private: Producer::ref_ptr<Producer::RenderSurface> rs; }; PhotoArchive::PhotoArchive(const std::string& filename) { readPhotoIndex(filename); } bool PhotoArchive::readPhotoIndex(const std::string& filename) { std::ifstream in(filename.c_str()); char* fileIndentifier = new char [FILE_IDENTIFER.size()]; in.read(fileIndentifier,FILE_IDENTIFER.size()); if (FILE_IDENTIFER!=fileIndentifier) return false; unsigned int numPhotos; in.read((char*)&numPhotos,sizeof(numPhotos)); _photoIndex.resize(numPhotos); in.read((char*)&_photoIndex.front(),sizeof(PhotoHeader)*numPhotos); // success record filename. _archiveFileName = filename; return true; } void PhotoArchive::getImageFileNameList(FileNameList& filenameList) { for(PhotoIndexList::const_iterator itr=_photoIndex.begin(); itr!=_photoIndex.end(); ++itr) { filenameList.push_back(std::string(itr->filename)); } } osg::Image* PhotoArchive::readImage(const std::string& filename, unsigned int target_s, unsigned target_t, float& original_s, float& original_t) { for(PhotoIndexList::const_iterator itr=_photoIndex.begin(); itr!=_photoIndex.end(); ++itr) { if (filename==itr->filename) { const PhotoHeader& photoHeader = *itr; if (target_s <= photoHeader.thumbnail_s && target_t <= photoHeader.thumbnail_t && photoHeader.thumbnail_position != 0) { std::ifstream in(_archiveFileName.c_str(),std::ios::in | std::ios::binary); // find image in.seekg(photoHeader.thumbnail_position); // read image header ImageHeader imageHeader; in.read((char*)&imageHeader,sizeof(ImageHeader)); unsigned char* data = new unsigned char[imageHeader.size]; in.read((char*)data,imageHeader.size); osg::Image* image = new osg::Image; image->setImage(photoHeader.thumbnail_s,photoHeader.thumbnail_t,1, imageHeader.pixelFormat,imageHeader.pixelFormat,imageHeader.type, data,osg::Image::USE_NEW_DELETE); original_s = photoHeader.original_s; original_t = photoHeader.original_t; return image; } if (photoHeader.fullsize_s && photoHeader.fullsize_t && photoHeader.fullsize_position != 0) { std::ifstream in(_archiveFileName.c_str(),std::ios::in | std::ios::binary); // find image in.seekg(photoHeader.fullsize_position); // read image header ImageHeader imageHeader; in.read((char*)&imageHeader,sizeof(ImageHeader)); unsigned char* data = new unsigned char[imageHeader.size]; in.read((char*)data,imageHeader.size); osg::Image* image = new osg::Image; image->setImage(photoHeader.fullsize_s,photoHeader.fullsize_t,1, imageHeader.pixelFormat,imageHeader.pixelFormat,imageHeader.type, data,osg::Image::USE_NEW_DELETE); original_s = photoHeader.original_s; original_t = photoHeader.original_t; return image; } } } return NULL; } void PhotoArchive::buildArchive(const std::string& filename, const FileNameList& imageList, unsigned int thumbnailSize, unsigned int maximumSize, bool /*compressed*/) { PhotoIndexList photoIndex; photoIndex.reserve(imageList.size()); for(FileNameList::const_iterator fitr=imageList.begin(); fitr!=imageList.end(); ++fitr) { PhotoHeader header; // set name strncpy(header.filename,fitr->c_str(),255); header.filename[255]=0; header.thumbnail_s = thumbnailSize; header.thumbnail_t = thumbnailSize; header.thumbnail_position = 0; header.fullsize_s = thumbnailSize; header.fullsize_t = thumbnailSize; header.fullsize_position = 0; photoIndex.push_back(header); } std::cout<<"Building photo archive containing "<<photoIndex.size()<<" pictures"<<std::endl; // create a graphics context so we can do data operations GraphicsContext context; // open up the archive for writing to std::ofstream out(filename.c_str(), std::ios::out | std::ios::binary); // write out file indentifier. out.write(FILE_IDENTIFER.c_str(),FILE_IDENTIFER.size()); unsigned int numPhotos = photoIndex.size(); out.write((char*)&numPhotos,sizeof(unsigned int)); // write the photo index to ensure we can the correct amount of space // available. unsigned int startOfPhotoIndex = out.tellp(); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); unsigned int photoCount=1; for(PhotoIndexList::iterator pitr=photoIndex.begin(); pitr!=photoIndex.end(); ++pitr,++photoCount) { PhotoHeader& photoHeader = *pitr; std::cout<<"Processing image "<<photoCount<<" of "<< photoIndex.size()<<" filename="<< photoHeader.filename << std::endl; std::cout<<" reading image...";std::cout.flush(); osg::ref_ptr<osg::Image> image = osgDB::readImageFile(photoHeader.filename); std::cout<<"done."<< std::endl; photoHeader.original_s = image->s(); photoHeader.original_t = image->t(); { std::cout<<" creating thumbnail image..."; // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(thumbnailSize,image->getPixelFormat(),image->getDataType(),image->getPacking())* thumbnailSize; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,image->getPacking()); glPixelStorei(GL_UNPACK_ALIGNMENT,image->getPacking()); GLint status = gluScaleImage(image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), thumbnailSize, thumbnailSize, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } // now set up the photo header. photoHeader.thumbnail_s = thumbnailSize; photoHeader.thumbnail_t = thumbnailSize; photoHeader.thumbnail_position = (unsigned int)out.tellp(); // set up image header ImageHeader imageHeader; imageHeader.s = thumbnailSize; imageHeader.t = thumbnailSize; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; // write out image header and image data. out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } { std::cout<<" creating fullsize image...";std::cout.flush(); photoHeader.fullsize_s = osg::minimum((unsigned int)image->s(),maximumSize); photoHeader.fullsize_t = osg::minimum((unsigned int)image->t(),maximumSize); photoHeader.fullsize_position = (unsigned int)out.tellp(); // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(photoHeader.fullsize_s,image->getPixelFormat(),image->getDataType(),image->getPacking())* photoHeader.fullsize_t; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,image->getPacking()); glPixelStorei(GL_UNPACK_ALIGNMENT,image->getPacking()); GLint status = gluScaleImage(image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), photoHeader.fullsize_s, photoHeader.fullsize_t, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } ImageHeader imageHeader; imageHeader.s = photoHeader.fullsize_s; imageHeader.t = photoHeader.fullsize_t; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); //out.write((char*)image->data(),imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } } // rewrite photo index now it has the correct sizes set out.seekp(startOfPhotoIndex); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); } <|endoftext|>
<commit_before>#include <delta/core/sys.h> #include "dem/runners/Runner.h" #include "dem/repositories/Repository.h" #include "dem/repositories/RepositoryFactory.h" #include "peano/utils/UserInterface.h" #include "peano/datatraversal/autotuning/Oracle.h" #include "peano/datatraversal/autotuning/OracleForOnePhaseDummy.h" #include "sharedmemoryoracles/OracleForOnePhaseWithShrinkingGrainSize.h" #include "tarch/Assertions.h" #include "tarch/parallel/Node.h" #include "tarch/parallel/NodePool.h" #include "tarch/multicore/Core.h" #include "tarch/logging/Log.h" #include "peano/geometry/Hexahedron.h" #include "dem/mappings/MoveParticles.h" #include "dem/mappings/CreateGrid.h" #include "dem/mappings/Plot.h" #include "dem/mappings/ReluctantlyAdoptGrid.h" #include <stdlib.h> #include <string> tarch::logging::Log dem::runners::Runner::_log( "dem::runners::Runner" ); dem::runners::Runner::Runner() { } dem::runners::Runner::~Runner() { } void initHPCEnvironment() { peano::performanceanalysis::Analysis::getInstance().enable(false); } std::string initSharedMemory( int tbbThreads, dem::mappings::CreateGrid::GridType gridType, int numberOfTimeSteps, double stepSize, double realSnapshot, bool useAutotuning) { #ifdef SharedMemoryParallelisation tarch::multicore::Core::getInstance().configure(tbbThreads, tarch::multicore::Core::UseDefaultStackSize); std::string sharedMemoryPropertiesFileName = "shared-memory-"+ std::to_string( tbbThreads ) + "-threads-"; switch (gridType) { case dem::mappings::CreateGrid::NoGrid: sharedMemoryPropertiesFileName += "-no-grid"; break; case dem::mappings::CreateGrid::RegularGrid: sharedMemoryPropertiesFileName += "-regular-grid"; break; case dem::mappings::CreateGrid::AdaptiveGrid: sharedMemoryPropertiesFileName += "-adaptive-grid"; break; case dem::mappings::CreateGrid::ReluctantAdaptiveGrid: sharedMemoryPropertiesFileName += "-reluctant-grid"; break; } sharedMemoryPropertiesFileName += ".properties"; if (useAutotuning) { peano::datatraversal::autotuning::Oracle::getInstance().setOracle( new sharedmemoryoracles::OracleForOnePhaseWithShrinkingGrainSize(true,false)); peano::datatraversal::autotuning::Oracle::getInstance().loadStatistics(sharedMemoryPropertiesFileName); } else { peano::datatraversal::autotuning::Oracle::getInstance().setOracle( new peano::datatraversal::autotuning::OracleForOnePhaseDummy( true, // bool useMultithreading = true, 0, // int grainSizeOfUserDefinedRegions = 0, peano::datatraversal::autotuning::OracleForOnePhaseDummy::SplitVertexReadsOnRegularSubtree::Split, // SplitVertexReadsOnRegularSubtree splitTheTree = SplitVertexReadsOnRegularSubtree::Split, false, //bool pipelineDescendProcessing = false, false, // bool pipelineAscendProcessing = false, 0, // int smallestProblemSizeForAscendDescend = tarch::la::aPowI(DIMENSIONS,3*3*3*3/2), 0, // int grainSizeForAscendDescend = 3, 2, // int smallestProblemSizeForEnterLeaveCell = tarch::la::aPowI(DIMENSIONS,9/2), 2, // int grainSizeForEnterLeaveCell = 2, 2, // int smallestProblemSizeForTouchFirstLast = tarch::la::aPowI(DIMENSIONS,3*3*3*3+1), 2, // int grainSizeForTouchFirstLast = 64, 2, // int smallestProblemSizeForSplitLoadStore = tarch::la::aPowI(DIMENSIONS,3*3*3), 2 // int grainSizeForSplitLoadStore = 8 )); } return sharedMemoryPropertiesFileName; #endif return ""; } void shutSharedMemory(std::string sharedMemoryPropertiesFileName) { if("" == sharedMemoryPropertiesFileName) {return;} #ifdef SharedMemoryParallelisation peano::datatraversal::autotuning::Oracle::getInstance().plotStatistics(sharedMemoryPropertiesFileName); #endif } void initDistributedMemory() { #ifdef Parallel #endif } void shutDistributedMemory() { #ifdef Parallel tarch::parallel::NodePool::getInstance().terminate(); dem::repositories::RepositoryFactory::getInstance().shutdownAllParallelDatatypes(); #endif } int dem::runners::Runner::run(int numberOfTimeSteps, Plot plot, dem::mappings::CreateGrid::GridType gridType, int tbbThreads, double stepSize, double realSnapshot, bool useAutotuning) { peano::geometry::Hexahedron geometry(tarch::la::Vector<DIMENSIONS,double>(1.0), tarch::la::Vector<DIMENSIONS,double>(0.0)); dem::repositories::Repository* repository = dem::repositories::RepositoryFactory::getInstance().createWithSTDStackImplementation(geometry, tarch::la::Vector<DIMENSIONS,double>(1.0), // domainSize tarch::la::Vector<DIMENSIONS,double>(0.0)); // computationalDomainOffset //initHPCEnvironment(); std::string sharedMemoryPropertiesFileName = initSharedMemory(tbbThreads, gridType, numberOfTimeSteps, stepSize, realSnapshot, useAutotuning); //initDistributedMemory(); int result = 0; if (tarch::parallel::Node::getInstance().isGlobalMaster()) { result = runAsMaster( *repository, numberOfTimeSteps, plot, gridType, stepSize, realSnapshot); } #ifdef Parallel else { result = runAsWorker(*repository); } #endif shutSharedMemory(sharedMemoryPropertiesFileName); shutDistributedMemory(); delete repository; return result; } int dem::runners::Runner::runAsMaster(dem::repositories::Repository& repository, int iterations, Plot plot, dem::mappings::CreateGrid::GridType gridType, double initialStepSize, double realSnapshot) { peano::utils::UserInterface::writeHeader(); delta::core::Delta(); dem::mappings::AdoptGrid::_refinementCoefficient = 1.8; dem::mappings::AdoptGrid::_coarsenCoefficient = 0.5; dem::mappings::ReluctantlyAdoptGrid::_coarsenCoefficientReluctant = 1.8; dem::mappings::ReluctantlyAdoptGrid::_refinementCoefficientReluctant = 0.5; logInfo( "runAsMaster(...)", "create grid" ); repository.switchToCreateGrid(); repository.iterate(); //do { repository.iterate(); } while ( !repository.getState().isGridStationary() ); if(gridType == dem::mappings::CreateGrid::GridType::AdaptiveGrid) { logInfo( "runAsMaster(...)", "adopt grid" ); } else if(gridType == dem::mappings::CreateGrid::GridType::ReluctantAdaptiveGrid) { logInfo( "runAsMaster(...)", "reluctantly adopt grid" ); } repository.switchToAdopt(); for(int i=0; i<10; i++) repository.iterate(); logInfo( "runAsMaster(...)", "pre-conditioning" ); repository.getState().setInitialTimeStepSize(1E-16); repository.getState().setMaximumVelocityApproach(0.1); repository.switchToMoveParticles(); for(int i=0; i<8; i++) repository.iterate(); repository.getState().clearAccumulatedData(); repository.getState().setInitialTimeStepSize(initialStepSize); repository.iterate(); ///////////////////////////////////////////////////////////////////// logInfo( "runAsMaster(...)", "start time stepping" ); repository.getState().clearAccumulatedData(); repository.getState().setInitialTimeStepSize(initialStepSize); double elapsed = 0.0; double timestamp = 0.0; int minRange = 0; int maxRange = 50000; if(plot == EveryIteration) { dem::mappings::Plot::_mini = 0; dem::mappings::Plot::_maxi = iterations; } else { dem::mappings::Plot::_mini = minRange; dem::mappings::Plot::_maxi = maxRange; } /* //////////////////PLOT TIME ZERO////////////////////////////////////////////////////// if((plot == EveryIteration) || (plot == Track) || (plot == UponChange && (repository.getState().getNumberOfContactPoints()>0 || !repository.getState().isGridStationary() || 0%50==0 || repository.getState().getNumberOfParticleReassignments()>0 )) || (plot == EveryBatch && 0%50 == 0) || ((plot == Adaptive && ((elapsed > realSnapshot) || (0 == 0))))) { timestamp = repository.getState().getTime(); repository.getState().setTimeStep(0); repository.switchToPlotData(); repository.iterate(); logInfo("runAsMaster(...)", "i=" << 0 << ", reassigns=" << repository.getState().getNumberOfParticleReassignments() << ", par-cmp=" << repository.getState().getNumberOfParticleComparisons() << ", tri-cmp=" << repository.getState().getNumberOfTriangleComparisons() << ", cnpt=" << repository.getState().getNumberOfContactPoints() << ", v=" << repository.getState().getNumberOfInnerVertices() << ", t=" << repository.getState().getTime() << ", dt=" << repository.getState().getTimeStepSize() << ", mvij=" << repository.getState().getMaximumVelocityApproach() << ", plot=" << 1); logInfo("runAsMaster(...)", "h_min(real)=" << repository.getState().getMinimumMeshWidth() << ", h_max(real)=" << repository.getState().getMaximumMeshWidth()); elapsed = repository.getState().getTime() - timestamp; repository.getState().finishedTimeStep(initialStepSize); } */ /////////////////////////////////////////////////////////////////////////////////////// for (int i=0; i<iterations; i++) { timestamp = repository.getState().getTime(); repository.getState().setTimeStep(i); bool plotThisTraversal = (plot == EveryIteration) || (plot == Track) || (plot == UponChange && (repository.getState().getNumberOfContactPoints()>0 || !repository.getState().isGridStationary() || i%50==0 || repository.getState().getNumberOfParticleReassignments()>0 )) || (plot == EveryBatch && i%50 == 0) || ((plot == Adaptive && ((elapsed > realSnapshot) || (i == 0)))) || (plot == Range && ((i >= minRange) && (i < maxRange))); if(plotThisTraversal) { //delta::sys::Sys::saveIteration(repository.getState().getTimeStepSize(), i, iterations); if (gridType==mappings::CreateGrid::AdaptiveGrid) { repository.switchToTimeStepAndPlotOnDynamicGrid(); } else if (gridType==mappings::CreateGrid::ReluctantAdaptiveGrid) { repository.switchToTimeStepAndPlotOnReluctantDynamicGrid(); } else { repository.switchToTimeStepAndPlot(); } } else { if (gridType==mappings::CreateGrid::AdaptiveGrid) { repository.switchToTimeStepOnDynamicGridMerged(); } else if (gridType==mappings::CreateGrid::ReluctantAdaptiveGrid) { repository.switchToTimeStepOnReluctantDynamicGridMerged(); } else { repository.switchToTimeStep(); } } repository.iterate(); elapsed = repository.getState().getTime() - timestamp; logInfo("runAsMaster(...)", "i=" << i << ", reassigns=" << repository.getState().getNumberOfParticleReassignments() << ", par-cmp=" << repository.getState().getNumberOfParticleComparisons() << ", tri-cmp=" << repository.getState().getNumberOfTriangleComparisons() << ", cnpt=" << repository.getState().getNumberOfContactPoints() << ", v=" << repository.getState().getNumberOfInnerVertices() << ", t=" << repository.getState().getTime() << ", dt=" << repository.getState().getTimeStepSize() << ", mvij=" << repository.getState().getMaximumVelocityApproach() << ", plot=" << plotThisTraversal); logInfo("runAsMaster(...)", "h_min(real)=" << repository.getState().getMinimumMeshWidth() << ", h_max(real)=" << repository.getState().getMaximumMeshWidth()); repository.getState().finishedTimeStep(initialStepSize); repository.getState().clearAccumulatedData(); } repository.logIterationStatistics(false); repository.terminate(); return 0; } <commit_msg><commit_after>#include <delta/core/sys.h> #include "dem/runners/Runner.h" #include "dem/repositories/Repository.h" #include "dem/repositories/RepositoryFactory.h" #include "peano/utils/UserInterface.h" #include "peano/datatraversal/autotuning/Oracle.h" #include "peano/datatraversal/autotuning/OracleForOnePhaseDummy.h" #include "sharedmemoryoracles/OracleForOnePhaseWithShrinkingGrainSize.h" #include "tarch/Assertions.h" #include "tarch/parallel/Node.h" #include "tarch/parallel/NodePool.h" #include "tarch/multicore/Core.h" #include "tarch/logging/Log.h" #include "peano/geometry/Hexahedron.h" #include "dem/mappings/MoveParticles.h" #include "dem/mappings/CreateGrid.h" #include "dem/mappings/Plot.h" #include "dem/mappings/ReluctantlyAdoptGrid.h" #include <stdlib.h> #include <string> tarch::logging::Log dem::runners::Runner::_log( "dem::runners::Runner" ); dem::runners::Runner::Runner() { } dem::runners::Runner::~Runner() { } void initHPCEnvironment() { peano::performanceanalysis::Analysis::getInstance().enable(false); } std::string initSharedMemory( int tbbThreads, dem::mappings::CreateGrid::GridType gridType, int numberOfTimeSteps, double stepSize, double realSnapshot, bool useAutotuning) { #ifdef SharedMemoryParallelisation tarch::multicore::Core::getInstance().configure(tbbThreads, tarch::multicore::Core::UseDefaultStackSize); std::string sharedMemoryPropertiesFileName = "shared-memory-"+ std::to_string( tbbThreads ) + "-threads-"; switch (gridType) { case dem::mappings::CreateGrid::NoGrid: sharedMemoryPropertiesFileName += "-no-grid"; break; case dem::mappings::CreateGrid::RegularGrid: sharedMemoryPropertiesFileName += "-regular-grid"; break; case dem::mappings::CreateGrid::AdaptiveGrid: sharedMemoryPropertiesFileName += "-adaptive-grid"; break; case dem::mappings::CreateGrid::ReluctantAdaptiveGrid: sharedMemoryPropertiesFileName += "-reluctant-grid"; break; } sharedMemoryPropertiesFileName += ".properties"; if (useAutotuning) { peano::datatraversal::autotuning::Oracle::getInstance().setOracle( new sharedmemoryoracles::OracleForOnePhaseWithShrinkingGrainSize(true,false)); peano::datatraversal::autotuning::Oracle::getInstance().loadStatistics(sharedMemoryPropertiesFileName); } else { peano::datatraversal::autotuning::Oracle::getInstance().setOracle( new peano::datatraversal::autotuning::OracleForOnePhaseDummy( true, // bool useMultithreading = true, 0, // int grainSizeOfUserDefinedRegions = 0, peano::datatraversal::autotuning::OracleForOnePhaseDummy::SplitVertexReadsOnRegularSubtree::Split, // SplitVertexReadsOnRegularSubtree splitTheTree = SplitVertexReadsOnRegularSubtree::Split, false, //bool pipelineDescendProcessing = false, false, // bool pipelineAscendProcessing = false, 0, // int smallestProblemSizeForAscendDescend = tarch::la::aPowI(DIMENSIONS,3*3*3*3/2), 0, // int grainSizeForAscendDescend = 3, 2, // int smallestProblemSizeForEnterLeaveCell = tarch::la::aPowI(DIMENSIONS,9/2), 2, // int grainSizeForEnterLeaveCell = 2, 2, // int smallestProblemSizeForTouchFirstLast = tarch::la::aPowI(DIMENSIONS,3*3*3*3+1), 2, // int grainSizeForTouchFirstLast = 64, 2, // int smallestProblemSizeForSplitLoadStore = tarch::la::aPowI(DIMENSIONS,3*3*3), 2 // int grainSizeForSplitLoadStore = 8 )); } return sharedMemoryPropertiesFileName; #endif return ""; } void shutSharedMemory(std::string sharedMemoryPropertiesFileName) { if("" == sharedMemoryPropertiesFileName) {return;} #ifdef SharedMemoryParallelisation peano::datatraversal::autotuning::Oracle::getInstance().plotStatistics(sharedMemoryPropertiesFileName); #endif } void initDistributedMemory() { #ifdef Parallel #endif } void shutDistributedMemory() { #ifdef Parallel tarch::parallel::NodePool::getInstance().terminate(); dem::repositories::RepositoryFactory::getInstance().shutdownAllParallelDatatypes(); #endif } int dem::runners::Runner::run(int numberOfTimeSteps, Plot plot, dem::mappings::CreateGrid::GridType gridType, int tbbThreads, double stepSize, double realSnapshot, bool useAutotuning) { peano::geometry::Hexahedron geometry(tarch::la::Vector<DIMENSIONS,double>(1.0), tarch::la::Vector<DIMENSIONS,double>(0.0)); dem::repositories::Repository* repository = dem::repositories::RepositoryFactory::getInstance().createWithSTDStackImplementation(geometry, tarch::la::Vector<DIMENSIONS,double>(1.0), // domainSize tarch::la::Vector<DIMENSIONS,double>(0.0)); // computationalDomainOffset //initHPCEnvironment(); std::string sharedMemoryPropertiesFileName = initSharedMemory(tbbThreads, gridType, numberOfTimeSteps, stepSize, realSnapshot, useAutotuning); //initDistributedMemory(); int result = 0; if (tarch::parallel::Node::getInstance().isGlobalMaster()) { result = runAsMaster( *repository, numberOfTimeSteps, plot, gridType, stepSize, realSnapshot); } #ifdef Parallel else { result = runAsWorker(*repository); } #endif shutSharedMemory(sharedMemoryPropertiesFileName); shutDistributedMemory(); delete repository; return result; } int dem::runners::Runner::runAsMaster(dem::repositories::Repository& repository, int iterations, Plot plot, dem::mappings::CreateGrid::GridType gridType, double initialStepSize, double realSnapshot) { peano::utils::UserInterface::writeHeader(); delta::core::Delta(); dem::mappings::AdoptGrid::_refinementCoefficient = 1.8; dem::mappings::AdoptGrid::_coarsenCoefficient = 0.5; dem::mappings::ReluctantlyAdoptGrid::_coarsenCoefficientReluctant = 1.8; dem::mappings::ReluctantlyAdoptGrid::_refinementCoefficientReluctant = 0.5; logInfo( "runAsMaster(...)", "create grid" ); repository.switchToCreateGrid(); repository.iterate(); //do { repository.iterate(); } while ( !repository.getState().isGridStationary() ); if(gridType == dem::mappings::CreateGrid::GridType::AdaptiveGrid) { logInfo( "runAsMaster(...)", "adopt grid" ); } else if(gridType == dem::mappings::CreateGrid::GridType::ReluctantAdaptiveGrid) { logInfo( "runAsMaster(...)", "reluctantly adopt grid" ); } repository.switchToAdopt(); for(int i=0; i<10; i++) repository.iterate(); logInfo( "runAsMaster(...)", "pre-conditioning" ); repository.getState().setInitialTimeStepSize(1E-16); repository.getState().setMaximumVelocityApproach(0.1); repository.switchToMoveParticles(); for(int i=0; i<8; i++) repository.iterate(); repository.getState().clearAccumulatedData(); repository.getState().setInitialTimeStepSize(initialStepSize); for(int i=0; i<2; i++) repository.iterate(); ///////////////////////////////////////////////////////////////////// logInfo( "runAsMaster(...)", "start time stepping" ); repository.getState().clearAccumulatedData(); repository.getState().setInitialTimeStepSize(initialStepSize); double elapsed = 0.0; double timestamp = 0.0; int minRange = 0; int maxRange = 50000; if(plot == EveryIteration) { dem::mappings::Plot::_mini = 0; dem::mappings::Plot::_maxi = iterations; } else { dem::mappings::Plot::_mini = minRange; dem::mappings::Plot::_maxi = maxRange; } /* //////////////////PLOT TIME ZERO////////////////////////////////////////////////////// if((plot == EveryIteration) || (plot == Track) || (plot == UponChange && (repository.getState().getNumberOfContactPoints()>0 || !repository.getState().isGridStationary() || 0%50==0 || repository.getState().getNumberOfParticleReassignments()>0 )) || (plot == EveryBatch && 0%50 == 0) || ((plot == Adaptive && ((elapsed > realSnapshot) || (0 == 0))))) { timestamp = repository.getState().getTime(); repository.getState().setTimeStep(0); repository.switchToPlotData(); repository.iterate(); logInfo("runAsMaster(...)", "i=" << 0 << ", reassigns=" << repository.getState().getNumberOfParticleReassignments() << ", par-cmp=" << repository.getState().getNumberOfParticleComparisons() << ", tri-cmp=" << repository.getState().getNumberOfTriangleComparisons() << ", cnpt=" << repository.getState().getNumberOfContactPoints() << ", v=" << repository.getState().getNumberOfInnerVertices() << ", t=" << repository.getState().getTime() << ", dt=" << repository.getState().getTimeStepSize() << ", mvij=" << repository.getState().getMaximumVelocityApproach() << ", plot=" << 1); logInfo("runAsMaster(...)", "h_min(real)=" << repository.getState().getMinimumMeshWidth() << ", h_max(real)=" << repository.getState().getMaximumMeshWidth()); elapsed = repository.getState().getTime() - timestamp; repository.getState().finishedTimeStep(initialStepSize); } */ /////////////////////////////////////////////////////////////////////////////////////// for (int i=0; i<iterations; i++) { timestamp = repository.getState().getTime(); repository.getState().setTimeStep(i); bool plotThisTraversal = (plot == EveryIteration) || (plot == Track) || (plot == UponChange && (repository.getState().getNumberOfContactPoints()>0 || !repository.getState().isGridStationary() || i%50==0 || repository.getState().getNumberOfParticleReassignments()>0 )) || (plot == EveryBatch && i%50 == 0) || ((plot == Adaptive && ((elapsed > realSnapshot) || (i == 0)))) || (plot == Range && ((i >= minRange) && (i < maxRange))); if(plotThisTraversal) { //delta::sys::Sys::saveIteration(repository.getState().getTimeStepSize(), i, iterations); if (gridType==mappings::CreateGrid::AdaptiveGrid) { repository.switchToTimeStepAndPlotOnDynamicGrid(); } else if (gridType==mappings::CreateGrid::ReluctantAdaptiveGrid) { repository.switchToTimeStepAndPlotOnReluctantDynamicGrid(); } else { repository.switchToTimeStepAndPlot(); } } else { if (gridType==mappings::CreateGrid::AdaptiveGrid) { repository.switchToTimeStepOnDynamicGridMerged(); } else if (gridType==mappings::CreateGrid::ReluctantAdaptiveGrid) { repository.switchToTimeStepOnReluctantDynamicGridMerged(); } else { repository.switchToTimeStep(); } } repository.iterate(); elapsed = repository.getState().getTime() - timestamp; logInfo("runAsMaster(...)", "i=" << i << ", reassigns=" << repository.getState().getNumberOfParticleReassignments() << ", par-cmp=" << repository.getState().getNumberOfParticleComparisons() << ", tri-cmp=" << repository.getState().getNumberOfTriangleComparisons() << ", cnpt=" << repository.getState().getNumberOfContactPoints() << ", v=" << repository.getState().getNumberOfInnerVertices() << ", t=" << repository.getState().getTime() << ", dt=" << repository.getState().getTimeStepSize() << ", mvij=" << repository.getState().getMaximumVelocityApproach() << ", plot=" << plotThisTraversal); logInfo("runAsMaster(...)", "h_min(real)=" << repository.getState().getMinimumMeshWidth() << ", h_max(real)=" << repository.getState().getMaximumMeshWidth()); repository.getState().finishedTimeStep(initialStepSize); repository.getState().clearAccumulatedData(); } repository.logIterationStatistics(false); repository.terminate(); return 0; } <|endoftext|>
<commit_before>#include "functions.h" static void initialize() { static bool initialized = false; if (!initialized) { pg_query_init(); initialized = true; } } NAN_METHOD(parse) { initialize(); if (info.Length() < 1) { return Nan::ThrowError("query parameter must be provided"); } Nan::Utf8String query(info[0]); if (!*query) { return Nan::ThrowError("query parameter must be a string"); } auto result = pg_query_parse(*query); v8::Local<v8::Object> hash = Nan::New<v8::Object>(); if (result.error) { auto error = Nan::New<v8::Object>(); auto message = Nan::New(result.error->message).ToLocalChecked(); auto fileName = Nan::New(result.error->filename).ToLocalChecked(); auto lineNumber = Nan::New(result.error->lineno); auto cursorPosition = Nan::New(result.error->cursorpos); Nan::Set(error, Nan::New("message").ToLocalChecked(), message); Nan::Set(error, Nan::New("fileName").ToLocalChecked(), fileName); Nan::Set(error, Nan::New("lineNumber").ToLocalChecked(), lineNumber); Nan::Set(error, Nan::New("cursorPosition").ToLocalChecked(), cursorPosition); Nan::Set(hash, Nan::New("error").ToLocalChecked(), error); } if (result.parse_tree) { Nan::Set(hash, Nan::New("query").ToLocalChecked(), Nan::New(result.parse_tree).ToLocalChecked()); } if (result.stderr_buffer) { Nan::Set(hash, Nan::New("stderr").ToLocalChecked(), Nan::New(result.stderr_buffer).ToLocalChecked()); } pg_query_parse_free(result); info.GetReturnValue().Set(hash); } <commit_msg>Remove auto usage again.<commit_after>#include "functions.h" static void initialize() { static bool initialized = false; if (!initialized) { pg_query_init(); initialized = true; } } NAN_METHOD(parse) { initialize(); if (info.Length() < 1) { return Nan::ThrowError("query parameter must be provided"); } Nan::Utf8String query(info[0]); if (!*query) { return Nan::ThrowError("query parameter must be a string"); } PgQueryParseResult result = pg_query_parse(*query); v8::Local<v8::Object> hash = Nan::New<v8::Object>(); if (result.error) { v8::Local<v8::Object> error = Nan::New<v8::Object>(); v8::Local<v8::String> message = Nan::New(result.error->message).ToLocalChecked(); v8::Local<v8::String> fileName = Nan::New(result.error->filename).ToLocalChecked(); v8::Local<v8::Number> lineNumber = Nan::New(result.error->lineno); v8::Local<v8::Number> cursorPosition = Nan::New(result.error->cursorpos); Nan::Set(error, Nan::New("message").ToLocalChecked(), message); Nan::Set(error, Nan::New("fileName").ToLocalChecked(), fileName); Nan::Set(error, Nan::New("lineNumber").ToLocalChecked(), lineNumber); Nan::Set(error, Nan::New("cursorPosition").ToLocalChecked(), cursorPosition); Nan::Set(hash, Nan::New("error").ToLocalChecked(), error); } if (result.parse_tree) { Nan::Set(hash, Nan::New("query").ToLocalChecked(), Nan::New(result.parse_tree).ToLocalChecked()); } if (result.stderr_buffer) { Nan::Set(hash, Nan::New("stderr").ToLocalChecked(), Nan::New(result.stderr_buffer).ToLocalChecked()); } pg_query_parse_free(result); info.GetReturnValue().Set(hash); } <|endoftext|>
<commit_before>/** * @copyright Copyright (c) 2014, J-PET collaboration * @file JPetManager.cpp * @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl */ #include "./JPetManager.h" #include <cassert> #include <ctime> #include <string> #include <TDSet.h> #include <TThread.h> #include "../JPetCmdParser/JPetCmdParser.h" #include "../../JPetLoggerInclude.h" #include "../CommonTools/CommonTools.h" JPetManager& JPetManager::getManager() { static JPetManager instance; return instance; } void JPetManager::run() { INFO( "======== Starting processing all tasks: " + CommonTools::getTimeString() + " ========\n" ); std::vector<JPetAnalysisRunner*> runners; std::vector<TThread*> threads; //int numberOfFiles = getFullInputFileNames().size(); int i = 0; for (auto opt: fOptions) { JPetAnalysisRunner* runner = new JPetAnalysisRunner(ftaskGeneratorChain, i, opt); runners.push_back(runner); auto thr = runner->run(); if (thr) { threads.push_back(thr); } else { ERROR("thread pointer is null"); } i++; } for (auto thread : threads) { thread->Join(); } for (auto runner : runners) { delete runner; } INFO( "======== Finished processing all tasks: " + CommonTools::getTimeString() + " ========\n" ); } void JPetManager::parseCmdLine(int argc, char** argv) { JPetCmdParser parser; fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv); } JPetManager::~JPetManager() { } void JPetManager::addTaskGeneratorChain(TaskGeneratorChain* taskGeneratorChain) { ftaskGeneratorChain = taskGeneratorChain; } <commit_msg>Remove more commented code from JPetManager<commit_after>/** * @copyright Copyright (c) 2014, J-PET collaboration * @file JPetManager.cpp * @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl */ #include "./JPetManager.h" #include <cassert> #include <ctime> #include <string> #include <TDSet.h> #include <TThread.h> #include "../JPetCmdParser/JPetCmdParser.h" #include "../../JPetLoggerInclude.h" #include "../CommonTools/CommonTools.h" JPetManager& JPetManager::getManager() { static JPetManager instance; return instance; } void JPetManager::run() { INFO( "======== Starting processing all tasks: " + CommonTools::getTimeString() + " ========\n" ); std::vector<JPetAnalysisRunner*> runners; std::vector<TThread*> threads; int i = 0; for (auto opt: fOptions) { JPetAnalysisRunner* runner = new JPetAnalysisRunner(ftaskGeneratorChain, i, opt); runners.push_back(runner); auto thr = runner->run(); if (thr) { threads.push_back(thr); } else { ERROR("thread pointer is null"); } i++; } for (auto thread : threads) { thread->Join(); } for (auto runner : runners) { delete runner; } INFO( "======== Finished processing all tasks: " + CommonTools::getTimeString() + " ========\n" ); } void JPetManager::parseCmdLine(int argc, char** argv) { JPetCmdParser parser; fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv); } JPetManager::~JPetManager() { } void JPetManager::addTaskGeneratorChain(TaskGeneratorChain* taskGeneratorChain) { ftaskGeneratorChain = taskGeneratorChain; } <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_desktop_capturer.h" #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(OS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #endif // defined(OS_WIN) namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if defined(OS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // defined(OS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_WINDOW, content::desktop_capture::CreateWindowCapturer()); window_capturer_->SetThumbnailSize(thumbnail_size); window_capturer_->AddObserver(this); window_capturer_->Update(base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get())); } if (capture_screen) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_SCREEN, content::desktop_capture::CreateScreenCapturer()); screen_capturer_->SetThumbnailSize(thumbnail_size); screen_capturer_->AddObserver(this); screen_capturer_->Update(base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get())); } } } void DesktopCapturer::OnSourceUnchanged(DesktopMediaList* list) { UpdateSourcesList(list); } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == content::DesktopMediaID::TYPE_WINDOW) { capture_window_ = false; const auto& media_list_sources = list->GetSources(); std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(media_list_sources.size()); for (const auto& media_list_source : media_list_sources) { window_sources.emplace_back(DesktopCapturer::Source{ media_list_source, std::string(), fetch_window_icons_}); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == content::DesktopMediaID::TYPE_SCREEN) { capture_screen_ = false; const auto& media_list_sources = list->GetSources(); std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(media_list_sources.size()); for (const auto& media_list_source : media_list_sources) { screen_sources.emplace_back( DesktopCapturer::Source{media_list_source, std::string()}); } #if defined(OS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif defined(OS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #endif // defined(OS_WIN) // TODO(ajmacd): Add Linux support. The IDs across APIs differ but Chrome // only supports capturing the entire desktop on Linux. Revisit this if // individual screen support is added. std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); } } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { return gin::CreateHandle(isolate, new DesktopCapturer(isolate)); } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace api } // namespace electron namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize) <commit_msg>refactor: DesktopMediaList::Type replaces content::DesktopMediaType_*<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_desktop_capturer.h" #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(OS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #endif // defined(OS_WIN) namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if defined(OS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // defined(OS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, content::desktop_capture::CreateWindowCapturer()); window_capturer_->SetThumbnailSize(thumbnail_size); window_capturer_->AddObserver(this); window_capturer_->Update(base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get())); } if (capture_screen) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, content::desktop_capture::CreateScreenCapturer()); screen_capturer_->SetThumbnailSize(thumbnail_size); screen_capturer_->AddObserver(this); screen_capturer_->Update(base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get())); } } } void DesktopCapturer::OnSourceUnchanged(DesktopMediaList* list) { UpdateSourcesList(list); } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; const auto& media_list_sources = list->GetSources(); std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(media_list_sources.size()); for (const auto& media_list_source : media_list_sources) { window_sources.emplace_back(DesktopCapturer::Source{ media_list_source, std::string(), fetch_window_icons_}); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; const auto& media_list_sources = list->GetSources(); std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(media_list_sources.size()); for (const auto& media_list_source : media_list_sources) { screen_sources.emplace_back( DesktopCapturer::Source{media_list_source, std::string()}); } #if defined(OS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif defined(OS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #endif // defined(OS_WIN) // TODO(ajmacd): Add Linux support. The IDs across APIs differ but Chrome // only supports capturing the entire desktop on Linux. Revisit this if // individual screen support is added. std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); } } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { return gin::CreateHandle(isolate, new DesktopCapturer(isolate)); } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace api } // namespace electron namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize) <|endoftext|>
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; const int IP_HEADR_OFFSET = 14; const int IP_HEADER_SIZE = 20; const int UDP_HEADER_OFFSET = 34; const int UDP_HEADER_SIZE = 8; const int UDP_DATA_OFFSET = 42; ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP <commit_msg>Update prototype2/tools/ReaderPcap.cpp<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; const int IP_HEADR_OFFSET = 14; const int IP_HEADER_SIZE = 20; const int UDP_HEADER_OFFSET = 34; const int UDP_HEADER_SIZE = 8; const int UDP_DATA_OFFSET = 42; ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == nullptr) { return -1; } return 0; } int ReaderPcap::validatePacket(pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP <|endoftext|>
<commit_before>#ifndef st_partition_hpp #define st_partition_hpp #include <set> #include <vector> #include "partition_wall.hpp" namespace SorterThreadedHelper { class Partition { public: Partition(const std::set<double>& pivots, const std::vector<double>::iterator chunkBegin, const std::vector<double>::iterator chunkEnd); void fillPartition(); //single threaded private: const std::vector<double>::iterator chunkBegin_; const std::vector<double>::iterator chunkEnd_; std::set<double> pivots_; std::map<double,std::stack<double>> partition_; }; } #endif <commit_msg>map to pointers<commit_after>#ifndef st_partition_hpp #define st_partition_hpp #include <set> #include <vector> #include "partition_wall.hpp" namespace SorterThreadedHelper { class Partition { public: Partition(const std::set<double>& pivots, const std::vector<double>::iterator chunkBegin, const std::vector<double>::iterator chunkEnd); void fillPartition(); //single threaded private: const std::vector<double>::iterator chunkBegin_; const std::vector<double>::iterator chunkEnd_; std::set<double> pivots_; std::map<double,std::stack<double>*> partition_; }; } #endif <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { /// Generate framebuffer object glGenFramebuffers(1, &mFB); GL_CHECK_ERROR; mNumSamples = 0; mMultisampleFB = 0; // Check multisampling if supported #if GL_APPLE_framebuffer_multisample // Check samples supported glBindFramebuffer(GL_FRAMEBUFFER, mFB); GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples); glBindFramebuffer(GL_FRAMEBUFFER, 0); mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); #endif // Will we need a second FBO to do multisampling? if (mNumSamples) { glGenFramebuffers(1, &mMultisampleFB); } /// Initialise state mDepth.buffer=0; mStencil.buffer=0; for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); /// Delete framebuffer object glDeleteFramebuffers(1, &mFB); GL_CHECK_ERROR; if (mMultisampleFB) glDeleteFramebuffers(1, &mMultisampleFB); GL_CHECK_ERROR; } void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); /// First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil /// Store basic stats size_t width = mColour[0].buffer->getWidth(); size_t height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); // Bind simple buffer to add colour attachments glBindFramebuffer(GL_FRAMEBUFFER, mFB); GL_CHECK_ERROR; /// Bind all attachment points to frame buffer for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+x, GL_RENDERBUFFER, 0); } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB); GL_CHECK_ERROR; // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } /// Depth buffer is not handled here anymore. /// See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } /// Check status GLuint status; status = glCheckFramebufferStatus(GL_FRAMEBUFFER); GL_CHECK_ERROR; /// Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iPhone glBindFramebuffer(GL_FRAMEBUFFER, 1); #else glBindFramebuffer(GL_FRAMEBUFFER, 0); #endif GL_CHECK_ERROR; switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { /// Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; glBindFramebuffer(GL_FRAMEBUFFER, fb); GL_CHECK_ERROR; } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if GL_APPLE_framebuffer_multisample // Blit from multisample buffer to final buffer, triggers resolve // size_t width = mColour[0].buffer->getWidth(); // size_t height = mColour[0].buffer->getHeight(); glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, mMultisampleFB); glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, mFB); // glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ); GL_CHECK_ERROR; if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); // Truly attach depth buffer depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); // Truly attach stencil buffer, if it has one and isn't included w/ the depth buffer if( depthBuf != stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); else { glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; } } else { glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 ); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 ); GL_CHECK_ERROR; } size_t GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } size_t GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <commit_msg>GLES2: Some systems may not support up to OGRE_MAX_MULTIPLE_RENDER_TARGETS(8) for FBOs. So use the number reported in capabilities instead.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" #include "OgreRoot.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { /// Generate framebuffer object glGenFramebuffers(1, &mFB); GL_CHECK_ERROR; mNumSamples = 0; mMultisampleFB = 0; // Check multisampling if supported #if GL_APPLE_framebuffer_multisample // Check samples supported glBindFramebuffer(GL_FRAMEBUFFER, mFB); GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples); glBindFramebuffer(GL_FRAMEBUFFER, 0); mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); #endif // Will we need a second FBO to do multisampling? if (mNumSamples) { glGenFramebuffers(1, &mMultisampleFB); } /// Initialise state mDepth.buffer=0; mStencil.buffer=0; for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); /// Delete framebuffer object glDeleteFramebuffers(1, &mFB); GL_CHECK_ERROR; if (mMultisampleFB) glDeleteFramebuffers(1, &mMultisampleFB); GL_CHECK_ERROR; } void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); /// First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); /// Store basic stats size_t width = mColour[0].buffer->getWidth(); size_t height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); // Bind simple buffer to add colour attachments glBindFramebuffer(GL_FRAMEBUFFER, mFB); GL_CHECK_ERROR; /// Bind all attachment points to frame buffer for(size_t x=0; x<maxSupportedMRTs; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+x, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB); GL_CHECK_ERROR; // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } GL_CHECK_ERROR; /// Depth buffer is not handled here anymore. /// See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(size_t x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } /// Check status GLuint status; status = glCheckFramebufferStatus(GL_FRAMEBUFFER); GL_CHECK_ERROR; /// Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iPhone glBindFramebuffer(GL_FRAMEBUFFER, 1); #else glBindFramebuffer(GL_FRAMEBUFFER, 0); #endif GL_CHECK_ERROR; switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { /// Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; glBindFramebuffer(GL_FRAMEBUFFER, fb); GL_CHECK_ERROR; } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if GL_APPLE_framebuffer_multisample // Blit from multisample buffer to final buffer, triggers resolve // size_t width = mColour[0].buffer->getWidth(); // size_t height = mColour[0].buffer->getHeight(); glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, mMultisampleFB); glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, mFB); // glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ); GL_CHECK_ERROR; if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); // Truly attach depth buffer depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); // Truly attach stencil buffer, if it has one and isn't included w/ the depth buffer if( depthBuf != stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); else { glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; } } else { glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); GL_CHECK_ERROR; } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 ); GL_CHECK_ERROR; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 ); GL_CHECK_ERROR; } size_t GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } size_t GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "mk_thread.h" #include "mk_tcp_private.h" #include "Util/logger.h" #include "Poller/EventPoller.h" using namespace std; using namespace toolkit; API_EXPORT mk_thread API_CALL mk_thread_from_tcp_session(mk_tcp_session ctx){ assert(ctx); TcpSessionForC *obj = (TcpSessionForC *)ctx; return obj->getPoller().get(); } API_EXPORT mk_thread API_CALL mk_thread_from_tcp_client(mk_tcp_client ctx){ assert(ctx); TcpClientForC::Ptr *client = (TcpClientForC::Ptr *)ctx; return (*client)->getPoller().get(); } API_EXPORT void API_CALL mk_async_do(mk_thread ctx,on_mk_async cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; poller->async([cb,user_data](){ cb(user_data); }); } API_EXPORT void API_CALL mk_sync_do(mk_thread ctx,on_mk_async cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; poller->sync([cb,user_data](){ cb(user_data); }); } class TimerForC : public std::enable_shared_from_this<TimerForC>{ public: typedef std::shared_ptr<TimerForC> Ptr; TimerForC(on_mk_timer cb, void *user_data){ _cb = cb; _user_data = user_data; } ~TimerForC(){} uint64_t operator()(){ lock_guard<recursive_mutex> lck(_mxt); if(!_cb){ return 0; } return _cb(_user_data); } void cancel(){ lock_guard<recursive_mutex> lck(_mxt); _cb = nullptr; _task->cancel(); } void start(int ms ,EventPoller &poller){ weak_ptr<TimerForC> weak_self = shared_from_this(); poller.doDelayTask(ms, [weak_self](){ auto strong_self = weak_self.lock(); if(!strong_self){ return (uint64_t)0; } return (*strong_self)(); }); } private: on_mk_timer _cb = nullptr; void *_user_data = nullptr; recursive_mutex _mxt; DelayTask::Ptr _task; }; API_EXPORT mk_timer API_CALL mk_timer_create(mk_thread ctx,uint64_t delay_ms,on_mk_timer cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; TimerForC::Ptr *ret = new TimerForC::Ptr(new TimerForC(cb, user_data)); (*ret)->start(delay_ms,*poller); return ret; } API_EXPORT void API_CALL mk_timer_release(mk_timer ctx){ assert(ctx); TimerForC::Ptr *obj = (TimerForC::Ptr *)ctx; (*obj)->cancel(); delete obj; }<commit_msg>确保能同步取消定时器<commit_after>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "mk_thread.h" #include "mk_tcp_private.h" #include "Util/logger.h" #include "Poller/EventPoller.h" using namespace std; using namespace toolkit; API_EXPORT mk_thread API_CALL mk_thread_from_tcp_session(mk_tcp_session ctx){ assert(ctx); TcpSessionForC *obj = (TcpSessionForC *)ctx; return obj->getPoller().get(); } API_EXPORT mk_thread API_CALL mk_thread_from_tcp_client(mk_tcp_client ctx){ assert(ctx); TcpClientForC::Ptr *client = (TcpClientForC::Ptr *)ctx; return (*client)->getPoller().get(); } API_EXPORT void API_CALL mk_async_do(mk_thread ctx,on_mk_async cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; poller->async([cb,user_data](){ cb(user_data); }); } API_EXPORT void API_CALL mk_sync_do(mk_thread ctx,on_mk_async cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; poller->sync([cb,user_data](){ cb(user_data); }); } class TimerForC : public std::enable_shared_from_this<TimerForC>{ public: typedef std::shared_ptr<TimerForC> Ptr; TimerForC(on_mk_timer cb, void *user_data){ _cb = cb; _user_data = user_data; } ~TimerForC(){} uint64_t operator()(){ lock_guard<recursive_mutex> lck(_mxt); if(!_cb){ return 0; } return _cb(_user_data); } void cancel(){ lock_guard<recursive_mutex> lck(_mxt); _cb = nullptr; _task->cancel(); } void start(int ms ,EventPoller &poller){ weak_ptr<TimerForC> weak_self = shared_from_this(); _task = poller.doDelayTask(ms, [weak_self]() { auto strong_self = weak_self.lock(); if (!strong_self) { return (uint64_t) 0; } return (*strong_self)(); }); } private: on_mk_timer _cb = nullptr; void *_user_data = nullptr; recursive_mutex _mxt; DelayTask::Ptr _task; }; API_EXPORT mk_timer API_CALL mk_timer_create(mk_thread ctx,uint64_t delay_ms,on_mk_timer cb, void *user_data){ assert(ctx && cb); EventPoller *poller = (EventPoller *)ctx; TimerForC::Ptr *ret = new TimerForC::Ptr(new TimerForC(cb, user_data)); (*ret)->start(delay_ms,*poller); return ret; } API_EXPORT void API_CALL mk_timer_release(mk_timer ctx){ assert(ctx); TimerForC::Ptr *obj = (TimerForC::Ptr *)ctx; (*obj)->cancel(); delete obj; }<|endoftext|>
<commit_before>// Copyright 2012 Luis Pedro Coelho // This is an implementation of TIFF LZW compression coded from the spec. // License: MIT #include <vector> struct code_stream { public: code_stream(unsigned char* buf, unsigned long len) :buf_(buf) ,byte_pos_(0) ,bit_pos_(0) ,len_(len) { } unsigned short getbit() { unsigned char val = buf_[byte_pos_]; unsigned short res = (val & (1 << (8-bit_pos_))); ++bit_pos_; if (bit_pos_ == 8) { bit_pos_ = 0; ++byte_pos_; if (byte_pos_ > len_) { throw "overboard"; } } return res; } unsigned short get(int nbits) { unsigned short res = 0; for (int i = 0; i != nbits; ++i) { res <<= 1; res |= getbit(); } return res; } private: const unsigned char* buf_; int byte_pos_; int bit_pos_; const int len_; }; std::string table_at(const std::vector<std::string> table, unsigned short index) { if (index < 256) { std::string res = "0"; res[0] = (char)index; return res; } return table.at(index - 258); } void write_string(std::vector<unsigned char>& output, std::string s) { output.insert(output.end(), s.begin(), s.end()); } std::vector<unsigned char> lzw_decode(void* buf, unsigned long len) { std::vector<std::string> table; std::vector<unsigned char> output; code_stream st(static_cast<unsigned char*>(buf), len); int nbits = 9; unsigned short old_code = 0; const short ClearCode = 256; const short EoiCode = 257; while (true) { const short code = st.get(nbits); if (code == EoiCode) break; if (code == ClearCode) { table.clear(); nbits = 9; const short next_code = st.get(nbits); if (next_code == EoiCode) break; write_string(output, table[next_code]); old_code = next_code; } else if (code < 256 || (code - 258) < table.size()) { write_string(output, table_at(table,code)); table.push_back( table_at(table,old_code) + table_at(table,code)[0] ); old_code = code; } else { std::string out_string = table_at(table, old_code) + table_at(table, old_code)[0]; write_string(output, out_string); table.push_back(out_string); if (table.size() == ( 512-258)) nbits = 10; if (table.size() == (1024-258)) nbits = 11; if (table.size() == (2048-258)) nbits = 12; old_code = code; } } return output; } <commit_msg>MIN Better error message<commit_after>// Copyright 2012 Luis Pedro Coelho // This is an implementation of TIFF LZW compression coded from the spec. // License: MIT #include <vector> struct code_stream { public: code_stream(unsigned char* buf, unsigned long len) :buf_(buf) ,byte_pos_(0) ,bit_pos_(0) ,len_(len) { } unsigned short getbit() { unsigned char val = buf_[byte_pos_]; unsigned short res = (val & (1 << (8-bit_pos_))); ++bit_pos_; if (bit_pos_ == 8) { bit_pos_ = 0; ++byte_pos_; if (byte_pos_ > len_) { throw CannotReadError("Unexpected End of File"); } } return res; } unsigned short get(int nbits) { unsigned short res = 0; for (int i = 0; i != nbits; ++i) { res <<= 1; res |= getbit(); } return res; } private: const unsigned char* buf_; int byte_pos_; int bit_pos_; const int len_; }; std::string table_at(const std::vector<std::string> table, unsigned short index) { if (index < 256) { std::string res = "0"; res[0] = (char)index; return res; } return table.at(index - 258); } void write_string(std::vector<unsigned char>& output, std::string s) { output.insert(output.end(), s.begin(), s.end()); } std::vector<unsigned char> lzw_decode(void* buf, unsigned long len) { std::vector<std::string> table; std::vector<unsigned char> output; code_stream st(static_cast<unsigned char*>(buf), len); int nbits = 9; unsigned short old_code = 0; const short ClearCode = 256; const short EoiCode = 257; while (true) { const short code = st.get(nbits); if (code == EoiCode) break; if (code == ClearCode) { table.clear(); nbits = 9; const short next_code = st.get(nbits); if (next_code == EoiCode) break; write_string(output, table[next_code]); old_code = next_code; } else if (code < 256 || (code - 258) < table.size()) { write_string(output, table_at(table,code)); table.push_back( table_at(table,old_code) + table_at(table,code)[0] ); old_code = code; } else { std::string out_string = table_at(table, old_code) + table_at(table, old_code)[0]; write_string(output, out_string); table.push_back(out_string); if (table.size() == ( 512-258)) nbits = 10; if (table.size() == (1024-258)) nbits = 11; if (table.size() == (2048-258)) nbits = 12; old_code = code; } } return output; } <|endoftext|>
<commit_before>#include "kernel.h" #include "ilwisdata.h" #include "coverage.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "commandhandler.h" #include "operation.h" #include "mastercatalog.h" #include "uicontextmodel.h" #include "drawers/draweroperation.h" #include "drawers/drawerfactory.h" #include "models/visualizationmanager.h" #include "drawers/drawerinterface.h" #include "../layerdrawer.h" #include "removedrawer.h" #include "../rootdrawer.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_OPERATION(RemoveDrawer) RemoveDrawer::RemoveDrawer() { } RemoveDrawer::~RemoveDrawer() { } RemoveDrawer::RemoveDrawer(quint64 metaid, const Ilwis::OperationExpression &expr) : DrawerOperation(metaid, expr) { } bool RemoveDrawer::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx,symTable)) != sPREPARED) return false; RootDrawer *rootdrawer = static_cast<RootDrawer *>(_rootDrawer); if ( _drawerOrder == iUNDEF) rootdrawer->removeDrawer(_drawercode,true); else rootdrawer->removeDrawer(_drawerOrder,_drawerType); return true; } Ilwis::OperationImplementation *RemoveDrawer::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new RemoveDrawer(metaid, expr); } Ilwis::OperationImplementation::State RemoveDrawer::prepare(ExecutionContext *ctx, const SymbolTable &) { auto iter = ctx->_additionalInfo.find("rootdrawer"); if ( iter == ctx->_additionalInfo.end()) return sPREPAREFAILED; _rootDrawer = (DrawerInterface *) (*iter).second.value<void *>(); bool ok; _viewid = _expression.parm(0).value().toULongLong(&ok); if ( !ok){ ERROR3(ERR_ILLEGAL_PARM_3,"view id", _expression.parm(0).value(), _expression.toString()); return sPREPAREFAILED; } _drawerOrder = _expression.input<quint32>(1,ok); if ( !ok){ _drawercode = _expression.input<QString>(1); _drawerOrder = iUNDEF; } QString drwtype = _expression.input<QString>(2).toLower(); _drawerType = DrawerInterface::dtDONTCARE; if ( drwtype == "pre"){ _drawerType = DrawerInterface::dtPRE; } else if ( drwtype == "main"){ _drawerType = DrawerInterface::dtMAIN; } if ( drwtype == "post"){ _drawerType = DrawerInterface::dtPOST; } return sPREPARED; } quint64 RemoveDrawer::createMetadata() { OperationResource operation({"ilwis://operations/removedrawer"}); operation.setSyntax("removedrawer(viewid, drawercode)"); operation.setDescription(TR("changes the view extent")); operation.setInParameterCount({3}); operation.addInParameter(0,itINTEGER , TR("view id"),TR("id of the view to which this drawer has to be added")); operation.addInParameter(1,itSTRING , TR("Drawer code "), TR("unique code identifying the drawer")); operation.addInParameter(2,itSTRING , TR("Drawer type "), TR("pre, main or post drawer")); operation.setOutParameterCount({0}); operation.setKeywords("visualization"); mastercatalog()->addItems({operation}); return operation.id(); } <commit_msg>renamed include file<commit_after>#include "kernel.h" #include "ilwisdata.h" #include "coverage.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "commandhandler.h" #include "operation.h" #include "mastercatalog.h" #include "uicontextmodel.h" #include "drawers/draweroperation.h" #include "drawers/drawerfactory.h" #include "models/layermanager.h" #include "drawers/drawerinterface.h" #include "../layerdrawer.h" #include "removedrawer.h" #include "../rootdrawer.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_OPERATION(RemoveDrawer) RemoveDrawer::RemoveDrawer() { } RemoveDrawer::~RemoveDrawer() { } RemoveDrawer::RemoveDrawer(quint64 metaid, const Ilwis::OperationExpression &expr) : DrawerOperation(metaid, expr) { } bool RemoveDrawer::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx,symTable)) != sPREPARED) return false; RootDrawer *rootdrawer = static_cast<RootDrawer *>(_rootDrawer); if ( _drawerOrder == iUNDEF) rootdrawer->removeDrawer(_drawercode,true); else rootdrawer->removeDrawer(_drawerOrder,_drawerType); return true; } Ilwis::OperationImplementation *RemoveDrawer::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new RemoveDrawer(metaid, expr); } Ilwis::OperationImplementation::State RemoveDrawer::prepare(ExecutionContext *ctx, const SymbolTable &) { auto iter = ctx->_additionalInfo.find("rootdrawer"); if ( iter == ctx->_additionalInfo.end()) return sPREPAREFAILED; _rootDrawer = (DrawerInterface *) (*iter).second.value<void *>(); bool ok; _viewid = _expression.parm(0).value().toULongLong(&ok); if ( !ok){ ERROR3(ERR_ILLEGAL_PARM_3,"view id", _expression.parm(0).value(), _expression.toString()); return sPREPAREFAILED; } _drawerOrder = _expression.input<quint32>(1,ok); if ( !ok){ _drawercode = _expression.input<QString>(1); _drawerOrder = iUNDEF; } QString drwtype = _expression.input<QString>(2).toLower(); _drawerType = DrawerInterface::dtDONTCARE; if ( drwtype == "pre"){ _drawerType = DrawerInterface::dtPRE; } else if ( drwtype == "main"){ _drawerType = DrawerInterface::dtMAIN; } if ( drwtype == "post"){ _drawerType = DrawerInterface::dtPOST; } return sPREPARED; } quint64 RemoveDrawer::createMetadata() { OperationResource operation({"ilwis://operations/removedrawer"}); operation.setSyntax("removedrawer(viewid, drawercode)"); operation.setDescription(TR("changes the view extent")); operation.setInParameterCount({3}); operation.addInParameter(0,itINTEGER , TR("view id"),TR("id of the view to which this drawer has to be added")); operation.addInParameter(1,itSTRING , TR("Drawer code "), TR("unique code identifying the drawer")); operation.addInParameter(2,itSTRING , TR("Drawer type "), TR("pre, main or post drawer")); operation.setOutParameterCount({0}); operation.setKeywords("visualization"); mastercatalog()->addItems({operation}); return operation.id(); } <|endoftext|>
<commit_before>#include "common.th" #include "serial.th" #define CHANNEL "#tenyr" #define NICK "rynet" #define do(X) c <- rel(X) ; call(puts) ; c <- rel(rn) ; call(puts) _start: prologue do(nick) do(user) do(join) loop_line: call(getline) // use g as backing store for line ; c is stompable as arg g <- b c <- g d <- rel(ping) e <- 4 call(strncmp) jzrel(b,do_pong) c <- g d <- 1 call(skipwords) c <- b d <- rel(privmsg) e <- 7 call(strncmp) jnzrel(b,loop_line) c <- g d <- 3 call(skipwords) c <- b + 1 call(check_input) goto(loop_line) illegal do_pong: c <- rel(pong) call(puts) c <- g d <- 1 call(skipwords) c <- b call(puts) // respond with same identifier c <- rel(rn) call(puts) goto(loop_line) check_input: pushall(d,e) push(c) d <- rel(trigger) e <- 3 // strlen(trigger) call(strncmp) pop(c) jzrel(b,check_input_triggered) goto(check_input_done) check_input_triggered: c <- c + 3 call(parse_int) c <- b + 40 c <- c * 9 d <- 5 call(udiv) c <- b - 40 call(say_fahrenheit) check_input_done: popall(d,e) ret ping: .utf32 "PING" ; .word 0 pong: .utf32 "PONG " ; .word 0 // c <- address of first character of number parse_int: pushall(d,e,f) b <- 0 d <- [c] e <- d == '-' jnzrel(e,parse_int_negative) f <- 1 parse_int_top: d <- [c] c <- c + 1 d <- d - '0' e <- d > 9 jnzrel(e,parse_int_done) e <- d < 0 jnzrel(e,parse_int_done) b <- b * 10 + d goto(parse_int_top) parse_int_done: b <- b * f popall(d,e,f) ret parse_int_negative: f <- -1 c <- c + 1 goto(parse_int_top) say_hex: call(say_start) push(c) c <- rel(zero_x) call(puts) pop(c) call(convert_hex) c <- b call(puts) call(say_end) ret zero_x: .utf32 "0x" ; .word 0 convert_hex: b <- rel(tmpbuf_end) convert_hex_top: b <- b - 1 d <- c & 0xf d <- [d + rel(hexes)] d -> [b] c <- c >> 4 d <- c == 0 jzrel(d,convert_hex_top) ret hexes: .word '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' tmpbuf: .utf32 "0123456789abcdef" tmpbuf_end: .word 0 say_decimal: call(say_start) call(convert_decimal) c <- b call(puts) call(say_end) ret say_fahrenheit: call(say_start) call(convert_decimal) c <- b call(puts) c <- rel(degF) call(puts) call(say_end) ret degF: .utf32 "°F" ; .word 0 convert_decimal: b <- rel(tmpbuf_end) d <- c < 0 jnzrel(d,convert_decimal_negative) f <- 0 convert_decimal_top: push(f) b <- b - 1 push(b) push(c) d <- 10 call(umod) pop(c) d <- [b + rel(hexes)] pop(b) d -> [b] push(b) push(c) d <- 10 call(udiv) pop(c) c <- b pop(b) d <- c == 0 pop(f) jzrel(d,convert_decimal_top) jzrel(f,convert_decimal_done) b <- b - 1 [b] <- '-' convert_decimal_done: ret convert_decimal_negative: c <- - c f <- -1 goto(convert_decimal_top) say: call(say_start) call(puts) call(say_end) ret say_start: push(c) c <- rel(talk) call(puts) pop(c) ret say_end: push(c) c <- rel(rn) call(puts) pop(c) ret skipwords: pushall(e,g) skipwords_top: g <- [c] e <- g == 0 jnzrel(e,skipwords_done) e <- g == ' ' c <- c + 1 jnzrel(e,skipwords_foundspace) goto(skipwords_top) skipwords_foundspace: d <- d - 1 e <- d < 1 jzrel(e,skipwords_top) skipwords_done: b <- c popall(e,g) ret // :usermask PRIVMSG #channel :message getline: g <- rel(buffer) f <- g getline_top: getch(b) c <- b == '\r' d <- b == '\n' c <- c | d jnzrel(c,getline_eol) b -> [f] f <- f + 1 goto(getline_top) getline_eol: a -> [f] b <- g ret sleep: c <- c * 2047 c <- c * 2047 sleep_loop: c <- c - 1 d <- c == 0 jnzrel(d,sleep_done) goto(sleep_loop) sleep_done: ret // ---------------------------------------------------------------------------- buffer: // 512 chars .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" nick: .utf32 "NICK " NICK ; .word 0 user: .utf32 "USER " NICK " 0 * :get your own bot" ; .word 0 join: .utf32 "JOIN " CHANNEL ; .word 0 talk: .utf32 "PRIVMSG " CHANNEL " :" ; .word 0 privmsg: .utf32 "PRIVMSG" ; .word 0 trigger: .utf32 "!f " ; .word 0 rn: .word '\r', '\n', 0 <commit_msg>New EABI saves lines in ircbot<commit_after>#include "common.th" #include "serial.th" #define CHANNEL "#tenyr" #define NICK "rynet" #define do(X) c <- rel(X) ; call(puts) ; c <- rel(rn) ; call(puts) _start: prologue do(nick) do(user) do(join) loop_line: call(getline) // use g as backing store for line ; c is stompable as arg g <- b c <- g d <- rel(ping) e <- 5 call(strncmp) jzrel(b,do_pong) c <- g d <- 1 call(skipwords) c <- b d <- rel(privmsg) e <- 7 call(strncmp) jnzrel(b,loop_line) c <- g d <- 3 call(skipwords) c <- b + 1 call(check_input) goto(loop_line) illegal do_pong: c <- rel(pong) call(puts) c <- g d <- 1 call(skipwords) c <- b call(puts) // respond with same identifier c <- rel(rn) call(puts) goto(loop_line) check_input: pushall(d,e) push(c) d <- rel(trigger) e <- 3 // strlen(trigger) call(strncmp) pop(c) jzrel(b,check_input_triggered) goto(check_input_done) check_input_triggered: c <- c + 3 call(parse_int) c <- b + 40 c <- c * 9 d <- 5 call(udiv) c <- b - 40 call(say_fahrenheit) check_input_done: popall(d,e) ret ping: .utf32 "PING " ; .word 0 pong: .utf32 "PONG " ; .word 0 // c <- address of first character of number parse_int: pushall(d,e,f) b <- 0 d <- [c] e <- d == '-' jnzrel(e,parse_int_negative) f <- 1 parse_int_top: d <- [c] c <- c + 1 d <- d - '0' e <- d > 9 jnzrel(e,parse_int_done) e <- d < 0 jnzrel(e,parse_int_done) b <- b * 10 + d goto(parse_int_top) parse_int_done: b <- b * f popall(d,e,f) ret parse_int_negative: f <- -1 c <- c + 1 goto(parse_int_top) tmpbuf: .utf32 "0123456789abcdef" tmpbuf_end: .word 0 say_decimal: call(say_start) call(convert_decimal) c <- b call(puts) call(say_end) ret say_fahrenheit: call(say_start) call(convert_decimal) c <- b call(puts) c <- rel(degF) call(puts) call(say_end) ret // TODO this is actually being encoded as UTF-8 degF: .utf32 "°F" ; .word 0 convert_decimal: pushall(d,f,g,h) g <- c h <- rel(tmpbuf_end) d <- c < 0 jnzrel(d,convert_decimal_negative) f <- 0 convert_decimal_top: h <- h - 1 c <- g d <- 10 call(umod) [h] <- b + '0' c <- g d <- 10 call(udiv) g <- b d <- g == 0 jzrel(d,convert_decimal_top) jzrel(f,convert_decimal_done) h <- h - 1 [h] <- '-' convert_decimal_done: b <- h popall(d,f,g,h) ret convert_decimal_negative: g <- - g f <- -1 goto(convert_decimal_top) say: call(say_start) call(puts) call(say_end) ret say_start: push(c) c <- rel(talk) call(puts) pop(c) ret say_end: push(c) c <- rel(rn) call(puts) pop(c) ret skipwords: pushall(e,g) skipwords_top: g <- [c] e <- g == 0 jnzrel(e,skipwords_done) e <- g == ' ' c <- c + 1 jnzrel(e,skipwords_foundspace) goto(skipwords_top) skipwords_foundspace: d <- d - 1 e <- d < 1 jzrel(e,skipwords_top) skipwords_done: b <- c popall(e,g) ret // :usermask PRIVMSG #channel :message getline: g <- rel(buffer) f <- g getline_top: getch(b) c <- b == '\r' d <- b == '\n' c <- c | d jnzrel(c,getline_eol) b -> [f] f <- f + 1 goto(getline_top) getline_eol: a -> [f] b <- g ret sleep: c <- c * 2047 c <- c * 2047 sleep_loop: c <- c - 1 d <- c == 0 jnzrel(d,sleep_done) goto(sleep_loop) sleep_done: ret // ---------------------------------------------------------------------------- buffer: // 512 chars .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" .utf32 "----------------------------------------------------------------" nick: .utf32 "NICK " NICK ; .word 0 user: .utf32 "USER " NICK " 0 * :get your own bot" ; .word 0 join: .utf32 "JOIN " CHANNEL ; .word 0 talk: .utf32 "PRIVMSG " CHANNEL " :" ; .word 0 privmsg: .utf32 "PRIVMSG" ; .word 0 trigger: .utf32 "!f " ; .word 0 rn: .word '\r', '\n', 0 <|endoftext|>
<commit_before>/** * @file driver.cpp * @brief Component driver * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details Load components with driver */ #include "driver.hpp" #include <dlfcn.h> #include "xmlprofile.hpp" #include <iostream> #include "logger.hpp" #include "util/format.h" #include <tuple> #include "interface/imessage.hpp" using namespace std; namespace cossb { namespace driver { component_driver::component_driver(const char* component_name) :_component_name(component_name) { if(load(component_name)) { string profile_path = fmt::format("./{}.xml",component_name); if(!_ptr_component->set_profile(new profile::xmlprofile, profile_path.c_str())) unload(); else cossb_log->log(cossb::log::loglevel::INFO, fmt::format("Component load success : {}", component_name).c_str()); } else cossb_log->log(cossb::log::loglevel::ERROR, fmt::format("Component load failed : {}", component_name).c_str()); } component_driver::~component_driver() { unload(); } bool component_driver::load(const char* component_name) { string component_path = fmt::format("./{}.comp",component_name); _handle = dlopen(component_path.c_str(), RTLD_LAZY|RTLD_GLOBAL); if(_handle) { create_component pfcreate = (create_component)dlsym(_handle, "create"); if(!pfcreate) { dlclose(_handle); _handle = nullptr; return false; } _ptr_component = pfcreate(); return true; } return false; } void component_driver::unload() { if(_ptr_component) { destroy_component pfdestroy = (destroy_component)dlsym(_handle, "destroy"); destroy_task(_request_proc_task); if(pfdestroy) { cossb_log->log(cossb::log::loglevel::INFO, fmt::format("Component unload success : {}", _ptr_component->get_name()).c_str()); pfdestroy(); } _ptr_component = nullptr; } if(_handle) { dlclose(_handle); _handle = nullptr; } } void component_driver::setup() { if(_ptr_component) _ptr_component->setup(); } void component_driver::run() { if(_ptr_component) { if(!_request_proc_task) _request_proc_task = create_task(component_driver::request_proc); _ptr_component->run(); } } void component_driver::stop() { if(_ptr_component) _ptr_component->stop(); destroy_task(_request_proc_task); } bool component_driver::set_profile(interface::iprofile* profile, const char* path) { return true; } void component_driver::request_proc() { if(_ptr_component) { while(1) { boost::mutex::scoped_lock __lock(_mutex); _condition.wait(__lock); while(!_mailbox.empty()) { _ptr_component->request(&_mailbox.front()); _mailbox.pop(); } boost::this_thread::sleep(boost::posix_time::milliseconds(0)); } } } } /* namespace dirver */ } /* namespace cossb */ <commit_msg>add thread interruptable in request process<commit_after>/** * @file driver.cpp * @brief Component driver * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details Load components with driver */ #include "driver.hpp" #include <dlfcn.h> #include "xmlprofile.hpp" #include <iostream> #include "logger.hpp" #include "util/format.h" #include <tuple> #include "interface/imessage.hpp" using namespace std; namespace cossb { namespace driver { component_driver::component_driver(const char* component_name) :_component_name(component_name) { if(load(component_name)) { string profile_path = fmt::format("./{}.xml",component_name); if(!_ptr_component->set_profile(new profile::xmlprofile, profile_path.c_str())) unload(); else cossb_log->log(cossb::log::loglevel::INFO, fmt::format("Component load success : {}", component_name).c_str()); } else cossb_log->log(cossb::log::loglevel::ERROR, fmt::format("Component load failed : {}", component_name).c_str()); } component_driver::~component_driver() { unload(); } bool component_driver::load(const char* component_name) { string component_path = fmt::format("./{}.comp",component_name); _handle = dlopen(component_path.c_str(), RTLD_LAZY|RTLD_GLOBAL); if(_handle) { create_component pfcreate = (create_component)dlsym(_handle, "create"); if(!pfcreate) { dlclose(_handle); _handle = nullptr; return false; } _ptr_component = pfcreate(); return true; } return false; } void component_driver::unload() { if(_ptr_component) { destroy_component pfdestroy = (destroy_component)dlsym(_handle, "destroy"); destroy_task(_request_proc_task); if(pfdestroy) { cossb_log->log(cossb::log::loglevel::INFO, fmt::format("Component unload success : {}", _ptr_component->get_name()).c_str()); pfdestroy(); } _ptr_component = nullptr; } if(_handle) { dlclose(_handle); _handle = nullptr; } } void component_driver::setup() { if(_ptr_component) _ptr_component->setup(); } void component_driver::run() { if(_ptr_component) { if(!_request_proc_task) _request_proc_task = create_task(component_driver::request_proc); _ptr_component->run(); } } void component_driver::stop() { if(_ptr_component) _ptr_component->stop(); destroy_task(_request_proc_task); } bool component_driver::set_profile(interface::iprofile* profile, const char* path) { return true; } void component_driver::request_proc() { if(_ptr_component) { while(1) { try { boost::mutex::scoped_lock __lock(_mutex); _condition.wait(__lock); while(!_mailbox.empty()) { _ptr_component->request(&_mailbox.front()); _mailbox.pop(); } boost::this_thread::sleep(boost::posix_time::milliseconds(0)); } catch(thread_interrupted&) { break; } } } } } /* namespace dirver */ } /* namespace cossb */ <|endoftext|>
<commit_before>//===--- RequestedInformation.cpp - Requested Information Utilities ---===// // // This file is part of the Election Method Mathematics Application (EMMA) project. // // Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors // Licensed under the GNU Affero General Public License, version 3.0. // // See the file called "LICENSE" included with this distribution for license information. // //===----------------------------------------------------------------------===// // // Functionality related to determining requested information. // Analyzes information passed to the application and determines // how the application should act. // //===----------------------------------------------------------------------===// #include <iostream> #include "RequestedInformation.h" #include "docopt/docopt.h" namespace RequestedInformation { typedef std::map<std::string, docopt::value> RawParsedOptions; // Parses given options; `argc` and `argv` are the arguments // from `main()`. RawParsedOptions parseOptions(int argc, char **argv); // Determines the mode in which to run based on the parsed // options void determineMode(RawParsedOptions raw_parsed_options); // Determines the statistics to collect based on the parsed // options void determineStatisticsToCollect(RawParsedOptions raw_parsed_options); void determine(int argc, char **argv) { std::cout << "determine what is requested from simulations" << std::endl; RawParsedOptions raw_options = parseOptions(argc, argv); determineMode(raw_options); determineStatisticsToCollect(); } void determineMode(RawParsedOptions raw_parsed_options) { std::cout << "\tdetermine the mode to run in based on such parsing" << std::endl; } void determineStatisticsToCollect(RawParsedOptions raw_parsed_options) { std::cout << "\tdetermine what statistics to collect based on such parsing" << std::endl; } RawParsedOptions parseOptions(int argc, char **argv) { const std::string usage = R"(Usage: emma (-h | --help) emma options... Options: -h --help Show this screen. --use-seed=<#> The seed to pass to the PRNG function [default: a number representing the current time]. --number-of-elections=<#> Number of elections to simulate [default: 1]. --number-of-candidates=<#> Number of Candidates in each election [default: 3]. --number-of-voters=<#> Number of Voters in each election [default: 64]. --check-condorcet-agreement=yes|no Check each method for agreement with the Condorcet Candidate [default: yes]. --check-true-condorcet-agreement=<yes|no> Check each method for agreement with the True Condorcet Candidate [default: yes]. --test Perform diagnostic testing. --verbose Activate verbosity. )"; RawParsedOptions raw_options = docopt::docopt(usage, { argv + 1, argv + argc }, true); if (raw_options["--verbose"].asLong() == 1) { std::cout << "parsing given options: success" << std::endl; } return raw_options; } } <commit_msg>Adding a missing function argument<commit_after>//===--- RequestedInformation.cpp - Requested Information Utilities ---===// // // This file is part of the Election Method Mathematics Application (EMMA) project. // // Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors // Licensed under the GNU Affero General Public License, version 3.0. // // See the file called "LICENSE" included with this distribution for license information. // //===----------------------------------------------------------------------===// // // Functionality related to determining requested information. // Analyzes information passed to the application and determines // how the application should act. // //===----------------------------------------------------------------------===// #include <iostream> #include "RequestedInformation.h" #include "docopt/docopt.h" namespace RequestedInformation { typedef std::map<std::string, docopt::value> RawParsedOptions; // Parses given options; `argc` and `argv` are the arguments // from `main()`. RawParsedOptions parseOptions(int argc, char **argv); // Determines the mode in which to run based on the parsed // options void determineMode(RawParsedOptions raw_parsed_options); // Determines the statistics to collect based on the parsed // options void determineStatisticsToCollect(RawParsedOptions raw_parsed_options); void determine(int argc, char **argv) { std::cout << "determine what is requested from simulations" << std::endl; RawParsedOptions raw_options = parseOptions(argc, argv); determineMode(raw_options); determineStatisticsToCollect(raw_options); } void determineMode(RawParsedOptions raw_parsed_options) { std::cout << "\tdetermine the mode to run in based on such parsing" << std::endl; } void determineStatisticsToCollect(RawParsedOptions raw_parsed_options) { std::cout << "\tdetermine what statistics to collect based on such parsing" << std::endl; } RawParsedOptions parseOptions(int argc, char **argv) { const std::string usage = R"(Usage: emma (-h | --help) emma options... Options: -h --help Show this screen. --use-seed=<#> The seed to pass to the PRNG function [default: a number representing the current time]. --number-of-elections=<#> Number of elections to simulate [default: 1]. --number-of-candidates=<#> Number of Candidates in each election [default: 3]. --number-of-voters=<#> Number of Voters in each election [default: 64]. --check-condorcet-agreement=yes|no Check each method for agreement with the Condorcet Candidate [default: yes]. --check-true-condorcet-agreement=<yes|no> Check each method for agreement with the True Condorcet Candidate [default: yes]. --test Perform diagnostic testing. --verbose Activate verbosity. )"; RawParsedOptions raw_options = docopt::docopt(usage, { argv + 1, argv + argc }, true); if (raw_options["--verbose"].asLong() == 1) { std::cout << "parsing given options: success" << std::endl; } return raw_options; } } <|endoftext|>
<commit_before>#pragma once /** @file @brief MS Office encryption encoder Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. */ #include <cybozu/crypto.hpp> #include <cybozu/mmap.hpp> #include <cybozu/random_generator.hpp> #include "crypto_util.hpp" #include "cfb.hpp" #include "make_dataspace.hpp" #include "resource.hpp" //#define SAME_KEY namespace ms { inline cybozu::RandomGenerator& GetRandGen() { static cybozu::RandomGenerator rg; return rg; } inline void FillRand(std::string& str, size_t n) { str.resize(n); GetRandGen().read(&str[0], static_cast<int>(n)); } #if 0 inline void VerifyFormat(const char *data, uint32_t dataSize) { if (dataSize < 2) throw cybozu::Exception("ms:VerifyFormat:too small") << dataSize; if (memcmp(data, "PK", 2) != 0) throw cybozu::Exception("ms:VerifyFormat:bad format"); } #endif /* encryptedPackage = [uint64_t:encData] */ inline void MakeEncryptedPackage(std::string& encryptedPackage, const std::string& encData) { encryptedPackage.reserve(encData.size() + 8); encryptedPackage.resize(8); cybozu::Set64bitAsLE(&encryptedPackage[0], encData.size()); encryptedPackage += encData; } /* [MS-OFFCRYPTO] 2.3.4.14 */ inline void GenerateIntegrityParameter( std::string& encryptedHmacKey, std::string& encryptedHmacValue, const std::string& encryptedPackage, const CipherParam& keyData, const std::string& secretKey, const std::string& saltValue) { std::string salt; FillRand(salt, keyData.hashSize); #ifdef SAME_KEY salt = fromHex("C9FACA5436849906B600DE95E155B47A01ABEDD0"); #endif const std::string iv1 = generateIv(keyData, ms::blkKey_dataIntegrity1, saltValue); const std::string iv2 = generateIv(keyData, ms::blkKey_dataIntegrity2, saltValue); encryptedHmacKey = cipher(keyData.cipherName, salt, secretKey, iv1, cybozu::crypto::Cipher::Encoding); cybozu::crypto::Hmac hmac(keyData.hashName); std::string ret = hmac.eval(salt, encryptedPackage); encryptedHmacValue = cipher(keyData.cipherName, ret, secretKey, iv2, cybozu::crypto::Cipher::Encoding); } inline void EncContent(std::string& encryptedPackage, const std::string& org, const CipherParam& param, const std::string& key, const std::string& salt) { uint64_t orgSize = org.size(); const size_t blockSize = 4096; std::string data = org; data.resize(RoundUp(data.size(), size_t(16))); #ifdef SAME_KEY data[data.size() - 2] = 0x4b; // QQQ remove this data[data.size() - 1] = 0x6a; #endif encryptedPackage.reserve(data.size() + 8); encryptedPackage.resize(8); cybozu::Set64bitAsLE(&encryptedPackage[0], orgSize); const size_t n = (data.size() + blockSize - 1) / blockSize; for (size_t i = 0; i < n; i++) { const size_t len = (i < n - 1) ? blockSize : (data.size() % blockSize); std::string blockKey(4, 0); cybozu::Set32bitAsLE(&blockKey[0], static_cast<uint32_t>(i)); const std::string iv = generateKey(param, salt, blockKey); encryptedPackage.append(cipher(param.cipherName, data.c_str() + i * blockSize, len, key, iv, cybozu::crypto::Cipher::Encoding)); } } /* ̋tňÍ fix parameter : c1(blkKey_VerifierHashInput) c2(blkKey_encryptedVerifierHashValue) c3(blkKey_encryptedKeyValue) input : pass, spinCount output: iv, verifierHashInput, encryptedVerifierHashValue, encryptedKeyValue iv(encryptedKey.saltValue)_ pwHash = hashPassword(iv, pass, spinCount) skey1 = generateKey(pwHash, c1) skey2 = generateKey(pwHash, c2) verifierHashInput_ encryptedVerifierHashInput = Enc(verifierHashInput, skey1, iv) hashedVerifier = H(verifierHashInput) encryptedVerifierHashValue = Enc(verifierHash, skey2, iv) skey3 = generateKey(pwHash, c3) secretKey_ encryptedKeyValue = Enc(secretKey, skey3, iv) */ /* encode data by pass with cipherName, hashName, spinCount output encData and info */ inline bool encode_in( std::string& encryptedPackage, EncryptionInfo& info, const std::string& data, cybozu::crypto::Cipher::Name cipherName, cybozu::crypto::Hash::Name hashName, int spinCount, const std::string& pass, const std::string& masterKey) { if (spinCount > 10000000) throw cybozu::Exception("ms:encode_in:too large spinCount") << spinCount; CipherParam& keyData = info.keyData; CipherParam& encryptedKey = info.encryptedKey; keyData.setByName(cipherName, hashName); encryptedKey.setByName(cipherName, hashName); info.spinCount = spinCount; std::string& iv = encryptedKey.saltValue; FillRand(iv, encryptedKey.saltSize); #ifdef SAME_KEY puts("QQQ defined SAME_KEY QQQ"); iv = fromHex("F4994F9B2DCD5E0E84BC6386D4523D2C"); #endif const std::string pwHash = hashPassword(encryptedKey.hashName, iv, pass, spinCount); const std::string skey1 = generateKey(encryptedKey, pwHash, blkKey_VerifierHashInput); const std::string skey2 = generateKey(encryptedKey, pwHash, blkKey_encryptedVerifierHashValue); const std::string skey3 = generateKey(encryptedKey, pwHash, blkKey_encryptedKeyValue); std::string verifierHashInput; FillRand(verifierHashInput, encryptedKey.saltSize); #ifdef SAME_KEY verifierHashInput = fromHex("FEDAECD950F9E82C47CADA29B7837C6D"); #endif verifierHashInput.resize(RoundUp(verifierHashInput.size(), encryptedKey.blockSize)); info.encryptedVerifierHashInput = cipher(encryptedKey.cipherName, verifierHashInput, skey1, iv, cybozu::crypto::Cipher::Encoding); std::string hashedVerifier = cybozu::crypto::Hash::digest(encryptedKey.hashName, verifierHashInput); hashedVerifier.resize(RoundUp(hashedVerifier.size(), encryptedKey.blockSize)); info.encryptedVerifierHashValue = cipher(encryptedKey.cipherName, hashedVerifier, skey2, iv, cybozu::crypto::Cipher::Encoding); std::string secretKey; FillRand(secretKey, encryptedKey.saltSize); #ifdef SAME_KEY secretKey = fromHex("BF44FBB51BE1E88BF130156E117E7900"); #endif if (!masterKey.empty()) { secretKey = masterKey; } normalizeKey(secretKey, encryptedKey.keyBits / 8); info.encryptedKeyValue = cipher(encryptedKey.cipherName, secretKey, skey3, iv, cybozu::crypto::Cipher::Encoding); FillRand(keyData.saltValue, keyData.saltSize); #ifdef SAME_KEY keyData.saltValue = fromHex("C49AAAEE99004C6B017EE5CD11B86729"); #endif EncContent(encryptedPackage, data, encryptedKey, secretKey, keyData.saltValue); GenerateIntegrityParameter(info.encryptedHmacKey, info.encryptedHmacValue, encryptedPackage, keyData, secretKey, keyData.saltValue); return true; } template<class String> bool encode(const char *data, uint32_t dataSize, const String& outFile, const std::string& pass, bool isOffice2013, const std::string& masterKey, int spinCount) { std::string encryptedPackage; ms::EncryptionInfo info; const cybozu::crypto::Cipher::Name cipherName = isOffice2013 ? cybozu::crypto::Cipher::N_AES256_CBC : cybozu::crypto::Cipher::N_AES128_CBC; const cybozu::crypto::Hash::Name hashName = isOffice2013 ? cybozu::crypto::Hash::N_SHA512 : cybozu::crypto::Hash::N_SHA1; encode_in(encryptedPackage, info, std::string(data, dataSize), cipherName, hashName, spinCount, pass, masterKey); const std::string encryptionInfoStr = info.addHeader(info.toXml(isOffice2013)); dprintf("encryptionInfoStr size=%d\n", (int)encryptionInfoStr.size()); ms::cfb::CompoundFile cfb; ms::makeDataSpace(cfb.dirs, encryptedPackage, encryptionInfoStr); std::string outData; makeLayout(outData, cfb); { cybozu::File out; out.openW(outFile); out.write(outData.c_str(), outData.size()); } return true; } } // ms <commit_msg>fix the last block size<commit_after>#pragma once /** @file @brief MS Office encryption encoder Copyright (C) 2012 Cybozu Labs, Inc., all rights reserved. */ #include <cybozu/crypto.hpp> #include <cybozu/mmap.hpp> #include <cybozu/random_generator.hpp> #include "crypto_util.hpp" #include "cfb.hpp" #include "make_dataspace.hpp" #include "resource.hpp" //#define SAME_KEY namespace ms { inline cybozu::RandomGenerator& GetRandGen() { static cybozu::RandomGenerator rg; return rg; } inline void FillRand(std::string& str, size_t n) { str.resize(n); GetRandGen().read(&str[0], static_cast<int>(n)); } #if 0 inline void VerifyFormat(const char *data, uint32_t dataSize) { if (dataSize < 2) throw cybozu::Exception("ms:VerifyFormat:too small") << dataSize; if (memcmp(data, "PK", 2) != 0) throw cybozu::Exception("ms:VerifyFormat:bad format"); } #endif /* encryptedPackage = [uint64_t:encData] */ inline void MakeEncryptedPackage(std::string& encryptedPackage, const std::string& encData) { encryptedPackage.reserve(encData.size() + 8); encryptedPackage.resize(8); cybozu::Set64bitAsLE(&encryptedPackage[0], encData.size()); encryptedPackage += encData; } /* [MS-OFFCRYPTO] 2.3.4.14 */ inline void GenerateIntegrityParameter( std::string& encryptedHmacKey, std::string& encryptedHmacValue, const std::string& encryptedPackage, const CipherParam& keyData, const std::string& secretKey, const std::string& saltValue) { std::string salt; FillRand(salt, keyData.hashSize); #ifdef SAME_KEY salt = fromHex("C9FACA5436849906B600DE95E155B47A01ABEDD0"); #endif const std::string iv1 = generateIv(keyData, ms::blkKey_dataIntegrity1, saltValue); const std::string iv2 = generateIv(keyData, ms::blkKey_dataIntegrity2, saltValue); encryptedHmacKey = cipher(keyData.cipherName, salt, secretKey, iv1, cybozu::crypto::Cipher::Encoding); cybozu::crypto::Hmac hmac(keyData.hashName); std::string ret = hmac.eval(salt, encryptedPackage); encryptedHmacValue = cipher(keyData.cipherName, ret, secretKey, iv2, cybozu::crypto::Cipher::Encoding); } inline void EncContent(std::string& encryptedPackage, const std::string& org, const CipherParam& param, const std::string& key, const std::string& salt) { uint64_t orgSize = org.size(); const size_t blockSize = 4096; std::string data = org; data.resize(RoundUp(data.size(), size_t(16))); #ifdef SAME_KEY data[data.size() - 2] = 0x4b; // QQQ remove this data[data.size() - 1] = 0x6a; #endif encryptedPackage.reserve(data.size() + 8); encryptedPackage.resize(8); cybozu::Set64bitAsLE(&encryptedPackage[0], orgSize); const size_t n = (data.size() + blockSize - 1) / blockSize; for (size_t i = 0; i < n; i++) { const size_t len = (i < n - 1) ? blockSize : (data.size() - blockSize * i); std::string blockKey(4, 0); cybozu::Set32bitAsLE(&blockKey[0], static_cast<uint32_t>(i)); const std::string iv = generateKey(param, salt, blockKey); encryptedPackage.append(cipher(param.cipherName, data.c_str() + i * blockSize, len, key, iv, cybozu::crypto::Cipher::Encoding)); } } /* ̋tňÍ fix parameter : c1(blkKey_VerifierHashInput) c2(blkKey_encryptedVerifierHashValue) c3(blkKey_encryptedKeyValue) input : pass, spinCount output: iv, verifierHashInput, encryptedVerifierHashValue, encryptedKeyValue iv(encryptedKey.saltValue)_ pwHash = hashPassword(iv, pass, spinCount) skey1 = generateKey(pwHash, c1) skey2 = generateKey(pwHash, c2) verifierHashInput_ encryptedVerifierHashInput = Enc(verifierHashInput, skey1, iv) hashedVerifier = H(verifierHashInput) encryptedVerifierHashValue = Enc(verifierHash, skey2, iv) skey3 = generateKey(pwHash, c3) secretKey_ encryptedKeyValue = Enc(secretKey, skey3, iv) */ /* encode data by pass with cipherName, hashName, spinCount output encData and info */ inline bool encode_in( std::string& encryptedPackage, EncryptionInfo& info, const std::string& data, cybozu::crypto::Cipher::Name cipherName, cybozu::crypto::Hash::Name hashName, int spinCount, const std::string& pass, const std::string& masterKey) { if (spinCount > 10000000) throw cybozu::Exception("ms:encode_in:too large spinCount") << spinCount; CipherParam& keyData = info.keyData; CipherParam& encryptedKey = info.encryptedKey; keyData.setByName(cipherName, hashName); encryptedKey.setByName(cipherName, hashName); info.spinCount = spinCount; std::string& iv = encryptedKey.saltValue; FillRand(iv, encryptedKey.saltSize); #ifdef SAME_KEY puts("QQQ defined SAME_KEY QQQ"); iv = fromHex("F4994F9B2DCD5E0E84BC6386D4523D2C"); #endif const std::string pwHash = hashPassword(encryptedKey.hashName, iv, pass, spinCount); const std::string skey1 = generateKey(encryptedKey, pwHash, blkKey_VerifierHashInput); const std::string skey2 = generateKey(encryptedKey, pwHash, blkKey_encryptedVerifierHashValue); const std::string skey3 = generateKey(encryptedKey, pwHash, blkKey_encryptedKeyValue); std::string verifierHashInput; FillRand(verifierHashInput, encryptedKey.saltSize); #ifdef SAME_KEY verifierHashInput = fromHex("FEDAECD950F9E82C47CADA29B7837C6D"); #endif verifierHashInput.resize(RoundUp(verifierHashInput.size(), encryptedKey.blockSize)); info.encryptedVerifierHashInput = cipher(encryptedKey.cipherName, verifierHashInput, skey1, iv, cybozu::crypto::Cipher::Encoding); std::string hashedVerifier = cybozu::crypto::Hash::digest(encryptedKey.hashName, verifierHashInput); hashedVerifier.resize(RoundUp(hashedVerifier.size(), encryptedKey.blockSize)); info.encryptedVerifierHashValue = cipher(encryptedKey.cipherName, hashedVerifier, skey2, iv, cybozu::crypto::Cipher::Encoding); std::string secretKey; FillRand(secretKey, encryptedKey.saltSize); #ifdef SAME_KEY secretKey = fromHex("BF44FBB51BE1E88BF130156E117E7900"); #endif if (!masterKey.empty()) { secretKey = masterKey; } normalizeKey(secretKey, encryptedKey.keyBits / 8); info.encryptedKeyValue = cipher(encryptedKey.cipherName, secretKey, skey3, iv, cybozu::crypto::Cipher::Encoding); FillRand(keyData.saltValue, keyData.saltSize); #ifdef SAME_KEY keyData.saltValue = fromHex("C49AAAEE99004C6B017EE5CD11B86729"); #endif EncContent(encryptedPackage, data, encryptedKey, secretKey, keyData.saltValue); GenerateIntegrityParameter(info.encryptedHmacKey, info.encryptedHmacValue, encryptedPackage, keyData, secretKey, keyData.saltValue); return true; } template<class String> bool encode(const char *data, uint32_t dataSize, const String& outFile, const std::string& pass, bool isOffice2013, const std::string& masterKey, int spinCount) { std::string encryptedPackage; ms::EncryptionInfo info; const cybozu::crypto::Cipher::Name cipherName = isOffice2013 ? cybozu::crypto::Cipher::N_AES256_CBC : cybozu::crypto::Cipher::N_AES128_CBC; const cybozu::crypto::Hash::Name hashName = isOffice2013 ? cybozu::crypto::Hash::N_SHA512 : cybozu::crypto::Hash::N_SHA1; encode_in(encryptedPackage, info, std::string(data, dataSize), cipherName, hashName, spinCount, pass, masterKey); const std::string encryptionInfoStr = info.addHeader(info.toXml(isOffice2013)); dprintf("encryptionInfoStr size=%d\n", (int)encryptionInfoStr.size()); ms::cfb::CompoundFile cfb; ms::makeDataSpace(cfb.dirs, encryptedPackage, encryptionInfoStr); std::string outData; makeLayout(outData, cfb); { cybozu::File out; out.openW(outFile); out.write(outData.c_str(), outData.size()); } return true; } } // ms <|endoftext|>
<commit_before>/** * @file evaluate_circuit.cpp * * @author Benjamin Villalonga (main contributor), Bron Nelson, Sergio Boixo and * Salvatore Mandra * @contributors: The qFlex Developers (see CONTRIBUTORS.md) * @date Created: August 2018 * * @copyright: Copyright © 2019, United States Government, as represented * by the Administrator of the National Aeronautics and Space Administration. * All rights reserved. * @licence: Apache License, Version 2.0 */ #include "evaluate_circuit.h" #include "stopwatch.h" namespace qflex { // Gets the position in the output state vector of the qubit at tensor_pos. std::size_t find_output_pos(const QflexInput* input, std::vector<std::size_t> tensor_pos) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } std::size_t pos = (tensor_pos[0] * input->grid.J) + tensor_pos[1]; for (const auto off_pos : input->grid.qubits_off) { if (off_pos[0] < tensor_pos[0]) { --pos; } else if (off_pos[0] == tensor_pos[0] && off_pos[1] < tensor_pos[1]) { --pos; } } return pos; } std::string get_output_states( const QflexInput* input, const std::list<ContractionOperation>& ordering, std::vector<std::vector<std::size_t>>* final_qubits, std::vector<std::string>* output_states) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } if (final_qubits == nullptr) { throw ERROR_MSG("Final qubits must be non-null."); } if (output_states == nullptr) { throw ERROR_MSG("Output states must be non-null"); } std::vector<std::size_t> output_pos_map; std::vector<std::vector<std::size_t>> output_values_map; std::string base_state = input->final_state; // If the final state isn't provided, it should be all zeroes except for // qubits with terminal cuts (which should have 'x'). bool final_state_unspecified = false; if (input->final_state.empty()) { final_state_unspecified = true; base_state = std::string(input->initial_state.length(), '0'); } for (const auto& op : ordering) { // TODO(martinop): update to use the new operation. if (op.op_type != ContractionOperation::CUT) continue; // Any qubit with a terminal cut is in the final region. if (op.cut.tensors.size() != 1) continue; const std::size_t output_pos = find_output_pos(input, op.cut.tensors[0]); const auto tensor_pos = op.cut.tensors[0]; if (final_state_unspecified) { base_state[output_pos] = 'x'; } // TODO(martinop): reconsider requiring 'x' for cut indices. output_pos_map.push_back(output_pos); if (op.cut.values.empty()) { output_values_map.push_back({0, 1}); } else { output_values_map.push_back(op.cut.values); } final_qubits->push_back(tensor_pos); } // Construct the full set of output state strings. std::vector<std::string> temp_output_states; output_states->push_back(base_state); for (std::size_t i = 0; i < final_qubits->size(); ++i) { const std::size_t pos = output_pos_map[i]; for (const std::string& state : *output_states) { for (const std::size_t val : output_values_map[i]) { std::string partial_state = state; partial_state[pos] = std::to_string(val).at(0); temp_output_states.push_back(partial_state); } } *output_states = temp_output_states; temp_output_states.clear(); } // Verify that output states have no leftover "x" after replacement. for (std::size_t i = 0; i < output_states->at(0).length(); ++i) { char c = output_states->at(0)[i]; if (c != '0' && c != '1') { throw ERROR_MSG("Final state has non-binary character ", c, " at index ", i, "despite having no terminal cut there."); } } return base_state; } std::vector<std::pair<std::string, std::complex<double>>> EvaluateCircuit( QflexInput* input) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } utils::Stopwatch stopwatch; // Start stopwatch if (global::verbose > 0) stopwatch.start(); // Create the ordering for this tensor contraction from file. std::list<ContractionOperation> ordering; // Parse ordering ordering_data_to_contraction_ordering(*input, &ordering); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent making contraction ordering: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; std::size_t init_length = input->grid.I * input->grid.J - input->grid.qubits_off.size(); if (input->initial_state.empty()) { input->initial_state = std::string(init_length, '0'); } // Get a list of qubits and output states for the final region, and set the // final_state if one wasn't provided. std::vector<std::vector<std::size_t>> final_qubits; std::vector<std::string> output_states; try { input->final_state = get_output_states(input, ordering, &final_qubits, &output_states); } catch (const std::string& err_msg) { throw ERROR_MSG("Failed to call get_output_states(). Error:\n\t[", err_msg, "]"); } // Declaring and then filling 2D grid of tensors. std::vector<std::vector<Tensor>> tensor_grid( input->grid.I, std::vector<Tensor>(input->grid.J)); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent allocating 2D grid of tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Scope so that scratch space and the 3D grid of tensors are destructed. { // Scratch space for creating 3D tensor network. The largest single-gate // tensor we currently support is rank 4. s_type scratch_3D[16]; // Creating 3D grid of tensors from file. std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D; circuit_data_to_tensor_network(input->circuit, input->grid.I, input->grid.J, input->initial_state, input->final_state, final_qubits, input->grid.qubits_off, tensor_grid_3D, scratch_3D); if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent creating 3D grid of tensors from file: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; std::size_t max_size = 0; for (std::size_t i = 0; i < tensor_grid_3D.size(); ++i) { for (std::size_t j = 0; j < tensor_grid_3D[i].size(); ++j) { std::unordered_map<std::string, std::size_t> index_dim; for (const auto tensor : tensor_grid_3D[i][j]) { for (const auto& [index, dim] : tensor.get_index_to_dimension()) { if (index_dim.find(index) == index_dim.end()) { index_dim[index] = dim; } else { // Index is shared between adjacent tensors; remove it. index_dim.erase(index); } } } std::size_t tensor_size = 1; for (const auto& [index, dim] : index_dim) { tensor_size *= dim; } if (tensor_size > max_size) { max_size = tensor_size; } } } if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent to determine maximum size for tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Scratch space for contracting 3D to 2D grid. This must have enough space // to hold the largest single-qubit tensor in the 2D grid. std::vector<s_type> scratch_2D(max_size); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent allocating scratch space for 2D grid: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Contract 3D grid onto 2D grid of tensors, as usual. flatten_grid_of_tensors(tensor_grid_3D, tensor_grid, final_qubits, input->grid.qubits_off, ordering, scratch_2D.data()); if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent creating 2D grid of tensors from 3D one: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; } // Perform tensor grid contraction. std::vector<std::complex<double>> amplitudes(output_states.size()); std::vector<std::pair<std::string, std::complex<double>>> result; try { ContractGrid(ordering, &tensor_grid, &amplitudes); } catch (const std::string& err_msg) { throw ERROR_MSG("Failed to call ContractGrid(). Error:\n\t[", err_msg, "]"); } for (std::size_t c = 0; c < amplitudes.size(); ++c) { result.push_back(std::make_pair(output_states[c], amplitudes[c])); } if (global::verbose > 0) std::cerr << WARN_MSG("Time spent contracting tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Final time if (global::verbose > 0) { stopwatch.stop(); std::cerr << WARN_MSG("Total time: ", stopwatch.time_passed<utils::milliseconds>() / 1000., "s") << std::endl; } return result; } } // namespace qflex <commit_msg>hack to compile and get over not used error for index at line 191<commit_after>/** * @file evaluate_circuit.cpp * * @author Benjamin Villalonga (main contributor), Bron Nelson, Sergio Boixo and * Salvatore Mandra * @contributors: The qFlex Developers (see CONTRIBUTORS.md) * @date Created: August 2018 * * @copyright: Copyright © 2019, United States Government, as represented * by the Administrator of the National Aeronautics and Space Administration. * All rights reserved. * @licence: Apache License, Version 2.0 */ #include "evaluate_circuit.h" #include "stopwatch.h" namespace qflex { // Gets the position in the output state vector of the qubit at tensor_pos. std::size_t find_output_pos(const QflexInput* input, std::vector<std::size_t> tensor_pos) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } std::size_t pos = (tensor_pos[0] * input->grid.J) + tensor_pos[1]; for (const auto off_pos : input->grid.qubits_off) { if (off_pos[0] < tensor_pos[0]) { --pos; } else if (off_pos[0] == tensor_pos[0] && off_pos[1] < tensor_pos[1]) { --pos; } } return pos; } std::string get_output_states( const QflexInput* input, const std::list<ContractionOperation>& ordering, std::vector<std::vector<std::size_t>>* final_qubits, std::vector<std::string>* output_states) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } if (final_qubits == nullptr) { throw ERROR_MSG("Final qubits must be non-null."); } if (output_states == nullptr) { throw ERROR_MSG("Output states must be non-null"); } std::vector<std::size_t> output_pos_map; std::vector<std::vector<std::size_t>> output_values_map; std::string base_state = input->final_state; // If the final state isn't provided, it should be all zeroes except for // qubits with terminal cuts (which should have 'x'). bool final_state_unspecified = false; if (input->final_state.empty()) { final_state_unspecified = true; base_state = std::string(input->initial_state.length(), '0'); } for (const auto& op : ordering) { // TODO(martinop): update to use the new operation. if (op.op_type != ContractionOperation::CUT) continue; // Any qubit with a terminal cut is in the final region. if (op.cut.tensors.size() != 1) continue; const std::size_t output_pos = find_output_pos(input, op.cut.tensors[0]); const auto tensor_pos = op.cut.tensors[0]; if (final_state_unspecified) { base_state[output_pos] = 'x'; } // TODO(martinop): reconsider requiring 'x' for cut indices. output_pos_map.push_back(output_pos); if (op.cut.values.empty()) { output_values_map.push_back({0, 1}); } else { output_values_map.push_back(op.cut.values); } final_qubits->push_back(tensor_pos); } // Construct the full set of output state strings. std::vector<std::string> temp_output_states; output_states->push_back(base_state); for (std::size_t i = 0; i < final_qubits->size(); ++i) { const std::size_t pos = output_pos_map[i]; for (const std::string& state : *output_states) { for (const std::size_t val : output_values_map[i]) { std::string partial_state = state; partial_state[pos] = std::to_string(val).at(0); temp_output_states.push_back(partial_state); } } *output_states = temp_output_states; temp_output_states.clear(); } // Verify that output states have no leftover "x" after replacement. for (std::size_t i = 0; i < output_states->at(0).length(); ++i) { char c = output_states->at(0)[i]; if (c != '0' && c != '1') { throw ERROR_MSG("Final state has non-binary character ", c, " at index ", i, "despite having no terminal cut there."); } } return base_state; } std::vector<std::pair<std::string, std::complex<double>>> EvaluateCircuit( QflexInput* input) { if (input == nullptr) { throw ERROR_MSG("Input must be non-null."); } utils::Stopwatch stopwatch; // Start stopwatch if (global::verbose > 0) stopwatch.start(); // Create the ordering for this tensor contraction from file. std::list<ContractionOperation> ordering; // Parse ordering ordering_data_to_contraction_ordering(*input, &ordering); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent making contraction ordering: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; std::size_t init_length = input->grid.I * input->grid.J - input->grid.qubits_off.size(); if (input->initial_state.empty()) { input->initial_state = std::string(init_length, '0'); } // Get a list of qubits and output states for the final region, and set the // final_state if one wasn't provided. std::vector<std::vector<std::size_t>> final_qubits; std::vector<std::string> output_states; try { input->final_state = get_output_states(input, ordering, &final_qubits, &output_states); } catch (const std::string& err_msg) { throw ERROR_MSG("Failed to call get_output_states(). Error:\n\t[", err_msg, "]"); } // Declaring and then filling 2D grid of tensors. std::vector<std::vector<Tensor>> tensor_grid( input->grid.I, std::vector<Tensor>(input->grid.J)); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent allocating 2D grid of tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Scope so that scratch space and the 3D grid of tensors are destructed. { // Scratch space for creating 3D tensor network. The largest single-gate // tensor we currently support is rank 4. s_type scratch_3D[16]; // Creating 3D grid of tensors from file. std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D; circuit_data_to_tensor_network(input->circuit, input->grid.I, input->grid.J, input->initial_state, input->final_state, final_qubits, input->grid.qubits_off, tensor_grid_3D, scratch_3D); if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent creating 3D grid of tensors from file: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; std::size_t max_size = 0; for (std::size_t i = 0; i < tensor_grid_3D.size(); ++i) { for (std::size_t j = 0; j < tensor_grid_3D[i].size(); ++j) { std::unordered_map<std::string, std::size_t> index_dim; for (const auto tensor : tensor_grid_3D[i][j]) { for (const auto& [index, dim] : tensor.get_index_to_dimension()) { if (index_dim.find(index) == index_dim.end()) { index_dim[index] = dim; } else { // Index is shared between adjacent tensors; remove it. index_dim.erase(index); } } } std::size_t tensor_size = 1; for (const auto& [index, dim] : index_dim) { index + "do_nothing"; tensor_size *= dim; } if (tensor_size > max_size) { max_size = tensor_size; } } } if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent to determine maximum size for tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Scratch space for contracting 3D to 2D grid. This must have enough space // to hold the largest single-qubit tensor in the 2D grid. std::vector<s_type> scratch_2D(max_size); if (global::verbose > 0) std::cerr << WARN_MSG("Time spent allocating scratch space for 2D grid: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Contract 3D grid onto 2D grid of tensors, as usual. flatten_grid_of_tensors(tensor_grid_3D, tensor_grid, final_qubits, input->grid.qubits_off, ordering, scratch_2D.data()); if (global::verbose > 0) std::cerr << WARN_MSG( "Time spent creating 2D grid of tensors from 3D one: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; } // Perform tensor grid contraction. std::vector<std::complex<double>> amplitudes(output_states.size()); std::vector<std::pair<std::string, std::complex<double>>> result; try { ContractGrid(ordering, &tensor_grid, &amplitudes); } catch (const std::string& err_msg) { throw ERROR_MSG("Failed to call ContractGrid(). Error:\n\t[", err_msg, "]"); } for (std::size_t c = 0; c < amplitudes.size(); ++c) { result.push_back(std::make_pair(output_states[c], amplitudes[c])); } if (global::verbose > 0) std::cerr << WARN_MSG("Time spent contracting tensors: ", stopwatch.split<utils::milliseconds>() / 1000., "s") << std::endl; // Final time if (global::verbose > 0) { stopwatch.stop(); std::cerr << WARN_MSG("Total time: ", stopwatch.time_passed<utils::milliseconds>() / 1000., "s") << std::endl; } return result; } } // namespace qflex <|endoftext|>
<commit_before>#include "cv.h" #include "highgui.h" #include "opencv2/objdetect/objdetect.hpp" #include <iostream> #include <cstdlib> using namespace cv; using namespace std; int main(int argc, char *argv[]) { //OpenCV video capture object VideoCapture camera; //OpenCV image object Mat image; Mat img; //Initialize face detector object CascadeClassifier face_detect; face_detect.load("haarcascade_frontalface_default.xml"); //camera id . Associated to device number in /dev/videoX int cam_id; //check user args switch(argc) { case 1: //no argument provided, so try /dev/video0 cam_id = 0; break; case 2: //an argument is provided. Get it and set cam_id cam_id = atoi(argv[1]); break; default: cout << "Invalid number of arguments. Call program as: webcam_capture [video_device_id]. " << endl; cout << "EXIT program." << std::endl; break; } //advertising to the user cout << "Opening video device " << cam_id << endl; //open the video stream and make sure it's opened if( !camera.open(cam_id) ) { cout << "Error opening the camera. May be invalid device id. EXIT program." << endl; return -1; } //capture loop. Out of user press a key while(1) { //Read image and check it if(!camera.read(image)) { cout << "No frame" << endl; waitKey(); } //Copy frame for visualization img = image.clone(); // Convert the current frame to grayscale: Mat gray; cvtColor(img, gray, CV_BGR2GRAY); //Detect faces as rectangles vector< Rect_<int> > faces; face_detect.detectMultiScale(gray, faces); //For each detected face... for (int i = 0; i < faces.size(); i++) { // Process face by face: Rect face_i = faces[i]; // Crop the face from the image. So simple with OpenCV C++: Mat face = gray(face_i); // Write all we've found out to the original image! // First of all draw a green rectangle around the detected face: rectangle(img, face_i, CV_RGB(0, 255,0), 1); } //show image in a window imshow("faces", img); //Waits 1 millisecond to check if a key has been pressed. If so, breaks the loop. Otherwise continues. if(waitKey(1) >= 0) break; } } <commit_msg>Review with hat<commit_after>#include "cv.h" #include "highgui.h" #include "opencv2/objdetect/objdetect.hpp" #include <iostream> #include <cstdlib> #include "opencv2/imgproc/imgproc.hpp" //To Image Processing using namespace cv; using namespace std; int main(int argc, char *argv[]) { //OpenCV video capture object VideoCapture camera; //OpenCV image object Mat image; //Original image Mat img; //Cloned image Mat gray; //Used when convert image to gray //Load Hat and Moustache pictures Mat hat = imread("../img/hat.png"); // load hat picture with aplpha channel Mat hat_resized; //hat image once resized Mat moustache = imread("../img/moustache.png"); // load moustache picture with aplpha channel Mat moustache_resized; //moustache image once resized //Define 3 variables to get pixels combination on hat and ,oustache fussion double color_pixel_0, color_pixel_1, color_pixel_2; if(! hat.data ) // Check for invalid input image { cout << "Could not open or find the image <- hat.png ->" << endl ; return -1; } if(! moustache.data ) // Check for invalid input image { cout << "Could not open or find the image <- moustache.png ->" << endl ; return -1; } //Initialize face detector object CascadeClassifier face_detect; face_detect.load("haarcascade_frontalface_default.xml"); //camera id . Associated to device number in /dev/videoX int cam_id; //check user args switch(argc) { case 1: //no argument provided, so try /dev/video0 cam_id = 0; break; case 2: //an argument is provided. Get it and set cam_id cam_id = atoi(argv[1]); break; default: cout << "Invalid number of arguments. Call program as: webcam_capture [video_device_id]. " << endl; cout << "EXIT program." << std::endl; break; } //advertising to the user cout << "Opening video device " << cam_id << endl; //open the video stream and make sure it's opened if( !camera.open(cam_id) ) { cout << "Error opening the camera. May be invalid device id. EXIT program." << endl; return -1; } //capture loop. Out of user press a key while(1) { //Read image and check it if(!camera.read(image)) { cout << "No frame" << endl; waitKey(); } //Copy frame for visualization img = image.clone(); // Convert the current frame to grayscale: cvtColor(img, gray, CV_BGR2GRAY); //Detect faces as rectangles vector< Rect_<int> > faces; face_detect.detectMultiScale(gray, faces); //For each detected face... for (int i = 0; i < faces.size(); i++) { // Process face by face: Rect face_i = faces[i]; // Crop the face from the image. So simple with OpenCV C++: Mat face = gray(face_i); // Write all we've found out to the original image! // First of all draw a green rectangle around the detected face: rectangle(img, face_i, CV_RGB(0, 255,0), 1); //Add hat and moustache to picture int facew = face_i.width; //face width int faceh = face_i.height; //face height Size hat_size(facew,faceh); //resize hat picture giving same face width resize(hat, hat_resized, hat_size ); //Overlay hat and moustache for ( int j = 0; j < faceh ; j++) { for ( int k = 0; k < facew; k++) { // determine the opacity of the foregrond pixel, using its fourth (alpha) channel. double alpha = hat_resized.at<cv::Vec3b>(j, k)[3] / 255.0; color_pixel_0 = (hat_resized.at<cv::Vec3b>(j, k)[0] * (alpha)) + ((img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[0])* (1.0-alpha)); color_pixel_1 = (hat_resized.at<cv::Vec3b>(j, k)[1] * (alpha)) + ((img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[1])* (1.0-alpha)); color_pixel_2 = (hat_resized.at<cv::Vec3b>(j, k)[2] * (alpha)) + ((img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[2])* (1.0-alpha)); if((face_i.y +j-(faceh*0.60))>0){ img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[0] = color_pixel_0 ; img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[1] = color_pixel_1 ; img.at<cv::Vec3b>((face_i.y +j-(faceh*0.60)), (face_i.x +k))[2] = color_pixel_2 ; } } } } //show image in a window imshow("faces", img); //Waits 1 millisecond to check if a key has been pressed. If so, breaks the loop. Otherwise continues. if(waitKey(1) >= 0) break; } } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. 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. */ #include <fclaw2d_forestclaw.h> #include <fclaw2d_clawpatch.hpp> #include <fclaw2d_partition.h> #include <sc_statistics.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif #if 0 #define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \ SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \ "Timer " #NAME " still running in amrreset"); \ sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \ (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \ } while (0) #endif /* ------------------------------------------------------------------ Public interface ---------------------------------------------------------------- */ void fclaw2d_finalize(fclaw2d_domain_t **domain) { fclaw2d_domain_reset(domain); fclaw2d_timer_report(*domain); #if 0 fclaw2d_domain_data_t *ddata = fclaw2d_domain_get_data (*domain); for(int i = 0; i < (*domain)->num_blocks; i++) { fclaw2d_block_t *block = (*domain)->blocks + i; fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user; for(int j = 0; j < block->num_patches; j++) { fclaw2d_patch_t *patch = block->patches + j; fclaw2d_patch_data_delete(*domain,patch); } FCLAW2D_FREE (bd); block->user = NULL; } fclaw2d_partition_delete(domain); /* Output memory discrepancy for the ClawPatch */ if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) { printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n", (*domain)->mpirank, ddata->count_set_clawpatch, ddata->count_delete_clawpatch); } /* Evaluate timers if this domain has not been superseded yet. */ if (ddata->is_latest_domain) { sc_statinfo_t stats[FCLAW2D_TIMER_COUNT]; fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); FCLAW2D_STATS_SET (stats, ddata, INIT); FCLAW2D_STATS_SET (stats, ddata, REGRID); FCLAW2D_STATS_SET (stats, ddata, OUTPUT); FCLAW2D_STATS_SET (stats, ddata, CHECK); FCLAW2D_STATS_SET (stats, ddata, ADVANCE); FCLAW2D_STATS_SET (stats, ddata, EXCHANGE); FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES); FCLAW2D_STATS_SET (stats, ddata, WALLTIME); sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED], ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative - (ddata->timers[FCLAW2D_TIMER_INIT].cumulative + ddata->timers[FCLAW2D_TIMER_REGRID].cumulative + ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative + ddata->timers[FCLAW2D_TIMER_CHECK].cumulative + ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative + ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative), "UNACCOUNTED"); sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats); sc_stats_print (sc_package_id, SC_LP_ESSENTIAL, FCLAW2D_TIMER_COUNT, stats, 1, 0); SC_GLOBAL_ESSENTIALF ("Procs %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].average, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].average, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].average); SC_GLOBAL_ESSENTIALF ("Max/P %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].max, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].max, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].max); } fclaw2d_domain_data_delete(*domain); // Delete allocated pointers to set of functions. fclaw2d_domain_destroy(*domain); *domain = NULL; #endif } #ifdef __cplusplus #if 0 { #endif } #endif <commit_msg>Call timers before deleting domain (:-))<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. 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. */ #include <fclaw2d_forestclaw.h> #include <fclaw2d_clawpatch.hpp> #include <fclaw2d_partition.h> #include <sc_statistics.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif #if 0 #define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \ SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \ "Timer " #NAME " still running in amrreset"); \ sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \ (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \ } while (0) #endif /* ------------------------------------------------------------------ Public interface ---------------------------------------------------------------- */ void fclaw2d_finalize(fclaw2d_domain_t **domain) { fclaw2d_timer_report(*domain); fclaw2d_domain_reset(domain); #if 0 fclaw2d_domain_data_t *ddata = fclaw2d_domain_get_data (*domain); for(int i = 0; i < (*domain)->num_blocks; i++) { fclaw2d_block_t *block = (*domain)->blocks + i; fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user; for(int j = 0; j < block->num_patches; j++) { fclaw2d_patch_t *patch = block->patches + j; fclaw2d_patch_data_delete(*domain,patch); } FCLAW2D_FREE (bd); block->user = NULL; } fclaw2d_partition_delete(domain); /* Output memory discrepancy for the ClawPatch */ if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) { printf ("[%d] This domain had Clawpatch set %d and deleted %d times\n", (*domain)->mpirank, ddata->count_set_clawpatch, ddata->count_delete_clawpatch); } /* Evaluate timers if this domain has not been superseded yet. */ if (ddata->is_latest_domain) { sc_statinfo_t stats[FCLAW2D_TIMER_COUNT]; fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); FCLAW2D_STATS_SET (stats, ddata, INIT); FCLAW2D_STATS_SET (stats, ddata, REGRID); FCLAW2D_STATS_SET (stats, ddata, OUTPUT); FCLAW2D_STATS_SET (stats, ddata, CHECK); FCLAW2D_STATS_SET (stats, ddata, ADVANCE); FCLAW2D_STATS_SET (stats, ddata, EXCHANGE); FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES); FCLAW2D_STATS_SET (stats, ddata, WALLTIME); sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED], ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative - (ddata->timers[FCLAW2D_TIMER_INIT].cumulative + ddata->timers[FCLAW2D_TIMER_REGRID].cumulative + ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative + ddata->timers[FCLAW2D_TIMER_CHECK].cumulative + ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative + ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative), "UNACCOUNTED"); sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats); sc_stats_print (sc_package_id, SC_LP_ESSENTIAL, FCLAW2D_TIMER_COUNT, stats, 1, 0); SC_GLOBAL_ESSENTIALF ("Procs %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].average, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].average, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].average); SC_GLOBAL_ESSENTIALF ("Max/P %d advance %d %g exchange %d %g " "regrid %d %g\n", (*domain)->mpisize, ddata->count_amr_advance, stats[FCLAW2D_TIMER_ADVANCE].max, ddata->count_ghost_exchange, stats[FCLAW2D_TIMER_EXCHANGE].max, ddata->count_amr_regrid, stats[FCLAW2D_TIMER_REGRID].max); } fclaw2d_domain_data_delete(*domain); // Delete allocated pointers to set of functions. fclaw2d_domain_destroy(*domain); *domain = NULL; #endif } #ifdef __cplusplus #if 0 { #endif } #endif <|endoftext|>
<commit_before>/* * Basic Filters * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/basefilt.h> #include <botan/key_filt.h> namespace Botan { void Keyed_Filter::set_iv(const InitializationVector&) { // assert that the iv is empty? } /* * Chain Constructor */ Chain::Chain(Filter* f1, Filter* f2, Filter* f3, Filter* f4) { if(f1) { attach(f1); incr_owns(); } if(f2) { attach(f2); incr_owns(); } if(f3) { attach(f3); incr_owns(); } if(f4) { attach(f4); incr_owns(); } } /* * Chain Constructor */ Chain::Chain(Filter* filters[], u32bit count) { for(u32bit j = 0; j != count; ++j) if(filters[j]) { attach(filters[j]); incr_owns(); } } std::string Chain::name() const { return "Chain"; } /* * Fork Constructor */ Fork::Fork(Filter* f1, Filter* f2, Filter* f3, Filter* f4) { Filter* filters[4] = { f1, f2, f3, f4 }; set_next(filters, 4); } /* * Fork Constructor */ Fork::Fork(Filter* filters[], u32bit count) { set_next(filters, count); } std::string Fork::name() const { return "Fork"; } } <commit_msg>If the Keyed_Filter's set_iv is called (ie, in the case that the filter doesn't support IVs at all), throw an exception unless the IV has zero length.<commit_after>/* * Basic Filters * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/basefilt.h> #include <botan/key_filt.h> namespace Botan { void Keyed_Filter::set_iv(const InitializationVector& iv) { if(iv.length() != 0) throw Invalid_IV_Length(name(), iv.length()); } /* * Chain Constructor */ Chain::Chain(Filter* f1, Filter* f2, Filter* f3, Filter* f4) { if(f1) { attach(f1); incr_owns(); } if(f2) { attach(f2); incr_owns(); } if(f3) { attach(f3); incr_owns(); } if(f4) { attach(f4); incr_owns(); } } /* * Chain Constructor */ Chain::Chain(Filter* filters[], u32bit count) { for(u32bit j = 0; j != count; ++j) if(filters[j]) { attach(filters[j]); incr_owns(); } } std::string Chain::name() const { return "Chain"; } /* * Fork Constructor */ Fork::Fork(Filter* f1, Filter* f2, Filter* f3, Filter* f4) { Filter* filters[4] = { f1, f2, f3, f4 }; set_next(filters, 4); } /* * Fork Constructor */ Fork::Fork(Filter* filters[], u32bit count) { set_next(filters, count); } std::string Fork::name() const { return "Fork"; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "LogView.h" #include <QDateTime> #include <QThread> #include <QCoreApplication> LogView* LogView::_headView = nullptr; QIcon LogView::_warningIcon; QIcon LogView::_infoIcon; QIcon LogView::_errorIcon; LogView::LogView(QWidget* parent) : QWidget(parent) , _widget(new QListWidget(this)) { // register message handler - but only once if(!_headView) { qInstallMessageHandler(LogView::messageHandler); // open icon _warningIcon = QIcon(":/images/exclamation-white.png"); _infoIcon = QIcon(":/images/question-baloon.png"); _errorIcon = QIcon(":/images/exclamation-black.png"); } // append at the beginning _nextView = _headView; _headView = this; _layout = new QHBoxLayout(this); _layout->addWidget(_widget); _layout->setContentsMargins(0, 0, 0, 0); _layout->setSpacing(0); } LogView::~LogView() { // remove yourself from the list auto it = _headView; while(it->_nextView && it->_nextView != this) it = it->_nextView; if(it->_nextView == this) it->_nextView = _nextView; } void LogView::debug(const QString& msg) { qDebug(qPrintable(msg)); } void LogView::warn(const QString& msg) { qWarning(qPrintable(msg)); } void LogView::critical(const QString& msg) { qCritical(qPrintable(msg)); } void LogView::messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context) #if QT_VERSION == 0x050001 || QT_VERSION == 0x050000 // This should be fixed in 5.0.2 if(msg == "QWindowsNativeInterface::nativeResourceForWindow: 'handle' " "requested for null window or window without handle.") return; #endif // If this isn't UI thread if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return; } auto it = _headView; while(it) { auto item = new QListWidgetItem(msg); QString toolTip = QString("Time: %1 (%2:%3)") .arg(QDateTime::currentDateTime().toString("MM.dd.yyyy hh:mm:ss.zzz")) .arg(context.file) .arg(context.line); item->setToolTip(toolTip); switch(type) { case QtDebugMsg: item->setIcon(_infoIcon); break; case QtWarningMsg: item->setIcon(_warningIcon); break; case QtCriticalMsg: item->setBackgroundColor(Qt::red); item->setTextColor(Qt::blue); item->setIcon(_errorIcon); break; case QtFatalMsg: item->setBackgroundColor(Qt::red); item->setTextColor(Qt::yellow); item->setIcon(_errorIcon); break; } it->_widget->addItem(item); it->_widget->scrollToBottom(); // go to next logView it = it->_nextView; } } <commit_msg>dont show debug details in logview in release build<commit_after>/* * Copyright (c) 2013-2014 Kajetan Swierk <k0zmo@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "LogView.h" #include <QDateTime> #include <QThread> #include <QCoreApplication> LogView* LogView::_headView = nullptr; QIcon LogView::_warningIcon; QIcon LogView::_infoIcon; QIcon LogView::_errorIcon; LogView::LogView(QWidget* parent) : QWidget(parent) , _widget(new QListWidget(this)) { // register message handler - but only once if(!_headView) { qInstallMessageHandler(LogView::messageHandler); // open icon _warningIcon = QIcon(":/images/exclamation-white.png"); _infoIcon = QIcon(":/images/question-baloon.png"); _errorIcon = QIcon(":/images/exclamation-black.png"); } // append at the beginning _nextView = _headView; _headView = this; _layout = new QHBoxLayout(this); _layout->addWidget(_widget); _layout->setContentsMargins(0, 0, 0, 0); _layout->setSpacing(0); } LogView::~LogView() { // remove yourself from the list auto it = _headView; while(it->_nextView && it->_nextView != this) it = it->_nextView; if(it->_nextView == this) it->_nextView = _nextView; } void LogView::debug(const QString& msg) { qDebug(qPrintable(msg)); } void LogView::warn(const QString& msg) { qWarning(qPrintable(msg)); } void LogView::critical(const QString& msg) { qCritical(qPrintable(msg)); } void LogView::messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context) #if QT_VERSION == 0x050001 || QT_VERSION == 0x050000 // This should be fixed in 5.0.2 if(msg == "QWindowsNativeInterface::nativeResourceForWindow: 'handle' " "requested for null window or window without handle.") return; #endif // If this isn't UI thread if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return; } auto it = _headView; while(it) { auto item = new QListWidgetItem(msg); #if defined(QT_DEBUG) QString toolTip = QString("Time: %1 (%2:%3)") .arg(QDateTime::currentDateTime().toString("MM.dd.yyyy hh:mm:ss.zzz")) .arg(context.file) .arg(context.line); #else QString toolTip = QString("Time: %1") .arg(QDateTime::currentDateTime().toString("MM.dd.yyyy hh:mm:ss.zzz")); #endif item->setToolTip(toolTip); switch(type) { case QtDebugMsg: item->setIcon(_infoIcon); break; case QtWarningMsg: item->setIcon(_warningIcon); break; case QtCriticalMsg: item->setBackgroundColor(Qt::red); item->setTextColor(Qt::blue); item->setIcon(_errorIcon); break; case QtFatalMsg: item->setBackgroundColor(Qt::red); item->setTextColor(Qt::yellow); item->setIcon(_errorIcon); break; } it->_widget->addItem(item); it->_widget->scrollToBottom(); // go to next logView it = it->_nextView; } } <|endoftext|>
<commit_before>#include <iostream> #include "headings.h" #include "libaps.h" #include "constants.h" #include <concol.h> using namespace std; enum MODE {DRAM, EPROM}; MODE get_mode() { cout << concol::RED << "Programming options:" << concol::RESET << endl; cout << "1) Upload DRAM image" << endl; cout << "2) Update EPROM image" << endl << endl; cout << "Choose option [1]: "; char input; cin.get(input); switch (input) { case '1': default: return DRAM; break; case '2': return EPROM; break; } } vector<uint32_t> read_bit_file(string fileName) { std::ifstream FID (fileName, std::ios::in|std::ios::binary); if (!FID.is_open()){ throw runtime_error("Unable to open file."); } //Get the file size in bytes FID.seekg(0, std::ios::end); size_t fileSize = FID.tellg(); FILE_LOG(logDEBUG1) << "Bitfile is " << fileSize << " bytes"; FID.seekg(0, std::ios::beg); //Copy over the file data to the data vector vector<uint32_t> packedData; packedData.resize(fileSize/4); FID.read(reinterpret_cast<char *>(packedData.data()), fileSize); //Convert to big endian byte order - basically because it will be byte-swapped again when the packet is serialized for (auto & packet : packedData) { packet = htonl(packet); } cout << "Bit file is " << packedData.size() << " 32-bit words long" << endl; return packedData; } int write_image(string deviceSerial, string fileName) { vector<uint32_t> data; try { data = read_bit_file(fileName); } catch (std::exception &e) { cout << concol::RED << "Unable to open file." << concol::RESET << endl; return -1; } write_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR, data.data(), data.size()); //verify the write vector<uint32_t> buffer(256); uint32_t numWords = 256; cout << "Verifying:" << endl; for (size_t ct=0; ct < data.size(); ct+=256) { if (ct % 1000 == 0) { cout << "\r" << 100*ct/data.size() << "%" << flush; } if (std::distance(data.begin() + ct, data.end()) < 256) { numWords = std::distance(data.begin() + ct, data.end()); } read_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR + 4*ct, numWords, buffer.data()); if (!std::equal(buffer.begin(), buffer.begin()+numWords, data.begin()+ct)) { cout << endl << "Mismatched data at offset " << hexn<6> << ct << endl; return -2; } } cout << "\r100%" << endl; return reset(deviceSerial.c_str(), static_cast<int>(APS_RESET_MODE_STAT::RECONFIG_EPROM)); } int main (int argc, char* argv[]) { concol::concolinit(); cout << concol::RED << "BBN AP2 Programming Executable" << concol::RESET << endl; int dbgLevel = 4; set_logging_level(dbgLevel); string bitFile(argv[1]); cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl; init(); set_log("stdout"); int numDevices = get_numDevices(); cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << concol::RESET << endl; if (numDevices < 1) return 0; cout << concol::RED << "Attempting to get serials" << concol::RESET << endl; const char ** serialBuffer = new const char*[numDevices]; get_deviceSerials(serialBuffer); for (int cnt=0; cnt < numDevices; cnt++) { cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl; } string deviceSerial(serialBuffer[0]); connect_APS(deviceSerial.c_str()); MODE mode = get_mode(); switch (mode) { case EPROM: cout << concol::RED << "Reprogramming EPROM image" << concol::RESET << endl; write_image(deviceSerial, bitFile); break; case DRAM: cout << concol::RED << "Reprogramming DRAM image" << concol::RESET << endl; program_FPGA(deviceSerial.c_str(), bitFile.c_str()); break; } disconnect_APS(deviceSerial.c_str()); delete[] serialBuffer; cout << concol::RED << "Finished!" << concol::RESET << endl; return 0; } <commit_msg>Add ability to choose from multiple connected devices in APS2 programmer.<commit_after>#include <iostream> #include "headings.h" #include "libaps.h" #include "constants.h" #include <concol.h> using namespace std; enum MODE {DRAM, EPROM}; MODE get_mode() { cout << concol::RED << "Programming options:" << concol::RESET << endl; cout << "1) Upload DRAM image" << endl; cout << "2) Update EPROM image" << endl << endl; cout << "Choose option [1]: "; char input; cin.get(input); switch (input) { case '1': default: return DRAM; break; case '2': return EPROM; break; } } int get_device_id() { cout << "Choose device ID [0]: "; int device_id = 0; cin >> device_id; return device_id; } vector<uint32_t> read_bit_file(string fileName) { std::ifstream FID (fileName, std::ios::in|std::ios::binary); if (!FID.is_open()){ throw runtime_error("Unable to open file."); } //Get the file size in bytes FID.seekg(0, std::ios::end); size_t fileSize = FID.tellg(); FILE_LOG(logDEBUG1) << "Bitfile is " << fileSize << " bytes"; FID.seekg(0, std::ios::beg); //Copy over the file data to the data vector vector<uint32_t> packedData; packedData.resize(fileSize/4); FID.read(reinterpret_cast<char *>(packedData.data()), fileSize); //Convert to big endian byte order - basically because it will be byte-swapped again when the packet is serialized for (auto & packet : packedData) { packet = htonl(packet); } cout << "Bit file is " << packedData.size() << " 32-bit words long" << endl; return packedData; } int write_image(string deviceSerial, string fileName) { vector<uint32_t> data; try { data = read_bit_file(fileName); } catch (std::exception &e) { cout << concol::RED << "Unable to open file." << concol::RESET << endl; return -1; } write_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR, data.data(), data.size()); //verify the write vector<uint32_t> buffer(256); uint32_t numWords = 256; cout << "Verifying:" << endl; for (size_t ct=0; ct < data.size(); ct+=256) { if (ct % 1000 == 0) { cout << "\r" << 100*ct/data.size() << "%" << flush; } if (std::distance(data.begin() + ct, data.end()) < 256) { numWords = std::distance(data.begin() + ct, data.end()); } read_flash(deviceSerial.c_str(), EPROM_USER_IMAGE_ADDR + 4*ct, numWords, buffer.data()); if (!std::equal(buffer.begin(), buffer.begin()+numWords, data.begin()+ct)) { cout << endl << "Mismatched data at offset " << hexn<6> << ct << endl; return -2; } } cout << "\r100%" << endl; return reset(deviceSerial.c_str(), static_cast<int>(APS_RESET_MODE_STAT::RECONFIG_EPROM)); } int main (int argc, char* argv[]) { concol::concolinit(); cout << concol::RED << "BBN AP2 Programming Executable" << concol::RESET << endl; int dbgLevel = 4; set_logging_level(dbgLevel); string bitFile(argv[1]); cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl; init(); set_log("stdout"); int numDevices = get_numDevices(); cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << concol::RESET << endl; if (numDevices < 1) return 0; cout << concol::RED << "Attempting to get serials" << concol::RESET << endl; const char ** serialBuffer = new const char*[numDevices]; get_deviceSerials(serialBuffer); for (int cnt=0; cnt < numDevices; cnt++) { cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl; } string deviceSerial; if (numDevices == 1) { deviceSerial = string(serialBuffer[0]); } else { deviceSerial = string(serialBuffer[get_device_id()]); } connect_APS(deviceSerial.c_str()); MODE mode = get_mode(); switch (mode) { case EPROM: cout << concol::RED << "Reprogramming EPROM image" << concol::RESET << endl; write_image(deviceSerial, bitFile); break; case DRAM: cout << concol::RED << "Reprogramming DRAM image" << concol::RESET << endl; program_FPGA(deviceSerial.c_str(), bitFile.c_str()); break; } disconnect_APS(deviceSerial.c_str()); delete[] serialBuffer; cout << concol::RED << "Finished!" << concol::RESET << endl; return 0; } <|endoftext|>
<commit_before>/* * Sponge: hash sha-3 (keccak) */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "keccak.H" #include "action_sponge.H" #define HASH_SIZE 64 #define RESULT_SIZE 8 #undef TEST /* get faster turn-around time */ #ifdef TEST /* NO_SYNTH */ /* TEST */ # define NB_SLICES 4 # define NB_ROUND 1<<10 #else # ifndef NB_SLICES # define NB_SLICES 65536 /* 4 */ //65536--for first synthesis # endif # ifndef NB_ROUND # define NB_ROUND 1<<24 /* 10 */ //24--for first synthesis # endif #endif uint64_t sponge (const uint64_t rank) { uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul, 0xfdecba9876543210ul,0xeca86420fdb97531ul, 0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul, 0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful}; uint64_t odd[8],even[8],result; int i,j; even_init: for(i=0;i<RESULT_SIZE;i++) { even[i] = magic[i] + rank; } //keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE); keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE); nb_round_process: for(i=0;i<NB_ROUND;i++) { process_odd: for(j=0;j<4;j++) { odd[2*j] ^= ROTL64( even[2*j] , 4*j+1); odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3); } //keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE); keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE); process_even: for(j=0;j<4;j++) { even[2*j] += ROTL64( odd[2*j] , 4*j+5); even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7); } //keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE); keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE); } result=0; process_result: for(i=0;i<RESULT_SIZE;i++) { result += (even[i] ^ odd[i]); } return result; } /* * WRITE RESULTS IN MMIO REGS * * Always check that ALL Outputs are tied to a value or HLS will generate a * Action_Output_i and a Action_Output_o registers and address to read results * will be shifted ...and wrong * => easy checking in generated files: * grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd * this grep should return nothing if no duplication of registers * (which is expected) */ static void write_results(action_output_reg *Action_Output, action_input_reg *Action_Input, snapu32_t ReturnCode, snapu64_t field1, snapu64_t field2) { Action_Output->Retc = (snapu32_t)ReturnCode; Action_Output->Data.chk_out = field1; Action_Output->Data.timer_ticks = field2; Action_Output->Data.action_version = RELEASE_VERSION; Action_Output->Reserved = 0; Action_Output->Data.in = Action_Input->Data.in; Action_Output->Data.chk_type = Action_Input->Data.chk_type; Action_Output->Data.chk_in = Action_Input->Data.chk_in; Action_Output->Data.pe = Action_Input->Data.pe; Action_Output->Data.nb_pe = Action_Input->Data.nb_pe; Action_Output->Data.nb_slices = NB_SLICES; Action_Output->Data.nb_round = NB_ROUND; } //----------------------------------------------------------------------------- //--- MAIN PROGRAM ------------------------------------------------------------ //----------------------------------------------------------------------------- /** * Remarks: Using pointers for the din_gmem, ... parameters is requiring to * to set the depth=... parameter via the pragma below. If missing to do this * the cosimulation will not work, since the width of the interface cannot * be determined. Using an array din_gmem[...] works too to fix that. */ void action_wrapper(snap_membus_t *din_gmem, snap_membus_t *dout_gmem, snap_membus_t *d_ddrmem, action_input_reg *Action_Input, action_output_reg *Action_Output) { // Host Memory AXI Interface #pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem #pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem #pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg #pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg //DDR memory Interface #pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0 #pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg // Host Memory AXI Lite Master Interface #pragma HLS DATA_PACK variable=Action_Input #pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg #pragma HLS DATA_PACK variable=Action_Output #pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg #pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg snapu32_t ReturnCode = 0; uint64_t checksum = 0; uint32_t slice = 0; uint32_t pe, nb_pe; uint64_t timer_ticks = 0; pe = Action_Input->Data.pe; nb_pe = Action_Input->Data.nb_pe; do { /* FIXME Please check if the data alignment matches the expectations */ if (Action_Input->Control.action != SPONGE_ACTION_TYPE) { ReturnCode = RET_CODE_FAILURE; break; } for (slice = 0; slice < NB_SLICES; slice++) { if (pe == (slice % nb_pe)) checksum ^= sponge(slice); } timer_ticks += 42; } while (0); write_results(Action_Output, Action_Input, ReturnCode, checksum, timer_ticks); } #ifdef NO_SYNTH /** * FIXME We need to use action_wrapper from here to get the real thing * simulated. For now let's take the short path and try without it. */ int main(void) { uint64_t slice; //uint32_t pe,nb_pe; uint64_t checksum=0; short i, rc=0; typedef struct { uint32_t pe; uint32_t nb_pe; uint64_t checksum; } arguments_t; static arguments_t sequence[] = { { 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 }, { 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 }, { 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 }, { 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe }, { 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb }, { 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b }, { 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa } }; for(i=0; i < 7; i++) { checksum = 0; for(slice=0;slice<NB_SLICES;slice++) { if(sequence[i].pe == (slice % sequence[i].nb_pe)) checksum ^= sponge(slice); } printf("pe=%d - nb_pe=%d - processed checksum=%016llx ", sequence[i].pe, sequence[i].nb_pe, (unsigned long long) checksum); if (sequence[i].checksum == checksum) { printf(" ==> CORRECT \n"); rc |= 0; } else { printf(" ==> ERROR : expected checksum=%016llx \n", (unsigned long long) sequence[i].checksum); rc |= 1; } } if (rc != 0) printf("\n\t Checksums are given with use of -DTEST " "flag. Please check you have set it!\n\n"); return rc; } #endif // end of NO_SYNTH flag <commit_msg>HLS Sponge: Adding code to display status in MMIO registers ...<commit_after>/* * Sponge: hash sha-3 (keccak) */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "keccak.H" #include "action_sponge.H" #define HASH_SIZE 64 #define RESULT_SIZE 8 #undef TEST /* get faster turn-around time */ #ifdef TEST /* NO_SYNTH */ /* TEST */ # define NB_SLICES 4 # define NB_ROUND 1<<10 #else # ifndef NB_SLICES # define NB_SLICES 65536 /* 4 */ //65536--for first synthesis # endif # ifndef NB_ROUND # define NB_ROUND 1<<24 /* 10 */ //24--for first synthesis # endif #endif uint64_t sponge (const uint64_t rank) { uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul, 0xfdecba9876543210ul,0xeca86420fdb97531ul, 0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul, 0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful}; uint64_t odd[8],even[8],result; int i,j; even_init: for(i=0;i<RESULT_SIZE;i++) { even[i] = magic[i] + rank; } //keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE); keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE); nb_round_process: for(i=0;i<NB_ROUND;i++) { process_odd: for(j=0;j<4;j++) { odd[2*j] ^= ROTL64( even[2*j] , 4*j+1); odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3); } //keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE); keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE); process_even: for(j=0;j<4;j++) { even[2*j] += ROTL64( odd[2*j] , 4*j+5); even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7); } //keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE); keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE); } result=0; process_result: for(i=0;i<RESULT_SIZE;i++) { result += (even[i] ^ odd[i]); } return result; } /* * WRITE RESULTS IN MMIO REGS * * Always check that ALL Outputs are tied to a value or HLS will generate a * Action_Output_i and a Action_Output_o registers and address to read results * will be shifted ...and wrong * => easy checking in generated files: * grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd * this grep should return nothing if no duplication of registers * (which is expected) */ static void write_results(action_output_reg *Action_Output, action_input_reg *Action_Input, snapu32_t ReturnCode, snapu64_t field1, snapu64_t field2) { Action_Output->Retc = (snapu32_t)ReturnCode; Action_Output->Data.chk_out = field1; Action_Output->Data.timer_ticks = field2; Action_Output->Data.action_version = RELEASE_VERSION; Action_Output->Reserved = 0; Action_Output->Data.in = Action_Input->Data.in; Action_Output->Data.chk_type = Action_Input->Data.chk_type; Action_Output->Data.chk_in = Action_Input->Data.chk_in; Action_Output->Data.pe = Action_Input->Data.pe; Action_Output->Data.nb_pe = Action_Input->Data.nb_pe; Action_Output->Data.nb_slices = NB_SLICES; Action_Output->Data.nb_round = NB_ROUND; } //----------------------------------------------------------------------------- //--- MAIN PROGRAM ------------------------------------------------------------ //----------------------------------------------------------------------------- /** * Remarks: Using pointers for the din_gmem, ... parameters is requiring to * to set the depth=... parameter via the pragma below. If missing to do this * the cosimulation will not work, since the width of the interface cannot * be determined. Using an array din_gmem[...] works too to fix that. */ void action_wrapper(snap_membus_t *din_gmem, snap_membus_t *dout_gmem, snap_membus_t *d_ddrmem, action_input_reg *Action_Input, action_output_reg *Action_Output) { // Host Memory AXI Interface #pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem #pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem #pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg #pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg //DDR memory Interface #pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0 #pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg // Host Memory AXI Lite Master Interface #pragma HLS DATA_PACK variable=Action_Input #pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg #pragma HLS DATA_PACK variable=Action_Output #pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg #pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg snapu32_t ReturnCode = 0; uint64_t checksum = 0; uint32_t slice = 0; uint32_t pe, nb_pe; uint64_t timer_ticks = 0; pe = Action_Input->Data.pe; nb_pe = Action_Input->Data.nb_pe; do { /* FIXME Please check if the data alignment matches the expectations */ if (Action_Input->Control.action != SPONGE_ACTION_TYPE) { ReturnCode = RET_CODE_FAILURE; break; } for (slice = 0; slice < NB_SLICES; slice++) { if (pe == (slice % nb_pe)) { checksum ^= sponge(slice); /* Intermediate result display */ write_results(Action_Output, Action_Input, ReturnCode, checksum, slice); } } timer_ticks += 42; } while (0); /* Final output register writes */ write_results(Action_Output, Action_Input, ReturnCode, checksum, timer_ticks); } #ifdef NO_SYNTH /** * FIXME We need to use action_wrapper from here to get the real thing * simulated. For now let's take the short path and try without it. */ int main(void) { uint64_t slice; //uint32_t pe,nb_pe; uint64_t checksum=0; short i, rc=0; typedef struct { uint32_t pe; uint32_t nb_pe; uint64_t checksum; } arguments_t; static arguments_t sequence[] = { { 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 }, { 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 }, { 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 }, { 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe }, { 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb }, { 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b }, { 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa } }; for(i=0; i < 7; i++) { checksum = 0; for(slice=0;slice<NB_SLICES;slice++) { if(sequence[i].pe == (slice % sequence[i].nb_pe)) checksum ^= sponge(slice); } printf("pe=%d - nb_pe=%d - processed checksum=%016llx ", sequence[i].pe, sequence[i].nb_pe, (unsigned long long) checksum); if (sequence[i].checksum == checksum) { printf(" ==> CORRECT \n"); rc |= 0; } else { printf(" ==> ERROR : expected checksum=%016llx \n", (unsigned long long) sequence[i].checksum); rc |= 1; } } if (rc != 0) printf("\n\t Checksums are given with use of -DTEST " "flag. Please check you have set it!\n\n"); return rc; } #endif // end of NO_SYNTH flag <|endoftext|>
<commit_before>#include <coffee/core/CUnitTesting> #include <coffee/core/CFiles> using namespace Coffee; const cstring testfile = "fileapi_testfile.txt"; using File = FileFun; const cstring writetest = "file_write_large.bin"; byte_t write_data[100] = { "I'M THE TRASHMAN. I THROW GARBAGE ALL OVER THE RING, AND THEN I START EATING GARBAGE.\n" }; const constexpr szptr dynamic_size = Unit_GB*5; void* dynamic_store = nullptr; bool filewrite_test() { Resource rsc(writetest); rsc.size = dynamic_size; Profiler::Profile("Pre-allocation setup"); rsc.data = Calloc(1,rsc.size); Profiler::Profile("5GB allocation"); { byte_t* dest = (byte_t*)rsc.data; /* Write some data below 4GB mark */ MemCpy(dest,write_data,sizeof(write_data)); /* Write data above 4GB mark, requires 64-bit. Fuck 32-bit. */ MemCpy(&dest[Unit_GB*4],write_data,sizeof(write_data)); } Profiler::Profile("Copying data into segment"); dynamic_store = rsc.data; bool stat = FileCommit(rsc,false, ResourceAccess::WriteOnly | ResourceAccess::Discard); Profiler::Profile("Writing 5GB of data to disk"); return stat; } bool fileread_test() { bool status = true; Resource rsc(writetest); Profiler::Profile("Pre-reading setup"); status = CResources::FilePull(rsc); Profiler::Profile("Reading massive data"); if(status) { status = (dynamic_size == rsc.size); if(status) { status = MemCmp(dynamic_store,rsc.data,dynamic_size); Profiler::Profile("Comparing 5GB of data"); } CResources::FileFree(rsc); Profiler::Profile("Freeing 5GB of data"); File::Rm(writetest); Profiler::Profile("Deleting file"); } return status; } const constexpr CoffeeTest::Test _tests[2] = { {filewrite_test,"Massive file writing","Writing lots of text data to disk"}, {fileread_test,"Massive file reading","Reading lots of text data from disk"}, }; COFFEE_RUN_TESTS(_tests); <commit_msg> - Make use of user-defined literals for readability<commit_after>#include <coffee/core/CUnitTesting> #include <coffee/core/CFiles> using namespace Coffee; const cstring testfile = "fileapi_testfile.txt"; using File = FileFun; const cstring writetest = "file_write_large.bin"; byte_t write_data[100] = { "I'M THE TRASHMAN. I THROW GARBAGE ALL OVER THE RING, AND THEN I START EATING GARBAGE.\n" }; const szptr dynamic_size = 5_GB; void* dynamic_store = nullptr; bool filewrite_test() { Resource rsc(writetest); rsc.size = dynamic_size; Profiler::Profile("Pre-allocation setup"); rsc.data = Calloc(1,rsc.size); Profiler::Profile("5GB allocation"); { byte_t* dest = (byte_t*)rsc.data; /* Write some data below 4GB mark */ MemCpy(dest,write_data,sizeof(write_data)); /* Write data above 4GB mark, requires 64-bit. Fuck 32-bit. */ MemCpy(&dest[4_GB],write_data,sizeof(write_data)); } Profiler::Profile("Copying data into segment"); dynamic_store = rsc.data; bool stat = FileCommit(rsc,false, ResourceAccess::WriteOnly | ResourceAccess::Discard); Profiler::Profile("Writing 5GB of data to disk"); return stat; } bool fileread_test() { bool status = true; Resource rsc(writetest); Profiler::Profile("Pre-reading setup"); status = CResources::FilePull(rsc); Profiler::Profile("Reading massive data"); if(status) { status = (dynamic_size == rsc.size); if(status) { status = MemCmp(dynamic_store,rsc.data,dynamic_size); Profiler::Profile("Comparing 5GB of data"); } CResources::FileFree(rsc); Profiler::Profile("Freeing 5GB of data"); File::Rm(writetest); Profiler::Profile("Deleting file"); } return status; } const constexpr CoffeeTest::Test _tests[2] = { {filewrite_test,"Massive file writing","Writing lots of text data to disk"}, {fileread_test,"Massive file reading","Reading lots of text data from disk"}, }; COFFEE_RUN_TESTS(_tests); <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Arjen Hiemstra <> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * 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 */ #include "qtscriptcomponent.h" #include <QtScript/QScriptEngine> #include <QtCore/QDebug> #include <gameobject.h> #include <core/debughelper.h> #include <game.h> #include <engine/asset.h> #include <QMimeData> #include <core/gluonobject.h> REGISTER_OBJECTTYPE(GluonEngine, QtScriptComponent) using namespace GluonEngine; void qtscript_initialize_com_trolltech_qt_gui_bindings(QScriptValue &); class QtScriptComponent::QtScriptComponentPrivate { public: QtScriptComponentPrivate() { QScriptValue extensionObject = engine.globalObject(); qtscript_initialize_com_trolltech_qt_gui_bindings(extensionObject); script = 0; } QScriptEngine engine; QScriptValue drawFunc; QScriptValue updateFunc; GluonEngine::Asset* script; }; QtScriptComponent::QtScriptComponent(QObject* parent) : Component(parent) { d = new QtScriptComponentPrivate; qScriptRegisterMetaType(&d->engine, gluonObjectToScriptValue, gluonObjectFromScriptValue); qScriptRegisterMetaType(&d->engine, gameObjectToScriptValue, gameObjectFromScriptValue); } QtScriptComponent::QtScriptComponent(const QtScriptComponent& other) : Component(other), d(other.d) { } QtScriptComponent::~QtScriptComponent() { delete d; } void QtScriptComponent::initialize() { if (!d->script) return; d->script->load(); if (d->script->data()->hasText()) { d->engine.evaluate(d->script->data()->text(), gameObject()->name()); if (d->engine.uncaughtException().isValid()) { debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); return; } QScriptValue component = d->engine.newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("Component", component); QScriptValue gameObj = d->engine.newQObject(gameObject(), QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("GameObject", gameObj); QScriptValue game = d->engine.newQObject(Game::instance(), QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("Game", game); d->updateFunc = d->engine.globalObject().property("update"); d->drawFunc = d->engine.globalObject().property("draw"); QScriptValue initFunc = d->engine.globalObject().property("initialize"); if (initFunc.isFunction()) { initFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::start() { if(d->script) { QScriptValue startFunc = d->engine.globalObject().property("start"); if (startFunc.isFunction()) { startFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::draw(int timeLapse) { if(d->drawFunc.isFunction()) { d->drawFunc.call(QScriptValue(), QScriptValueList() << timeLapse); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } void QtScriptComponent::update(int elapsedMilliseconds) { if(d->updateFunc.isFunction()) { d->updateFunc.call(QScriptValue(), QScriptValueList() << elapsedMilliseconds); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } void QtScriptComponent::stop() { if(d->script) { QScriptValue stopFunc = d->engine.globalObject().property("stop"); if (stopFunc.isFunction()) { stopFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::cleanup() { if(d->script) { QScriptValue cleanupFunc = d->engine.globalObject().property("cleanup"); if (cleanupFunc.isFunction()) { cleanupFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } Asset* QtScriptComponent::script() { return d->script; } void QtScriptComponent::setScript(Asset* asset) { d->script = asset; } QScriptValue gluonObjectToScriptValue(QScriptEngine *engine, const pGluonObject &in) { return engine->newQObject(in); } void gluonObjectFromScriptValue(const QScriptValue &object, pGluonObject &out) { out = qobject_cast<GluonCore::GluonObject*>(object.toQObject()); } QScriptValue gameObjectToScriptValue(QScriptEngine *engine, const pGameObject &in) { return engine->newQObject(in); } void gameObjectFromScriptValue(const QScriptValue &object, pGameObject &out) { out = qobject_cast<GameObject*>(object.toQObject()); } Q_EXPORT_PLUGIN2(gluon_component_qtscript, GluonEngine::QtScriptComponent); #include "qtscriptcomponent.moc" <commit_msg>Stop updating/drawing if an error occurs. This prevents message flood<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Arjen Hiemstra <> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * 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 */ #include "qtscriptcomponent.h" #include <QtScript/QScriptEngine> #include <QtCore/QDebug> #include <gameobject.h> #include <core/debughelper.h> #include <game.h> #include <engine/asset.h> #include <QMimeData> #include <core/gluonobject.h> REGISTER_OBJECTTYPE(GluonEngine, QtScriptComponent) using namespace GluonEngine; void qtscript_initialize_com_trolltech_qt_gui_bindings(QScriptValue &); class QtScriptComponent::QtScriptComponentPrivate { public: QtScriptComponentPrivate() { QScriptValue extensionObject = engine.globalObject(); qtscript_initialize_com_trolltech_qt_gui_bindings(extensionObject); script = 0; } QScriptEngine engine; QScriptValue drawFunc; QScriptValue updateFunc; GluonEngine::Asset* script; }; QtScriptComponent::QtScriptComponent(QObject* parent) : Component(parent) { d = new QtScriptComponentPrivate; qScriptRegisterMetaType(&d->engine, gluonObjectToScriptValue, gluonObjectFromScriptValue); qScriptRegisterMetaType(&d->engine, gameObjectToScriptValue, gameObjectFromScriptValue); } QtScriptComponent::QtScriptComponent(const QtScriptComponent& other) : Component(other), d(other.d) { } QtScriptComponent::~QtScriptComponent() { delete d; } void QtScriptComponent::initialize() { if (!d->script) return; d->script->load(); if (d->script->data()->hasText()) { d->engine.evaluate(d->script->data()->text(), gameObject()->name()); if (d->engine.uncaughtException().isValid()) { debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); return; } QScriptValue component = d->engine.newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("Component", component); QScriptValue gameObj = d->engine.newQObject(gameObject(), QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("GameObject", gameObj); QScriptValue game = d->engine.newQObject(Game::instance(), QScriptEngine::QtOwnership, QScriptEngine::AutoCreateDynamicProperties); d->engine.globalObject().setProperty("Game", game); d->updateFunc = d->engine.globalObject().property("update"); d->drawFunc = d->engine.globalObject().property("draw"); QScriptValue initFunc = d->engine.globalObject().property("initialize"); if (initFunc.isFunction()) { initFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::start() { if(d->script) { QScriptValue startFunc = d->engine.globalObject().property("start"); if (startFunc.isFunction()) { startFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::draw(int timeLapse) { if(d->drawFunc.isFunction()) { d->drawFunc.call(QScriptValue(), QScriptValueList() << timeLapse); if (d->engine.uncaughtException().isValid()) { debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); d->drawFunc = QScriptValue(); } } } void QtScriptComponent::update(int elapsedMilliseconds) { if(d->updateFunc.isFunction()) { d->updateFunc.call(QScriptValue(), QScriptValueList() << elapsedMilliseconds); if (d->engine.uncaughtException().isValid()) { debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); d->updateFunc = QScriptValue(); } } } void QtScriptComponent::stop() { if(d->script) { QScriptValue stopFunc = d->engine.globalObject().property("stop"); if (stopFunc.isFunction()) { stopFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } void QtScriptComponent::cleanup() { if(d->script) { QScriptValue cleanupFunc = d->engine.globalObject().property("cleanup"); if (cleanupFunc.isFunction()) { cleanupFunc.call(QScriptValue()); if (d->engine.uncaughtException().isValid()) debug(QString("%1: %2").arg(d->engine.uncaughtException().toString()).arg(d->engine.uncaughtExceptionBacktrace().join(" "))); } } } Asset* QtScriptComponent::script() { return d->script; } void QtScriptComponent::setScript(Asset* asset) { d->script = asset; } QScriptValue gluonObjectToScriptValue(QScriptEngine *engine, const pGluonObject &in) { return engine->newQObject(in); } void gluonObjectFromScriptValue(const QScriptValue &object, pGluonObject &out) { out = qobject_cast<GluonCore::GluonObject*>(object.toQObject()); } QScriptValue gameObjectToScriptValue(QScriptEngine *engine, const pGameObject &in) { return engine->newQObject(in); } void gameObjectFromScriptValue(const QScriptValue &object, pGameObject &out) { out = qobject_cast<GameObject*>(object.toQObject()); } Q_EXPORT_PLUGIN2(gluon_component_qtscript, GluonEngine::QtScriptComponent); #include "qtscriptcomponent.moc" <|endoftext|>
<commit_before>#include "coreclrutil.h" #include <dirent.h> #include <dlfcn.h> #include <assert.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <cstdlib> #include <iostream> #include <set> #include <unicode/unistr.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) constexpr char coreClrDll[] = "libcoreclr.dylib"; #else constexpr char coreClrDll[] = "libcoreclr.so"; #endif void* coreclrLib; // Prototype of the coreclr_initialize function from the libcoreclr.so typedef int (*InitializeCoreCLRFunction)( const char* exePath, const char* appDomainFriendlyName, int propertyCount, const char** propertyKeys, const char** propertyValues, void** hostHandle, unsigned int* domainId); // Prototype of the coreclr_shutdown function from the libcoreclr.so typedef int (*ShutdownCoreCLRFunction)( void* hostHandle, unsigned int domainId); InitializeCoreCLRFunction initializeCoreCLR; ShutdownCoreCLRFunction shutdownCoreCLR; ExecuteAssemblyFunction executeAssembly; CreateDelegateFunction createDelegate; // // Below is from unixcoreruncommon/coreruncommon.cpp // bool GetAbsolutePath(const char* path, std::string& absolutePath) { char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); return true; } std::cerr << "failed to get absolute path for " << path << std::endl; return false; } // TODO use dirname bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } std::cerr << "failed to get directory for " << absolutePath << std::endl; return false; } // // Get the absolute path given the environment variable. // // Return true in case of a success, false otherwise. // bool GetEnvAbsolutePath(const char* env_var, std::string& absolutePath) { const char* filesPathLocal = std::getenv(env_var);; if (filesPathLocal == nullptr) { std::cerr << "failed because $" << env_var << " was empty" << std::endl; return false; } if (!GetAbsolutePath(filesPathLocal, absolutePath)) { std::cerr << "failed to get absolute path for " << env_var << std::endl; return false; } return true; } // Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory to the tpaList string. void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (unsigned int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } // // Below is our custom start/stop interface // int startCoreCLR( const char* appDomainFriendlyName, void** hostHandle, unsigned int* domainId) { // get path to current executable char exePath[PATH_MAX] = { 0 }; readlink("/proc/self/exe", exePath, PATH_MAX); // get the CoreCLR root path std::string clrFilesAbsolutePath; if(!GetEnvAbsolutePath("CORE_ROOT", clrFilesAbsolutePath)) { return -1; } // get the CoreCLR shared library path std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); // open the shared library coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW|RTLD_LOCAL); if (coreclrLib == nullptr) { char* error = dlerror(); std::cerr << "dlopen failed to open the CoreCLR library: " << error << std::endl; return -1; } // query and verify the function pointers initializeCoreCLR = (InitializeCoreCLRFunction)dlsym(coreclrLib,"coreclr_initialize"); shutdownCoreCLR = (ShutdownCoreCLRFunction)dlsym(coreclrLib,"coreclr_shutdown"); executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib,"coreclr_execute_assembly"); createDelegate = (CreateDelegateFunction)dlsym(coreclrLib,"coreclr_create_delegate"); if (initializeCoreCLR == nullptr) { std::cerr << "function coreclr_initialize not found in CoreCLR library" << std::endl; return -1; } if (executeAssembly == nullptr) { std::cerr << "function coreclr_execute_assembly not found in CoreCLR library" << std::endl; return -1; } if (shutdownCoreCLR == nullptr) { std::cerr << "function coreclr_shutdown not found in CoreCLR library" << std::endl; return -1; } if (createDelegate == nullptr) { std::cerr << "function coreclr_create_delegate not found in CoreCLR library" << std::endl; return -1; } // generate the Trusted Platform Assemblies list std::string tpaList; // add assemblies in the CoreCLR root path AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath.c_str(), tpaList); // get path to AssemblyLoadContext.dll std::string psAbsolutePath; if(!GetEnvAbsolutePath("PWRSH_ROOT", psAbsolutePath)) { return -1; } std::string assemblyLoadContextAbsoluteFilePath(psAbsolutePath + "/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll"); // add AssemblyLoadContext tpaList.append(assemblyLoadContextAbsoluteFilePath); // generate the assembly search paths std::string appPath(psAbsolutePath); // TODO: add LD_LIBRARY_PATH? std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); // create list of properties to initialize CoreCLR const char* propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char* propertyValues[] = { tpaList.c_str(), appPath.c_str(), appPath.c_str(), nativeDllSearchDirs.c_str(), "UseLatestBehaviorWhenTFMNotSpecified" }; // initialize CoreCLR int status = initializeCoreCLR( exePath, appDomainFriendlyName, sizeof(propertyKeys)/sizeof(propertyKeys[0]), propertyKeys, propertyValues, hostHandle, domainId); if (!SUCCEEDED(status)) { std::cerr << "coreclr_initialize failed - status: " << std::hex << status << std::endl; return -1; } // initialize PowerShell's custom assembly load context typedef void (*LoaderRunHelperFp)(const char16_t* appPath); LoaderRunHelperFp loaderDelegate = nullptr; status = createDelegate( *hostHandle, *domainId, "Microsoft.PowerShell.CoreCLR.AssemblyLoadContext, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Management.Automation.PowerShellAssemblyLoadContextInitializer", "SetPowerShellAssemblyLoadContext", (void**)&loaderDelegate); if (!SUCCEEDED(status)) { std::cerr << "could not create delegate for SetPowerShellAssemblyLoadContext - status: " << std::hex << status << std::endl; return -1; } icu::UnicodeString psUnicodeAbsolutePath = icu::UnicodeString::fromUTF8(psAbsolutePath.c_str()); loaderDelegate((const char16_t*)psUnicodeAbsolutePath.getTerminatedBuffer()); return status; } int stopCoreCLR(void* hostHandle, unsigned int domainId) { // shutdown CoreCLR int status = shutdownCoreCLR(hostHandle, domainId); if (!SUCCEEDED(status)) { std::cerr << "coreclr_shutdown failed - status: " << std::hex << status << std::endl; } // close the dynamic library if (0 != dlclose(coreclrLib)) { std::cerr << "failed to close CoreCLR library" << std::endl; } return status; } <commit_msg>Rename variables and reorganize<commit_after>#include "coreclrutil.h" #include <dirent.h> #include <dlfcn.h> #include <assert.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <cstdlib> #include <iostream> #include <set> #include <unicode/unistr.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) constexpr char coreClrDll[] = "libcoreclr.dylib"; #else constexpr char coreClrDll[] = "libcoreclr.so"; #endif void* coreclrLib; // Prototype of the coreclr_initialize function from the libcoreclr.so typedef int (*InitializeCoreCLRFunction)( const char* exePath, const char* appDomainFriendlyName, int propertyCount, const char** propertyKeys, const char** propertyValues, void** hostHandle, unsigned int* domainId); // Prototype of the coreclr_shutdown function from the libcoreclr.so typedef int (*ShutdownCoreCLRFunction)( void* hostHandle, unsigned int domainId); InitializeCoreCLRFunction initializeCoreCLR; ShutdownCoreCLRFunction shutdownCoreCLR; ExecuteAssemblyFunction executeAssembly; CreateDelegateFunction createDelegate; // // Below is from unixcoreruncommon/coreruncommon.cpp // bool GetAbsolutePath(const char* path, std::string& absolutePath) { char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); return true; } std::cerr << "failed to get absolute path for " << path << std::endl; return false; } // TODO use dirname bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } std::cerr << "failed to get directory for " << absolutePath << std::endl; return false; } // // Get the absolute path given the environment variable. // // Return true in case of a success, false otherwise. // bool GetEnvAbsolutePath(const char* env_var, std::string& absolutePath) { const char* filesPathLocal = std::getenv(env_var);; if (filesPathLocal == nullptr) { std::cerr << "failed because $" << env_var << " was empty" << std::endl; return false; } if (!GetAbsolutePath(filesPathLocal, absolutePath)) { std::cerr << "failed to get absolute path for " << env_var << std::endl; return false; } return true; } // Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory to the tpaList string. void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (unsigned int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } // // Below is our custom start/stop interface // int startCoreCLR( const char* appDomainFriendlyName, void** hostHandle, unsigned int* domainId) { // get the CoreCLR root path std::string clrAbsolutePath; if(!GetEnvAbsolutePath("CORE_ROOT", clrAbsolutePath)) { return -1; } // get the CoreCLR shared library path std::string coreClrDllPath(clrAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); // open the shared library coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW|RTLD_LOCAL); if (coreclrLib == nullptr) { char* error = dlerror(); std::cerr << "dlopen failed to open the CoreCLR library: " << error << std::endl; return -1; } // query and verify the function pointers initializeCoreCLR = (InitializeCoreCLRFunction)dlsym(coreclrLib,"coreclr_initialize"); shutdownCoreCLR = (ShutdownCoreCLRFunction)dlsym(coreclrLib,"coreclr_shutdown"); executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib,"coreclr_execute_assembly"); createDelegate = (CreateDelegateFunction)dlsym(coreclrLib,"coreclr_create_delegate"); if (initializeCoreCLR == nullptr) { std::cerr << "function coreclr_initialize not found in CoreCLR library" << std::endl; return -1; } if (executeAssembly == nullptr) { std::cerr << "function coreclr_execute_assembly not found in CoreCLR library" << std::endl; return -1; } if (shutdownCoreCLR == nullptr) { std::cerr << "function coreclr_shutdown not found in CoreCLR library" << std::endl; return -1; } if (createDelegate == nullptr) { std::cerr << "function coreclr_create_delegate not found in CoreCLR library" << std::endl; return -1; } // generate the Trusted Platform Assemblies list std::string tpaList; // add assemblies in the CoreCLR root path AddFilesFromDirectoryToTpaList(clrAbsolutePath.c_str(), tpaList); // get path to AssemblyLoadContext.dll std::string psAbsolutePath; if(!GetEnvAbsolutePath("PWRSH_ROOT", psAbsolutePath)) { return -1; } std::string alcAbsolutePath(psAbsolutePath); alcAbsolutePath.append("/"); alcAbsolutePath.append("Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll"); // add AssemblyLoadContext tpaList.append(alcAbsolutePath); // generate the assembly search paths std::string appPath(psAbsolutePath); // TODO: add LD_LIBRARY_PATH? std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrAbsolutePath); // create list of properties to initialize CoreCLR const char* propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char* propertyValues[] = { tpaList.c_str(), appPath.c_str(), appPath.c_str(), nativeDllSearchDirs.c_str(), "UseLatestBehaviorWhenTFMNotSpecified" }; // get path to current executable char exePath[PATH_MAX] = { 0 }; readlink("/proc/self/exe", exePath, PATH_MAX); // initialize CoreCLR int status = initializeCoreCLR( exePath, appDomainFriendlyName, sizeof(propertyKeys)/sizeof(propertyKeys[0]), propertyKeys, propertyValues, hostHandle, domainId); if (!SUCCEEDED(status)) { std::cerr << "coreclr_initialize failed - status: " << std::hex << status << std::endl; return -1; } // initialize PowerShell's custom assembly load context typedef void (*LoaderRunHelperFp)(const char16_t* appPath); LoaderRunHelperFp loaderDelegate = nullptr; status = createDelegate( *hostHandle, *domainId, "Microsoft.PowerShell.CoreCLR.AssemblyLoadContext, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Management.Automation.PowerShellAssemblyLoadContextInitializer", "SetPowerShellAssemblyLoadContext", (void**)&loaderDelegate); if (!SUCCEEDED(status)) { std::cerr << "could not create delegate for SetPowerShellAssemblyLoadContext - status: " << std::hex << status << std::endl; return -1; } icu::UnicodeString psUnicodeAbsolutePath = icu::UnicodeString::fromUTF8(psAbsolutePath.c_str()); loaderDelegate((const char16_t*)psUnicodeAbsolutePath.getTerminatedBuffer()); return status; } int stopCoreCLR(void* hostHandle, unsigned int domainId) { // shutdown CoreCLR int status = shutdownCoreCLR(hostHandle, domainId); if (!SUCCEEDED(status)) { std::cerr << "coreclr_shutdown failed - status: " << std::hex << status << std::endl; } // close the dynamic library if (0 != dlclose(coreclrLib)) { std::cerr << "failed to close CoreCLR library" << std::endl; } return status; } <|endoftext|>
<commit_before>/** * @file mean_shift_impl.hpp * @author Shangtong Zhang * * Mean shift clustering implementation. */ #ifndef __MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP #define __MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP #include <mlpack/core/kernels/gaussian_kernel.hpp> #include <mlpack/core/kernels/kernel_traits.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <mlpack/methods/neighbor_search/neighbor_search.hpp> #include <mlpack/methods/neighbor_search/neighbor_search_stat.hpp> #include <mlpack/methods/range_search/range_search.hpp> #include "map" // In case it hasn't been included yet. #include "mean_shift.hpp" namespace mlpack { namespace meanshift { /** * Construct the Mean Shift object. */ template<bool UseKernel, typename KernelType, typename MatType> MeanShift<UseKernel, KernelType, MatType>:: MeanShift(const double radius, const size_t maxIterations, const KernelType kernel) : radius(radius), maxIterations(maxIterations), kernel(kernel) { // Nothing to do. } template<bool UseKernel, typename KernelType, typename MatType> void MeanShift<UseKernel, KernelType, MatType>::Radius(double radius) { this->radius = radius; } // Estimate radius based on given dataset. template<bool UseKernel, typename KernelType, typename MatType> double MeanShift<UseKernel, KernelType, MatType>:: EstimateRadius(const MatType& data, double ratio) { neighbor::AllkNN neighborSearch(data); /** * For each point in dataset, select nNeighbors nearest points and get * nNeighbors distances. Use the maximum distance to estimate the duplicate * threshhold. */ const size_t nNeighbors = size_t(data.n_cols * ratio); arma::Mat<size_t> neighbors; arma::mat distances; neighborSearch.Search(nNeighbors, neighbors, distances); // Get max distance for each point. arma::rowvec maxDistances = max(distances); // Calculate and return the radius. return sum(maxDistances) / (double) data.n_cols; } // Class to compare two vectors. template <typename VecType> class less { public: bool operator()(const VecType& first, const VecType& second) const { for (size_t i = 0; i < first.n_rows; ++i) { if (first[i] == second[i]) continue; return first(i) < second(i); } return false; } }; // Generate seeds from given data set. template<bool UseKernel, typename KernelType, typename MatType> void MeanShift<UseKernel, KernelType, MatType>::GenSeeds( const MatType& data, const double binSize, const int minFreq, MatType& seeds) { typedef arma::colvec VecType; std::map<VecType, int, less<VecType> > allSeeds; for (size_t i = 0; i < data.n_cols; ++i) { VecType binnedPoint = arma::floor(data.unsafe_col(i) / binSize); if (allSeeds.find(binnedPoint) == allSeeds.end()) allSeeds[binnedPoint] = 1; else allSeeds[binnedPoint]++; } // Remove seeds with too few points. std::map<VecType, int, less<VecType> >::iterator it; for (it = allSeeds.begin(); it != allSeeds.end(); ++it) { if (it->second >= minFreq) seeds.insert_cols(seeds.n_cols, it->first); } seeds = seeds * binSize; } // Calculate new centroid with given kernel. template<bool UseKernel, typename KernelType, typename MatType> template<bool ApplyKernel> typename std::enable_if<ApplyKernel, bool>::type MeanShift<UseKernel, KernelType, MatType>:: CalculateCentroid(const MatType& data, const std::vector<size_t>& neighbors, const std::vector<double>& distances, arma::colvec& centroid) { double sumWeight = 0; for (size_t i = 0; i < neighbors.size(); ++i) { if (distances[i] > 0) { double dist = distances[i] / radius; double weight = kernel.Gradient(dist) / dist; sumWeight += weight; centroid += weight * data.unsafe_col(neighbors[i]); } } if (sumWeight != 0) { centroid /= sumWeight; return true; } return false; } // Calculate new centroid by mean. template<bool UseKernel, typename KernelType, typename MatType> template<bool ApplyKernel> typename std::enable_if<!ApplyKernel, bool>::type MeanShift<UseKernel, KernelType, MatType>:: CalculateCentroid(const MatType& data, const std::vector<size_t>& neighbors, const std::vector<double>&, /*unused*/ arma::colvec& centroid) { for (size_t i = 0; i < neighbors.size(); ++i) centroid += data.unsafe_col(neighbors[i]); centroid /= neighbors.size(); return true; } /** * Perform Mean Shift clustering on the data set, returning a list of cluster * assignments and centroids. */ template<bool UseKernel, typename KernelType, typename MatType> inline void MeanShift<UseKernel, KernelType, MatType>::Cluster( const MatType& data, arma::Col<size_t>& assignments, arma::mat& centroids, bool useSeeds) { if (radius <= 0) { // An invalid radius is given; an estimation is needed. Radius(EstimateRadius(data)); } MatType seeds; const MatType* pSeeds = &data; if (useSeeds) { GenSeeds(data, radius, 1, seeds); pSeeds = &seeds; } // Holds all centroids before removing duplicate ones. arma::mat allCentroids(pSeeds->n_rows, pSeeds->n_cols); assignments.set_size(data.n_cols); range::RangeSearch<> rangeSearcher(data); math::Range validRadius(0, radius); std::vector<std::vector<size_t> > neighbors; std::vector<std::vector<double> > distances; // For each seed, perform mean shift algorithm. for (size_t i = 0; i < pSeeds->n_cols; ++i) { // Initial centroid is the seed itself. allCentroids.col(i) = pSeeds->unsafe_col(i); for (size_t completedIterations = 0; completedIterations < maxIterations; completedIterations++) { // Store new centroid in this. arma::colvec newCentroid = arma::zeros<arma::colvec>(pSeeds->n_rows); rangeSearcher.Search(allCentroids.unsafe_col(i), validRadius, neighbors, distances); if (neighbors[0].size() <= 1) break; // Calculate new centroid. if (!CalculateCentroid(data, neighbors[0], distances[0], newCentroid)) newCentroid = allCentroids.unsafe_col(i); // If the mean shift vector is small enough, it has converged. if (metric::EuclideanDistance::Evaluate(newCentroid, allCentroids.unsafe_col(i)) < 1e-3 * radius) { // Determine if the new centroid is duplicate with old ones. bool isDuplicated = false; for (size_t k = 0; k < centroids.n_cols; ++k) { const double distance = metric::EuclideanDistance::Evaluate( allCentroids.unsafe_col(i), centroids.unsafe_col(k)); if (distance < radius) { isDuplicated = true; break; } } if (!isDuplicated) centroids.insert_cols(centroids.n_cols, allCentroids.unsafe_col(i)); // Get out of the loop. break; } // Update the centroid. allCentroids.col(i) = newCentroid; } } // Assign centroids to each point. neighbor::AllkNN neighborSearcher(centroids); arma::mat neighborDistances; arma::Mat<size_t> resultingNeighbors; neighborSearcher.Search(data, 1, resultingNeighbors, neighborDistances); assignments = resultingNeighbors.t(); } } // namespace meanshift } // namespace mlpack #endif <commit_msg>Minor/trivial speedup: preallocate the matrix.<commit_after>/** * @file mean_shift_impl.hpp * @author Shangtong Zhang * * Mean shift clustering implementation. */ #ifndef __MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP #define __MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP #include <mlpack/core/kernels/gaussian_kernel.hpp> #include <mlpack/core/kernels/kernel_traits.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <mlpack/methods/neighbor_search/neighbor_search.hpp> #include <mlpack/methods/neighbor_search/neighbor_search_stat.hpp> #include <mlpack/methods/range_search/range_search.hpp> #include "map" // In case it hasn't been included yet. #include "mean_shift.hpp" namespace mlpack { namespace meanshift { /** * Construct the Mean Shift object. */ template<bool UseKernel, typename KernelType, typename MatType> MeanShift<UseKernel, KernelType, MatType>:: MeanShift(const double radius, const size_t maxIterations, const KernelType kernel) : radius(radius), maxIterations(maxIterations), kernel(kernel) { // Nothing to do. } template<bool UseKernel, typename KernelType, typename MatType> void MeanShift<UseKernel, KernelType, MatType>::Radius(double radius) { this->radius = radius; } // Estimate radius based on given dataset. template<bool UseKernel, typename KernelType, typename MatType> double MeanShift<UseKernel, KernelType, MatType>:: EstimateRadius(const MatType& data, double ratio) { neighbor::AllkNN neighborSearch(data); /** * For each point in dataset, select nNeighbors nearest points and get * nNeighbors distances. Use the maximum distance to estimate the duplicate * threshhold. */ const size_t nNeighbors = size_t(data.n_cols * ratio); arma::Mat<size_t> neighbors; arma::mat distances; neighborSearch.Search(nNeighbors, neighbors, distances); // Get max distance for each point. arma::rowvec maxDistances = max(distances); // Calculate and return the radius. return sum(maxDistances) / (double) data.n_cols; } // Class to compare two vectors. template <typename VecType> class less { public: bool operator()(const VecType& first, const VecType& second) const { for (size_t i = 0; i < first.n_rows; ++i) { if (first[i] == second[i]) continue; return first(i) < second(i); } return false; } }; // Generate seeds from given data set. template<bool UseKernel, typename KernelType, typename MatType> void MeanShift<UseKernel, KernelType, MatType>::GenSeeds( const MatType& data, const double binSize, const int minFreq, MatType& seeds) { typedef arma::colvec VecType; std::map<VecType, int, less<VecType> > allSeeds; for (size_t i = 0; i < data.n_cols; ++i) { VecType binnedPoint = arma::floor(data.unsafe_col(i) / binSize); if (allSeeds.find(binnedPoint) == allSeeds.end()) allSeeds[binnedPoint] = 1; else allSeeds[binnedPoint]++; } // Remove seeds with too few points. First we count the number of seeds we // end up with, then we add them. std::map<VecType, int, less<VecType> >::iterator it; size_t count = 0; for (it = allSeeds.begin(); it != allSeeds.end(); ++it) if (it->second >= minFreq) ++count; seeds.set_size(data.n_rows, count); count = 0; for (it = allSeeds.begin(); it != allSeeds.end(); ++it) { if (it->second >= minFreq) { seeds.col(count) = it->first; ++count; } } seeds *= binSize; } // Calculate new centroid with given kernel. template<bool UseKernel, typename KernelType, typename MatType> template<bool ApplyKernel> typename std::enable_if<ApplyKernel, bool>::type MeanShift<UseKernel, KernelType, MatType>:: CalculateCentroid(const MatType& data, const std::vector<size_t>& neighbors, const std::vector<double>& distances, arma::colvec& centroid) { double sumWeight = 0; for (size_t i = 0; i < neighbors.size(); ++i) { if (distances[i] > 0) { double dist = distances[i] / radius; double weight = kernel.Gradient(dist) / dist; sumWeight += weight; centroid += weight * data.unsafe_col(neighbors[i]); } } if (sumWeight != 0) { centroid /= sumWeight; return true; } return false; } // Calculate new centroid by mean. template<bool UseKernel, typename KernelType, typename MatType> template<bool ApplyKernel> typename std::enable_if<!ApplyKernel, bool>::type MeanShift<UseKernel, KernelType, MatType>:: CalculateCentroid(const MatType& data, const std::vector<size_t>& neighbors, const std::vector<double>&, /*unused*/ arma::colvec& centroid) { for (size_t i = 0; i < neighbors.size(); ++i) centroid += data.unsafe_col(neighbors[i]); centroid /= neighbors.size(); return true; } /** * Perform Mean Shift clustering on the data set, returning a list of cluster * assignments and centroids. */ template<bool UseKernel, typename KernelType, typename MatType> inline void MeanShift<UseKernel, KernelType, MatType>::Cluster( const MatType& data, arma::Col<size_t>& assignments, arma::mat& centroids, bool useSeeds) { if (radius <= 0) { // An invalid radius is given; an estimation is needed. Radius(EstimateRadius(data)); } MatType seeds; const MatType* pSeeds = &data; if (useSeeds) { GenSeeds(data, radius, 1, seeds); pSeeds = &seeds; } // Holds all centroids before removing duplicate ones. arma::mat allCentroids(pSeeds->n_rows, pSeeds->n_cols); assignments.set_size(data.n_cols); range::RangeSearch<> rangeSearcher(data); math::Range validRadius(0, radius); std::vector<std::vector<size_t> > neighbors; std::vector<std::vector<double> > distances; // For each seed, perform mean shift algorithm. for (size_t i = 0; i < pSeeds->n_cols; ++i) { // Initial centroid is the seed itself. allCentroids.col(i) = pSeeds->unsafe_col(i); for (size_t completedIterations = 0; completedIterations < maxIterations; completedIterations++) { // Store new centroid in this. arma::colvec newCentroid = arma::zeros<arma::colvec>(pSeeds->n_rows); rangeSearcher.Search(allCentroids.unsafe_col(i), validRadius, neighbors, distances); if (neighbors[0].size() <= 1) break; // Calculate new centroid. if (!CalculateCentroid(data, neighbors[0], distances[0], newCentroid)) newCentroid = allCentroids.unsafe_col(i); // If the mean shift vector is small enough, it has converged. if (metric::EuclideanDistance::Evaluate(newCentroid, allCentroids.unsafe_col(i)) < 1e-3 * radius) { // Determine if the new centroid is duplicate with old ones. bool isDuplicated = false; for (size_t k = 0; k < centroids.n_cols; ++k) { const double distance = metric::EuclideanDistance::Evaluate( allCentroids.unsafe_col(i), centroids.unsafe_col(k)); if (distance < radius) { isDuplicated = true; break; } } if (!isDuplicated) centroids.insert_cols(centroids.n_cols, allCentroids.unsafe_col(i)); // Get out of the loop. break; } // Update the centroid. allCentroids.col(i) = newCentroid; } } // Assign centroids to each point. neighbor::AllkNN neighborSearcher(centroids); arma::mat neighborDistances; arma::Mat<size_t> resultingNeighbors; neighborSearcher.Search(data, 1, resultingNeighbors, neighborDistances); assignments = resultingNeighbors.t(); } } // namespace meanshift } // namespace mlpack #endif <|endoftext|>
<commit_before>#include "MeshSymLoader.h" #include "FilepathHelper.h" #include "SymbolPool.h" #include "JsonSerializer.h" #include "MeshIO.h" #include "ArrayLoader.h" #include <simp/NodeMesh.h> #include <simp/from_int.h> #include <simp/SIMP_PointsMesh.h> #include <simp/SIMP_TrianglesMesh.h> #include <simp/SIMP_Skin2Mesh.h> #include <simp/from_int.h> #include <polymesh/PointsMesh.h> #include <polymesh/TrianglesMesh.h> #include <polymesh/Skin2Mesh.h> #include <polymesh/MeshTransform.h> #include <sprite2/MeshSymbol.h> #include <sprite2/S2_Mesh.h> #include <json/json.h> #include <fstream> namespace gum { MeshSymLoader::MeshSymLoader(s2::MeshSymbol* sym, bool flatten) : m_sym(sym) , m_flatten(flatten) { if (m_sym) { m_sym->AddReference(); } } MeshSymLoader::~MeshSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void MeshSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); if (!value.isMember("base_symbol")) { return; } std::string dir = FilepathHelper::Dir(filepath); std::string base_path = FilepathHelper::Absolute(dir, value["base_symbol"].asString()); s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path); if (!base_sym) { return; } std::string type = value["type"].asString(); s2::Mesh* mesh = NULL; if (type == "strip") { } else if (type == "network" || type == "points") { mesh = CreatePointsMesh(value, base_sym); } if (mesh) { m_sym->SetMesh(mesh); mesh->RemoveReference(); } } void MeshSymLoader::LoadBin(const simp::NodeMesh* node) { if (!m_sym) { return; } s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id, m_flatten); if (!base_sym) { return; } s2::Mesh* mesh = NULL; switch (node->shape->type) { case simp::MESH_POINTS: mesh = LoadPointsMesh(base_sym, static_cast<simp::PointsMesh*>(node->shape)); break; case simp::MESH_TRIANGLES: mesh = LoadTrianglesMesh(base_sym, static_cast<simp::TrianglesMesh*>(node->shape)); break; case simp::MESH_SKIN2: mesh = LoadSkin2Mesh(base_sym, static_cast<simp::Skin2Mesh*>(node->shape)); break; default: break; } m_sym->SetMesh(mesh); base_sym->RemoveReference(); if (mesh) { mesh->RemoveReference(); } } s2::Mesh* MeshSymLoader::LoadPointsMesh(s2::Symbol* base_sym, simp::PointsMesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> outline; ArrayLoader::Load(outline, node->outline, node->outline_n, 16); std::vector<sm::vec2> points; ArrayLoader::Load(points, node->points, node->points_n, 16); sm::rect r = base_sym->GetBounding(); pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height()); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::LoadTrianglesMesh(s2::Symbol* base_sym, simp::TrianglesMesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> vertices; ArrayLoader::Load(vertices, node->vertices, node->vertices_n, 16); std::vector<sm::vec2> texcoords; ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192); std::vector<int> triangles; ArrayLoader::Load(triangles, node->triangle, node->triangle_n); pm::Mesh* pm_mesh = new pm::TrianglesMesh(vertices, texcoords, triangles); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::LoadSkin2Mesh(s2::Symbol* base_sym, simp::Skin2Mesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<pm::Skin2Joint> joints; int joints_n = 0; for (int i = 0; i < node->vertices_n; ++i) { joints_n += node->joints_n[i]; } joints.reserve(joints_n); for (int i = 0; i < joints_n; ++i) { const simp::Skin2Mesh::Joint& src = node->joints[i]; pm::Skin2Joint dst; dst.joint = src.joint; dst.vertex.x = simp::int2float(src.vx, 64); dst.vertex.y = simp::int2float(src.vy, 64); dst.offset.Set(0, 0); dst.weight = simp::int2float(src.weight, 2048) + 0.5f; joints.push_back(dst); } std::vector<int> vertices; vertices.reserve(node->vertices_n); for (int i = 0; i < node->vertices_n; ++i) { vertices.push_back(node->joints_n[i]); } std::vector<sm::vec2> texcoords; ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192); std::vector<int> triangles; ArrayLoader::Load(triangles, node->triangle, node->triangle_n); pm::Mesh* pm_mesh = new pm::Skin2Mesh(joints, vertices, texcoords, triangles); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::CreatePointsMesh(const Json::Value& val, const s2::Symbol* base_sym) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> outline; JsonSerializer::Load(val["shape"]["outline"], outline); std::vector<sm::vec2> points; JsonSerializer::Load(val["shape"]["inner"], points); sm::rect r = base_sym->GetBounding(); pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height()); pm::MeshTransform trans; MeshIO::Load(val, trans, *s2_mesh); pm_mesh->LoadFromTransform(trans); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } }<commit_msg>[FIXED] skin2 mesh loader<commit_after>#include "MeshSymLoader.h" #include "FilepathHelper.h" #include "SymbolPool.h" #include "JsonSerializer.h" #include "MeshIO.h" #include "ArrayLoader.h" #include <simp/NodeMesh.h> #include <simp/from_int.h> #include <simp/SIMP_PointsMesh.h> #include <simp/SIMP_TrianglesMesh.h> #include <simp/SIMP_Skin2Mesh.h> #include <simp/from_int.h> #include <polymesh/PointsMesh.h> #include <polymesh/TrianglesMesh.h> #include <polymesh/Skin2Mesh.h> #include <polymesh/MeshTransform.h> #include <sprite2/MeshSymbol.h> #include <sprite2/S2_Mesh.h> #include <json/json.h> #include <fstream> namespace gum { MeshSymLoader::MeshSymLoader(s2::MeshSymbol* sym, bool flatten) : m_sym(sym) , m_flatten(flatten) { if (m_sym) { m_sym->AddReference(); } } MeshSymLoader::~MeshSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void MeshSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); if (!value.isMember("base_symbol")) { return; } std::string dir = FilepathHelper::Dir(filepath); std::string base_path = FilepathHelper::Absolute(dir, value["base_symbol"].asString()); s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path); if (!base_sym) { return; } std::string type = value["type"].asString(); s2::Mesh* mesh = NULL; if (type == "strip") { } else if (type == "network" || type == "points") { mesh = CreatePointsMesh(value, base_sym); } if (mesh) { m_sym->SetMesh(mesh); mesh->RemoveReference(); } } void MeshSymLoader::LoadBin(const simp::NodeMesh* node) { if (!m_sym) { return; } s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id, m_flatten); if (!base_sym) { return; } s2::Mesh* mesh = NULL; switch (node->shape->type) { case simp::MESH_POINTS: mesh = LoadPointsMesh(base_sym, static_cast<simp::PointsMesh*>(node->shape)); break; case simp::MESH_TRIANGLES: mesh = LoadTrianglesMesh(base_sym, static_cast<simp::TrianglesMesh*>(node->shape)); break; case simp::MESH_SKIN2: mesh = LoadSkin2Mesh(base_sym, static_cast<simp::Skin2Mesh*>(node->shape)); break; default: break; } m_sym->SetMesh(mesh); base_sym->RemoveReference(); if (mesh) { mesh->RemoveReference(); } } s2::Mesh* MeshSymLoader::LoadPointsMesh(s2::Symbol* base_sym, simp::PointsMesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> outline; ArrayLoader::Load(outline, node->outline, node->outline_n, 16); std::vector<sm::vec2> points; ArrayLoader::Load(points, node->points, node->points_n, 16); sm::rect r = base_sym->GetBounding(); pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height()); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::LoadTrianglesMesh(s2::Symbol* base_sym, simp::TrianglesMesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> vertices; ArrayLoader::Load(vertices, node->vertices, node->vertices_n, 16); std::vector<sm::vec2> texcoords; ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192); std::vector<int> triangles; ArrayLoader::Load(triangles, node->triangle, node->triangle_n); pm::Mesh* pm_mesh = new pm::TrianglesMesh(vertices, texcoords, triangles); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::LoadSkin2Mesh(s2::Symbol* base_sym, simp::Skin2Mesh* node) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<pm::Skin2Joint> joints; int joints_n = 0; for (int i = 0; i < node->vertices_n; ++i) { joints_n += node->joints_n[i]; } joints.reserve(joints_n); for (int i = 0; i < joints_n; ++i) { const simp::Skin2Mesh::Joint& src = node->joints[i]; pm::Skin2Joint dst; dst.joint = src.joint; dst.vertex.x = simp::int2float(src.vx, 16); dst.vertex.y = simp::int2float(src.vy, 16); dst.offset.Set(0, 0); dst.weight = simp::int2float(src.weight, 2048) + 0.5f; joints.push_back(dst); } std::vector<int> vertices; vertices.reserve(node->vertices_n); for (int i = 0; i < node->vertices_n; ++i) { vertices.push_back(node->joints_n[i]); } std::vector<sm::vec2> texcoords; ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192); std::vector<int> triangles; ArrayLoader::Load(triangles, node->triangle, node->triangle_n); pm::Mesh* pm_mesh = new pm::Skin2Mesh(joints, vertices, texcoords, triangles); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } s2::Mesh* MeshSymLoader::CreatePointsMesh(const Json::Value& val, const s2::Symbol* base_sym) { s2::Mesh* s2_mesh = new s2::Mesh(base_sym); std::vector<sm::vec2> outline; JsonSerializer::Load(val["shape"]["outline"], outline); std::vector<sm::vec2> points; JsonSerializer::Load(val["shape"]["inner"], points); sm::rect r = base_sym->GetBounding(); pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height()); pm::MeshTransform trans; MeshIO::Load(val, trans, *s2_mesh); pm_mesh->LoadFromTransform(trans); s2_mesh->SetMesh(pm_mesh); return s2_mesh; } }<|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------------- // Particle generator according to 4 correlated variables : here // z, ptot, r, theta. The input is a THnSparse object included in // the root file (path and name to be set via the SetTHnSparse method). // This class is similar to AliGenFunction. //----------------------------------------------------------------------- // Author : X. Lopez - LPC Clermont (fr) //----------------------------------------------------------------------- /* Example for generation : AliGenTHnSparse *gener = new AliGenTHnSparse(); gener->SetNumberParticles(10); gener->SetPart(13); gener->SetThnSparse("file_name","thn_name"); gener->Init(); */ #include <TRandom.h> #include <TFile.h> #include "THnSparse.h" #include "AliGenTHnSparse.h" ClassImp(AliGenTHnSparse) //_______________________________________________________________________ AliGenTHnSparse::AliGenTHnSparse(): AliGenerator(), fHn(0), fFile(0), fIpart(0) { // Default constructor SetNumberParticles(1); } //_______________________________________________________________________ AliGenTHnSparse::AliGenTHnSparse(const AliGenTHnSparse& func): AliGenerator(), fHn(func.fHn), fFile(func.fFile), fIpart(func.fIpart) { // Copy constructor SetNumberParticles(1); } //_______________________________________________________________________ AliGenTHnSparse & AliGenTHnSparse::operator=(const AliGenTHnSparse& func) { // Assigment operator if(&func == this) return *this; fHn = func.fHn; fFile = func.fFile; fIpart = func.fIpart; return *this; } //_______________________________________________________________________ AliGenTHnSparse::~AliGenTHnSparse() { // Destructor delete fFile; } //_______________________________________________________________________ void AliGenTHnSparse::Generate() { // Generate Npart of id Ipart Double_t rand[4]; // z, ptot, r, theta Float_t pos[3], phi, ptot, theta, pt, z, r; Float_t mom[3]; Int_t pdg = fIpart; for (Int_t ipart = 0; ipart < fNpart; ipart++) { fHn->GetRandom(rand); z=rand[0]; ptot=rand[1]; r=rand[2]; theta=rand[3]; // Phi: same for position and momemtum phi=(-180+gRandom->Rndm()*360)*TMath::Pi()/180; // position at production pos[0] = r*TMath::Cos(phi); pos[1] = r*TMath::Sin(phi); pos[2] = z; // momentum at production pt = ptot*TMath::Sin(theta); mom[0] = pt*TMath::Cos(phi); mom[1] = pt*TMath::Sin(phi); mom[2] = ptot*TMath::Cos(theta); // propagation Float_t polarization[3]= {0,0,0}; Int_t nt; PushTrack(fTrackIt,-1,pdg,mom, pos, polarization,0,kPPrimary,nt); } return; } //_______________________________________________________________________ void AliGenTHnSparse::Init() { // Initialisation, check consistency of selected file printf("************ AliGenTHnSparse ****************\n"); printf("*********************************************\n"); if (!fHn){ AliFatal("THnSparse file not specified"); } return; } //_______________________________________________________________________ void AliGenTHnSparse::SetThnSparse(char *file_name, char *thn_name) { // Open the file and get object TFile *fFile = new TFile(file_name); fHn = (THnSparseF*)(fFile->Get(thn_name)); } <commit_msg>Member data shadowing corrected.<commit_after>/************************************************************************** * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------------- // Particle generator according to 4 correlated variables : here // z, ptot, r, theta. The input is a THnSparse object included in // the root file (path and name to be set via the SetTHnSparse method). // This class is similar to AliGenFunction. //----------------------------------------------------------------------- // Author : X. Lopez - LPC Clermont (fr) //----------------------------------------------------------------------- /* Example for generation : AliGenTHnSparse *gener = new AliGenTHnSparse(); gener->SetNumberParticles(10); gener->SetPart(13); gener->SetThnSparse("file_name","thn_name"); gener->Init(); */ #include <TRandom.h> #include <TFile.h> #include "THnSparse.h" #include "AliGenTHnSparse.h" ClassImp(AliGenTHnSparse) //_______________________________________________________________________ AliGenTHnSparse::AliGenTHnSparse(): AliGenerator(), fHn(0), fFile(0), fIpart(0) { // Default constructor SetNumberParticles(1); } //_______________________________________________________________________ AliGenTHnSparse::AliGenTHnSparse(const AliGenTHnSparse& func): AliGenerator(), fHn(func.fHn), fFile(func.fFile), fIpart(func.fIpart) { // Copy constructor SetNumberParticles(1); } //_______________________________________________________________________ AliGenTHnSparse & AliGenTHnSparse::operator=(const AliGenTHnSparse& func) { // Assigment operator if(&func == this) return *this; fHn = func.fHn; fFile = func.fFile; fIpart = func.fIpart; return *this; } //_______________________________________________________________________ AliGenTHnSparse::~AliGenTHnSparse() { // Destructor delete fFile; } //_______________________________________________________________________ void AliGenTHnSparse::Generate() { // Generate Npart of id Ipart Double_t rand[4]; // z, ptot, r, theta Float_t pos[3], phi, ptot, theta, pt, z, r; Float_t mom[3]; Int_t pdg = fIpart; for (Int_t ipart = 0; ipart < fNpart; ipart++) { fHn->GetRandom(rand); z=rand[0]; ptot=rand[1]; r=rand[2]; theta=rand[3]; // Phi: same for position and momemtum phi=(-180+gRandom->Rndm()*360)*TMath::Pi()/180; // position at production pos[0] = r*TMath::Cos(phi); pos[1] = r*TMath::Sin(phi); pos[2] = z; // momentum at production pt = ptot*TMath::Sin(theta); mom[0] = pt*TMath::Cos(phi); mom[1] = pt*TMath::Sin(phi); mom[2] = ptot*TMath::Cos(theta); // propagation Float_t polarization[3]= {0,0,0}; Int_t nt; PushTrack(fTrackIt,-1,pdg,mom, pos, polarization,0,kPPrimary,nt); } return; } //_______________________________________________________________________ void AliGenTHnSparse::Init() { // Initialisation, check consistency of selected file printf("************ AliGenTHnSparse ****************\n"); printf("*********************************************\n"); if (!fHn){ AliFatal("THnSparse file not specified"); } return; } //_______________________________________________________________________ void AliGenTHnSparse::SetThnSparse(char *file_name, char *thn_name) { // Open the file and get object fFile = new TFile(file_name); fHn = (THnSparseF*)(fFile->Get(thn_name)); } <|endoftext|>
<commit_before>#ifndef SM_STRING_ROUTINES_H #define SM_STRING_ROUTINES_H #include <string> #include <cstdlib> #include <sstream> #include <iostream> namespace sm { /// replaces the 'target' with 'replacement' searching forward through /// the string and skipping 'skip' occurences inline std::string replace(std::string str, char target, char replacement, unsigned int skip = 0) { std::string::size_type pos = 0; while( (pos = str.find(target, pos)) != std::string::npos) { if(skip) { skip--; pos++; } else str[pos] = replacement; } return str; } /// replaces the 'target' with 'replacement' searching backward through /// the string and skipping 'skip' occurences inline std::string replace_reverse(std::string str, char target, char replacement, unsigned int skip = 0) { std::string::size_type pos = std::string::npos; while( (pos = str.rfind(target, pos)) != std::string::npos) { if(skip) { skip--; pos--; } else str[pos] = replacement; } return str; } inline std::string leading_pad( std::string str, unsigned int desiredLength, char padChar ) { std::string result; if ( str.length() < desiredLength ) { std::string padding( desiredLength - str.length(), padChar ); result = padding.append(str); } else { result = str; } return result; } inline std::string tolower(std::string s) { for(unsigned int i = 0; i < s.size(); i++) s[i] = ::tolower(s[i]); // call tolower from the c std lib. return s; } // Find all substrings of the form $(XXX) and replace them // with the associated environment variable if they exist. inline std::string substituteEnvVars(std::string const & s) { std::string::size_type off = 0, pidx=0, idx=0, idxe=0; std::ostringstream out; idx = s.find("$(",off); while(idx != std::string::npos){ //std::cout << "Found \"$(\" at " << idx << std::endl; idxe = s.find(')',idx); if(idxe != std::string::npos) { //std::cout << "Found \")\" at " << idxe << std::endl; // We've found an environment variable. std::string envVar = s.substr(idx+2,idxe-idx-2); //std::cout << "evname: " << envVar << std::endl; char * envSub = getenv(envVar.c_str()); if(envSub != NULL) { // Dump everything before the envVar out << s.substr(pidx,idx-pidx); out << envSub; pidx = idxe+1; } off = idxe+1; idx = s.find("$(",off); } else { // No close brackets means no env vars. idx = std::string::npos; } } out << s.substr(pidx); return out.str(); } inline std::string ensureTrailingBackslash(std::string const & s) { if(s.size() == 0) return "/"; if(s[s.size()-1] == '/') return s; return s + "/"; } // a nice and short to-string function. template<typename T> std::string ts(T t) { std::ostringstream s; s << t; return s.str(); } // pad an int with zeros. template<typename T> inline std::string padded(const T & val, unsigned int digits, char fillChar = '0') { std::ostringstream s; s.fill(fillChar); s.width(digits); s << val; return s.str(); } inline std::string padded(double val, unsigned width, unsigned precision) { std::ostringstream s; s.fill(' '); s.width(width); s.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed s.precision(precision); s << val; return s.str(); } inline std::string scientific(double val, unsigned width, unsigned precision) { std::ostringstream s; s.fill(' '); s.width(width); s.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed s.precision(precision); s.setf(std::ios_base::scientific); s << val; return s.str(); } template<typename T> std::string s_tuple(T t) { std::ostringstream s; s << t; return s.str(); } template<typename T, typename U> std::string s_tuple(T t, U u) { std::ostringstream s; s << "[" << t << "," << u << "]"; return s.str(); } template<typename T, typename U, typename V> std::string s_tuple(T t, U u, V v) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "]"; return s.str(); } template<typename T, typename U, typename V, typename W> std::string s_tuple(T t, U u, V v, W w) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X> std::string s_tuple(T t, U u, V v, W w, X x) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x <<"]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X, typename Y> std::string s_tuple(T t, U u, V v, W w, X x, Y y) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X, typename Y, typename Z> std::string s_tuple(T t, U u, V v, W w, X x, Y y, Z z) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "," << z << "]"; return s.str(); } template<typename ConstIterator> inline void toStream(std::ostream & stream, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { ConstIterator i = begin; stream << prefix; if(i != end) { stream << *i; i++; for( ; i != end; ++i) stream << delimiter << *i; } stream << postfix; } template<typename Iterator> std::string arrToString(Iterator start, Iterator end) { std::ostringstream s; toStream(s, start, end, ",", "[", "]"); return s.str(); } template<typename T> std::string arrToString(T * thearr, unsigned int size) { return arrToString((T*)thearr, (T*)(thearr + size)); } template<typename ConstIterator> inline void paddedToStream(std::ostream & stream, int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { stream << prefix; ConstIterator i = begin; if(i != end) { stream.fill(' '); stream.width(padLength); stream.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed stream.precision(decimalLength); stream << *i; i++; for( ; i != end; ++i){ stream << delimiter; stream.fill(' '); stream.width(padLength); stream.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed stream.precision(decimalLength); stream << *i; } } stream << postfix; } template<typename ConstIterator> inline std::string paddedToString( int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { std::ostringstream stream; paddedToStream(stream,padLength,decimalLength,begin,end,delimiter,prefix,postfix); return stream.str(); } } // namespace sm #endif <commit_msg>Added fixed precision float string to string_routines<commit_after>#ifndef SM_STRING_ROUTINES_H #define SM_STRING_ROUTINES_H #include <string> #include <cstdlib> #include <sstream> #include <iostream> namespace sm { /// replaces the 'target' with 'replacement' searching forward through /// the string and skipping 'skip' occurences inline std::string replace(std::string str, char target, char replacement, unsigned int skip = 0) { std::string::size_type pos = 0; while( (pos = str.find(target, pos)) != std::string::npos) { if(skip) { skip--; pos++; } else str[pos] = replacement; } return str; } /// replaces the 'target' with 'replacement' searching backward through /// the string and skipping 'skip' occurences inline std::string replace_reverse(std::string str, char target, char replacement, unsigned int skip = 0) { std::string::size_type pos = std::string::npos; while( (pos = str.rfind(target, pos)) != std::string::npos) { if(skip) { skip--; pos--; } else str[pos] = replacement; } return str; } inline std::string leading_pad( std::string str, unsigned int desiredLength, char padChar ) { std::string result; if ( str.length() < desiredLength ) { std::string padding( desiredLength - str.length(), padChar ); result = padding.append(str); } else { result = str; } return result; } inline std::string tolower(std::string s) { for(unsigned int i = 0; i < s.size(); i++) s[i] = ::tolower(s[i]); // call tolower from the c std lib. return s; } // Find all substrings of the form $(XXX) and replace them // with the associated environment variable if they exist. inline std::string substituteEnvVars(std::string const & s) { std::string::size_type off = 0, pidx=0, idx=0, idxe=0; std::ostringstream out; idx = s.find("$(",off); while(idx != std::string::npos){ //std::cout << "Found \"$(\" at " << idx << std::endl; idxe = s.find(')',idx); if(idxe != std::string::npos) { //std::cout << "Found \")\" at " << idxe << std::endl; // We've found an environment variable. std::string envVar = s.substr(idx+2,idxe-idx-2); //std::cout << "evname: " << envVar << std::endl; char * envSub = getenv(envVar.c_str()); if(envSub != NULL) { // Dump everything before the envVar out << s.substr(pidx,idx-pidx); out << envSub; pidx = idxe+1; } off = idxe+1; idx = s.find("$(",off); } else { // No close brackets means no env vars. idx = std::string::npos; } } out << s.substr(pidx); return out.str(); } inline std::string ensureTrailingBackslash(std::string const & s) { if(s.size() == 0) return "/"; if(s[s.size()-1] == '/') return s; return s + "/"; } // a nice and short to-string function. template<typename T> std::string ts(T t) { std::ostringstream s; s << t; return s.str(); } // pad an int with zeros. template<typename T> inline std::string padded(const T & val, unsigned int digits, char fillChar = '0') { std::ostringstream s; s.fill(fillChar); s.width(digits); s << val; return s.str(); } inline std::string padded(double val, unsigned width, unsigned precision) { std::ostringstream s; s.fill(' '); s.width(width); s.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed s.precision(precision); s << val; return s.str(); } inline std::string scientific(double val, unsigned width, unsigned precision) { std::ostringstream s; s.fill(' '); s.width(width); s.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed s.precision(precision); s.setf(std::ios_base::scientific); s << val; return s.str(); } inline std::string fixedFloat(double val, unsigned precision) { std::ostringstream s; s.precision(precision); s << std::fixed << val; return s.str(); } template<typename T> std::string s_tuple(T t) { std::ostringstream s; s << t; return s.str(); } template<typename T, typename U> std::string s_tuple(T t, U u) { std::ostringstream s; s << "[" << t << "," << u << "]"; return s.str(); } template<typename T, typename U, typename V> std::string s_tuple(T t, U u, V v) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "]"; return s.str(); } template<typename T, typename U, typename V, typename W> std::string s_tuple(T t, U u, V v, W w) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X> std::string s_tuple(T t, U u, V v, W w, X x) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x <<"]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X, typename Y> std::string s_tuple(T t, U u, V v, W w, X x, Y y) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "]"; return s.str(); } template<typename T, typename U, typename V, typename W, typename X, typename Y, typename Z> std::string s_tuple(T t, U u, V v, W w, X x, Y y, Z z) { std::ostringstream s; s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "," << z << "]"; return s.str(); } template<typename ConstIterator> inline void toStream(std::ostream & stream, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { ConstIterator i = begin; stream << prefix; if(i != end) { stream << *i; i++; for( ; i != end; ++i) stream << delimiter << *i; } stream << postfix; } template<typename Iterator> std::string arrToString(Iterator start, Iterator end) { std::ostringstream s; toStream(s, start, end, ",", "[", "]"); return s.str(); } template<typename T> std::string arrToString(T * thearr, unsigned int size) { return arrToString((T*)thearr, (T*)(thearr + size)); } template<typename ConstIterator> inline void paddedToStream(std::ostream & stream, int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { stream << prefix; ConstIterator i = begin; if(i != end) { stream.fill(' '); stream.width(padLength); stream.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed stream.precision(decimalLength); stream << *i; i++; for( ; i != end; ++i){ stream << delimiter; stream.fill(' '); stream.width(padLength); stream.setf(std::ios::fixed,std::ios::floatfield); // floatfield set to fixed stream.precision(decimalLength); stream << *i; } } stream << postfix; } template<typename ConstIterator> inline std::string paddedToString( int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "") { std::ostringstream stream; paddedToStream(stream,padLength,decimalLength,begin,end,delimiter,prefix,postfix); return stream.str(); } } // namespace sm #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PlotterBase.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:43:37 $ * * 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 _CHART2_PLOTTERBASE_HXX #define _CHART2_PLOTTERBASE_HXX #ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_ #include <com/sun/star/drawing/HomogenMatrix.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif /* #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif */ //---- #include <vector> //---- chart2 #ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_ #include <com/sun/star/chart2/ExplicitScaleData.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_ #include <com/sun/star/chart2/XTransformation.hpp> #endif /* #ifndef _COM_SUN_STAR_CHART2_XPLOTTER_HPP_ #include <com/sun/star/chart2/XPlotter.hpp> #endif */ //---- #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _B3D_HMATRIX_HXX #include <goodies/hmatrix.hxx> #endif //............................................................................. namespace chart { //............................................................................. class ShapeFactory; class PlottingPositionHelper; class PlotterBase { public: PlotterBase( sal_Int32 nDimension ); virtual ~PlotterBase(); // ___chart2::XPlotter___ virtual void SAL_CALL init( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xFinalTarget , const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setScales( const ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ExplicitScaleData >& rScales ) throw (::com::sun::star::uno::RuntimeException); void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix ); virtual void SAL_CALL createShapes() = 0; /* virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException); */ //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- private: //methods //no default constructor PlotterBase(); protected: //methods ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > createGroupShape( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget , ::rtl::OUString rName=::rtl::OUString() ); protected: //member ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLogicTarget; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFinalTarget; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xShapeFactory; ShapeFactory* m_pShapeFactory; //::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext> m_xCC; sal_Int32 m_nDimension; // needs to be created and deleted by the derived class PlottingPositionHelper* m_pPosHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS aw024 (1.10.72); FILE MERGED 2005/09/19 15:29:32 aw 1.10.72.2: RESYNC: (1.10-1.11); FILE MERGED 2005/04/26 14:50:17 aw 1.10.72.1: #i39528#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PlotterBase.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: ihi $ $Date: 2006-11-14 15:35:03 $ * * 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 _CHART2_PLOTTERBASE_HXX #define _CHART2_PLOTTERBASE_HXX #ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_ #include <com/sun/star/drawing/HomogenMatrix.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif /* #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif */ //---- #include <vector> //---- chart2 #ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_ #include <com/sun/star/chart2/ExplicitScaleData.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_ #include <com/sun/star/chart2/XTransformation.hpp> #endif /* #ifndef _COM_SUN_STAR_CHART2_XPLOTTER_HPP_ #include <com/sun/star/chart2/XPlotter.hpp> #endif */ //---- #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif //#ifndef _B3D_HMATRIX_HXX //#include <goodies/hmatrix.hxx> //#endif //............................................................................. namespace chart { //............................................................................. class ShapeFactory; class PlottingPositionHelper; class PlotterBase { public: PlotterBase( sal_Int32 nDimension ); virtual ~PlotterBase(); // ___chart2::XPlotter___ virtual void SAL_CALL init( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xFinalTarget , const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setScales( const ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ExplicitScaleData >& rScales ) throw (::com::sun::star::uno::RuntimeException); void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix ); virtual void SAL_CALL createShapes() = 0; /* virtual ::rtl::OUString SAL_CALL getCoordinateSystemTypeID( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTransformation( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToLogicTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >& xTransformationToFinalPage ) throw (::com::sun::star::uno::RuntimeException); */ //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- private: //methods //no default constructor PlotterBase(); protected: //methods ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > createGroupShape( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget , ::rtl::OUString rName=::rtl::OUString() ); protected: //member ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLogicTarget; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFinalTarget; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xShapeFactory; ShapeFactory* m_pShapeFactory; //::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext> m_xCC; sal_Int32 m_nDimension; // needs to be created and deleted by the derived class PlottingPositionHelper* m_pPosHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "../../src/endpoint.hpp" #include "../../src/roles/server.hpp" #include "../../src/sockets/ssl.hpp" #include <cstring> #include <set> typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::plain> plain_endpoint_type; typedef plain_endpoint_type::handler_ptr plain_handler_ptr; typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::ssl> tls_endpoint_type; typedef tls_endpoint_type::handler_ptr tls_handler_ptr; template <typename endpoint_type> class broadcast_server_handler : public endpoint_type::handler { public: typedef broadcast_server_handler<endpoint_type> type; typedef typename endpoint_type::connection_ptr connection_ptr; std::string get_password() const { return "test"; } boost::shared_ptr<boost::asio::ssl::context> on_tls_init() { // create a tls context, init, and return. boost::shared_ptr<boost::asio::ssl::context> context(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1)); try { context->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); context->set_password_callback(boost::bind(&type::get_password, this)); context->use_certificate_chain_file("../../src/ssl/server.pem"); context->use_private_key_file("../../src/ssl/server.pem", boost::asio::ssl::context::pem); context->use_tmp_dh_file("../../src/ssl/dh512.pem"); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return context; } void validate(connection_ptr connection) { //std::cout << "state: " << connection->get_state() << std::endl; } void on_open(connection_ptr connection) { //std::cout << "connection opened" << std::endl; m_connections.insert(connection); } void on_close(connection_ptr connection) { //std::cout << "connection closed" << std::endl; m_connections.erase(connection); } void on_message(connection_ptr connection,websocketpp::message::data_ptr msg) { typename std::set<connection_ptr>::iterator it; for (it = m_connections.begin(); it != m_connections.end(); it++) { (*it)->send(msg->get_payload(),(msg->get_opcode() == websocketpp::frame::opcode::BINARY)); } connection->recycle(msg); } void http(connection_ptr connection) { std::stringstream foo; foo << "<html><body><p>" << m_connections.size() << " current connections.</p></body></html>"; connection->set_body(foo.str()); } void on_fail(connection_ptr connection) { std::cout << "connection failed" << std::endl; } private: std::set<connection_ptr> m_connections; }; int main(int argc, char* argv[]) { unsigned short port = 9002; bool tls = false; if (argc == 2) { // TODO: input validation? port = atoi(argv[1]); } if (argc == 3) { // TODO: input validation? port = atoi(argv[1]); tls = !strcmp(argv[2],"-tls"); } try { if (tls) { tls_handler_ptr h(new broadcast_server_handler<tls_endpoint_type>()); tls_endpoint_type e(h); e.alog().unset_level(websocketpp::log::alevel::ALL); e.elog().set_level(websocketpp::log::elevel::ALL); std::cout << "Starting Secure WebSocket broadcast server on port " << port << std::endl; e.listen(port); } else { plain_handler_ptr h(new broadcast_server_handler<plain_endpoint_type>()); plain_endpoint_type e(h); e.alog().unset_level(websocketpp::log::alevel::ALL); e.elog().set_level(websocketpp::log::elevel::ALL); std::cout << "Starting WebSocket broadcast server on port " << port << std::endl; e.listen(port); } } catch (std::string e) { //std::cerr << "Exception: " << e.what() << std::endl; } return 0; } <commit_msg>adds some code to broadcast server to allow it to increase its file descriptor limits on unix systems<commit_after>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "../../src/endpoint.hpp" #include "../../src/roles/server.hpp" #include "../../src/sockets/ssl.hpp" #include <cstring> #include <set> #include <sys/resource.h> typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::plain> plain_endpoint_type; typedef plain_endpoint_type::handler_ptr plain_handler_ptr; typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::ssl> tls_endpoint_type; typedef tls_endpoint_type::handler_ptr tls_handler_ptr; template <typename endpoint_type> class broadcast_server_handler : public endpoint_type::handler { public: typedef broadcast_server_handler<endpoint_type> type; typedef typename endpoint_type::connection_ptr connection_ptr; std::string get_password() const { return "test"; } boost::shared_ptr<boost::asio::ssl::context> on_tls_init() { // create a tls context, init, and return. boost::shared_ptr<boost::asio::ssl::context> context(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1)); try { context->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); context->set_password_callback(boost::bind(&type::get_password, this)); context->use_certificate_chain_file("../../src/ssl/server.pem"); context->use_private_key_file("../../src/ssl/server.pem", boost::asio::ssl::context::pem); context->use_tmp_dh_file("../../src/ssl/dh512.pem"); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return context; } void validate(connection_ptr connection) { //std::cout << "state: " << connection->get_state() << std::endl; } void on_open(connection_ptr connection) { //std::cout << "connection opened" << std::endl; m_connections.insert(connection); } void on_close(connection_ptr connection) { //std::cout << "connection closed" << std::endl; m_connections.erase(connection); } void on_message(connection_ptr connection,websocketpp::message::data_ptr msg) { typename std::set<connection_ptr>::iterator it; for (it = m_connections.begin(); it != m_connections.end(); it++) { (*it)->send(msg->get_payload(),(msg->get_opcode() == websocketpp::frame::opcode::BINARY)); } connection->recycle(msg); } void http(connection_ptr connection) { std::stringstream foo; foo << "<html><body><p>" << m_connections.size() << " current connections.</p></body></html>"; connection->set_body(foo.str()); } void on_fail(connection_ptr connection) { std::cout << "connection failed" << std::endl; } private: std::set<connection_ptr> m_connections; }; int main(int argc, char* argv[]) { unsigned short port = 9002; bool tls = false; // 12288 is max OS X limit without changing kernal settings const rlim_t ideal_size = 100000; rlim_t old_size; struct rlimit rl; int result; result = getrlimit(RLIMIT_NOFILE, &rl); if (result == 0) { std::cout << "cur: " << rl.rlim_cur << " max: " << rl.rlim_max << std::endl; old_size = rl.rlim_cur; if (rl.rlim_cur < ideal_size) { rl.rlim_cur = ideal_size; //rl.rlim_cur = rl.rlim_max; result = setrlimit(RLIMIT_NOFILE, &rl); if (result != 0) { std::cout << "Unable to request an increase in the file descripter limit. This server will be limited to " << old_size << " concurrent connections. Error code: " << errno << std::endl; } } } if (argc == 2) { // TODO: input validation? port = atoi(argv[1]); } if (argc == 3) { // TODO: input validation? port = atoi(argv[1]); tls = !strcmp(argv[2],"-tls"); } try { if (tls) { tls_handler_ptr h(new broadcast_server_handler<tls_endpoint_type>()); tls_endpoint_type e(h); e.alog().unset_level(websocketpp::log::alevel::ALL); e.elog().set_level(websocketpp::log::elevel::ALL); std::cout << "Starting Secure WebSocket broadcast server on port " << port << std::endl; e.listen(port); } else { plain_handler_ptr h(new broadcast_server_handler<plain_endpoint_type>()); plain_endpoint_type e(h); e.alog().unset_level(websocketpp::log::alevel::ALL); e.elog().set_level(websocketpp::log::elevel::ALL); std::cout << "Starting WebSocket broadcast server on port " << port << std::endl; e.listen(port); } } catch (std::string e) { //std::cerr << "Exception: " << e.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include "mainframe.h" #include "icons.h" #include "demoTutorialDialog.h" #include <BALL/VIEW/KERNEL/iconLoader.h> #include <BALL/VIEW/RENDERING/POVRenderer.h> #include <BALL/VIEW/RENDERING/VRMLRenderer.h> #include <BALL/VIEW/WIDGETS/molecularStructure.h> #include <BALL/VIEW/WIDGETS/molecularControl.h> #include <BALL/VIEW/WIDGETS/geometricControl.h> #include <BALL/VIEW/WIDGETS/logView.h> #include <BALL/VIEW/WIDGETS/helpViewer.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/WIDGETS/editableScene.h> #include <BALL/VIEW/WIDGETS/fileObserver.h> #include <BALL/VIEW/DIALOGS/pubchemDialog.h> #include <BALL/VIEW/DIALOGS/undoManagerDialog.h> #include <BALL/VIEW/DIALOGS/downloadPDBFile.h> #include <BALL/VIEW/DIALOGS/downloadElectronDensity.h> #include <BALL/VIEW/DIALOGS/labelDialog.h> #include <BALL/VIEW/DIALOGS/displayProperties.h> #include <BALL/VIEW/DIALOGS/molecularFileDialog.h> #include <BALL/VIEW/DATATYPE/standardDatasets.h> #ifdef BALL_PYTHON_SUPPORT # include <BALL/VIEW/WIDGETS/pyWidget.h> # include <BALL/VIEW/WIDGETS/testFramework.h> #endif #include <BALL/SYSTEM/path.h> #include <BALL/KERNEL/forEach.h> #include <BALL/COMMON/version.h> #include <QtGui/QKeyEvent> #include <QtGui/QTreeWidget> #include <BALL/CONCEPT/moleculeObjectCreator.h> #ifdef BALL_HAS_ASIO #include <BALL/VIEW/KERNEL/serverWidget.h> #endif #include "ui_aboutDialog.h" #include <BALL/VIEW/DIALOGS/pluginDialog.h> using namespace std; //#define BALL_VIEW_DEBUG namespace BALL { using namespace std; using namespace BALL::VIEW; Mainframe::Mainframe(QWidget* parent, const char* name) : MainControl(parent, name, ".BALLView"), scene_(0) { #ifdef BALL_VIEW_DEBUG Log.error() << "new Mainframe " << this << std::endl; #endif // --------------------- // setup main window // --------------------- setWindowTitle("BALLView"); setWindowIcon(QPixmap(bucky_64x64_xpm)); // make sure submenus are the first initPopupMenu(FILE_OPEN); initPopupMenu(EDIT); initPopupMenu(BUILD); initPopupMenu(DISPLAY); initPopupMenu(MOLECULARMECHANICS); initPopupMenu(TOOLS); #ifdef BALL_PYTHON_SUPPORT initPopupMenu(TOOLS_PYTHON); initPopupMenu(MainControl::USER); #endif initPopupMenu(WINDOWS); initPopupMenu(MACRO); // --------------------- // Logstream setup ----- // --------------------- // Log.remove(std::cout); // Log.remove(std::cerr); setLoggingFilename("BALLView.log"); // Display Menu String description = "Shortcut|Display|Toggle_Fullscreen"; fullscreen_action_ = insertMenuEntry(MainControl::DISPLAY, (String)tr("Toggle Fullscreen"), this, SLOT(toggleFullScreen()), description, QKeySequence("Alt+X")); fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-fullscreen")); insertPopupMenuSeparator(DISPLAY); initPopupMenu(DISPLAY_VIEWPOINT); new MolecularFileDialog(this, ((String)tr("MolecularFileDialog")).c_str()); new DownloadPDBFile( this, ((String)tr("DownloadPDBFile")).c_str(), false); new DownloadElectronDensity(this, ((String)tr("DownloadElectronDensity")).c_str(), false); new PubChemDialog( this, ((String)tr("PubChemDialog")).c_str()); new PluginDialog( this, ((String)tr("PluginDialog")).c_str()); new UndoManagerDialog( this, ((String)tr("UndoManagerDialog")).c_str()); addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, ((String)tr("Structures")).c_str())); addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, ((String)tr("Representations")).c_str())); addDockWidget(Qt::TopDockWidgetArea, new DatasetControl(this, ((String)tr("Datasets")).c_str())); DatasetControl* dc = DatasetControl::getInstance(0); dc->registerController(new RegularData3DController()); dc->registerController(new TrajectoryController()); dc->registerController(new VectorGridController()); dc->registerController(new DockResultController()); // NOTE: raytraceable grids have been deferred until 1.4/2.0 // dc->registerController(new RaytraceableGridController()); DatasetControl::getInstance(0)->hide(); new DemoTutorialDialog(this, ((String)tr("BALLViewDemo")).c_str()); Path path; // NOTE: disable the link to the BALL documentation until we can use webkit to correctly // display full HTML including remote links String dirp = path.find("../doc/BALL/"); if (dirp != "") { HelpViewer* BALL_docu = new HelpViewer(this, ((String)tr("BALL Docu")).c_str()); addDockWidget(Qt::BottomDockWidgetArea, BALL_docu); BALL_docu->setBaseDirectory(dirp); BALL_docu->setWhatsThisEnabled(false); BALL_docu->setProject("BALL"); BALL_docu->setDefaultPage("index.html"); } addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu")); new LabelDialog( this, ((String)tr("LabelDialog")).c_str()); new MolecularStructure( this, ((String)tr("MolecularStructure")).c_str()); addDockWidget(Qt::BottomDockWidgetArea, new LogView( this, ((String)tr("Logs")).c_str())); addDockWidget(Qt::BottomDockWidgetArea, new FileObserver( this, ((String)tr("FileObserver")).c_str())); Scene::stereoBufferSupportTest(); scene_ = new EditableScene(this, ((String)tr("3D View")).c_str()); setCentralWidget(scene_); setAcceptDrops(true); new DisplayProperties(this, ((String)tr("DisplayProperties")).c_str()); // setup the VIEW server #ifdef BALL_HAS_ASIO ServerWidget* server = new ServerWidget(this); // registering object generator MoleculeObjectCreator* object_creator = new MoleculeObjectCreator; server->registerObjectCreator(*object_creator); #endif #ifdef BALL_PYTHON_SUPPORT new TestFramework(this, ((String)"Test Framework").c_str()); addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, ((String)tr("Python Interpreter")).c_str())); #endif // --------------------- // Menus --------------- // --------------------- description = "Shortcut|File|Open|Project"; insertMenuEntry(MainControl::FILE_OPEN, ((String)tr("Project")).c_str(), this, SLOT(loadBALLViewProjectFile()), description); description = "Shortcut|File|Save_Project"; save_project_action_ = insertMenuEntry(MainControl::FILE, ((String)tr("Save Project")).c_str(), this, SLOT(saveBALLViewProjectFile()), description); // Help-Menu ------------------------------------------------------------------- QAction* action = 0; description = "Shortcut|Help|About"; action = insertMenuEntry(MainControl::HELP, (String)tr("About"), this, SLOT(about()), description); setMenuHint(action, (String)tr("Show informations on this version of BALLView")); description = "Shortcut|Help|How_to_cite"; action = insertMenuEntry(MainControl::HELP, (String)tr("How to cite"), this, SLOT(howToCite()), description); setMenuHint(action, (String)tr("Show infos on how to cite BALL and BALLView")); // TODO: why is this done here and not, e.g., in mainControl()??? description = "Shortcut|MolecularMechanics|Abort_Calculation"; stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, (String)tr("Abort Calculation"), this, SLOT(stopSimulation()), description, QKeySequence("Alt+C")); stop_simulation_action_->setEnabled(false); insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS); setMenuHint(stop_simulation_action_, (String)tr("Abort a running simulation")); stop_simulation_action_->setIcon(IconLoader::instance().getIcon("actions/process-stop")); description = "Shortcut|Edit|Invert_Selection"; complement_selection_action_ = insertMenuEntry(MainControl::EDIT, (String)tr("Invert Selection"), this, SLOT(complementSelection()), description); description = "Shortcut|Edit|Clear_Selection"; clear_selection_action_ = insertMenuEntry(MainControl::EDIT, (String)tr("Clear Selection"), this, SLOT(clearSelection()), description); qApp->installEventFilter(this); setStatusbarText((String)tr("Ready.")); } Mainframe::~Mainframe() { } bool Mainframe::eventFilter(QObject* sender, QEvent* event) { if (event->type() != QEvent::KeyPress) return false; QKeyEvent* e = dynamic_cast<QKeyEvent*>(event); if (e->key() == Qt::Key_Escape && HelpViewer::getInstance("BALLView Docu")->isWhatsThisEnabled()) { HelpViewer::getInstance("BALLView Docu")->exitWhatsThisMode(); } QPoint point = QCursor::pos(); QWidget* widget = qApp->widgetAt(point); if (widget == scene_ && qApp->focusWidget() != scene_) { scene_->keyPressEvent(e); return true; } if (e->key() == Qt::Key_Delete && RTTI::isKindOf<QTreeWidget>(*sender)) { deleteClicked(); return true; } if (e->key() == Qt::Key_Enter) { if (composite_manager_.getNumberOfComposites() == 0) return false; if (getMolecularControlSelection().size() == 0) { control_selection_.push_back(*composite_manager_.begin()); } MolecularStructure::getInstance(0)->centerCamera(); return true; } // check all menu entries if Alt or CTRL is pressed to enable shortcuts if (e->key() == Qt::Key_Alt || e->key() == Qt::Key_Control) { checkMenus(); return false; } #ifdef BALL_PYTHON_SUPPORT PyWidget::getInstance(0)->reactTo(*e); e->accept(); #endif return false; } void Mainframe::reset() { if (composites_locked_ || getRepresentationManager().updateRunning()) return; clearData(); DisplayProperties* dp = DisplayProperties::getInstance(0); dp->setDrawingPrecision(DRAWING_PRECISION_HIGH); dp->selectModel(MODEL_STICK); dp->selectColoringMethod(COLORING_ELEMENT); dp->selectMode(DRAWING_MODE_SOLID); dp->setTransparency(0); dp->setSurfaceDrawingPrecision(6.5); } void Mainframe::howToCite() { HelpViewer::getInstance("BALLView Docu")->showHelp("tips.html", (String)tr("cite")); } void Mainframe::show() { // prevent multiple inserting of menu entries, by calls of showFullScreen(), ... if (preferences_action_ != 0) { MainControl::show(); return; } QToolBar* tb = new QToolBar("Main Toolbar", this); tb->setObjectName(tr("Main Toolbar")); tb->setIconSize(QSize(22,22)); addToolBar(Qt::TopToolBarArea, tb); MainControl::show(); initPopupMenu(MainControl::WINDOWS)->addSeparator(); initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction()); MolecularFileDialog::getInstance(0)->addToolBarEntries(tb); DownloadPDBFile::getInstance(0)->addToolBarEntries(tb); DownloadElectronDensity::getInstance(0)->addToolBarEntries(tb); PubChemDialog::getInstance(0)->addToolBarEntries(tb); UndoManagerDialog::getInstance(0)->addToolBarEntries(tb); tb->addAction(fullscreen_action_); Path path; IconLoader& loader = IconLoader::instance(); qload_action_ = new QAction(loader.getIcon("actions/quickopen-file"), tr("quickload"), this); qload_action_->setObjectName(tr("quickload")); connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm())); HelpViewer::getInstance("BALLView Docu")->registerForHelpSystem(qload_action_, "tips.html#quickload"); tb->addAction(qload_action_); qsave_action_ = new QAction(loader.getIcon("actions/quicksave"), tr("quicksave"), this); qsave_action_->setObjectName(tr("quicksave")); connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave())); HelpViewer::getInstance("BALLView Docu")->registerForHelpSystem(qsave_action_, "tips.html#quickload"); tb->addAction(qsave_action_); tb->addSeparator(); DisplayProperties::getInstance(0)->addToolBarEntries(tb); MolecularStructure::getInstance(0)->addToolBarEntries(tb); scene_->addToolBarEntries(tb); tb->addAction(stop_simulation_action_); tb->addAction(preferences_action_); HelpViewer::getInstance("BALLView Docu")->addToolBarEntries(tb); // we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have // to restore the window state again! restoreWindows(); // finally, apply all values our modular widgets have fetched from their preferences applyPreferences(); } void Mainframe::about() { // Display about dialog QDialog w; Ui_AboutDialog about; about.setupUi(&w); QString version = QString(tr("QT ")) + qVersion(); #ifdef BALL_QT_HAS_THREADS version += "(mt)"; #endif about.qt_version_label->setText(version); QFont font = about.BALLView_version_label->font(); about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING); font.setPixelSize(18); about.BALLView_version_label->setFont(font); about.BALL_version_label->setText(__DATE__); // find the BALLView log Path p; String logo_path = p.find("graphics/logo.png"); if (logo_path != "") about.BALLView_logo_label->setPixmap(QPixmap(logo_path.c_str())); w.exec(); } void Mainframe::changeEvent(QEvent* evt) { if(evt->type() == QEvent::WindowStateChange) { if (isFullScreen()) { fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-restore")); } else { fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-fullscreen")); } } } } <commit_msg>Add translation to BALLView.<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include "mainframe.h" #include "icons.h" #include "demoTutorialDialog.h" #include <BALL/VIEW/KERNEL/iconLoader.h> #include <BALL/VIEW/RENDERING/POVRenderer.h> #include <BALL/VIEW/RENDERING/VRMLRenderer.h> #include <BALL/VIEW/WIDGETS/molecularStructure.h> #include <BALL/VIEW/WIDGETS/molecularControl.h> #include <BALL/VIEW/WIDGETS/geometricControl.h> #include <BALL/VIEW/WIDGETS/logView.h> #include <BALL/VIEW/WIDGETS/helpViewer.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/WIDGETS/editableScene.h> #include <BALL/VIEW/WIDGETS/fileObserver.h> #include <BALL/VIEW/DIALOGS/pubchemDialog.h> #include <BALL/VIEW/DIALOGS/undoManagerDialog.h> #include <BALL/VIEW/DIALOGS/downloadPDBFile.h> #include <BALL/VIEW/DIALOGS/downloadElectronDensity.h> #include <BALL/VIEW/DIALOGS/labelDialog.h> #include <BALL/VIEW/DIALOGS/displayProperties.h> #include <BALL/VIEW/DIALOGS/molecularFileDialog.h> #include <BALL/VIEW/DATATYPE/standardDatasets.h> #ifdef BALL_PYTHON_SUPPORT # include <BALL/VIEW/WIDGETS/pyWidget.h> # include <BALL/VIEW/WIDGETS/testFramework.h> #endif #include <BALL/SYSTEM/path.h> #include <BALL/KERNEL/forEach.h> #include <BALL/COMMON/version.h> #include <QtGui/QKeyEvent> #include <QtGui/QTreeWidget> #include <BALL/CONCEPT/moleculeObjectCreator.h> #ifdef BALL_HAS_ASIO #include <BALL/VIEW/KERNEL/serverWidget.h> #endif #include "ui_aboutDialog.h" #include <BALL/VIEW/DIALOGS/pluginDialog.h> using namespace std; //#define BALL_VIEW_DEBUG namespace BALL { using namespace std; using namespace BALL::VIEW; Mainframe::Mainframe(QWidget* parent, const char* name) : MainControl(parent, name, ".BALLView"), scene_(0) { #ifdef BALL_VIEW_DEBUG Log.error() << "new Mainframe " << this << std::endl; #endif // --------------------- // setup main window // --------------------- setWindowTitle(tr("BALLView")); setWindowIcon(QPixmap(bucky_64x64_xpm)); // make sure submenus are the first initPopupMenu(FILE_OPEN); initPopupMenu(EDIT); initPopupMenu(BUILD); initPopupMenu(DISPLAY); initPopupMenu(MOLECULARMECHANICS); initPopupMenu(TOOLS); #ifdef BALL_PYTHON_SUPPORT initPopupMenu(TOOLS_PYTHON); initPopupMenu(MainControl::USER); #endif initPopupMenu(WINDOWS); initPopupMenu(MACRO); // --------------------- // Logstream setup ----- // --------------------- // Log.remove(std::cout); // Log.remove(std::cerr); setLoggingFilename("BALLView.log"); // Display Menu String description = "Shortcut|Display|Toggle_Fullscreen"; fullscreen_action_ = insertMenuEntry(MainControl::DISPLAY, (String)tr("Toggle Fullscreen"), this, SLOT(toggleFullScreen()), description, QKeySequence("Alt+X")); fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-fullscreen")); insertPopupMenuSeparator(DISPLAY); initPopupMenu(DISPLAY_VIEWPOINT); new MolecularFileDialog(this, ((String)tr("MolecularFileDialog")).c_str()); new DownloadPDBFile( this, ((String)tr("DownloadPDBFile")).c_str(), false); new DownloadElectronDensity(this, ((String)tr("DownloadElectronDensity")).c_str(), false); new PubChemDialog( this, ((String)tr("PubChemDialog")).c_str()); new PluginDialog( this, ((String)tr("PluginDialog")).c_str()); new UndoManagerDialog( this, ((String)tr("UndoManagerDialog")).c_str()); addDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, ((String)tr("Structures")).c_str())); addDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, ((String)tr("Representations")).c_str())); addDockWidget(Qt::TopDockWidgetArea, new DatasetControl(this, ((String)tr("Datasets")).c_str())); DatasetControl* dc = DatasetControl::getInstance(0); dc->registerController(new RegularData3DController()); dc->registerController(new TrajectoryController()); dc->registerController(new VectorGridController()); dc->registerController(new DockResultController()); // NOTE: raytraceable grids have been deferred until 1.4/2.0 // dc->registerController(new RaytraceableGridController()); DatasetControl::getInstance(0)->hide(); new DemoTutorialDialog(this, ((String)tr("BALLViewDemo")).c_str()); Path path; // NOTE: disable the link to the BALL documentation until we can use webkit to correctly // display full HTML including remote links String dirp = path.find("../doc/BALL/"); if (dirp != "") { HelpViewer* BALL_docu = new HelpViewer(this, ((String)tr("BALL Docu")).c_str()); addDockWidget(Qt::BottomDockWidgetArea, BALL_docu); BALL_docu->setBaseDirectory(dirp); BALL_docu->setWhatsThisEnabled(false); BALL_docu->setProject("BALL"); BALL_docu->setDefaultPage("index.html"); } addDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, "BALLView Docu")); new LabelDialog( this, ((String)tr("LabelDialog")).c_str()); new MolecularStructure( this, ((String)tr("MolecularStructure")).c_str()); addDockWidget(Qt::BottomDockWidgetArea, new LogView( this, ((String)tr("Logs")).c_str())); addDockWidget(Qt::BottomDockWidgetArea, new FileObserver( this, ((String)tr("FileObserver")).c_str())); Scene::stereoBufferSupportTest(); scene_ = new EditableScene(this, ((String)tr("3D View")).c_str()); setCentralWidget(scene_); setAcceptDrops(true); new DisplayProperties(this, ((String)tr("DisplayProperties")).c_str()); // setup the VIEW server #ifdef BALL_HAS_ASIO ServerWidget* server = new ServerWidget(this); // registering object generator MoleculeObjectCreator* object_creator = new MoleculeObjectCreator; server->registerObjectCreator(*object_creator); #endif #ifdef BALL_PYTHON_SUPPORT new TestFramework(this, ((String)"Test Framework").c_str()); addDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, ((String)tr("Python Interpreter")).c_str())); #endif // --------------------- // Menus --------------- // --------------------- description = "Shortcut|File|Open|Project"; insertMenuEntry(MainControl::FILE_OPEN, ((String)tr("Project")).c_str(), this, SLOT(loadBALLViewProjectFile()), description); description = "Shortcut|File|Save_Project"; save_project_action_ = insertMenuEntry(MainControl::FILE, ((String)tr("Save Project")).c_str(), this, SLOT(saveBALLViewProjectFile()), description); // Help-Menu ------------------------------------------------------------------- QAction* action = 0; description = "Shortcut|Help|About"; action = insertMenuEntry(MainControl::HELP, (String)tr("About"), this, SLOT(about()), description); setMenuHint(action, (String)tr("Show informations on this version of BALLView")); description = "Shortcut|Help|How_to_cite"; action = insertMenuEntry(MainControl::HELP, (String)tr("How to cite"), this, SLOT(howToCite()), description); setMenuHint(action, (String)tr("Show infos on how to cite BALL and BALLView")); // TODO: why is this done here and not, e.g., in mainControl()??? description = "Shortcut|MolecularMechanics|Abort_Calculation"; stop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, (String)tr("Abort Calculation"), this, SLOT(stopSimulation()), description, QKeySequence("Alt+C")); stop_simulation_action_->setEnabled(false); insertPopupMenuSeparator(MainControl::MOLECULARMECHANICS); setMenuHint(stop_simulation_action_, (String)tr("Abort a running simulation")); stop_simulation_action_->setIcon(IconLoader::instance().getIcon("actions/process-stop")); description = "Shortcut|Edit|Invert_Selection"; complement_selection_action_ = insertMenuEntry(MainControl::EDIT, (String)tr("Invert Selection"), this, SLOT(complementSelection()), description); description = "Shortcut|Edit|Clear_Selection"; clear_selection_action_ = insertMenuEntry(MainControl::EDIT, (String)tr("Clear Selection"), this, SLOT(clearSelection()), description); qApp->installEventFilter(this); setStatusbarText((String)tr("Ready.")); } Mainframe::~Mainframe() { } bool Mainframe::eventFilter(QObject* sender, QEvent* event) { if (event->type() != QEvent::KeyPress) return false; QKeyEvent* e = dynamic_cast<QKeyEvent*>(event); if (e->key() == Qt::Key_Escape && HelpViewer::getInstance("BALLView Docu")->isWhatsThisEnabled()) { HelpViewer::getInstance("BALLView Docu")->exitWhatsThisMode(); } QPoint point = QCursor::pos(); QWidget* widget = qApp->widgetAt(point); if (widget == scene_ && qApp->focusWidget() != scene_) { scene_->keyPressEvent(e); return true; } if (e->key() == Qt::Key_Delete && RTTI::isKindOf<QTreeWidget>(*sender)) { deleteClicked(); return true; } if (e->key() == Qt::Key_Enter) { if (composite_manager_.getNumberOfComposites() == 0) return false; if (getMolecularControlSelection().size() == 0) { control_selection_.push_back(*composite_manager_.begin()); } MolecularStructure::getInstance(0)->centerCamera(); return true; } // check all menu entries if Alt or CTRL is pressed to enable shortcuts if (e->key() == Qt::Key_Alt || e->key() == Qt::Key_Control) { checkMenus(); return false; } #ifdef BALL_PYTHON_SUPPORT PyWidget::getInstance(0)->reactTo(*e); e->accept(); #endif return false; } void Mainframe::reset() { if (composites_locked_ || getRepresentationManager().updateRunning()) return; clearData(); DisplayProperties* dp = DisplayProperties::getInstance(0); dp->setDrawingPrecision(DRAWING_PRECISION_HIGH); dp->selectModel(MODEL_STICK); dp->selectColoringMethod(COLORING_ELEMENT); dp->selectMode(DRAWING_MODE_SOLID); dp->setTransparency(0); dp->setSurfaceDrawingPrecision(6.5); } void Mainframe::howToCite() { HelpViewer::getInstance("BALLView Docu")->showHelp("tips.html", (String)tr("cite")); } void Mainframe::show() { // prevent multiple inserting of menu entries, by calls of showFullScreen(), ... if (preferences_action_ != 0) { MainControl::show(); return; } QToolBar* tb = new QToolBar("Main Toolbar", this); tb->setObjectName(tr("Main Toolbar")); tb->setIconSize(QSize(22,22)); addToolBar(Qt::TopToolBarArea, tb); MainControl::show(); initPopupMenu(MainControl::WINDOWS)->addSeparator(); initPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction()); MolecularFileDialog::getInstance(0)->addToolBarEntries(tb); DownloadPDBFile::getInstance(0)->addToolBarEntries(tb); DownloadElectronDensity::getInstance(0)->addToolBarEntries(tb); PubChemDialog::getInstance(0)->addToolBarEntries(tb); UndoManagerDialog::getInstance(0)->addToolBarEntries(tb); tb->addAction(fullscreen_action_); Path path; IconLoader& loader = IconLoader::instance(); qload_action_ = new QAction(loader.getIcon("actions/quickopen-file"), tr("quickload"), this); qload_action_->setObjectName(tr("quickload")); connect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm())); HelpViewer::getInstance("BALLView Docu")->registerForHelpSystem(qload_action_, "tips.html#quickload"); tb->addAction(qload_action_); qsave_action_ = new QAction(loader.getIcon("actions/quicksave"), tr("quicksave"), this); qsave_action_->setObjectName(tr("quicksave")); connect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave())); HelpViewer::getInstance("BALLView Docu")->registerForHelpSystem(qsave_action_, "tips.html#quickload"); tb->addAction(qsave_action_); tb->addSeparator(); DisplayProperties::getInstance(0)->addToolBarEntries(tb); MolecularStructure::getInstance(0)->addToolBarEntries(tb); scene_->addToolBarEntries(tb); tb->addAction(stop_simulation_action_); tb->addAction(preferences_action_); HelpViewer::getInstance("BALLView Docu")->addToolBarEntries(tb); // we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have // to restore the window state again! restoreWindows(); // finally, apply all values our modular widgets have fetched from their preferences applyPreferences(); } void Mainframe::about() { // Display about dialog QDialog w; Ui_AboutDialog about; about.setupUi(&w); QString version = QString(tr("QT ")) + qVersion(); #ifdef BALL_QT_HAS_THREADS version += "(mt)"; #endif about.qt_version_label->setText(version); QFont font = about.BALLView_version_label->font(); about.BALLView_version_label->setText(QString("BALLView ") + BALL_RELEASE_STRING); font.setPixelSize(18); about.BALLView_version_label->setFont(font); about.BALL_version_label->setText(__DATE__); // find the BALLView log Path p; String logo_path = p.find("graphics/logo.png"); if (logo_path != "") about.BALLView_logo_label->setPixmap(QPixmap(logo_path.c_str())); w.exec(); } void Mainframe::changeEvent(QEvent* evt) { if(evt->type() == QEvent::WindowStateChange) { if (isFullScreen()) { fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-restore")); } else { fullscreen_action_->setIcon(IconLoader::instance().getIcon("actions/view-fullscreen")); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2015-2016 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "val/validation_state.h" #include <cassert> #include "opcode.h" #include "val/basic_block.h" #include "val/construct.h" #include "val/function.h" using std::deque; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; namespace libspirv { namespace { bool IsInstructionInLayoutSection(ModuleLayoutSection layout, SpvOp op) { // See Section 2.4 bool out = false; // clang-format off switch (layout) { case kLayoutCapabilities: out = op == SpvOpCapability; break; case kLayoutExtensions: out = op == SpvOpExtension; break; case kLayoutExtInstImport: out = op == SpvOpExtInstImport; break; case kLayoutMemoryModel: out = op == SpvOpMemoryModel; break; case kLayoutEntryPoint: out = op == SpvOpEntryPoint; break; case kLayoutExecutionMode: out = op == SpvOpExecutionMode; break; case kLayoutDebug1: switch (op) { case SpvOpSourceContinued: case SpvOpSource: case SpvOpSourceExtension: case SpvOpString: out = true; break; default: break; } break; case kLayoutDebug2: switch (op) { case SpvOpName: case SpvOpMemberName: out = true; break; default: break; } break; case kLayoutAnnotations: switch (op) { case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpGroupDecorate: case SpvOpGroupMemberDecorate: case SpvOpDecorationGroup: out = true; break; default: break; } break; case kLayoutTypes: if (spvOpcodeGeneratesType(op) || spvOpcodeIsConstant(op)) { out = true; break; } switch (op) { case SpvOpTypeForwardPointer: case SpvOpVariable: case SpvOpLine: case SpvOpNoLine: case SpvOpUndef: out = true; break; default: break; } break; case kLayoutFunctionDeclarations: case kLayoutFunctionDefinitions: // NOTE: These instructions should NOT be in these layout sections if (spvOpcodeGeneratesType(op) || spvOpcodeIsConstant(op)) { out = false; break; } switch (op) { case SpvOpCapability: case SpvOpExtension: case SpvOpExtInstImport: case SpvOpMemoryModel: case SpvOpEntryPoint: case SpvOpExecutionMode: case SpvOpSourceContinued: case SpvOpSource: case SpvOpSourceExtension: case SpvOpString: case SpvOpName: case SpvOpMemberName: case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpGroupDecorate: case SpvOpGroupMemberDecorate: case SpvOpDecorationGroup: case SpvOpTypeForwardPointer: out = false; break; default: out = true; break; } } // clang-format on return out; } } // anonymous namespace ValidationState_t::ValidationState_t(const spv_const_context ctx, const spv_const_validator_options opt) : context_(ctx), options_(opt), instruction_counter_(0), unresolved_forward_ids_{}, operand_names_{}, current_layout_section_(kLayoutCapabilities), module_functions_(), module_capabilities_(), module_extensions_(), ordered_instructions_(), all_definitions_(), global_vars_(), local_vars_(), struct_nesting_depth_(), grammar_(ctx), addressing_model_(SpvAddressingModelLogical), memory_model_(SpvMemoryModelSimple), in_function_(false) { assert(opt && "Validator options may not be Null."); } spv_result_t ValidationState_t::ForwardDeclareId(uint32_t id) { unresolved_forward_ids_.insert(id); return SPV_SUCCESS; } spv_result_t ValidationState_t::RemoveIfForwardDeclared(uint32_t id) { unresolved_forward_ids_.erase(id); return SPV_SUCCESS; } spv_result_t ValidationState_t::RegisterForwardPointer(uint32_t id) { forward_pointer_ids_.insert(id); return SPV_SUCCESS; } bool ValidationState_t::IsForwardPointer(uint32_t id) const { return (forward_pointer_ids_.find(id) != forward_pointer_ids_.end()); } void ValidationState_t::AssignNameToId(uint32_t id, string name) { operand_names_[id] = name; } string ValidationState_t::getIdName(uint32_t id) const { std::stringstream out; out << id; if (operand_names_.find(id) != end(operand_names_)) { out << "[" << operand_names_.at(id) << "]"; } return out.str(); } string ValidationState_t::getIdOrName(uint32_t id) const { std::stringstream out; if (operand_names_.find(id) != end(operand_names_)) { out << operand_names_.at(id); } else { out << id; } return out.str(); } size_t ValidationState_t::unresolved_forward_id_count() const { return unresolved_forward_ids_.size(); } vector<uint32_t> ValidationState_t::UnresolvedForwardIds() const { vector<uint32_t> out(begin(unresolved_forward_ids_), end(unresolved_forward_ids_)); return out; } bool ValidationState_t::IsDefinedId(uint32_t id) const { return all_definitions_.find(id) != end(all_definitions_); } const Instruction* ValidationState_t::FindDef(uint32_t id) const { if (all_definitions_.count(id) == 0) { return nullptr; } else { /// We are in a const function, so we cannot use defs.operator[](). /// Luckily we know the key exists, so defs_.at() won't throw an /// exception. return all_definitions_.at(id); } } Instruction* ValidationState_t::FindDef(uint32_t id) { if (all_definitions_.count(id) == 0) { return nullptr; } else { /// We are in a const function, so we cannot use defs.operator[](). /// Luckily we know the key exists, so defs_.at() won't throw an /// exception. return all_definitions_.at(id); } } // Increments the instruction count. Used for diagnostic int ValidationState_t::increment_instruction_count() { return instruction_counter_++; } ModuleLayoutSection ValidationState_t::current_layout_section() const { return current_layout_section_; } void ValidationState_t::ProgressToNextLayoutSectionOrder() { // Guard against going past the last element(kLayoutFunctionDefinitions) if (current_layout_section_ <= kLayoutFunctionDefinitions) { current_layout_section_ = static_cast<ModuleLayoutSection>(current_layout_section_ + 1); } } bool ValidationState_t::IsOpcodeInCurrentLayoutSection(SpvOp op) { return IsInstructionInLayoutSection(current_layout_section_, op); } DiagnosticStream ValidationState_t::diag(spv_result_t error_code) const { return libspirv::DiagnosticStream( {0, 0, static_cast<size_t>(instruction_counter_)}, context_->consumer, error_code); } deque<Function>& ValidationState_t::functions() { return module_functions_; } Function& ValidationState_t::current_function() { assert(in_function_body()); return module_functions_.back(); } bool ValidationState_t::in_function_body() const { return in_function_; } bool ValidationState_t::in_block() const { return module_functions_.empty() == false && module_functions_.back().current_block() != nullptr; } void ValidationState_t::RegisterCapability(SpvCapability cap) { // Avoid redundant work. Otherwise the recursion could induce work // quadrdatic in the capability dependency depth. (Ok, not much, but // it's something.) if (module_capabilities_.Contains(cap)) return; module_capabilities_.Add(cap); spv_operand_desc desc; if (SPV_SUCCESS == grammar_.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) { desc->capabilities.ForEach( [this](SpvCapability c) { RegisterCapability(c); }); } switch (cap) { case SpvCapabilityInt16: features_.declare_int16_type = true; break; case SpvCapabilityFloat16: case SpvCapabilityFloat16Buffer: features_.declare_float16_type = true; break; case SpvCapabilityStorageUniformBufferBlock16: case SpvCapabilityStorageUniform16: case SpvCapabilityStoragePushConstant16: case SpvCapabilityStorageInputOutput16: features_.declare_int16_type = true; features_.declare_float16_type = true; features_.free_fp_rounding_mode = true; break; case SpvCapabilityVariablePointers: features_.variable_pointers = true; features_.variable_pointers_storage_buffer = true; break; case SpvCapabilityVariablePointersStorageBuffer: features_.variable_pointers_storage_buffer = true; break; default: break; } } void ValidationState_t::RegisterExtension(Extension ext) { if (module_extensions_.Contains(ext)) return; module_extensions_.Add(ext); } bool ValidationState_t::HasAnyOfCapabilities( const CapabilitySet& capabilities) const { return module_capabilities_.HasAnyOf(capabilities); } bool ValidationState_t::HasAnyOfExtensions( const ExtensionSet& extensions) const { return module_extensions_.HasAnyOf(extensions); } void ValidationState_t::set_addressing_model(SpvAddressingModel am) { addressing_model_ = am; } SpvAddressingModel ValidationState_t::addressing_model() const { return addressing_model_; } void ValidationState_t::set_memory_model(SpvMemoryModel mm) { memory_model_ = mm; } SpvMemoryModel ValidationState_t::memory_model() const { return memory_model_; } spv_result_t ValidationState_t::RegisterFunction( uint32_t id, uint32_t ret_type_id, SpvFunctionControlMask function_control, uint32_t function_type_id) { assert(in_function_body() == false && "RegisterFunction can only be called when parsing the binary outside " "of another function"); in_function_ = true; module_functions_.emplace_back(id, ret_type_id, function_control, function_type_id); // TODO(umar): validate function type and type_id return SPV_SUCCESS; } spv_result_t ValidationState_t::RegisterFunctionEnd() { assert(in_function_body() == true && "RegisterFunctionEnd can only be called when parsing the binary " "inside of another function"); assert(in_block() == false && "RegisterFunctionParameter can only be called when parsing the binary " "ouside of a block"); current_function().RegisterFunctionEnd(); in_function_ = false; return SPV_SUCCESS; } void ValidationState_t::RegisterInstruction( const spv_parsed_instruction_t& inst) { if (in_function_body()) { ordered_instructions_.emplace_back(&inst, &current_function(), current_function().current_block()); } else { ordered_instructions_.emplace_back(&inst, nullptr, nullptr); } uint32_t id = ordered_instructions_.back().id(); if (id) { all_definitions_.insert(make_pair(id, &ordered_instructions_.back())); } // If the instruction is using an OpTypeSampledImage as an operand, it should // be recorded. The validator will ensure that all usages of an // OpTypeSampledImage and its definition are in the same basic block. for (uint16_t i = 0; i < inst.num_operands; ++i) { const spv_parsed_operand_t& operand = inst.operands[i]; if (SPV_OPERAND_TYPE_ID == operand.type) { const uint32_t operand_word = inst.words[operand.offset]; Instruction* operand_inst = FindDef(operand_word); if (operand_inst && SpvOpSampledImage == operand_inst->opcode()) { RegisterSampledImageConsumer(operand_word, inst.result_id); } } } } std::vector<uint32_t> ValidationState_t::getSampledImageConsumers( uint32_t sampled_image_id) const { std::vector<uint32_t> result; auto iter = sampled_image_consumers_.find(sampled_image_id); if (iter != sampled_image_consumers_.end()) { result = iter->second; } return result; } void ValidationState_t::RegisterSampledImageConsumer(uint32_t sampled_image_id, uint32_t consumer_id) { sampled_image_consumers_[sampled_image_id].push_back(consumer_id); } uint32_t ValidationState_t::getIdBound() const { return id_bound_; } void ValidationState_t::setIdBound(const uint32_t bound) { id_bound_ = bound; } bool ValidationState_t::RegisterUniqueTypeDeclaration( const spv_parsed_instruction_t& inst) { std::vector<uint32_t> key; key.push_back(static_cast<uint32_t>(inst.opcode)); for (int index = 0; index < inst.num_operands; ++index) { const spv_parsed_operand_t& operand = inst.operands[index]; if (operand.type == SPV_OPERAND_TYPE_RESULT_ID) continue; const int words_begin = operand.offset; const int words_end = words_begin + operand.num_words; assert(words_end <= static_cast<int>(inst.num_words)); key.insert(key.end(), inst.words + words_begin, inst.words + words_end); } return unique_type_declarations_.insert(std::move(key)).second; } } /// namespace libspirv <commit_msg>Don't do hash lookup twice in FindDef<commit_after>// Copyright (c) 2015-2016 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "val/validation_state.h" #include <cassert> #include "opcode.h" #include "val/basic_block.h" #include "val/construct.h" #include "val/function.h" using std::deque; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; namespace libspirv { namespace { bool IsInstructionInLayoutSection(ModuleLayoutSection layout, SpvOp op) { // See Section 2.4 bool out = false; // clang-format off switch (layout) { case kLayoutCapabilities: out = op == SpvOpCapability; break; case kLayoutExtensions: out = op == SpvOpExtension; break; case kLayoutExtInstImport: out = op == SpvOpExtInstImport; break; case kLayoutMemoryModel: out = op == SpvOpMemoryModel; break; case kLayoutEntryPoint: out = op == SpvOpEntryPoint; break; case kLayoutExecutionMode: out = op == SpvOpExecutionMode; break; case kLayoutDebug1: switch (op) { case SpvOpSourceContinued: case SpvOpSource: case SpvOpSourceExtension: case SpvOpString: out = true; break; default: break; } break; case kLayoutDebug2: switch (op) { case SpvOpName: case SpvOpMemberName: out = true; break; default: break; } break; case kLayoutAnnotations: switch (op) { case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpGroupDecorate: case SpvOpGroupMemberDecorate: case SpvOpDecorationGroup: out = true; break; default: break; } break; case kLayoutTypes: if (spvOpcodeGeneratesType(op) || spvOpcodeIsConstant(op)) { out = true; break; } switch (op) { case SpvOpTypeForwardPointer: case SpvOpVariable: case SpvOpLine: case SpvOpNoLine: case SpvOpUndef: out = true; break; default: break; } break; case kLayoutFunctionDeclarations: case kLayoutFunctionDefinitions: // NOTE: These instructions should NOT be in these layout sections if (spvOpcodeGeneratesType(op) || spvOpcodeIsConstant(op)) { out = false; break; } switch (op) { case SpvOpCapability: case SpvOpExtension: case SpvOpExtInstImport: case SpvOpMemoryModel: case SpvOpEntryPoint: case SpvOpExecutionMode: case SpvOpSourceContinued: case SpvOpSource: case SpvOpSourceExtension: case SpvOpString: case SpvOpName: case SpvOpMemberName: case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpGroupDecorate: case SpvOpGroupMemberDecorate: case SpvOpDecorationGroup: case SpvOpTypeForwardPointer: out = false; break; default: out = true; break; } } // clang-format on return out; } } // anonymous namespace ValidationState_t::ValidationState_t(const spv_const_context ctx, const spv_const_validator_options opt) : context_(ctx), options_(opt), instruction_counter_(0), unresolved_forward_ids_{}, operand_names_{}, current_layout_section_(kLayoutCapabilities), module_functions_(), module_capabilities_(), module_extensions_(), ordered_instructions_(), all_definitions_(), global_vars_(), local_vars_(), struct_nesting_depth_(), grammar_(ctx), addressing_model_(SpvAddressingModelLogical), memory_model_(SpvMemoryModelSimple), in_function_(false) { assert(opt && "Validator options may not be Null."); } spv_result_t ValidationState_t::ForwardDeclareId(uint32_t id) { unresolved_forward_ids_.insert(id); return SPV_SUCCESS; } spv_result_t ValidationState_t::RemoveIfForwardDeclared(uint32_t id) { unresolved_forward_ids_.erase(id); return SPV_SUCCESS; } spv_result_t ValidationState_t::RegisterForwardPointer(uint32_t id) { forward_pointer_ids_.insert(id); return SPV_SUCCESS; } bool ValidationState_t::IsForwardPointer(uint32_t id) const { return (forward_pointer_ids_.find(id) != forward_pointer_ids_.end()); } void ValidationState_t::AssignNameToId(uint32_t id, string name) { operand_names_[id] = name; } string ValidationState_t::getIdName(uint32_t id) const { std::stringstream out; out << id; if (operand_names_.find(id) != end(operand_names_)) { out << "[" << operand_names_.at(id) << "]"; } return out.str(); } string ValidationState_t::getIdOrName(uint32_t id) const { std::stringstream out; if (operand_names_.find(id) != end(operand_names_)) { out << operand_names_.at(id); } else { out << id; } return out.str(); } size_t ValidationState_t::unresolved_forward_id_count() const { return unresolved_forward_ids_.size(); } vector<uint32_t> ValidationState_t::UnresolvedForwardIds() const { vector<uint32_t> out(begin(unresolved_forward_ids_), end(unresolved_forward_ids_)); return out; } bool ValidationState_t::IsDefinedId(uint32_t id) const { return all_definitions_.find(id) != end(all_definitions_); } const Instruction* ValidationState_t::FindDef(uint32_t id) const { auto it = all_definitions_.find(id); if (it == all_definitions_.end()) return nullptr; return it->second; } Instruction* ValidationState_t::FindDef(uint32_t id) { auto it = all_definitions_.find(id); if (it == all_definitions_.end()) return nullptr; return it->second; } // Increments the instruction count. Used for diagnostic int ValidationState_t::increment_instruction_count() { return instruction_counter_++; } ModuleLayoutSection ValidationState_t::current_layout_section() const { return current_layout_section_; } void ValidationState_t::ProgressToNextLayoutSectionOrder() { // Guard against going past the last element(kLayoutFunctionDefinitions) if (current_layout_section_ <= kLayoutFunctionDefinitions) { current_layout_section_ = static_cast<ModuleLayoutSection>(current_layout_section_ + 1); } } bool ValidationState_t::IsOpcodeInCurrentLayoutSection(SpvOp op) { return IsInstructionInLayoutSection(current_layout_section_, op); } DiagnosticStream ValidationState_t::diag(spv_result_t error_code) const { return libspirv::DiagnosticStream( {0, 0, static_cast<size_t>(instruction_counter_)}, context_->consumer, error_code); } deque<Function>& ValidationState_t::functions() { return module_functions_; } Function& ValidationState_t::current_function() { assert(in_function_body()); return module_functions_.back(); } bool ValidationState_t::in_function_body() const { return in_function_; } bool ValidationState_t::in_block() const { return module_functions_.empty() == false && module_functions_.back().current_block() != nullptr; } void ValidationState_t::RegisterCapability(SpvCapability cap) { // Avoid redundant work. Otherwise the recursion could induce work // quadrdatic in the capability dependency depth. (Ok, not much, but // it's something.) if (module_capabilities_.Contains(cap)) return; module_capabilities_.Add(cap); spv_operand_desc desc; if (SPV_SUCCESS == grammar_.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) { desc->capabilities.ForEach( [this](SpvCapability c) { RegisterCapability(c); }); } switch (cap) { case SpvCapabilityInt16: features_.declare_int16_type = true; break; case SpvCapabilityFloat16: case SpvCapabilityFloat16Buffer: features_.declare_float16_type = true; break; case SpvCapabilityStorageUniformBufferBlock16: case SpvCapabilityStorageUniform16: case SpvCapabilityStoragePushConstant16: case SpvCapabilityStorageInputOutput16: features_.declare_int16_type = true; features_.declare_float16_type = true; features_.free_fp_rounding_mode = true; break; case SpvCapabilityVariablePointers: features_.variable_pointers = true; features_.variable_pointers_storage_buffer = true; break; case SpvCapabilityVariablePointersStorageBuffer: features_.variable_pointers_storage_buffer = true; break; default: break; } } void ValidationState_t::RegisterExtension(Extension ext) { if (module_extensions_.Contains(ext)) return; module_extensions_.Add(ext); } bool ValidationState_t::HasAnyOfCapabilities( const CapabilitySet& capabilities) const { return module_capabilities_.HasAnyOf(capabilities); } bool ValidationState_t::HasAnyOfExtensions( const ExtensionSet& extensions) const { return module_extensions_.HasAnyOf(extensions); } void ValidationState_t::set_addressing_model(SpvAddressingModel am) { addressing_model_ = am; } SpvAddressingModel ValidationState_t::addressing_model() const { return addressing_model_; } void ValidationState_t::set_memory_model(SpvMemoryModel mm) { memory_model_ = mm; } SpvMemoryModel ValidationState_t::memory_model() const { return memory_model_; } spv_result_t ValidationState_t::RegisterFunction( uint32_t id, uint32_t ret_type_id, SpvFunctionControlMask function_control, uint32_t function_type_id) { assert(in_function_body() == false && "RegisterFunction can only be called when parsing the binary outside " "of another function"); in_function_ = true; module_functions_.emplace_back(id, ret_type_id, function_control, function_type_id); // TODO(umar): validate function type and type_id return SPV_SUCCESS; } spv_result_t ValidationState_t::RegisterFunctionEnd() { assert(in_function_body() == true && "RegisterFunctionEnd can only be called when parsing the binary " "inside of another function"); assert(in_block() == false && "RegisterFunctionParameter can only be called when parsing the binary " "ouside of a block"); current_function().RegisterFunctionEnd(); in_function_ = false; return SPV_SUCCESS; } void ValidationState_t::RegisterInstruction( const spv_parsed_instruction_t& inst) { if (in_function_body()) { ordered_instructions_.emplace_back(&inst, &current_function(), current_function().current_block()); } else { ordered_instructions_.emplace_back(&inst, nullptr, nullptr); } uint32_t id = ordered_instructions_.back().id(); if (id) { all_definitions_.insert(make_pair(id, &ordered_instructions_.back())); } // If the instruction is using an OpTypeSampledImage as an operand, it should // be recorded. The validator will ensure that all usages of an // OpTypeSampledImage and its definition are in the same basic block. for (uint16_t i = 0; i < inst.num_operands; ++i) { const spv_parsed_operand_t& operand = inst.operands[i]; if (SPV_OPERAND_TYPE_ID == operand.type) { const uint32_t operand_word = inst.words[operand.offset]; Instruction* operand_inst = FindDef(operand_word); if (operand_inst && SpvOpSampledImage == operand_inst->opcode()) { RegisterSampledImageConsumer(operand_word, inst.result_id); } } } } std::vector<uint32_t> ValidationState_t::getSampledImageConsumers( uint32_t sampled_image_id) const { std::vector<uint32_t> result; auto iter = sampled_image_consumers_.find(sampled_image_id); if (iter != sampled_image_consumers_.end()) { result = iter->second; } return result; } void ValidationState_t::RegisterSampledImageConsumer(uint32_t sampled_image_id, uint32_t consumer_id) { sampled_image_consumers_[sampled_image_id].push_back(consumer_id); } uint32_t ValidationState_t::getIdBound() const { return id_bound_; } void ValidationState_t::setIdBound(const uint32_t bound) { id_bound_ = bound; } bool ValidationState_t::RegisterUniqueTypeDeclaration( const spv_parsed_instruction_t& inst) { std::vector<uint32_t> key; key.push_back(static_cast<uint32_t>(inst.opcode)); for (int index = 0; index < inst.num_operands; ++index) { const spv_parsed_operand_t& operand = inst.operands[index]; if (operand.type == SPV_OPERAND_TYPE_RESULT_ID) continue; const int words_begin = operand.offset; const int words_end = words_begin + operand.num_words; assert(words_end <= static_cast<int>(inst.num_words)); key.insert(key.end(), inst.words + words_begin, inst.words + words_end); } return unique_type_declarations_.insert(std::move(key)).second; } } /// namespace libspirv <|endoftext|>
<commit_before>#include <iostream> #include <typeinfo> #include <map> using std::cout; using std::endl; #include "viennagrid/storage/view.hpp" #include "viennagrid/storage/container_collection.hpp" #include "viennagrid/storage/inserter.hpp" #include "viennagrid/storage/id.hpp" #include "viennagrid/storage/id_generator.hpp" #include "viennagrid/storage/io.hpp" template<typename _numeric_type> struct vertex : public viennagrid::storage::id_handler<int> { typedef _numeric_type numeric_type; typedef typename viennameta::make_typelist< vertex<numeric_type> >::type required_types; enum { dim = 2 }; vertex(numeric_type _x, numeric_type _y) : x(_x), y(_y) {} template<typename inserter_type> void insert_callback( inserter_type & inserter, bool inserted ) {} numeric_type x; numeric_type y; }; template <typename numeric_type> std::ostream & operator<<(std::ostream & os, const vertex<numeric_type> & v) { os << "[Vertex id=" << v.id() << "] (" << v.x << "," << v.y << ")"; return os; } template<typename _vertex_type> struct line : public viennagrid::storage::id_handler<int> { typedef _vertex_type vertex_type; typedef typename viennameta::typelist::result_of::push_back<typename vertex_type::required_types, line<vertex_type> >::type required_types; template<typename inserter_type> void insert_callback( inserter_type & inserter, bool inserted ) {} vertex_type * vertices[2]; }; template <typename vertex_type> std::ostream & operator<<(std::ostream & os, const line<vertex_type> & l) { os << "[Line id=" << l.id() << "] " << *l.vertices[0] << " " << *l.vertices[1]; return os; } template<typename _vertex_type> struct triangle : public viennagrid::storage::id_handler<int> { typedef _vertex_type vertex_type; typedef line<vertex_type> line_type; typedef typename viennameta::typelist::result_of::push_back<typename line_type::required_types, triangle<vertex_type> >::type required_types; template<typename inserter_type> void insert_callback( inserter_type & inserter, bool inserted ) { line_type l; l.vertices[0] = vertices[0]; l.vertices[1] = vertices[1]; lines[0] = &* inserter(l).first; l.vertices[0] = vertices[1]; l.vertices[1] = vertices[2]; lines[1] = &* inserter(l).first; l.vertices[0] = vertices[2]; l.vertices[1] = vertices[0]; lines[2] = &* inserter(l).first; } line_type * lines[3]; vertex_type * vertices[3]; }; template <typename vertex_type> std::ostream & operator<<(std::ostream & os, const triangle<vertex_type> & t) { os << "[Triangle id=" << t.id() << "] \n"; os << " " << *t.vertices[0] << "\n"; os << " " << *t.vertices[1] << "\n"; os << " " << *t.vertices[2] << "\n"; os << " " << *t.lines[0] << "\n"; os << " " << *t.lines[1] << "\n"; os << " " << *t.lines[2] << "\n"; return os; } int main() { typedef vertex<double> vertex_type; typedef line<vertex_type> line_type; typedef triangle<vertex_type> triangle_type; typedef viennagrid::storage::result_of::container_collection< triangle<vertex_type>::required_types, viennagrid::storage::container_collection::default_container_config >::type collection_type; collection_type collection; typedef viennagrid::storage::result_of::continuous_id_generator< triangle<vertex_type>::required_types >::type id_generator_type; id_generator_type id_generator; typedef viennagrid::storage::result_of::physical_inserter< collection_type, id_generator_type& >::type inserter_type; inserter_type inserter(collection, id_generator); triangle_type t; t.vertices[0] = &* inserter( vertex_type(0.0, 0.0) ).first; t.vertices[1] = &* inserter( vertex_type(1.0, 0.0) ).first; t.vertices[2] = &* inserter( vertex_type(0.0, 1.0) ).first; inserter( t ); cout << "collection" << endl; cout << collection << endl; typedef viennagrid::storage::container_collection::result_of::container_typelist<collection_type>::type collection_containers; typedef viennagrid::storage::result_of::view_collection< viennameta::typelist::result_of::erase_at<collection_containers, 1>::type, viennagrid::storage::container_collection::default_container_config >::type view_collection_type; view_collection_type view_collection; viennagrid::storage::container_collection::hook(collection, view_collection); cout << "view_collection" << endl; cout << view_collection << endl; typedef viennagrid::storage::result_of::recursive_inserter<view_collection_type, inserter_type>::type view_inserter_type; view_inserter_type view_inserter(view_collection, inserter); t.vertices[0] = &* view_inserter( vertex_type(5.0, 0.0) ).first; t.vertices[1] = &* view_inserter( vertex_type(7.0, 5.0) ).first; t.vertices[2] = &* view_inserter( vertex_type(0.0, 7.0) ).first; view_inserter( t ); cout << "After Insert" << endl; cout << "collection" << endl; cout << collection << endl; cout << "view_collection" << endl; cout << view_collection << endl; return 0; } <commit_msg>adapted to new insert_callback<commit_after>#include <iostream> #include <typeinfo> #include <map> using std::cout; using std::endl; #include "viennagrid/storage/view.hpp" #include "viennagrid/storage/container_collection.hpp" #include "viennagrid/storage/inserter.hpp" #include "viennagrid/storage/id.hpp" #include "viennagrid/storage/id_generator.hpp" #include "viennagrid/storage/io.hpp" template<typename _numeric_type> struct vertex : public viennagrid::storage::id_handler<int> { typedef _numeric_type numeric_type; typedef typename viennameta::make_typelist< vertex<numeric_type> >::type required_types; enum { dim = 2 }; vertex(numeric_type _x, numeric_type _y) : x(_x), y(_y) {} template<typename inserter_type, typename container_collection_type> void insert_callback( inserter_type & inserter, bool inserted, container_collection_type & container_collection ) {} numeric_type x; numeric_type y; }; template <typename numeric_type> std::ostream & operator<<(std::ostream & os, const vertex<numeric_type> & v) { os << "[Vertex id=" << v.id() << "] (" << v.x << "," << v.y << ")"; return os; } template<typename _vertex_type> struct line : public viennagrid::storage::id_handler<int> { typedef _vertex_type vertex_type; typedef typename viennameta::typelist::result_of::push_back<typename vertex_type::required_types, line<vertex_type> >::type required_types; template<typename inserter_type, typename container_collection_type> void insert_callback( inserter_type & inserter, bool inserted, container_collection_type & container_collection ) {} vertex_type * vertices[2]; }; template <typename vertex_type> std::ostream & operator<<(std::ostream & os, const line<vertex_type> & l) { os << "[Line id=" << l.id() << "] " << *l.vertices[0] << " " << *l.vertices[1]; return os; } template<typename _vertex_type> struct triangle : public viennagrid::storage::id_handler<int> { typedef _vertex_type vertex_type; typedef line<vertex_type> line_type; typedef typename viennameta::typelist::result_of::push_back<typename line_type::required_types, triangle<vertex_type> >::type required_types; template<typename inserter_type, typename container_collection_type> void insert_callback( inserter_type & inserter, bool inserted, container_collection_type & container_collection ) { line_type l; l.vertices[0] = vertices[0]; l.vertices[1] = vertices[1]; lines[0] = &* inserter(l).first; l.vertices[0] = vertices[1]; l.vertices[1] = vertices[2]; lines[1] = &* inserter(l).first; l.vertices[0] = vertices[2]; l.vertices[1] = vertices[0]; lines[2] = &* inserter(l).first; } line_type * lines[3]; vertex_type * vertices[3]; }; template <typename vertex_type> std::ostream & operator<<(std::ostream & os, const triangle<vertex_type> & t) { os << "[Triangle id=" << t.id() << "] \n"; os << " " << *t.vertices[0] << "\n"; os << " " << *t.vertices[1] << "\n"; os << " " << *t.vertices[2] << "\n"; os << " " << *t.lines[0] << "\n"; os << " " << *t.lines[1] << "\n"; os << " " << *t.lines[2] << "\n"; return os; } int main() { typedef vertex<double> vertex_type; typedef line<vertex_type> line_type; typedef triangle<vertex_type> triangle_type; typedef viennagrid::storage::result_of::container_collection< triangle<vertex_type>::required_types, viennagrid::storage::container_collection::default_container_config >::type collection_type; collection_type collection; typedef viennagrid::storage::result_of::continuous_id_generator< triangle<vertex_type>::required_types >::type id_generator_type; id_generator_type id_generator; typedef viennagrid::storage::result_of::physical_inserter< collection_type, id_generator_type& >::type inserter_type; inserter_type inserter(collection, id_generator); triangle_type t; t.vertices[0] = &* inserter( vertex_type(0.0, 0.0) ).first; t.vertices[1] = &* inserter( vertex_type(1.0, 0.0) ).first; t.vertices[2] = &* inserter( vertex_type(0.0, 1.0) ).first; inserter( t ); cout << "collection" << endl; cout << collection << endl; typedef viennagrid::storage::container_collection::result_of::container_typelist<collection_type>::type collection_containers; typedef viennagrid::storage::result_of::view_collection< viennameta::typelist::result_of::erase_at<collection_containers, 1>::type, viennagrid::storage::container_collection::default_container_config >::type view_collection_type; view_collection_type view_collection; viennagrid::storage::container_collection::hook(collection, view_collection); cout << "view_collection" << endl; cout << view_collection << endl; typedef viennagrid::storage::result_of::recursive_inserter<view_collection_type, inserter_type>::type view_inserter_type; view_inserter_type view_inserter(view_collection, inserter); t.vertices[0] = &* view_inserter( vertex_type(5.0, 0.0) ).first; t.vertices[1] = &* view_inserter( vertex_type(7.0, 5.0) ).first; t.vertices[2] = &* view_inserter( vertex_type(0.0, 7.0) ).first; view_inserter( t ); cout << "After Insert" << endl; cout << "collection" << endl; cout << collection << endl; cout << "view_collection" << endl; cout << view_collection << endl; return 0; } <|endoftext|>
<commit_before>// RUN: %clangxx_asan -O %s -o %t // RUN: not %run %t crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t crash // // RUN: %clangxx_asan -flto=thin -O %s -o %t.thinlto // RUN: not %run %t.thinlto crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t.thinlto bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t.thinlto bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t.thinlto crash // // Test crash due to __sanitizer_annotate_contiguous_container. #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <commit_msg>Revert "[ThinLTO] Ensure sanitizer passes are run"<commit_after>// RUN: %clangxx_asan -O %s -o %t // RUN: not %run %t crash 2>&1 | FileCheck --check-prefix=CHECK-CRASH %s // RUN: not %run %t bad-bounds 2>&1 | FileCheck --check-prefix=CHECK-BAD-BOUNDS %s // RUN: not %run %t bad-alignment 2>&1 | FileCheck --check-prefix=CHECK-BAD-ALIGNMENT %s // RUN: %env_asan_opts=detect_container_overflow=0 %run %t crash // // Test crash due to __sanitizer_annotate_contiguous_container. #include <assert.h> #include <string.h> extern "C" { void __sanitizer_annotate_contiguous_container(const void *beg, const void *end, const void *old_mid, const void *new_mid); } // extern "C" static volatile int one = 1; int TestCrash() { long t[100]; t[60] = 0; __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 100, &t[0] + 50); // CHECK-CRASH: AddressSanitizer: container-overflow // CHECK-CRASH: if you don't care about these errors you may set ASAN_OPTIONS=detect_container_overflow=0 return (int)t[60 * one]; // Touches the poisoned memory. } void BadBounds() { long t[100]; // CHECK-BAD-BOUNDS: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container __sanitizer_annotate_contiguous_container(&t[0], &t[0] + 100, &t[0] + 101, &t[0] + 50); } void BadAlignment() { int t[100]; // CHECK-BAD-ALIGNMENT: ERROR: AddressSanitizer: bad parameters to __sanitizer_annotate_contiguous_container // CHECK-BAD-ALIGNMENT: ERROR: beg is not aligned by 8 __sanitizer_annotate_contiguous_container(&t[1], &t[0] + 100, &t[1] + 10, &t[0] + 50); } int main(int argc, char **argv) { assert(argc == 2); if (!strcmp(argv[1], "crash")) return TestCrash(); else if (!strcmp(argv[1], "bad-bounds")) BadBounds(); else if (!strcmp(argv[1], "bad-alignment")) BadAlignment(); } <|endoftext|>
<commit_before>#include <mantella_bits/helper/statistic.hpp> // C++ standard library #include <cmath> // Mantella #include <mantella_bits/helper/assert.hpp> namespace mant { double getMedianAbsoluteError( const arma::Row<double>& data) { return getMedian(arma::abs(data - getMedian(data))); } double getPercentile( const arma::Row<double>& data, const double nthPercentile) { double index = nthPercentile * data.n_elem / 100; verify(0.0 < nthPercentile && nthPercentile <= 100.0, ""); // TODO arma::uword lowerIndex = static_cast<arma::uword>(std::floor(index)); arma::uword upperIndex = static_cast<arma::uword>(std::ceil(index)); if (lowerIndex != upperIndex) { return (index - lowerIndex) * data(lowerIndex) + (upperIndex - index) * data(upperIndex); } else { return data(upperIndex); } } double getDecile( const arma::Row<double>& data, const double nthDecile) { verify(0.0 < nthDecile && nthDecile <= 10.0, ""); // TODO return getPercentile(data, nthDecile * 10.0); } double getQuartile( const arma::Row<double>& data, const double nthQuartile) { verify(0.0 < nthQuartile && nthQuartile <= 4.0, ""); // TODO return getPercentile(data, nthQuartile * 25.0); } double getMedian( const arma::Row<double>& data) { return arma::median(data); } } <commit_msg>Fixed getPercentile<commit_after>#include <mantella_bits/helper/statistic.hpp> // C++ standard library #include <cmath> // Mantella #include <mantella_bits/helper/assert.hpp> namespace mant { double getMedianAbsoluteError( const arma::Row<double>& data) { return getMedian(arma::abs(data - getMedian(data))); } double getPercentile( const arma::Row<double>& data, const double nthPercentile) { verify(0.0 < nthPercentile && nthPercentile <= 100.0, ""); // TODO const arma::Row<double>& sortedData = arma::sort(data, "descend"); double index = nthPercentile * sortedData.n_elem / 100; arma::uword lowerIndex = static_cast<arma::uword>(std::floor(index)); arma::uword upperIndex = static_cast<arma::uword>(std::ceil(index)); if (lowerIndex != upperIndex) { return (index - lowerIndex) * sortedData(lowerIndex) + (upperIndex - index) * sortedData(upperIndex); } else { return sortedData(upperIndex); } } double getDecile( const arma::Row<double>& data, const double nthDecile) { verify(0.0 < nthDecile && nthDecile <= 10.0, ""); // TODO return getPercentile(data, nthDecile * 10.0); } double getQuartile( const arma::Row<double>& data, const double nthQuartile) { verify(0.0 < nthQuartile && nthQuartile <= 4.0, ""); // TODO return getPercentile(data, nthQuartile * 25.0); } double getMedian( const arma::Row<double>& data) { return arma::median(data); } } <|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/google/google_update.h" #include <atlbase.h> #include <atlcom.h> #include "base/file_path.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_comptr_win.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "base/win/windows_version.h" #include "chrome/browser/browser_thread.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/install_util.h" #include "views/window/window.h" #include "google_update_idl_i.c" using views::Window; namespace { // Check if the currently running instance can be updated by Google Update. // Returns true only if the instance running is a Google Chrome // distribution installed in a standard location. bool CanUpdateCurrentChrome(const std::wstring& chrome_exe_path) { #if !defined(GOOGLE_CHROME_BUILD) return false; #else std::wstring user_exe_path = installer::GetChromeInstallPath(false); std::wstring machine_exe_path = installer::GetChromeInstallPath(true); std::transform(user_exe_path.begin(), user_exe_path.end(), user_exe_path.begin(), tolower); std::transform(machine_exe_path.begin(), machine_exe_path.end(), machine_exe_path.begin(), tolower); if (chrome_exe_path != user_exe_path && chrome_exe_path != machine_exe_path ) { LOG(ERROR) << L"Google Update cannot update Chrome installed in a " << L"non-standard location: " << chrome_exe_path.c_str() << L". The standard location is: " << user_exe_path.c_str() << L" or " << machine_exe_path.c_str() << L"."; return false; } return true; #endif } // Creates an instance of a COM Local Server class using either plain vanilla // CoCreateInstance, or using the Elevation moniker if running on Vista. // hwnd must refer to a foregound window in order to get the UAC prompt // showing up in the foreground if running on Vista. It can also be NULL if // background UAC prompts are desired. HRESULT CoCreateInstanceAsAdmin(REFCLSID class_id, REFIID interface_id, HWND hwnd, void** interface_ptr) { if (!interface_ptr) return E_POINTER; // For Vista we need to instantiate the COM server via the elevation // moniker. This ensures that the UAC dialog shows up. if (base::win::GetVersion() >= base::win::VERSION_VISTA) { wchar_t class_id_as_string[MAX_PATH] = {0}; StringFromGUID2(class_id, class_id_as_string, arraysize(class_id_as_string)); std::wstring elevation_moniker_name = StringPrintf(L"Elevation:Administrator!new:%ls", class_id_as_string); BIND_OPTS3 bind_opts; memset(&bind_opts, 0, sizeof(bind_opts)); bind_opts.cbStruct = sizeof(bind_opts); bind_opts.dwClassContext = CLSCTX_LOCAL_SERVER; bind_opts.hwnd = hwnd; return CoGetObject(elevation_moniker_name.c_str(), &bind_opts, interface_id, reinterpret_cast<void**>(interface_ptr)); } return CoCreateInstance(class_id, NULL, CLSCTX_LOCAL_SERVER, interface_id, reinterpret_cast<void**>(interface_ptr)); } } // namespace //////////////////////////////////////////////////////////////////////////////// // // The GoogleUpdateJobObserver COM class is responsible for receiving status // reports from google Update. It keeps track of the progress as Google Update // notifies us and ends the message loop we are spinning in once Google Update // reports that it is done. // //////////////////////////////////////////////////////////////////////////////// class GoogleUpdateJobObserver : public CComObjectRootEx<CComSingleThreadModel>, public IJobObserver { public: BEGIN_COM_MAP(GoogleUpdateJobObserver) COM_INTERFACE_ENTRY(IJobObserver) END_COM_MAP() GoogleUpdateJobObserver() : result_(UPGRADE_ERROR) { } virtual ~GoogleUpdateJobObserver() {} // Notifications from Google Update: STDMETHOD(OnShow)() { return S_OK; } STDMETHOD(OnCheckingForUpdate)() { result_ = UPGRADE_CHECK_STARTED; return S_OK; } STDMETHOD(OnUpdateAvailable)(const TCHAR* version_string) { result_ = UPGRADE_IS_AVAILABLE; new_version_ = version_string; return S_OK; } STDMETHOD(OnWaitingToDownload)() { return S_OK; } STDMETHOD(OnDownloading)(int time_remaining_ms, int pos) { return S_OK; } STDMETHOD(OnWaitingToInstall)() { return S_OK; } STDMETHOD(OnInstalling)() { result_ = UPGRADE_STARTED; return S_OK; } STDMETHOD(OnPause)() { return S_OK; } STDMETHOD(OnComplete)(CompletionCodes code, const TCHAR* text) { switch (code) { case COMPLETION_CODE_SUCCESS_CLOSE_UI: case COMPLETION_CODE_SUCCESS: { if (result_ == UPGRADE_STARTED) result_ = UPGRADE_SUCCESSFUL; else if (result_ == UPGRADE_CHECK_STARTED) result_ = UPGRADE_ALREADY_UP_TO_DATE; break; } default: { NOTREACHED(); result_ = UPGRADE_ERROR; break; } } event_sink_ = NULL; // We no longer need to spin the message loop that we started spinning in // InitiateGoogleUpdateCheck. MessageLoop::current()->Quit(); return S_OK; } STDMETHOD(SetEventSink)(IProgressWndEvents* event_sink) { event_sink_ = event_sink; return S_OK; } // Returns the results of the update operation. STDMETHOD(GetResult)(GoogleUpdateUpgradeResult* result) { // Intermediary steps should never be reported to the client. DCHECK(result_ != UPGRADE_STARTED && result_ != UPGRADE_CHECK_STARTED); *result = result_; return S_OK; } // Returns which version Google Update found on the server (if a more // recent version was found). Otherwise, this will be blank. STDMETHOD(GetVersionInfo)(std::wstring* version_string) { *version_string = new_version_; return S_OK; } private: // The status/result of the Google Update operation. GoogleUpdateUpgradeResult result_; // The version string Google Update found. std::wstring new_version_; // Allows us control the upgrade process to a small degree. After OnComplete // has been called, this object can not be used. ScopedComPtr<IProgressWndEvents> event_sink_; }; //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, public: GoogleUpdate::GoogleUpdate() : listener_(NULL) { } GoogleUpdate::~GoogleUpdate() { } //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, views::DialogDelegate implementation: void GoogleUpdate::CheckForUpdate(bool install_if_newer, Window* window) { // We need to shunt this request over to InitiateGoogleUpdateCheck and have // it run in the file thread. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod( this, &GoogleUpdate::InitiateGoogleUpdateCheck, install_if_newer, window, MessageLoop::current())); } //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, private: bool GoogleUpdate::InitiateGoogleUpdateCheck(bool install_if_newer, Window* window, MessageLoop* main_loop) { FilePath chrome_exe_path; if (!PathService::Get(base::DIR_EXE, &chrome_exe_path)) { NOTREACHED(); return false; } std::wstring chrome_exe = chrome_exe_path.value(); std::transform(chrome_exe.begin(), chrome_exe.end(), chrome_exe.begin(), tolower); if (!CanUpdateCurrentChrome(chrome_exe)) { main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, UPGRADE_ERROR, CANNOT_UPGRADE_CHROME_IN_THIS_DIRECTORY)); return false; } CComObject<GoogleUpdateJobObserver>* job_observer; HRESULT hr = CComObject<GoogleUpdateJobObserver>::CreateInstance(&job_observer); if (hr != S_OK) { return ReportFailure(hr, GOOGLE_UPDATE_JOB_SERVER_CREATION_FAILED, main_loop); } ScopedComPtr<IJobObserver> job_holder(job_observer); ScopedComPtr<IGoogleUpdate> on_demand; if (InstallUtil::IsPerUserInstall(chrome_exe.c_str())) { hr = on_demand.CreateInstance(CLSID_OnDemandUserAppsClass); } else { // The Update operation needs Admin privileges for writing // to %ProgramFiles%. On Vista we need to elevate before instantiating // the updater instance. if (!install_if_newer) { hr = on_demand.CreateInstance(CLSID_OnDemandMachineAppsClass); } else { HWND foreground_hwnd = NULL; if (window != NULL) { foreground_hwnd = window->GetNativeWindow(); } hr = CoCreateInstanceAsAdmin(CLSID_OnDemandMachineAppsClass, IID_IGoogleUpdate, foreground_hwnd, reinterpret_cast<void**>(on_demand.Receive())); } } if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_NOT_FOUND, main_loop); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!install_if_newer) hr = on_demand->CheckForUpdate(dist->GetAppGuid().c_str(), job_observer); else hr = on_demand->Update(dist->GetAppGuid().c_str(), job_observer); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR, main_loop); // We need to spin the message loop while Google Update is running so that it // can report back to us through GoogleUpdateJobObserver. This message loop // will terminate once Google Update sends us the completion status // (success/error). See OnComplete(). MessageLoop::current()->Run(); GoogleUpdateUpgradeResult results; hr = job_observer->GetResult(&results); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_GET_RESULT_CALL_FAILED, main_loop); if (results == UPGRADE_ERROR) return ReportFailure(hr, GOOGLE_UPDATE_ERROR_UPDATING, main_loop); hr = job_observer->GetVersionInfo(&version_available_); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_GET_VERSION_INFO_FAILED, main_loop); main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, results, GOOGLE_UPDATE_NO_ERROR)); job_holder = NULL; on_demand = NULL; return true; } void GoogleUpdate::ReportResults(GoogleUpdateUpgradeResult results, GoogleUpdateErrorCode error_code) { // If we get an error, then error code must not be blank, and vice versa. DCHECK(results == UPGRADE_ERROR ? error_code != GOOGLE_UPDATE_NO_ERROR : error_code == GOOGLE_UPDATE_NO_ERROR); if (listener_) listener_->OnReportResults(results, error_code, version_available_); } bool GoogleUpdate::ReportFailure(HRESULT hr, GoogleUpdateErrorCode error_code, MessageLoop* main_loop) { NOTREACHED() << "Communication with Google Update failed: " << hr << " error: " << error_code; main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, UPGRADE_ERROR, error_code)); return false; } <commit_msg>A build fix for our official bot. This just adds a pointer to BrowserDistribution as the second parameter for installer::GetChromeInstallPath() to fix the build breaks on the "Google Chrome Win" bot.<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/google/google_update.h" #include <atlbase.h> #include <atlcom.h> #include "base/file_path.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_comptr_win.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "base/win/windows_version.h" #include "chrome/browser/browser_thread.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/install_util.h" #include "views/window/window.h" #include "google_update_idl_i.c" using views::Window; namespace { // Check if the currently running instance can be updated by Google Update. // Returns true only if the instance running is a Google Chrome // distribution installed in a standard location. bool CanUpdateCurrentChrome(const std::wstring& chrome_exe_path) { #if !defined(GOOGLE_CHROME_BUILD) return false; #else // TODO(tommi): Check if using the default distribution is always the right // thing to do. BrowserDistribution* dist = BrowserDistribution::GetDistribution() std::wstring user_exe_path = installer::GetChromeInstallPath(false, dist); std::wstring machine_exe_path = installer::GetChromeInstallPath(true, dist); std::transform(user_exe_path.begin(), user_exe_path.end(), user_exe_path.begin(), tolower); std::transform(machine_exe_path.begin(), machine_exe_path.end(), machine_exe_path.begin(), tolower); if (chrome_exe_path != user_exe_path && chrome_exe_path != machine_exe_path ) { LOG(ERROR) << L"Google Update cannot update Chrome installed in a " << L"non-standard location: " << chrome_exe_path.c_str() << L". The standard location is: " << user_exe_path.c_str() << L" or " << machine_exe_path.c_str() << L"."; return false; } return true; #endif } // Creates an instance of a COM Local Server class using either plain vanilla // CoCreateInstance, or using the Elevation moniker if running on Vista. // hwnd must refer to a foregound window in order to get the UAC prompt // showing up in the foreground if running on Vista. It can also be NULL if // background UAC prompts are desired. HRESULT CoCreateInstanceAsAdmin(REFCLSID class_id, REFIID interface_id, HWND hwnd, void** interface_ptr) { if (!interface_ptr) return E_POINTER; // For Vista we need to instantiate the COM server via the elevation // moniker. This ensures that the UAC dialog shows up. if (base::win::GetVersion() >= base::win::VERSION_VISTA) { wchar_t class_id_as_string[MAX_PATH] = {0}; StringFromGUID2(class_id, class_id_as_string, arraysize(class_id_as_string)); std::wstring elevation_moniker_name = StringPrintf(L"Elevation:Administrator!new:%ls", class_id_as_string); BIND_OPTS3 bind_opts; memset(&bind_opts, 0, sizeof(bind_opts)); bind_opts.cbStruct = sizeof(bind_opts); bind_opts.dwClassContext = CLSCTX_LOCAL_SERVER; bind_opts.hwnd = hwnd; return CoGetObject(elevation_moniker_name.c_str(), &bind_opts, interface_id, reinterpret_cast<void**>(interface_ptr)); } return CoCreateInstance(class_id, NULL, CLSCTX_LOCAL_SERVER, interface_id, reinterpret_cast<void**>(interface_ptr)); } } // namespace //////////////////////////////////////////////////////////////////////////////// // // The GoogleUpdateJobObserver COM class is responsible for receiving status // reports from google Update. It keeps track of the progress as Google Update // notifies us and ends the message loop we are spinning in once Google Update // reports that it is done. // //////////////////////////////////////////////////////////////////////////////// class GoogleUpdateJobObserver : public CComObjectRootEx<CComSingleThreadModel>, public IJobObserver { public: BEGIN_COM_MAP(GoogleUpdateJobObserver) COM_INTERFACE_ENTRY(IJobObserver) END_COM_MAP() GoogleUpdateJobObserver() : result_(UPGRADE_ERROR) { } virtual ~GoogleUpdateJobObserver() {} // Notifications from Google Update: STDMETHOD(OnShow)() { return S_OK; } STDMETHOD(OnCheckingForUpdate)() { result_ = UPGRADE_CHECK_STARTED; return S_OK; } STDMETHOD(OnUpdateAvailable)(const TCHAR* version_string) { result_ = UPGRADE_IS_AVAILABLE; new_version_ = version_string; return S_OK; } STDMETHOD(OnWaitingToDownload)() { return S_OK; } STDMETHOD(OnDownloading)(int time_remaining_ms, int pos) { return S_OK; } STDMETHOD(OnWaitingToInstall)() { return S_OK; } STDMETHOD(OnInstalling)() { result_ = UPGRADE_STARTED; return S_OK; } STDMETHOD(OnPause)() { return S_OK; } STDMETHOD(OnComplete)(CompletionCodes code, const TCHAR* text) { switch (code) { case COMPLETION_CODE_SUCCESS_CLOSE_UI: case COMPLETION_CODE_SUCCESS: { if (result_ == UPGRADE_STARTED) result_ = UPGRADE_SUCCESSFUL; else if (result_ == UPGRADE_CHECK_STARTED) result_ = UPGRADE_ALREADY_UP_TO_DATE; break; } default: { NOTREACHED(); result_ = UPGRADE_ERROR; break; } } event_sink_ = NULL; // We no longer need to spin the message loop that we started spinning in // InitiateGoogleUpdateCheck. MessageLoop::current()->Quit(); return S_OK; } STDMETHOD(SetEventSink)(IProgressWndEvents* event_sink) { event_sink_ = event_sink; return S_OK; } // Returns the results of the update operation. STDMETHOD(GetResult)(GoogleUpdateUpgradeResult* result) { // Intermediary steps should never be reported to the client. DCHECK(result_ != UPGRADE_STARTED && result_ != UPGRADE_CHECK_STARTED); *result = result_; return S_OK; } // Returns which version Google Update found on the server (if a more // recent version was found). Otherwise, this will be blank. STDMETHOD(GetVersionInfo)(std::wstring* version_string) { *version_string = new_version_; return S_OK; } private: // The status/result of the Google Update operation. GoogleUpdateUpgradeResult result_; // The version string Google Update found. std::wstring new_version_; // Allows us control the upgrade process to a small degree. After OnComplete // has been called, this object can not be used. ScopedComPtr<IProgressWndEvents> event_sink_; }; //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, public: GoogleUpdate::GoogleUpdate() : listener_(NULL) { } GoogleUpdate::~GoogleUpdate() { } //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, views::DialogDelegate implementation: void GoogleUpdate::CheckForUpdate(bool install_if_newer, Window* window) { // We need to shunt this request over to InitiateGoogleUpdateCheck and have // it run in the file thread. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod( this, &GoogleUpdate::InitiateGoogleUpdateCheck, install_if_newer, window, MessageLoop::current())); } //////////////////////////////////////////////////////////////////////////////// // GoogleUpdate, private: bool GoogleUpdate::InitiateGoogleUpdateCheck(bool install_if_newer, Window* window, MessageLoop* main_loop) { FilePath chrome_exe_path; if (!PathService::Get(base::DIR_EXE, &chrome_exe_path)) { NOTREACHED(); return false; } std::wstring chrome_exe = chrome_exe_path.value(); std::transform(chrome_exe.begin(), chrome_exe.end(), chrome_exe.begin(), tolower); if (!CanUpdateCurrentChrome(chrome_exe)) { main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, UPGRADE_ERROR, CANNOT_UPGRADE_CHROME_IN_THIS_DIRECTORY)); return false; } CComObject<GoogleUpdateJobObserver>* job_observer; HRESULT hr = CComObject<GoogleUpdateJobObserver>::CreateInstance(&job_observer); if (hr != S_OK) { return ReportFailure(hr, GOOGLE_UPDATE_JOB_SERVER_CREATION_FAILED, main_loop); } ScopedComPtr<IJobObserver> job_holder(job_observer); ScopedComPtr<IGoogleUpdate> on_demand; if (InstallUtil::IsPerUserInstall(chrome_exe.c_str())) { hr = on_demand.CreateInstance(CLSID_OnDemandUserAppsClass); } else { // The Update operation needs Admin privileges for writing // to %ProgramFiles%. On Vista we need to elevate before instantiating // the updater instance. if (!install_if_newer) { hr = on_demand.CreateInstance(CLSID_OnDemandMachineAppsClass); } else { HWND foreground_hwnd = NULL; if (window != NULL) { foreground_hwnd = window->GetNativeWindow(); } hr = CoCreateInstanceAsAdmin(CLSID_OnDemandMachineAppsClass, IID_IGoogleUpdate, foreground_hwnd, reinterpret_cast<void**>(on_demand.Receive())); } } if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_NOT_FOUND, main_loop); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!install_if_newer) hr = on_demand->CheckForUpdate(dist->GetAppGuid().c_str(), job_observer); else hr = on_demand->Update(dist->GetAppGuid().c_str(), job_observer); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR, main_loop); // We need to spin the message loop while Google Update is running so that it // can report back to us through GoogleUpdateJobObserver. This message loop // will terminate once Google Update sends us the completion status // (success/error). See OnComplete(). MessageLoop::current()->Run(); GoogleUpdateUpgradeResult results; hr = job_observer->GetResult(&results); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_GET_RESULT_CALL_FAILED, main_loop); if (results == UPGRADE_ERROR) return ReportFailure(hr, GOOGLE_UPDATE_ERROR_UPDATING, main_loop); hr = job_observer->GetVersionInfo(&version_available_); if (hr != S_OK) return ReportFailure(hr, GOOGLE_UPDATE_GET_VERSION_INFO_FAILED, main_loop); main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, results, GOOGLE_UPDATE_NO_ERROR)); job_holder = NULL; on_demand = NULL; return true; } void GoogleUpdate::ReportResults(GoogleUpdateUpgradeResult results, GoogleUpdateErrorCode error_code) { // If we get an error, then error code must not be blank, and vice versa. DCHECK(results == UPGRADE_ERROR ? error_code != GOOGLE_UPDATE_NO_ERROR : error_code == GOOGLE_UPDATE_NO_ERROR); if (listener_) listener_->OnReportResults(results, error_code, version_available_); } bool GoogleUpdate::ReportFailure(HRESULT hr, GoogleUpdateErrorCode error_code, MessageLoop* main_loop) { NOTREACHED() << "Communication with Google Update failed: " << hr << " error: " << error_code; main_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &GoogleUpdate::ReportResults, UPGRADE_ERROR, error_code)); return false; } <|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/browser_titlebar.h" #include <gtk/gtk.h> #include "app/l10n_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/browser.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/tabs/tab_strip_gtk.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" namespace { // The space above the titlebars. const int kTitlebarHeight = 14; // A linux specific menu item for toggling window decorations. const int kShowWindowDecorationsCommand = 200; } BrowserTitlebar::BrowserTitlebar(BrowserWindowGtk* browser_window, GtkWindow* window) : browser_window_(browser_window), window_(window) { Init(); } void BrowserTitlebar::Init() { titlebar_background_.reset(new NineBox( browser_window_->browser()->profile()->GetThemeProvider(), 0, IDR_THEME_FRAME, 0, 0, 0, 0, 0, 0, 0)); titlebar_background_otr_.reset(new NineBox( browser_window_->browser()->profile()->GetThemeProvider(), 0, IDR_THEME_FRAME_INCOGNITO, 0, 0, 0, 0, 0, 0, 0)); // The widget hierarchy is shown below. In addition to the diagram, there is // a gtk event box surrounding the titlebar_hbox which catches mouse events // in the titlebar. // // +- HBox (titlebar_hbox) -----------------------------------------------+ // |+- Alignment (titlebar_alignment_)-++- VBox (titlebar_buttons_box_) -+| // || ||+- HBox -----------------------+|| // || |||+- button -++- button -+ ||| // ||+- TabStripGtk ------------------+|||| minimize || restore | ... ||| // ||| tab tab tab tabclose +|||+----------++----------+ ||| // ||+--------------------------------+||+------------------------------+|| // |+----------------------------------++--------------------------------+| // +----------------------------------------------------------------------+ container_ = gtk_event_box_new(); GtkWidget* titlebar_hbox = gtk_hbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(container_), titlebar_hbox); g_signal_connect(G_OBJECT(container_), "button-press-event", G_CALLBACK(OnMouseButtonPress), this); g_signal_connect(G_OBJECT(titlebar_hbox), "expose-event", G_CALLBACK(OnExpose), this); g_signal_connect(window_, "window-state-event", G_CALLBACK(OnWindowStateChanged), this); // We use an alignment to control the titlebar height. titlebar_alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_box_pack_start(GTK_BOX(titlebar_hbox), titlebar_alignment_, TRUE, TRUE, 0); // Put the tab strip in the titlebar. gtk_container_add(GTK_CONTAINER(titlebar_alignment_), browser_window_->tabstrip()->widget()); // We put the min/max/restore/close buttons in a vbox so they are top aligned // and don't vertically stretch. titlebar_buttons_box_ = gtk_vbox_new(FALSE, 0); GtkWidget* buttons_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), buttons_hbox, FALSE, FALSE, 0); close_button_.reset(BuildTitlebarButton(IDR_CLOSE, IDR_CLOSE_P, IDR_CLOSE_H, buttons_hbox, IDS_XPFRAME_CLOSE_TOOLTIP)); restore_button_.reset(BuildTitlebarButton(IDR_RESTORE, IDR_RESTORE_P, IDR_RESTORE_H, buttons_hbox, IDS_XPFRAME_RESTORE_TOOLTIP)); maximize_button_.reset(BuildTitlebarButton(IDR_MAXIMIZE, IDR_MAXIMIZE_P, IDR_MAXIMIZE_H, buttons_hbox, IDS_XPFRAME_MAXIMIZE_TOOLTIP)); minimize_button_.reset(BuildTitlebarButton(IDR_MINIMIZE, IDR_MINIMIZE_P, IDR_MINIMIZE_H, buttons_hbox, IDS_XPFRAME_MINIMIZE_TOOLTIP)); gtk_box_pack_end(GTK_BOX(titlebar_hbox), titlebar_buttons_box_, FALSE, FALSE, 0); gtk_widget_show_all(container_); } CustomDrawButton* BrowserTitlebar::BuildTitlebarButton(int image, int image_pressed, int image_hot, GtkWidget* box, int tooltip) { CustomDrawButton* button = new CustomDrawButton(image, image_pressed, image_hot, 0); g_signal_connect(button->widget(), "clicked", G_CALLBACK(OnButtonClicked), this); std::string localized_tooltip = l10n_util::GetStringUTF8(tooltip); gtk_widget_set_tooltip_text(button->widget(), localized_tooltip.c_str()); gtk_box_pack_end(GTK_BOX(box), button->widget(), FALSE, FALSE, 0); return button; } void BrowserTitlebar::UpdateCustomFrame(bool use_custom_frame) { if (use_custom_frame) { gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_), kTitlebarHeight, 0, 0, 0); gtk_widget_show_all(titlebar_buttons_box_); } else { gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_), 0, 0, 0, 0); gtk_widget_hide(titlebar_buttons_box_); } } gboolean BrowserTitlebar::OnExpose(GtkWidget* widget, GdkEventExpose* e, BrowserTitlebar* titlebar) { cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window)); cairo_rectangle(cr, e->area.x, e->area.y, e->area.width, e->area.height); cairo_clip(cr); Profile* profile = titlebar->browser_window_->browser()->profile(); NineBox* image = profile->IsOffTheRecord() ? titlebar->titlebar_background_otr_.get() : titlebar->titlebar_background_.get(); image->RenderTopCenterStrip(cr, e->area.x, 0, e->area.width); cairo_destroy(cr); return FALSE; // Allow subwidgets to paint. } gboolean BrowserTitlebar::OnMouseButtonPress(GtkWidget* widget, GdkEventButton* event, BrowserTitlebar* titlebar) { if (1 == event->button) { if (GDK_BUTTON_PRESS == event->type) { gtk_window_begin_move_drag(GTK_WINDOW(titlebar->window_), event->button, event->x_root, event->y_root, event->time); return TRUE; } else if (GDK_2BUTTON_PRESS == event->type) { // Maximize/restore on double click. if (titlebar->browser_window_->IsMaximized()) { gtk_window_unmaximize(titlebar->window_); } else { gtk_window_maximize(titlebar->window_); } return TRUE; } } else if (3 == event->button) { titlebar->ShowContextMenu(); return TRUE; } return FALSE; // Continue to propagate the event. } gboolean BrowserTitlebar::OnWindowStateChanged(GtkWindow* window, GdkEventWindowState* event, BrowserTitlebar* titlebar) { // Update the maximize/restore button. if (titlebar->browser_window_->IsMaximized()) { gtk_widget_hide(titlebar->maximize_button_->widget()); gtk_widget_show(titlebar->restore_button_->widget()); } else { gtk_widget_hide(titlebar->restore_button_->widget()); gtk_widget_show(titlebar->maximize_button_->widget()); } return FALSE; } void BrowserTitlebar::OnButtonClicked(GtkWidget* button, BrowserTitlebar* titlebar) { if (titlebar->close_button_->widget() == button) { titlebar->browser_window_->Close(); } else if (titlebar->restore_button_->widget() == button) { gtk_window_unmaximize(titlebar->window_); } else if (titlebar->maximize_button_->widget() == button) { gtk_window_maximize(titlebar->window_); } else if (titlebar->minimize_button_->widget() == button) { gtk_window_iconify(titlebar->window_); } } void BrowserTitlebar::ShowContextMenu() { if (!context_menu_.get()) { context_menu_.reset(new MenuGtk(this, false)); context_menu_->AppendMenuItemWithLabel( IDC_NEW_TAB, l10n_util::GetStringUTF8(IDS_TAB_CXMENU_NEWTAB)); context_menu_->AppendMenuItemWithLabel( IDC_RESTORE_TAB, l10n_util::GetStringUTF8(IDS_RESTORE_TAB)); context_menu_->AppendSeparator(); context_menu_->AppendMenuItemWithLabel( IDC_TASK_MANAGER, l10n_util::GetStringUTF8(IDS_TASK_MANAGER)); context_menu_->AppendSeparator(); context_menu_->AppendCheckMenuItemWithLabel( kShowWindowDecorationsCommand, l10n_util::GetStringUTF8(IDS_SHOW_WINDOW_DECORATIONS)); } context_menu_->PopupAsContext(gtk_get_current_event_time()); } bool BrowserTitlebar::IsCommandEnabled(int command_id) const { switch (command_id) { case IDC_NEW_TAB: case kShowWindowDecorationsCommand: return true; case IDC_RESTORE_TAB: return browser_window_->browser()->CanRestoreTab(); case IDC_TASK_MANAGER: // TODO(tc): Task manager needs to be implemented. return false; default: NOTREACHED(); } return false; } bool BrowserTitlebar::IsItemChecked(int command_id) const { DCHECK(command_id == kShowWindowDecorationsCommand); PrefService* prefs = browser_window_->browser()->profile()->GetPrefs(); return !prefs->GetBoolean(prefs::kUseCustomChromeFrame); } void BrowserTitlebar::ExecuteCommand(int command_id) { switch (command_id) { case IDC_NEW_TAB: case IDC_RESTORE_TAB: case IDC_TASK_MANAGER: browser_window_->browser()->ExecuteCommand(command_id); break; case kShowWindowDecorationsCommand: { PrefService* prefs = browser_window_->browser()->profile()->GetPrefs(); prefs->SetBoolean(prefs::kUseCustomChromeFrame, !prefs->GetBoolean(prefs::kUseCustomChromeFrame)); break; } default: NOTREACHED(); } } <commit_msg>Fix a bug where both restore and maximize buttons were showing after toggling window manager decorations on/off.<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/browser_titlebar.h" #include <gtk/gtk.h> #include "app/l10n_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/browser.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/tabs/tab_strip_gtk.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" namespace { // The space above the titlebars. const int kTitlebarHeight = 14; // A linux specific menu item for toggling window decorations. const int kShowWindowDecorationsCommand = 200; } BrowserTitlebar::BrowserTitlebar(BrowserWindowGtk* browser_window, GtkWindow* window) : browser_window_(browser_window), window_(window) { Init(); } void BrowserTitlebar::Init() { titlebar_background_.reset(new NineBox( browser_window_->browser()->profile()->GetThemeProvider(), 0, IDR_THEME_FRAME, 0, 0, 0, 0, 0, 0, 0)); titlebar_background_otr_.reset(new NineBox( browser_window_->browser()->profile()->GetThemeProvider(), 0, IDR_THEME_FRAME_INCOGNITO, 0, 0, 0, 0, 0, 0, 0)); // The widget hierarchy is shown below. In addition to the diagram, there is // a gtk event box surrounding the titlebar_hbox which catches mouse events // in the titlebar. // // +- HBox (titlebar_hbox) -----------------------------------------------+ // |+- Alignment (titlebar_alignment_)-++- VBox (titlebar_buttons_box_) -+| // || ||+- HBox -----------------------+|| // || |||+- button -++- button -+ ||| // ||+- TabStripGtk ------------------+|||| minimize || restore | ... ||| // ||| tab tab tab tabclose +|||+----------++----------+ ||| // ||+--------------------------------+||+------------------------------+|| // |+----------------------------------++--------------------------------+| // +----------------------------------------------------------------------+ container_ = gtk_event_box_new(); GtkWidget* titlebar_hbox = gtk_hbox_new(FALSE, 0); gtk_container_add(GTK_CONTAINER(container_), titlebar_hbox); g_signal_connect(G_OBJECT(container_), "button-press-event", G_CALLBACK(OnMouseButtonPress), this); g_signal_connect(G_OBJECT(titlebar_hbox), "expose-event", G_CALLBACK(OnExpose), this); g_signal_connect(window_, "window-state-event", G_CALLBACK(OnWindowStateChanged), this); // We use an alignment to control the titlebar height. titlebar_alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_box_pack_start(GTK_BOX(titlebar_hbox), titlebar_alignment_, TRUE, TRUE, 0); // Put the tab strip in the titlebar. gtk_container_add(GTK_CONTAINER(titlebar_alignment_), browser_window_->tabstrip()->widget()); // We put the min/max/restore/close buttons in a vbox so they are top aligned // and don't vertically stretch. titlebar_buttons_box_ = gtk_vbox_new(FALSE, 0); GtkWidget* buttons_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(titlebar_buttons_box_), buttons_hbox, FALSE, FALSE, 0); close_button_.reset(BuildTitlebarButton(IDR_CLOSE, IDR_CLOSE_P, IDR_CLOSE_H, buttons_hbox, IDS_XPFRAME_CLOSE_TOOLTIP)); restore_button_.reset(BuildTitlebarButton(IDR_RESTORE, IDR_RESTORE_P, IDR_RESTORE_H, buttons_hbox, IDS_XPFRAME_RESTORE_TOOLTIP)); maximize_button_.reset(BuildTitlebarButton(IDR_MAXIMIZE, IDR_MAXIMIZE_P, IDR_MAXIMIZE_H, buttons_hbox, IDS_XPFRAME_MAXIMIZE_TOOLTIP)); minimize_button_.reset(BuildTitlebarButton(IDR_MINIMIZE, IDR_MINIMIZE_P, IDR_MINIMIZE_H, buttons_hbox, IDS_XPFRAME_MINIMIZE_TOOLTIP)); gtk_box_pack_end(GTK_BOX(titlebar_hbox), titlebar_buttons_box_, FALSE, FALSE, 0); gtk_widget_show_all(container_); } CustomDrawButton* BrowserTitlebar::BuildTitlebarButton(int image, int image_pressed, int image_hot, GtkWidget* box, int tooltip) { CustomDrawButton* button = new CustomDrawButton(image, image_pressed, image_hot, 0); g_signal_connect(button->widget(), "clicked", G_CALLBACK(OnButtonClicked), this); std::string localized_tooltip = l10n_util::GetStringUTF8(tooltip); gtk_widget_set_tooltip_text(button->widget(), localized_tooltip.c_str()); gtk_box_pack_end(GTK_BOX(box), button->widget(), FALSE, FALSE, 0); return button; } void BrowserTitlebar::UpdateCustomFrame(bool use_custom_frame) { if (use_custom_frame) { gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_), kTitlebarHeight, 0, 0, 0); gtk_widget_show(titlebar_buttons_box_); } else { gtk_alignment_set_padding(GTK_ALIGNMENT(titlebar_alignment_), 0, 0, 0, 0); gtk_widget_hide(titlebar_buttons_box_); } } gboolean BrowserTitlebar::OnExpose(GtkWidget* widget, GdkEventExpose* e, BrowserTitlebar* titlebar) { cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window)); cairo_rectangle(cr, e->area.x, e->area.y, e->area.width, e->area.height); cairo_clip(cr); Profile* profile = titlebar->browser_window_->browser()->profile(); NineBox* image = profile->IsOffTheRecord() ? titlebar->titlebar_background_otr_.get() : titlebar->titlebar_background_.get(); image->RenderTopCenterStrip(cr, e->area.x, 0, e->area.width); cairo_destroy(cr); return FALSE; // Allow subwidgets to paint. } gboolean BrowserTitlebar::OnMouseButtonPress(GtkWidget* widget, GdkEventButton* event, BrowserTitlebar* titlebar) { if (1 == event->button) { if (GDK_BUTTON_PRESS == event->type) { gtk_window_begin_move_drag(GTK_WINDOW(titlebar->window_), event->button, event->x_root, event->y_root, event->time); return TRUE; } else if (GDK_2BUTTON_PRESS == event->type) { // Maximize/restore on double click. if (titlebar->browser_window_->IsMaximized()) { gtk_window_unmaximize(titlebar->window_); } else { gtk_window_maximize(titlebar->window_); } return TRUE; } } else if (3 == event->button) { titlebar->ShowContextMenu(); return TRUE; } return FALSE; // Continue to propagate the event. } gboolean BrowserTitlebar::OnWindowStateChanged(GtkWindow* window, GdkEventWindowState* event, BrowserTitlebar* titlebar) { // Update the maximize/restore button. if (titlebar->browser_window_->IsMaximized()) { gtk_widget_hide(titlebar->maximize_button_->widget()); gtk_widget_show(titlebar->restore_button_->widget()); } else { gtk_widget_hide(titlebar->restore_button_->widget()); gtk_widget_show(titlebar->maximize_button_->widget()); } return FALSE; } void BrowserTitlebar::OnButtonClicked(GtkWidget* button, BrowserTitlebar* titlebar) { if (titlebar->close_button_->widget() == button) { titlebar->browser_window_->Close(); } else if (titlebar->restore_button_->widget() == button) { gtk_window_unmaximize(titlebar->window_); } else if (titlebar->maximize_button_->widget() == button) { gtk_window_maximize(titlebar->window_); } else if (titlebar->minimize_button_->widget() == button) { gtk_window_iconify(titlebar->window_); } } void BrowserTitlebar::ShowContextMenu() { if (!context_menu_.get()) { context_menu_.reset(new MenuGtk(this, false)); context_menu_->AppendMenuItemWithLabel( IDC_NEW_TAB, l10n_util::GetStringUTF8(IDS_TAB_CXMENU_NEWTAB)); context_menu_->AppendMenuItemWithLabel( IDC_RESTORE_TAB, l10n_util::GetStringUTF8(IDS_RESTORE_TAB)); context_menu_->AppendSeparator(); context_menu_->AppendMenuItemWithLabel( IDC_TASK_MANAGER, l10n_util::GetStringUTF8(IDS_TASK_MANAGER)); context_menu_->AppendSeparator(); context_menu_->AppendCheckMenuItemWithLabel( kShowWindowDecorationsCommand, l10n_util::GetStringUTF8(IDS_SHOW_WINDOW_DECORATIONS)); } context_menu_->PopupAsContext(gtk_get_current_event_time()); } bool BrowserTitlebar::IsCommandEnabled(int command_id) const { switch (command_id) { case IDC_NEW_TAB: case kShowWindowDecorationsCommand: return true; case IDC_RESTORE_TAB: return browser_window_->browser()->CanRestoreTab(); case IDC_TASK_MANAGER: // TODO(tc): Task manager needs to be implemented. return false; default: NOTREACHED(); } return false; } bool BrowserTitlebar::IsItemChecked(int command_id) const { DCHECK(command_id == kShowWindowDecorationsCommand); PrefService* prefs = browser_window_->browser()->profile()->GetPrefs(); return !prefs->GetBoolean(prefs::kUseCustomChromeFrame); } void BrowserTitlebar::ExecuteCommand(int command_id) { switch (command_id) { case IDC_NEW_TAB: case IDC_RESTORE_TAB: case IDC_TASK_MANAGER: browser_window_->browser()->ExecuteCommand(command_id); break; case kShowWindowDecorationsCommand: { PrefService* prefs = browser_window_->browser()->profile()->GetPrefs(); prefs->SetBoolean(prefs::kUseCustomChromeFrame, !prefs->GetBoolean(prefs::kUseCustomChromeFrame)); break; } default: NOTREACHED(); } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH #define DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH #include <dune/geometry/genericgeometry/referenceelements.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/dgfparser/dgfparser.hh> #include <dune/stuff/common/filesystem.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/ranges.hh> namespace Dune { namespace Stuff { namespace Grid { struct ElementVisualization { //! Parameter for mapper class template<int dim> struct P0Layout { bool contains (const Dune::GeometryType& gt) { if (gt.dim()==dim) return true; return false; } }; // demonstrate attaching data to elements template<class Grid, class F> static void elementdata (const Grid& grid, const F& f) { // get grid view on leaf part const auto gridView = grid.leafGridView(); // make a mapper for codim 0 entities in the leaf grid Dune::LeafMultipleCodimMultipleGeomTypeMapper<Grid,P0Layout> mapper(grid); std::vector<double> values(mapper.size()); for (const auto& entity : DSC::entityRange(gridView)) { values[mapper.map(entity)] = f(entity); } Dune::VTKWriter<typename Grid::LeafGridView> vtkwriter(gridView); vtkwriter.addCellData(values,"data"); const std::string piecefilesFolderName = "piecefiles"; const std::string piecefilesPath = f.dir() + "/" + piecefilesFolderName + "/"; DSC::testCreateDirectory( piecefilesPath ); vtkwriter.pwrite( f.filename(), f.dir(), piecefilesFolderName, Dune::VTK::appendedraw); } class FunctorBase { public: FunctorBase ( const std::string fname, const std::string dname) : filename_(fname) , dir_(dname) {} const std::string filename() const { return filename_; } const std::string dir() const { return dir_; } protected: const std::string filename_; const std::string dir_; }; class VolumeFunctor : public FunctorBase { public: VolumeFunctor ( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& ent ) const { return ent.geometry().volume(); } }; class ProcessIdFunctor : public FunctorBase { public: ProcessIdFunctor ( const std::string fname, const std::string dname ) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& /*ent*/ ) const { return Dune::MPIHelper::getCollectiveCommunication().rank(); } }; template < class GridType > class BoundaryFunctor : public FunctorBase { const GridType& grid_; public: BoundaryFunctor ( const GridType& grid, const std::string fname, const std::string dname) : FunctorBase(fname, dname) , grid_(grid) {} template <class Entity> double operator() ( const Entity& entity ) const { double ret( 0.0 ); int numberOfBoundarySegments( 0 ); bool isOnBoundary = false; const auto leafview = grid_.leafGridView(); for ( const auto& intersection : DSC::intersectionRange(leafview, entity) ) { if ( !intersection.neighbor() && intersection.boundary() ) { isOnBoundary = true; numberOfBoundarySegments += 1; ret += double( intersection.boundaryId() ); } } if ( isOnBoundary ) { ret /= double( numberOfBoundarySegments ); } return ret; } }; class AreaMarker : public FunctorBase { public: AreaMarker( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& entity ) const { typedef typename Entity::Geometry EntityGeometryType; typedef Dune::FieldVector< typename EntityGeometryType::ctype, EntityGeometryType::coorddimension> DomainType; const EntityGeometryType& geometry = entity.geometry(); DomainType baryCenter( 0.0 ); for ( decltype(geometry.corners()) corner = 0; corner < geometry.corners(); ++corner ) { baryCenter += geometry.corner( corner ); } baryCenter /= geometry.corners(); double ret( 0.0 ); if ( !( ( baryCenter[0] < 0.0 ) || ( baryCenter[0] > 1.0 ) ) ) { // only in unit square if ( !( ( baryCenter[1] < 0.0 ) || ( baryCenter[1] > 1.0 ) ) ) { ret = 1.0; } } return ret; } }; class GeometryFunctor : public FunctorBase { public: GeometryFunctor ( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& ent ) const { const typename Entity::Geometry& geo = ent.geometry(); double vol = geo.volume(); if ( vol < 0 ) { std::cout << std::setiosflags( std::ios::fixed ) << std::setprecision( 6 ) << std::setw( 8 ); //std::cout.showpoint(); for ( decltype(geo.corners()) i = 0; i < geo.corners(); ++i ) { std::cout << geo.corner( i ) << "\t\t" ; } std::cout << std::endl; } return vol; } }; //! supply functor template<class Grid> static void all( const Grid& grid, const std::string outputDir = "visualisation") { // make function objects BoundaryFunctor<Grid> boundaryFunctor(grid, "boundaryFunctor", outputDir); AreaMarker areaMarker("areaMarker", outputDir); GeometryFunctor geometryFunctor("geometryFunctor", outputDir); ProcessIdFunctor processIdFunctor("ProcessIdFunctor", outputDir); VolumeFunctor volumeFunctor("volumeFunctor", outputDir); // call the visualization functions elementdata( grid, boundaryFunctor ); elementdata( grid, areaMarker ); elementdata( grid, geometryFunctor ); elementdata( grid, processIdFunctor ); elementdata( grid, volumeFunctor ); } }; } //namespace Stuff } //namespace Grid } //namespace Dune #endif // DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH <commit_msg>[grid.output.entity_visualization] use valueRange, refs #10<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH #define DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH #include <dune/geometry/genericgeometry/referenceelements.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/dgfparser/dgfparser.hh> #include <dune/stuff/common/filesystem.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/ranges.hh> namespace Dune { namespace Stuff { namespace Grid { struct ElementVisualization { //! Parameter for mapper class template<int dim> struct P0Layout { bool contains (const Dune::GeometryType& gt) { if (gt.dim()==dim) return true; return false; } }; // demonstrate attaching data to elements template<class Grid, class F> static void elementdata (const Grid& grid, const F& f) { // get grid view on leaf part const auto gridView = grid.leafGridView(); // make a mapper for codim 0 entities in the leaf grid Dune::LeafMultipleCodimMultipleGeomTypeMapper<Grid,P0Layout> mapper(grid); std::vector<double> values(mapper.size()); for (const auto& entity : DSC::entityRange(gridView)) { values[mapper.map(entity)] = f(entity); } Dune::VTKWriter<typename Grid::LeafGridView> vtkwriter(gridView); vtkwriter.addCellData(values,"data"); const std::string piecefilesFolderName = "piecefiles"; const std::string piecefilesPath = f.dir() + "/" + piecefilesFolderName + "/"; DSC::testCreateDirectory( piecefilesPath ); vtkwriter.pwrite( f.filename(), f.dir(), piecefilesFolderName, Dune::VTK::appendedraw); } class FunctorBase { public: FunctorBase ( const std::string fname, const std::string dname) : filename_(fname) , dir_(dname) {} const std::string filename() const { return filename_; } const std::string dir() const { return dir_; } protected: const std::string filename_; const std::string dir_; }; class VolumeFunctor : public FunctorBase { public: VolumeFunctor ( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& ent ) const { return ent.geometry().volume(); } }; class ProcessIdFunctor : public FunctorBase { public: ProcessIdFunctor ( const std::string fname, const std::string dname ) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& /*ent*/ ) const { return Dune::MPIHelper::getCollectiveCommunication().rank(); } }; template < class GridType > class BoundaryFunctor : public FunctorBase { const GridType& grid_; public: BoundaryFunctor ( const GridType& grid, const std::string fname, const std::string dname) : FunctorBase(fname, dname) , grid_(grid) {} template <class Entity> double operator() ( const Entity& entity ) const { double ret( 0.0 ); int numberOfBoundarySegments( 0 ); bool isOnBoundary = false; const auto leafview = grid_.leafGridView(); for ( const auto& intersection : DSC::intersectionRange(leafview, entity) ) { if ( !intersection.neighbor() && intersection.boundary() ) { isOnBoundary = true; numberOfBoundarySegments += 1; ret += double( intersection.boundaryId() ); } } if ( isOnBoundary ) { ret /= double( numberOfBoundarySegments ); } return ret; } }; class AreaMarker : public FunctorBase { public: AreaMarker( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& entity ) const { typedef typename Entity::Geometry EntityGeometryType; typedef Dune::FieldVector< typename EntityGeometryType::ctype, EntityGeometryType::coorddimension> DomainType; const EntityGeometryType& geometry = entity.geometry(); DomainType baryCenter( 0.0 ); for (auto corner : DSC::valueRange(geometry.corners())) { baryCenter += geometry.corner( corner ); } baryCenter /= geometry.corners(); double ret( 0.0 ); if ( !( ( baryCenter[0] < 0.0 ) || ( baryCenter[0] > 1.0 ) ) ) { // only in unit square if ( !( ( baryCenter[1] < 0.0 ) || ( baryCenter[1] > 1.0 ) ) ) { ret = 1.0; } } return ret; } }; class GeometryFunctor : public FunctorBase { public: GeometryFunctor ( const std::string fname, const std::string dname) : FunctorBase(fname, dname) {} template <class Entity> double operator() ( const Entity& ent ) const { const typename Entity::Geometry& geo = ent.geometry(); double vol = geo.volume(); if ( vol < 0 ) { std::cout << std::setiosflags( std::ios::fixed ) << std::setprecision( 6 ) << std::setw( 8 ); //std::cout.showpoint(); for (auto i : DSC::valueRange(geo.corners())) { std::cout << geo.corner( i ) << "\t\t" ; } std::cout << std::endl; } return vol; } }; //! supply functor template<class Grid> static void all( const Grid& grid, const std::string outputDir = "visualisation") { // make function objects BoundaryFunctor<Grid> boundaryFunctor(grid, "boundaryFunctor", outputDir); AreaMarker areaMarker("areaMarker", outputDir); GeometryFunctor geometryFunctor("geometryFunctor", outputDir); ProcessIdFunctor processIdFunctor("ProcessIdFunctor", outputDir); VolumeFunctor volumeFunctor("volumeFunctor", outputDir); // call the visualization functions elementdata( grid, boundaryFunctor ); elementdata( grid, areaMarker ); elementdata( grid, geometryFunctor ); elementdata( grid, processIdFunctor ); elementdata( grid, volumeFunctor ); } }; } //namespace Stuff } //namespace Grid } //namespace Dune #endif // DUNE_STUFF_GRID_ENTITY_VISUALIZATION_HH <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." //////////////////////////////////////////////////////////////////// // ftverify - Command line tool that checks the validity of a given // fractal tree file, one block at a time. //////////////////////////////////////////////////////////////////// #include <toku_portability.h> #include <toku_assert.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "fttypes.h" #include "ft-internal.h" #include "ft_layout_version.h" #include "block_table.h" #include "x1764.h" #include "rbuf.h" #include "sub_block.h" #include "threadpool.h" #include "toku_list.h" static int num_cores = 0; // cache the number of cores for the parallelization static struct toku_thread_pool *ft_pool = NULL; static FILE *outf; static double pct = 0.5; // Struct for reporting sub block stats. struct verify_block_extra { BLOCKNUM b; int n_sub_blocks; uint32_t header_length; uint32_t calc_xsum; uint32_t stored_xsum; bool header_valid; bool sub_blocks_valid; struct sub_block_info *sub_block_results; }; // Initialization function for the sub block stats. static void init_verify_block_extra(BLOCKNUM b, struct verify_block_extra *e) { static const struct verify_block_extra default_vbe = { .b = { 0 }, .n_sub_blocks = 0, .header_length = 0, .calc_xsum = 0, .stored_xsum = 0, .header_valid = true, .sub_blocks_valid = true, .sub_block_results = NULL }; *e = default_vbe; e->b = b; } // Reports percentage of completed blocks. static void report(int64_t blocks_done, int64_t blocks_failed, int64_t total_blocks) { int64_t blocks_per_report = llrint(pct * total_blocks / 100.0); if (blocks_per_report < 1) { blocks_per_report = 1; } if (blocks_done % blocks_per_report == 0) { double pct_actually_done = (100.0 * blocks_done) / total_blocks; printf("% 3.3lf%% | %" PRId64 " blocks checked, %" PRId64 " bad block(s) detected\n", pct_actually_done, blocks_done, blocks_failed); fflush(stdout); } } // Helper function to deserialize one of the two headers for the ft // we are checking. static void deserialize_headers(int fd, struct ft **h1p, struct ft **h2p) { struct rbuf rb_0; struct rbuf rb_1; uint64_t checkpoint_count_0; uint64_t checkpoint_count_1; LSN checkpoint_lsn_0; LSN checkpoint_lsn_1; uint32_t version_0, version_1; bool h0_acceptable = false; bool h1_acceptable = false; int r0, r1; int r; { toku_off_t header_0_off = 0; r0 = deserialize_ft_from_fd_into_rbuf( fd, header_0_off, &rb_0, &checkpoint_count_0, &checkpoint_lsn_0, &version_0 ); if ((r0==0) && (checkpoint_lsn_0.lsn <= MAX_LSN.lsn)) { h0_acceptable = true; } } { toku_off_t header_1_off = BLOCK_ALLOCATOR_HEADER_RESERVE; r1 = deserialize_ft_from_fd_into_rbuf( fd, header_1_off, &rb_1, &checkpoint_count_1, &checkpoint_lsn_1, &version_1 ); if ((r1==0) && (checkpoint_lsn_1.lsn <= MAX_LSN.lsn)) { h1_acceptable = true; } } // If either header is too new, the dictionary is unreadable if (r0 == TOKUDB_DICTIONARY_TOO_NEW || r1 == TOKUDB_DICTIONARY_TOO_NEW) { fprintf(stderr, "This dictionary was created with too new a version of TokuDB. Aborting.\n"); abort(); } if (h0_acceptable) { printf("Found dictionary header 1 with LSN %" PRIu64 "\n", checkpoint_lsn_0.lsn); r = deserialize_ft_versioned(fd, &rb_0, h1p, version_0); if (r != 0) { printf("---Header Error----\n"); } } else { *h1p = NULL; } if (h1_acceptable) { printf("Found dictionary header 2 with LSN %" PRIu64 "\n", checkpoint_lsn_1.lsn); r = deserialize_ft_versioned(fd, &rb_1, h2p, version_1); if (r != 0) { printf("---Header Error----\n"); } } else { *h2p = NULL; } if (rb_0.buf) toku_free(rb_0.buf); if (rb_1.buf) toku_free(rb_1.buf); } // Helper struct for tracking block checking progress. struct check_block_table_extra { int fd; int64_t blocks_done, blocks_failed, total_blocks; struct ft *h; }; // Check non-upgraded (legacy) node. // NOTE: These nodes have less checksumming than more // recent nodes. This effectively means that we are // skipping over these nodes. static int check_old_node(FTNODE node, struct rbuf *rb, int version) { int r = 0; read_legacy_node_info(node, rb, version); // For version 14 nodes, advance the buffer to the end // and verify the checksum. if (version == FT_FIRST_LAYOUT_VERSION_WITH_END_TO_END_CHECKSUM) { // Advance the buffer to the end. rb->ndone = rb->size - 4; r = check_legacy_end_checksum(rb); } return r; } // Read, decompress, and check the given block. static int check_block(BLOCKNUM blocknum, int64_t UU(blocksize), int64_t UU(address), void *extra) { int r = 0; int failure = 0; struct check_block_table_extra *CAST_FROM_VOIDP(cbte, extra); int fd = cbte->fd; FT ft = cbte->h; struct verify_block_extra be; init_verify_block_extra(blocknum, &be); // Let's read the block off of disk and fill a buffer with that // block. struct rbuf rb = RBUF_INITIALIZER; read_block_from_fd_into_rbuf(fd, blocknum, ft, &rb); // Allocate the node. FTNODE XMALLOC(node); initialize_ftnode(node, blocknum); r = read_and_check_magic(&rb); if (r == DB_BADFORMAT) { printf(" Magic failed.\n"); failure++; } r = read_and_check_version(node, &rb); if (r != 0) { printf(" Version check failed.\n"); failure++; } int version = node->layout_version_read_from_disk; //////////////////////////// // UPGRADE FORK GOES HERE // //////////////////////////// // Check nodes before major layout changes in version 15. // All newer versions should follow the same layout, for now. // This predicate would need to be changed if the layout // of the nodes on disk does indeed change in the future. if (version < FT_FIRST_LAYOUT_VERSION_WITH_BASEMENT_NODES) { struct rbuf nrb; // Use old decompression method for legacy nodes. r = decompress_from_raw_block_into_rbuf(rb.buf, rb.size, &nrb, blocknum); if (r != 0) { failure++; goto cleanup; } // Check the end-to-end checksum. r = check_old_node(node, &nrb, version); if (r != 0) { failure++; } goto cleanup; } read_node_info(node, &rb, version); FTNODE_DISK_DATA ndd; allocate_and_read_partition_offsets(node, &rb, &ndd); r = check_node_info_checksum(&rb); if (r == TOKUDB_BAD_CHECKSUM) { printf(" Node info checksum failed.\n"); failure++; } // Get the partition info sub block. struct sub_block sb; sub_block_init(&sb); r = read_compressed_sub_block(&rb, &sb); if (r != 0) { printf(" Partition info checksum failed.\n"); failure++; } just_decompress_sub_block(&sb); // If we want to inspect the data inside the partitions, we need // to call setup_ftnode_partitions(node, bfe, true) // <CER> TODO: Create function for this. // Using the node info, decompress all the keys and pivots to // detect any corruptions. for (int i = 0; i < node->n_children; ++i) { uint32_t curr_offset = BP_START(ndd,i); uint32_t curr_size = BP_SIZE(ndd,i); struct rbuf curr_rbuf = {.buf = NULL, .size = 0, .ndone = 0}; rbuf_init(&curr_rbuf, rb.buf + curr_offset, curr_size); struct sub_block curr_sb; sub_block_init(&curr_sb); r = read_compressed_sub_block(&rb, &sb); if (r != 0) { printf(" Compressed child partition %d checksum failed.\n", i); failure++; } just_decompress_sub_block(&sb); r = verify_ftnode_sub_block(&sb); if (r != 0) { printf(" Uncompressed child partition %d checksum failed.\n", i); failure++; } // <CER> If needed, we can print row and/or pivot info at this // point. } cleanup: // Cleanup and error incrementing. if (failure) { cbte->blocks_failed++; } cbte->blocks_done++; if (node) { toku_free(node); } // Print the status of this block to the console. report(cbte->blocks_done, cbte->blocks_failed, cbte->total_blocks); // We need to ALWAYS return 0 if we want to continue iterating // through the nodes in the file. r = 0; return r; } // This calls toku_blocktable_iterate on the given block table. // Passes our check_block() function to be called as we iterate over // the block table. This will print any interesting failures and // update us on our progress. static void check_block_table(int fd, BLOCK_TABLE bt, struct ft *h) { int64_t num_blocks = toku_block_get_blocks_in_use_unlocked(bt); printf("Starting verification of checkpoint containing"); printf(" %" PRId64 " blocks.\n", num_blocks); fflush(stdout); struct check_block_table_extra extra = { .fd = fd, .blocks_done = 0, .blocks_failed = 0, .total_blocks = num_blocks, .h = h }; int r = 0; r = toku_blocktable_iterate(bt, TRANSLATION_CURRENT, check_block, &extra, true, true); if (r != 0) { // We can print more information here if necessary. } assert(extra.blocks_done == extra.total_blocks); printf("Finished verification. "); printf(" %" PRId64 " blocks checked,", extra.blocks_done); printf(" %" PRId64 " bad block(s) detected\n", extra.blocks_failed); fflush(stdout); } // Validate arguments and print usage if number of arguments is // incorrect. static int check_args(int argc) { int r = 0; if (argc < 3 || argc > 4) { printf("ERROR: "); printf("Too few arguments.\n"); printf("USAGE:\n"); printf(" verify_block_checksum"); printf(" DICTIONARY_FILE OUTPUT_FILE [PERCENTAGE]\n"); printf(" [PERCENTAGE] is optional.\n"); r = 1; } return r; } // Main diver for verify_block_checksum. int main(int argc, char *argv[]) { // open the file int r = 0; int dictfd; char *dictfname, *outfname; r = check_args(argc); if (r) { goto exit; } assert(argc == 3 || argc == 4); dictfname = argv[1]; outfname = argv[2]; if (argc == 4) { set_errno(0); pct = strtod(argv[3], NULL); assert_zero(get_maybe_error_errno()); assert(pct > 0.0 && pct <= 100.0); } // Open the file as read-only. dictfd = open(dictfname, O_RDONLY | O_BINARY, S_IRWXU | S_IRWXG | S_IRWXO); if (dictfd < 0) { perror(dictfname); fflush(stderr); abort(); } outf = fopen(outfname, "w"); if (!outf) { perror(outfname); fflush(stderr); abort(); } // body of toku_ft_serialize_init(); num_cores = toku_os_get_number_active_processors(); r = toku_thread_pool_create(&ft_pool, num_cores); lazy_assert_zero(r); assert_zero(r); // deserialize the header(s) struct ft *h1, *h2; deserialize_headers(dictfd, &h1, &h2); // walk over the block table and check blocks if (h1) { printf("Checking dictionary from header 1.\n"); check_block_table(dictfd, h1->blocktable, h1); } if (h2) { printf("Checking dictionary from header 2.\n"); check_block_table(dictfd, h2->blocktable, h2); } if (h1 == NULL && h2 == NULL) { printf("Both headers have a corruption and could not be used.\n"); } toku_thread_pool_destroy(&ft_pool); exit: return 0; } <commit_msg>refs #5543 make ftverify use argv[0] to name itself<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." //////////////////////////////////////////////////////////////////// // ftverify - Command line tool that checks the validity of a given // fractal tree file, one block at a time. //////////////////////////////////////////////////////////////////// #include <toku_portability.h> #include <toku_assert.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sysexits.h> #include <unistd.h> #include "fttypes.h" #include "ft-internal.h" #include "ft_layout_version.h" #include "block_table.h" #include "x1764.h" #include "rbuf.h" #include "sub_block.h" #include "threadpool.h" #include "toku_list.h" static int num_cores = 0; // cache the number of cores for the parallelization static struct toku_thread_pool *ft_pool = NULL; static FILE *outf; static double pct = 0.5; // Struct for reporting sub block stats. struct verify_block_extra { BLOCKNUM b; int n_sub_blocks; uint32_t header_length; uint32_t calc_xsum; uint32_t stored_xsum; bool header_valid; bool sub_blocks_valid; struct sub_block_info *sub_block_results; }; // Initialization function for the sub block stats. static void init_verify_block_extra(BLOCKNUM b, struct verify_block_extra *e) { static const struct verify_block_extra default_vbe = { .b = { 0 }, .n_sub_blocks = 0, .header_length = 0, .calc_xsum = 0, .stored_xsum = 0, .header_valid = true, .sub_blocks_valid = true, .sub_block_results = NULL }; *e = default_vbe; e->b = b; } // Reports percentage of completed blocks. static void report(int64_t blocks_done, int64_t blocks_failed, int64_t total_blocks) { int64_t blocks_per_report = llrint(pct * total_blocks / 100.0); if (blocks_per_report < 1) { blocks_per_report = 1; } if (blocks_done % blocks_per_report == 0) { double pct_actually_done = (100.0 * blocks_done) / total_blocks; printf("% 3.3lf%% | %" PRId64 " blocks checked, %" PRId64 " bad block(s) detected\n", pct_actually_done, blocks_done, blocks_failed); fflush(stdout); } } // Helper function to deserialize one of the two headers for the ft // we are checking. static void deserialize_headers(int fd, struct ft **h1p, struct ft **h2p) { struct rbuf rb_0; struct rbuf rb_1; uint64_t checkpoint_count_0; uint64_t checkpoint_count_1; LSN checkpoint_lsn_0; LSN checkpoint_lsn_1; uint32_t version_0, version_1; bool h0_acceptable = false; bool h1_acceptable = false; int r0, r1; int r; { toku_off_t header_0_off = 0; r0 = deserialize_ft_from_fd_into_rbuf( fd, header_0_off, &rb_0, &checkpoint_count_0, &checkpoint_lsn_0, &version_0 ); if ((r0==0) && (checkpoint_lsn_0.lsn <= MAX_LSN.lsn)) { h0_acceptable = true; } } { toku_off_t header_1_off = BLOCK_ALLOCATOR_HEADER_RESERVE; r1 = deserialize_ft_from_fd_into_rbuf( fd, header_1_off, &rb_1, &checkpoint_count_1, &checkpoint_lsn_1, &version_1 ); if ((r1==0) && (checkpoint_lsn_1.lsn <= MAX_LSN.lsn)) { h1_acceptable = true; } } // If either header is too new, the dictionary is unreadable if (r0 == TOKUDB_DICTIONARY_TOO_NEW || r1 == TOKUDB_DICTIONARY_TOO_NEW) { fprintf(stderr, "This dictionary was created with too new a version of TokuDB. Aborting.\n"); abort(); } if (h0_acceptable) { printf("Found dictionary header 1 with LSN %" PRIu64 "\n", checkpoint_lsn_0.lsn); r = deserialize_ft_versioned(fd, &rb_0, h1p, version_0); if (r != 0) { printf("---Header Error----\n"); } } else { *h1p = NULL; } if (h1_acceptable) { printf("Found dictionary header 2 with LSN %" PRIu64 "\n", checkpoint_lsn_1.lsn); r = deserialize_ft_versioned(fd, &rb_1, h2p, version_1); if (r != 0) { printf("---Header Error----\n"); } } else { *h2p = NULL; } if (rb_0.buf) toku_free(rb_0.buf); if (rb_1.buf) toku_free(rb_1.buf); } // Helper struct for tracking block checking progress. struct check_block_table_extra { int fd; int64_t blocks_done, blocks_failed, total_blocks; struct ft *h; }; // Check non-upgraded (legacy) node. // NOTE: These nodes have less checksumming than more // recent nodes. This effectively means that we are // skipping over these nodes. static int check_old_node(FTNODE node, struct rbuf *rb, int version) { int r = 0; read_legacy_node_info(node, rb, version); // For version 14 nodes, advance the buffer to the end // and verify the checksum. if (version == FT_FIRST_LAYOUT_VERSION_WITH_END_TO_END_CHECKSUM) { // Advance the buffer to the end. rb->ndone = rb->size - 4; r = check_legacy_end_checksum(rb); } return r; } // Read, decompress, and check the given block. static int check_block(BLOCKNUM blocknum, int64_t UU(blocksize), int64_t UU(address), void *extra) { int r = 0; int failure = 0; struct check_block_table_extra *CAST_FROM_VOIDP(cbte, extra); int fd = cbte->fd; FT ft = cbte->h; struct verify_block_extra be; init_verify_block_extra(blocknum, &be); // Let's read the block off of disk and fill a buffer with that // block. struct rbuf rb = RBUF_INITIALIZER; read_block_from_fd_into_rbuf(fd, blocknum, ft, &rb); // Allocate the node. FTNODE XMALLOC(node); initialize_ftnode(node, blocknum); r = read_and_check_magic(&rb); if (r == DB_BADFORMAT) { printf(" Magic failed.\n"); failure++; } r = read_and_check_version(node, &rb); if (r != 0) { printf(" Version check failed.\n"); failure++; } int version = node->layout_version_read_from_disk; //////////////////////////// // UPGRADE FORK GOES HERE // //////////////////////////// // Check nodes before major layout changes in version 15. // All newer versions should follow the same layout, for now. // This predicate would need to be changed if the layout // of the nodes on disk does indeed change in the future. if (version < FT_FIRST_LAYOUT_VERSION_WITH_BASEMENT_NODES) { struct rbuf nrb; // Use old decompression method for legacy nodes. r = decompress_from_raw_block_into_rbuf(rb.buf, rb.size, &nrb, blocknum); if (r != 0) { failure++; goto cleanup; } // Check the end-to-end checksum. r = check_old_node(node, &nrb, version); if (r != 0) { failure++; } goto cleanup; } read_node_info(node, &rb, version); FTNODE_DISK_DATA ndd; allocate_and_read_partition_offsets(node, &rb, &ndd); r = check_node_info_checksum(&rb); if (r == TOKUDB_BAD_CHECKSUM) { printf(" Node info checksum failed.\n"); failure++; } // Get the partition info sub block. struct sub_block sb; sub_block_init(&sb); r = read_compressed_sub_block(&rb, &sb); if (r != 0) { printf(" Partition info checksum failed.\n"); failure++; } just_decompress_sub_block(&sb); // If we want to inspect the data inside the partitions, we need // to call setup_ftnode_partitions(node, bfe, true) // <CER> TODO: Create function for this. // Using the node info, decompress all the keys and pivots to // detect any corruptions. for (int i = 0; i < node->n_children; ++i) { uint32_t curr_offset = BP_START(ndd,i); uint32_t curr_size = BP_SIZE(ndd,i); struct rbuf curr_rbuf = {.buf = NULL, .size = 0, .ndone = 0}; rbuf_init(&curr_rbuf, rb.buf + curr_offset, curr_size); struct sub_block curr_sb; sub_block_init(&curr_sb); r = read_compressed_sub_block(&rb, &sb); if (r != 0) { printf(" Compressed child partition %d checksum failed.\n", i); failure++; } just_decompress_sub_block(&sb); r = verify_ftnode_sub_block(&sb); if (r != 0) { printf(" Uncompressed child partition %d checksum failed.\n", i); failure++; } // <CER> If needed, we can print row and/or pivot info at this // point. } cleanup: // Cleanup and error incrementing. if (failure) { cbte->blocks_failed++; } cbte->blocks_done++; if (node) { toku_free(node); } // Print the status of this block to the console. report(cbte->blocks_done, cbte->blocks_failed, cbte->total_blocks); // We need to ALWAYS return 0 if we want to continue iterating // through the nodes in the file. r = 0; return r; } // This calls toku_blocktable_iterate on the given block table. // Passes our check_block() function to be called as we iterate over // the block table. This will print any interesting failures and // update us on our progress. static void check_block_table(int fd, BLOCK_TABLE bt, struct ft *h) { int64_t num_blocks = toku_block_get_blocks_in_use_unlocked(bt); printf("Starting verification of checkpoint containing"); printf(" %" PRId64 " blocks.\n", num_blocks); fflush(stdout); struct check_block_table_extra extra = { .fd = fd, .blocks_done = 0, .blocks_failed = 0, .total_blocks = num_blocks, .h = h }; int r = 0; r = toku_blocktable_iterate(bt, TRANSLATION_CURRENT, check_block, &extra, true, true); if (r != 0) { // We can print more information here if necessary. } assert(extra.blocks_done == extra.total_blocks); printf("Finished verification. "); printf(" %" PRId64 " blocks checked,", extra.blocks_done); printf(" %" PRId64 " bad block(s) detected\n", extra.blocks_failed); fflush(stdout); } int main(int argc, char const * const argv[]) { // open the file int r = 0; int dictfd; const char *dictfname, *outfname; if (argc < 3 || argc > 4) { fprintf(stderr, "%s: Invalid arguments.\n", argv[0]); fprintf(stderr, "Usage: %s <dictionary> <logfile> [report%%]\n", argv[0]); r = EX_USAGE; goto exit; } assert(argc == 3 || argc == 4); dictfname = argv[1]; outfname = argv[2]; if (argc == 4) { set_errno(0); pct = strtod(argv[3], NULL); assert_zero(get_maybe_error_errno()); assert(pct > 0.0 && pct <= 100.0); } // Open the file as read-only. dictfd = open(dictfname, O_RDONLY | O_BINARY, S_IRWXU | S_IRWXG | S_IRWXO); if (dictfd < 0) { perror(dictfname); fflush(stderr); abort(); } outf = fopen(outfname, "w"); if (!outf) { perror(outfname); fflush(stderr); abort(); } // body of toku_ft_serialize_init(); num_cores = toku_os_get_number_active_processors(); r = toku_thread_pool_create(&ft_pool, num_cores); lazy_assert_zero(r); assert_zero(r); // deserialize the header(s) struct ft *h1, *h2; deserialize_headers(dictfd, &h1, &h2); // walk over the block table and check blocks if (h1) { printf("Checking dictionary from header 1.\n"); check_block_table(dictfd, h1->blocktable, h1); } if (h2) { printf("Checking dictionary from header 2.\n"); check_block_table(dictfd, h2->blocktable, h2); } if (h1 == NULL && h2 == NULL) { printf("Both headers have a corruption and could not be used.\n"); } toku_thread_pool_destroy(&ft_pool); exit: return r; } <|endoftext|>
<commit_before>#include "SemposScorer.h" #include <algorithm> #include <vector> #include <stdexcept> #include <fstream> #include "Util.h" #include "SemposOverlapping.h" using namespace std; SemposScorer::SemposScorer(const string& config) : StatisticsBasedScorer("SEMPOS", config), m_ovr(SemposOverlappingFactory::GetOverlapping(getConfig("overlapping", "cap-micro"),this)), m_enable_debug(false) { const string& debugSwitch = getConfig("debug", "0"); if (debugSwitch == "1") m_enable_debug = true; m_semposMap.clear(); string weightsfile = getConfig("weightsfile", ""); if (weightsfile != "") { loadWeights(weightsfile); } } SemposScorer::~SemposScorer() {} void SemposScorer::setReferenceFiles(const vector<string>& referenceFiles) { //make sure reference data is clear m_ref_sentences.clear(); //load reference data for (size_t rid = 0; rid < referenceFiles.size(); ++rid) { ifstream refin(referenceFiles[rid].c_str()); if (!refin) { throw runtime_error("Unable to open: " + referenceFiles[rid]); } m_ref_sentences.push_back(vector<sentence_t>()); string line; while (getline(refin,line)) { line = preprocessSentence(line); str_sentence_t sentence; splitSentence(line, sentence); sentence_t encodedSentence; encodeSentence(sentence, encodedSentence); m_ref_sentences[rid].push_back(encodedSentence); } } } void SemposScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) { vector<ScoreStatsType> stats; const string& sentence = preprocessSentence(text); str_sentence_t splitCandSentence; splitSentence(sentence, splitCandSentence); sentence_t encodedCandSentence; encodeSentence(splitCandSentence, encodedCandSentence); if (m_ref_sentences.size() == 1) { stats = m_ovr->prepareStats(encodedCandSentence, m_ref_sentences[0][sid]); } else { float max = -1.0f; for (size_t rid = 0; rid < m_ref_sentences.size(); ++rid) { const vector<ScoreStatsType>& tmp = m_ovr->prepareStats(encodedCandSentence, m_ref_sentences[rid][sid]); if (m_ovr->calculateScore(tmp) > max) { stats = tmp; } } } entry.set(stats); } void SemposScorer::splitSentence(const string& sentence, str_sentence_t& splitSentence) { splitSentence.clear(); vector<string> tokens; split(sentence, ' ', tokens); for (vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) { vector<string> factors; split(*it, '|', factors); if (factors.size() != 2) throw runtime_error("Sempos scorer accepts two factors (item|class)"); const string& item = factors[0]; const string& klass = factors[1]; splitSentence.push_back(make_pair(item, klass)); } } void SemposScorer::encodeSentence(const str_sentence_t& sentence, sentence_t& encodedSentence) { for (str_sentence_it it = sentence.begin(); it != sentence.end(); ++it) { const int tlemma = encodeString(it->first); const int sempos = encodeSempos(it->second); if (sempos >= 0) { encodedSentence.insert(make_pair(tlemma,sempos)); } } } int SemposScorer::encodeString(const string& str) { encoding_it encoding = m_stringMap.find(str); int encoded_str; if (encoding == m_stringMap.end()) { encoded_str = static_cast<int>(m_stringMap.size()); m_stringMap[str] = encoded_str; } else { encoded_str = encoding->second; } return encoded_str; } int SemposScorer::encodeSempos(const string& sempos) { if (sempos == "-") return -1; encoding_it it = m_semposMap.find(sempos); if (it == m_semposMap.end()) { const int classNumber = static_cast<int>(m_semposMap.size()); if (classNumber == kMaxNOC) { throw std::runtime_error("Number of classes is greater than kMaxNOC"); } m_semposMap[sempos] = classNumber; return classNumber; } else { return it->second; } } float SemposScorer::weight(int item) const { std::map<int,float>::const_iterator it = weightsMap.find(item); if (it == weightsMap.end()) { return 1.0f; } else { return it->second; } } void SemposScorer::loadWeights(const string& weightsfile) { string line; ifstream myfile; myfile.open(weightsfile.c_str(), ifstream::in); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); vector<string> fields; if (line == "") continue; split(line, '\t', fields); if (fields.size() != 2) throw std::runtime_error("Bad format of a row in weights file."); int encoded = encodeString(fields[0]); float weight = atof(fields[1].c_str()); weightsMap[encoded] = weight; } myfile.close(); } else { cerr << "Unable to open file "<< weightsfile << endl; exit(1); } } <commit_msg>Fixed bug in SemposScorer.cpp<commit_after>#include "SemposScorer.h" #include <algorithm> #include <vector> #include <stdexcept> #include <fstream> #include "Util.h" #include "SemposOverlapping.h" using namespace std; SemposScorer::SemposScorer(const string& config) : StatisticsBasedScorer("SEMPOS", config), m_ovr(SemposOverlappingFactory::GetOverlapping(getConfig("overlapping", "cap-micro"),this)), m_enable_debug(false) { const string& debugSwitch = getConfig("debug", "0"); if (debugSwitch == "1") m_enable_debug = true; m_semposMap.clear(); string weightsfile = getConfig("weightsfile", ""); if (weightsfile != "") { loadWeights(weightsfile); } } SemposScorer::~SemposScorer() {} void SemposScorer::setReferenceFiles(const vector<string>& referenceFiles) { //make sure reference data is clear m_ref_sentences.clear(); //load reference data for (size_t rid = 0; rid < referenceFiles.size(); ++rid) { ifstream refin(referenceFiles[rid].c_str()); if (!refin) { throw runtime_error("Unable to open: " + referenceFiles[rid]); } m_ref_sentences.push_back(vector<sentence_t>()); string line; while (getline(refin,line)) { line = preprocessSentence(line); str_sentence_t sentence; splitSentence(line, sentence); sentence_t encodedSentence; encodeSentence(sentence, encodedSentence); m_ref_sentences[rid].push_back(encodedSentence); } } } void SemposScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry) { vector<ScoreStatsType> stats; const string& sentence = preprocessSentence(text); str_sentence_t splitCandSentence; splitSentence(sentence, splitCandSentence); sentence_t encodedCandSentence; encodeSentence(splitCandSentence, encodedCandSentence); if (m_ref_sentences.size() == 1) { stats = m_ovr->prepareStats(encodedCandSentence, m_ref_sentences[0][sid]); } else { float max = -1.0f; for (size_t rid = 0; rid < m_ref_sentences.size(); ++rid) { const vector<ScoreStatsType>& tmp = m_ovr->prepareStats(encodedCandSentence, m_ref_sentences[rid][sid]); if (m_ovr->calculateScore(tmp) > max) { stats = tmp; } } } entry.set(stats); } void SemposScorer::splitSentence(const string& sentence, str_sentence_t& splitSentence) { splitSentence.clear(); vector<string> tokens; split(sentence, ' ', tokens); for (vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it) { vector<string> factors; if (it->empty()) continue; split(*it, '|', factors); if (factors.size() != 2) throw runtime_error("Sempos scorer accepts two factors (item|class)"); const string& item = factors[0]; const string& klass = factors[1]; splitSentence.push_back(make_pair(item, klass)); } } void SemposScorer::encodeSentence(const str_sentence_t& sentence, sentence_t& encodedSentence) { for (str_sentence_it it = sentence.begin(); it != sentence.end(); ++it) { const int tlemma = encodeString(it->first); const int sempos = encodeSempos(it->second); if (sempos >= 0) { encodedSentence.insert(make_pair(tlemma,sempos)); } } } int SemposScorer::encodeString(const string& str) { encoding_it encoding = m_stringMap.find(str); int encoded_str; if (encoding == m_stringMap.end()) { encoded_str = static_cast<int>(m_stringMap.size()); m_stringMap[str] = encoded_str; } else { encoded_str = encoding->second; } return encoded_str; } int SemposScorer::encodeSempos(const string& sempos) { if (sempos == "-") return -1; encoding_it it = m_semposMap.find(sempos); if (it == m_semposMap.end()) { const int classNumber = static_cast<int>(m_semposMap.size()); if (classNumber == kMaxNOC) { throw std::runtime_error("Number of classes is greater than kMaxNOC"); } m_semposMap[sempos] = classNumber; return classNumber; } else { return it->second; } } float SemposScorer::weight(int item) const { std::map<int,float>::const_iterator it = weightsMap.find(item); if (it == weightsMap.end()) { return 1.0f; } else { return it->second; } } void SemposScorer::loadWeights(const string& weightsfile) { string line; ifstream myfile; myfile.open(weightsfile.c_str(), ifstream::in); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); vector<string> fields; if (line == "") continue; split(line, '\t', fields); if (fields.size() != 2) throw std::runtime_error("Bad format of a row in weights file."); int encoded = encodeString(fields[0]); float weight = atof(fields[1].c_str()); weightsMap[encoded] = weight; } myfile.close(); } else { cerr << "Unable to open file "<< weightsfile << endl; exit(1); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OPropertySet.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:47:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_OPROPERTYSET_HXX #define CHART_OPROPERTYSET_HXX // helper classes #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif // interfaces and types // #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ // #include <com/sun/star/lang/XServiceInfo.hpp> // #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_ #include <com/sun/star/beans/XMultiPropertyStates.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #ifndef _COM_SUN_STAR_STYLE_XSTYLESUPPLIER_HPP_ #include <com/sun/star/style/XStyleSupplier.hpp> #endif // #ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSTATE_HPP_ // #include <com/sun/star/beans/XFastPropertyState.hpp> // #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <memory> namespace property { namespace impl { class ImplOPropertySet; } class OPropertySet : public ::cppu::OBroadcastHelper, // includes beans::XPropertySet, XMultiPropertySet and XFastPropertySet public ::cppu::OPropertySetHelper, // includes uno::XWeak (and XInterface, esp. ref-counting) // public virtual ::cppu::OWeakObject, // public virtual ::com::sun::star::lang::XServiceInfo, public ::com::sun::star::lang::XTypeProvider, public ::com::sun::star::beans::XPropertyState, public ::com::sun::star::beans::XMultiPropertyStates, public ::com::sun::star::style::XStyleSupplier // public ::com::sun::star::beans::XFastPropertyState { public: OPropertySet( ::osl::Mutex & rMutex ); virtual ~OPropertySet(); protected: explicit OPropertySet( const OPropertySet & rOther, ::osl::Mutex & rMutex ); /** implement this method to provide default values for all properties supporting defaults. If a property does not have a default value, you may throw an UnknownPropertyException. */ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException) = 0; /** The InfoHelper table contains all property names and types of this object. @return the object that provides information for the PropertySetInfo @see ::cppu::OPropertySetHelper */ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() = 0; // ____ XPropertySet ____ /** sample implementation using the InfoHelper: <pre> uno::Reference&lt; beans::XPropertySetInfo &gt; SAL_CALL OPropertySet::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference&lt; beans::XPropertySetInfo &gt; xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } </pre> <p>(The reason why this isn't implemented here is, that the static object is only valid per concrete PropertySet. Otherwise all PropertySets derived from this base calss would have the same properties.)</p> @see ::cppu::OPropertySetHelper */ // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL // getPropertySetInfo() // throw (::com::sun::star::uno::RuntimeException) = 0; /** Try to convert the value <code>rValue</code> to the type required by the property associated with <code>nHandle</code>. Overload this method to take influence in modification of properties. If the conversion changed , </TRUE> is returned and the converted value is in <code>rConvertedValue</code>. The former value is contained in <code>rOldValue</code>. After this call returns successfully, the vetoable listeners are notified. @throws IllegalArgumentException, if the conversion was not successful, or if there is no corresponding property to the given handle. @param rConvertedValue the converted value. Only set if return is true. @param rOldValue the old value. Only set if return is true. @param nHandle the handle of the property. @return true, if the conversion was successful and converted value differs from the old value. @see ::cppu::OPropertySetHelper */ virtual sal_Bool SAL_CALL convertFastPropertyValue ( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); /** The same as setFastProperyValue; nHandle is always valid. The changes must not be broadcasted in this method. @attention Although you are permitted to throw any UNO exception, only the following are valid for usage: -- ::com::sun::star::beans::UnknownPropertyException -- ::com::sun::star::beans::PropertyVetoException -- ::com::sun::star::lang::IllegalArgumentException -- ::com::sun::star::lang::WrappedTargetException -- ::com::sun::star::uno::RuntimeException @param nHandle handle @param rValue value @see ::cppu::OPropertySetHelper */ virtual void SAL_CALL setFastPropertyValue_NoBroadcast ( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception); /** The same as getFastProperyValue, but return the value through rValue and nHandle is always valid. @see ::cppu::OPropertySetHelper */ virtual void SAL_CALL getFastPropertyValue ( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; /// make original interface function visible again using ::com::sun::star::beans::XFastPropertySet::getFastPropertyValue; /** implement this method in derived classes to get called when properties change. */ virtual void firePropertyChangeEvent(); /// call this when a derived component is disposed virtual void disposePropertySet(); // ======================================== // Interfaces // ======================================== // ____ XInterface ____ virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); // virtual void SAL_CALL acquire() throw (); // virtual void SAL_CALL release() throw (); // ____ XServiceInfo ____ // virtual ::rtl::OUString SAL_CALL // getImplementationName() // throw (::com::sun::star::uno::RuntimeException); // virtual sal_Bool SAL_CALL // supportsService( const ::rtl::OUString& ServiceName ) // throw (::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL // getSupportedServiceNames() // throw (::com::sun::star::uno::RuntimeException); // ____ XTypeProvider ____ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // ____ XPropertyState ____ virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XMultiPropertyStates ____ // Note: getPropertyStates() is already implemented in XPropertyState with the // same signature virtual void SAL_CALL setAllPropertiesToDefault() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertiesToDefault( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getPropertyDefaults( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XStyleSupplier ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > SAL_CALL getStyle() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // ____ XFastPropertyState ____ // virtual ::com::sun::star::beans::PropertyState SAL_CALL getFastPropertyState( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getFastPropertyStates( const ::com::sun::star::uno::Sequence< sal_Int32 >& aHandles ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual void SAL_CALL setFastPropertyToDefault( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyDefault( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::lang::WrappedTargetException, // ::com::sun::star::uno::RuntimeException); // ____ XMultiPropertySet ____ virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XFastPropertySet ____ virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Note: it is assumed that the base class implements setPropertyValue by // using setFastPropertyValue private: /// reference to mutex of class deriving from here ::osl::Mutex & m_rMutex; /// pImpl idiom implementation ::std::auto_ptr< impl::ImplOPropertySet > m_pImplProperties; }; } // namespace property // CHART_OPROPERTYSET_HXX #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.94); FILE MERGED 2008/04/01 15:04:13 thb 1.5.94.3: #i85898# Stripping all external header guards 2008/04/01 10:50:29 thb 1.5.94.2: #i85898# Stripping all external header guards 2008/03/28 16:43:55 rt 1.5.94.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: OPropertySet.hxx,v $ * $Revision: 1.6 $ * * 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 CHART_OPROPERTYSET_HXX #define CHART_OPROPERTYSET_HXX // helper classes #include <cppuhelper/propshlp.hxx> #include <cppuhelper/interfacecontainer.hxx> #include <cppuhelper/weak.hxx> // interfaces and types // #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ // #include <com/sun/star/lang/XServiceInfo.hpp> // #endif #include <com/sun/star/lang/XTypeProvider.hpp> #include <com/sun/star/beans/XPropertyState.hpp> #include <com/sun/star/beans/XMultiPropertyStates.hpp> #include <com/sun/star/beans/Property.hpp> #include <com/sun/star/style/XStyleSupplier.hpp> // #ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSTATE_HPP_ // #include <com/sun/star/beans/XFastPropertyState.hpp> // #endif #include <osl/mutex.hxx> #include <memory> namespace property { namespace impl { class ImplOPropertySet; } class OPropertySet : public ::cppu::OBroadcastHelper, // includes beans::XPropertySet, XMultiPropertySet and XFastPropertySet public ::cppu::OPropertySetHelper, // includes uno::XWeak (and XInterface, esp. ref-counting) // public virtual ::cppu::OWeakObject, // public virtual ::com::sun::star::lang::XServiceInfo, public ::com::sun::star::lang::XTypeProvider, public ::com::sun::star::beans::XPropertyState, public ::com::sun::star::beans::XMultiPropertyStates, public ::com::sun::star::style::XStyleSupplier // public ::com::sun::star::beans::XFastPropertyState { public: OPropertySet( ::osl::Mutex & rMutex ); virtual ~OPropertySet(); protected: explicit OPropertySet( const OPropertySet & rOther, ::osl::Mutex & rMutex ); /** implement this method to provide default values for all properties supporting defaults. If a property does not have a default value, you may throw an UnknownPropertyException. */ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException) = 0; /** The InfoHelper table contains all property names and types of this object. @return the object that provides information for the PropertySetInfo @see ::cppu::OPropertySetHelper */ virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper() = 0; // ____ XPropertySet ____ /** sample implementation using the InfoHelper: <pre> uno::Reference&lt; beans::XPropertySetInfo &gt; SAL_CALL OPropertySet::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference&lt; beans::XPropertySetInfo &gt; xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } </pre> <p>(The reason why this isn't implemented here is, that the static object is only valid per concrete PropertySet. Otherwise all PropertySets derived from this base calss would have the same properties.)</p> @see ::cppu::OPropertySetHelper */ // virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL // getPropertySetInfo() // throw (::com::sun::star::uno::RuntimeException) = 0; /** Try to convert the value <code>rValue</code> to the type required by the property associated with <code>nHandle</code>. Overload this method to take influence in modification of properties. If the conversion changed , </TRUE> is returned and the converted value is in <code>rConvertedValue</code>. The former value is contained in <code>rOldValue</code>. After this call returns successfully, the vetoable listeners are notified. @throws IllegalArgumentException, if the conversion was not successful, or if there is no corresponding property to the given handle. @param rConvertedValue the converted value. Only set if return is true. @param rOldValue the old value. Only set if return is true. @param nHandle the handle of the property. @return true, if the conversion was successful and converted value differs from the old value. @see ::cppu::OPropertySetHelper */ virtual sal_Bool SAL_CALL convertFastPropertyValue ( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); /** The same as setFastProperyValue; nHandle is always valid. The changes must not be broadcasted in this method. @attention Although you are permitted to throw any UNO exception, only the following are valid for usage: -- ::com::sun::star::beans::UnknownPropertyException -- ::com::sun::star::beans::PropertyVetoException -- ::com::sun::star::lang::IllegalArgumentException -- ::com::sun::star::lang::WrappedTargetException -- ::com::sun::star::uno::RuntimeException @param nHandle handle @param rValue value @see ::cppu::OPropertySetHelper */ virtual void SAL_CALL setFastPropertyValue_NoBroadcast ( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception); /** The same as getFastProperyValue, but return the value through rValue and nHandle is always valid. @see ::cppu::OPropertySetHelper */ virtual void SAL_CALL getFastPropertyValue ( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; /// make original interface function visible again using ::com::sun::star::beans::XFastPropertySet::getFastPropertyValue; /** implement this method in derived classes to get called when properties change. */ virtual void firePropertyChangeEvent(); /// call this when a derived component is disposed virtual void disposePropertySet(); // ======================================== // Interfaces // ======================================== // ____ XInterface ____ virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); // virtual void SAL_CALL acquire() throw (); // virtual void SAL_CALL release() throw (); // ____ XServiceInfo ____ // virtual ::rtl::OUString SAL_CALL // getImplementationName() // throw (::com::sun::star::uno::RuntimeException); // virtual sal_Bool SAL_CALL // supportsService( const ::rtl::OUString& ServiceName ) // throw (::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL // getSupportedServiceNames() // throw (::com::sun::star::uno::RuntimeException); // ____ XTypeProvider ____ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // ____ XPropertyState ____ virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XMultiPropertyStates ____ // Note: getPropertyStates() is already implemented in XPropertyState with the // same signature virtual void SAL_CALL setAllPropertiesToDefault() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertiesToDefault( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL getPropertyDefaults( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyNames ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XStyleSupplier ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle > SAL_CALL getStyle() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // ____ XFastPropertyState ____ // virtual ::com::sun::star::beans::PropertyState SAL_CALL getFastPropertyState( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getFastPropertyStates( const ::com::sun::star::uno::Sequence< sal_Int32 >& aHandles ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual void SAL_CALL setFastPropertyToDefault( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyDefault( sal_Int32 nHandle ) // throw (::com::sun::star::beans::UnknownPropertyException, // ::com::sun::star::lang::WrappedTargetException, // ::com::sun::star::uno::RuntimeException); // ____ XMultiPropertySet ____ virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // ____ XFastPropertySet ____ virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // Note: it is assumed that the base class implements setPropertyValue by // using setFastPropertyValue private: /// reference to mutex of class deriving from here ::osl::Mutex & m_rMutex; /// pImpl idiom implementation ::std::auto_ptr< impl::ImplOPropertySet > m_pImplProperties; }; } // namespace property // CHART_OPROPERTYSET_HXX #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ncw is the nodecast worker, client of the nodecast server ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncw ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Affero General Public License as ** published by the Free Software Foundation, either version 3 of the ** License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include "service.h" Service::Service(ncw_params a_ncw) : Worker(), m_ncw(a_ncw) { qDebug() << "Service::Service constructer"; child_process = new QProcess(); m_mutex = new QMutex; timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(watchdog ()), Qt::DirectConnection); timer->start (5000); } Service::~Service() { delete(child_process); } void Service::init() { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = m_ncw.child_exec; m_service_name = m_ncw.worker_name; m_node_uuid = m_ncw.node_uuid; m_node_password = m_ncw.node_password; BSONObj tracker = BSON("type" << "service" << "name" << m_service_name.toStdString() << "node_uuid" << m_node_uuid.toStdString() << "command" << m_child_exec.toStdString() << "action" << "register" << "pid" << QCoreApplication::applicationPid() << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); /* qDebug() << "!!!! EXEC PROCESS : " << ncw.child_exec; child_process->start(m_child_exec); bool start = child_process->waitForStarted(30000); if (!start) { qDebug() << "SERVICE IS NOT STARTED"; qApp->exit(); } connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid();*/ } void Service::launch() { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = m_ncw.child_exec; m_service_name = m_ncw.worker_name; m_node_uuid = m_ncw.node_uuid; m_node_password = m_ncw.node_password; qDebug() << "!!!! EXEC PROCESS : " << m_ncw.child_exec; /************* START GRUIK CODE ***** because I must waiting for the pub sub socket is ready **/ sleep(2); /************* END GRUIK CODE *****/ child_process->start(m_child_exec); bool start = child_process->waitForStarted(30000); if (!start) { qDebug() << "SERVICE IS NOT STARTED"; qApp->exit(); } if (m_ncw.stdout) connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid(); } void Service::watchdog() { /* if (child_process->state() == QProcess::NotRunning) { ** child is dead, so we exit the worker qDebug() << "SERVICE IS NOT RUNNING"; qApp->exit(); } */ QDateTime timestamp = QDateTime::currentDateTime(); BSONObj tracker = BSON("type" << "service" << "action" << "watchdog" << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); } //void Service::get_pubsub(bson::bo data) void Service::get_pubsub(string data) { std::cout << "Service::get_pubsub data : " << data << std::endl; QDateTime timestamp = QDateTime::currentDateTime(); QString payload = QString::fromStdString(data); QRegExp filter("([^@]*@).*"); int pos = filter.indexIn(payload); QStringList cap = filter.capturedTexts(); qDebug() << " cap 1 : " << cap[1]; payload.remove(cap[1]); qDebug() << "PAYLOAD : " << payload; BSONObj l_data; try { //l_data = BSONObj((char*)payload.data()); l_data = mongo::fromjson(payload.toAscii()); if (l_data.isValid() && !l_data.isEmpty()) { std::cout << "Service::get_pubsub : " << l_data << std::endl; if (l_data.hasField("session_uuid")) { BSONElement session_uuid = l_data.getField("session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); } if (l_data.hasField("command")) { string command = l_data.getField("command").str(); std::cout << "COMMAND : " << command << std::endl; BSONObjBuilder b_datas; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (command.compare("get_file") == 0) { string filename = l_data.getField("filename").str(); std::cout << "Service::s_job_receive filename : " << filename << std::endl; qDebug() << "WORKER SERVICE BEFORE EMIT get_file"; bool status = true; emit get_stream(s_datas, filename, &status); qDebug() << "WORKER SERVICE AFTER EMIT get_file"; received_file(filename, status); } } else { //child_process->write(data.toString().data()); child_process->write(payload.toAscii()); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } } else { std::cout << "DATA NO VALID :" << l_data << std::endl; } } catch (mongo::MsgAssertionException &e) { std::cout << "error on data : " << l_data << std::endl; std::cout << "error on data BSON : " << e.what() << std::endl; } } void Service::s_job_receive(bson::bo data) { std::cout << "Service::s_job_receive DATA : " << data << std::endl; //m_mutex->lock(); BSONElement session_uuid = data.getFieldDotted("payload.session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); BSONElement action = data.getFieldDotted("payload.action"); //data.getField("step_id").Obj().getObjectID(step_id); std::cout << "BE SESSION UUID " << session_uuid << std::endl; std::cout << "QS SESSION UUID " << m_session_uuid.toStdString() << std::endl; //be step_id; //data.getObjectID (step_id); std::cout << "RECEIVE MESSAGE : " << data << std::endl; QString param; QDateTime timestamp = QDateTime::currentDateTime(); BSONObjBuilder b_tracker; b_tracker << "type" << "service"; b_tracker.append(session_uuid); b_tracker << "name" << m_service_name.toStdString() << "action" << "receive" << "timestamp" << timestamp.toTime_t(); BSONObj tracker = b_tracker.obj(); emit push_payload(tracker); qDebug() << "AFTER EMIT PUSH PAYLOAD"; BSONObj raw_data = mongo::fromjson(data.getFieldDotted("payload.data").str()); std::cout << "Service::s_job_receive RAW DATA : " << raw_data << std::endl; if (action.str().compare("publish") == 0) { qDebug() << "PUBLISH !"; BSONObjBuilder b_datas; b_datas << "action" << "publish"; b_datas << "gridfs" << false; b_datas << "dest" << m_service_name.toStdString(); b_datas << "data" << raw_data; b_datas << "payload_type" << raw_data.getFieldDotted("payload_type"); b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE BEFORE CREATE PUBSUB PAYLOAD EMIT"; emit push_payload(s_datas); qDebug() << "WORKER SERVICE AFTER CREATE PUBSUB PAYLOAD EMIT"; return; } if (data.getField("payload").Obj().hasField("command")) { string command = data.getFieldDotted("payload.command").str(); std::cout << "COMMAND : " << command << std::endl; BSONObjBuilder b_datas; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (command.compare("get_file") == 0) { string filename = data.getFieldDotted("payload.filename").str(); std::cout << "Service::s_job_receive filename : " << filename << std::endl; qDebug() << "WORKER SERVICE BEFORE EMIT get_file"; bool status = true; emit get_stream(s_datas, filename, &status); qDebug() << "WORKER SERVICE AFTER EMIT get_file"; received_file(filename, status); } } else if (data.getField("payload").Obj().hasField("data")) { BSONElement r_datas = data.getFieldDotted("payload.data"); param.append(" ").append(QString::fromStdString(r_datas.str())); QByteArray q_datas = r_datas.valuestr(); qDebug() << "!!!! SEND PAYLOAD TO STDIN : " << q_datas; child_process->write(q_datas); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } } void Service::received_file(string filename, bool status) { if (status) { QString json = "{\"received_file\": \""; json.append(filename.c_str()); json.append("\"}"); child_process->write(json.toAscii()); child_process->write("\n"); qDebug() << "RECEIVED FILE " << json; } else { QString json = "{\"error\": \""; json.append(filename.c_str()); json.append("\"}"); child_process->write(json.toAscii()); child_process->write("\n"); qDebug() << "ERROR ON RECEIVED FILE " << json; } } void Service::readyReadStandardOutput() { QByteArray service_stdout = child_process->readAllStandardOutput(); QString json = service_stdout; json = json.simplified(); std::cout << "STDOUT : " << json.toStdString() << std::endl; std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; BSONObjBuilder b_datas; BSONObj b_out; QDateTime timestamp = QDateTime::currentDateTime(); try { b_out = mongo::fromjson(json.toAscii()); std::cout << "b_out : " << b_out << std::endl; if (b_out.hasField("action") && (b_out.getField("action").str().compare("push") == 0 || b_out.getField("action").str().compare("publish") == 0 || b_out.getField("action").str().compare("replay") == 0)) { qDebug() << "WORKER SERVICE BEFORE CREATE PAYLOAD EMIT"; emit push_payload(b_out); qDebug() << "WORKER SERVICE AFTER CREATE PAYLOAD EMIT"; return; } else if (b_out.hasField("action") && b_out.getField("action").str().compare("get_file") == 0) { qDebug() << "WORKER SERVICE BEFORE GET FILE PAYLOAD EMIT"; BSONElement filename = b_out.getField("filename"); b_datas << "type" << "service"; b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); b_datas << "filename" << filename.str(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD BEFORE EMIT"; bool status = true; emit get_stream(s_datas, filename.str(), &status); qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD EMIT"; received_file(filename.str(), status); return; } else if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "data" << b_out; } } catch (mongo::MsgAssertionException &e) { std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; std::cout << "m_service_name : " << m_service_name.toStdString() << std::endl; std::cout << "error on parsing JSON : " << e.what() << std::endl; if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "data" << json.toStdString(); } } BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (s_datas.isValid() && !s_datas.isEmpty()) { qDebug() << "WORKER PROCESS BEFORE EMIT"; emit push_payload(s_datas); qDebug() << "WORKER PROCESS AFTER EMIT"; } //m_mutex->unlock(); } <commit_msg>update service<commit_after>/**************************************************************************** ** ncw is the nodecast worker, client of the nodecast server ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncw ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Affero General Public License as ** published by the Free Software Foundation, either version 3 of the ** License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include "service.h" Service::Service(ncw_params a_ncw) : Worker(), m_ncw(a_ncw) { qDebug() << "Service::Service constructer"; child_process = new QProcess(); m_mutex = new QMutex; timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(watchdog ()), Qt::DirectConnection); timer->start (5000); } Service::~Service() { delete(child_process); } void Service::init() { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = m_ncw.child_exec; m_service_name = m_ncw.worker_name; m_node_uuid = m_ncw.node_uuid; m_node_password = m_ncw.node_password; BSONObj tracker = BSON("type" << "service" << "name" << m_service_name.toStdString() << "node_uuid" << m_node_uuid.toStdString() << "command" << m_child_exec.toStdString() << "action" << "register" << "pid" << QCoreApplication::applicationPid() << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); /* qDebug() << "!!!! EXEC PROCESS : " << ncw.child_exec; child_process->start(m_child_exec); bool start = child_process->waitForStarted(30000); if (!start) { qDebug() << "SERVICE IS NOT STARTED"; qApp->exit(); } connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid();*/ } void Service::launch() { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = m_ncw.child_exec; m_service_name = m_ncw.worker_name; m_node_uuid = m_ncw.node_uuid; m_node_password = m_ncw.node_password; qDebug() << "!!!! EXEC PROCESS : " << m_ncw.child_exec; /************* START GRUIK CODE ***** because I must waiting for the pub sub socket is ready **/ sleep(2); /************* END GRUIK CODE *****/ child_process->start(m_child_exec); bool start = child_process->waitForStarted(30000); if (!start) { qDebug() << "SERVICE IS NOT STARTED"; qApp->exit(); } if (m_ncw.stdout) connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid(); } void Service::watchdog() { /* if (child_process->state() == QProcess::NotRunning) { ** child is dead, so we exit the worker qDebug() << "SERVICE IS NOT RUNNING"; qApp->exit(); } */ QDateTime timestamp = QDateTime::currentDateTime(); BSONObj tracker = BSON("type" << "service" << "action" << "watchdog" << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); } //void Service::get_pubsub(bson::bo data) void Service::get_pubsub(string data) { std::cout << "Service::get_pubsub data : " << data << std::endl; QDateTime timestamp = QDateTime::currentDateTime(); QString payload = QString::fromStdString(data); QRegExp filter("([^@]*@).*"); int pos = filter.indexIn(payload); QStringList cap = filter.capturedTexts(); qDebug() << " cap 1 : " << cap[1]; payload.remove(cap[1]); qDebug() << "PAYLOAD : " << payload; BSONObj l_data; try { //l_data = BSONObj((char*)payload.data()); l_data = mongo::fromjson(payload.toAscii()); if (l_data.isValid() && !l_data.isEmpty()) { std::cout << "Service::get_pubsub : " << l_data << std::endl; if (l_data.hasField("session_uuid")) { BSONElement session_uuid = l_data.getField("session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); } if (l_data.hasField("command")) { string command = l_data.getField("command").str(); std::cout << "COMMAND : " << command << std::endl; BSONObjBuilder b_datas; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (command.compare("get_file") == 0) { string filename = l_data.getField("filename").str(); std::cout << "Service::s_job_receive filename : " << filename << std::endl; qDebug() << "WORKER SERVICE BEFORE EMIT get_file"; bool status = true; emit get_stream(s_datas, filename, &status); qDebug() << "WORKER SERVICE AFTER EMIT get_file"; received_file(filename, status); } } else { //child_process->write(data.toString().data()); child_process->write(payload.toAscii()); child_process->write("\n"); child_process->waitForBytesWritten(); } } else { std::cout << "DATA NO VALID :" << l_data << std::endl; } } catch (mongo::MsgAssertionException &e) { std::cout << "error on data : " << l_data << std::endl; std::cout << "error on data BSON : " << e.what() << std::endl; } } void Service::s_job_receive(bson::bo data) { std::cout << "Service::s_job_receive DATA : " << data << std::endl; //m_mutex->lock(); BSONElement session_uuid = data.getFieldDotted("payload.session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); BSONElement action = data.getFieldDotted("payload.action"); //data.getField("step_id").Obj().getObjectID(step_id); std::cout << "BE SESSION UUID " << session_uuid << std::endl; std::cout << "QS SESSION UUID " << m_session_uuid.toStdString() << std::endl; //be step_id; //data.getObjectID (step_id); std::cout << "RECEIVE MESSAGE : " << data << std::endl; QString param; QDateTime timestamp = QDateTime::currentDateTime(); BSONObjBuilder b_tracker; b_tracker << "type" << "service"; b_tracker.append(session_uuid); b_tracker << "name" << m_service_name.toStdString() << "action" << "receive" << "timestamp" << timestamp.toTime_t(); BSONObj tracker = b_tracker.obj(); emit push_payload(tracker); qDebug() << "AFTER EMIT PUSH PAYLOAD"; BSONObj raw_data = mongo::fromjson(data.getFieldDotted("payload.data").str()); std::cout << "Service::s_job_receive RAW DATA : " << raw_data << std::endl; if (action.str().compare("publish") == 0) { qDebug() << "PUBLISH !"; BSONObjBuilder b_datas; b_datas << "action" << "publish"; b_datas << "gridfs" << false; b_datas << "dest" << m_service_name.toStdString(); b_datas << "data" << raw_data; b_datas << "payload_type" << raw_data.getFieldDotted("payload_type"); b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE BEFORE CREATE PUBSUB PAYLOAD EMIT"; emit push_payload(s_datas); qDebug() << "WORKER SERVICE AFTER CREATE PUBSUB PAYLOAD EMIT"; return; } if (data.getField("payload").Obj().hasField("command")) { string command = data.getFieldDotted("payload.command").str(); std::cout << "COMMAND : " << command << std::endl; BSONObjBuilder b_datas; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (command.compare("get_file") == 0) { string filename = data.getFieldDotted("payload.filename").str(); std::cout << "Service::s_job_receive filename : " << filename << std::endl; qDebug() << "WORKER SERVICE BEFORE EMIT get_file"; bool status = true; emit get_stream(s_datas, filename, &status); qDebug() << "WORKER SERVICE AFTER EMIT get_file"; received_file(filename, status); } } else if (data.getField("payload").Obj().hasField("data")) { BSONElement r_datas = data.getFieldDotted("payload.data"); param.append(" ").append(QString::fromStdString(r_datas.str())); QByteArray q_datas = r_datas.valuestr(); qDebug() << "!!!! SEND PAYLOAD TO STDIN : " << q_datas; child_process->write(q_datas); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } } void Service::received_file(string filename, bool status) { if (status) { QString json = "{\"received_file\": \""; json.append(filename.c_str()); json.append("\"}"); child_process->write(json.toAscii()); child_process->write("\n"); qDebug() << "RECEIVED FILE " << json; } else { QString json = "{\"error\": \""; json.append(filename.c_str()); json.append("\"}"); child_process->write(json.toAscii()); child_process->write("\n"); qDebug() << "ERROR ON RECEIVED FILE " << json; } } void Service::readyReadStandardOutput() { QByteArray service_stdout = child_process->readAllStandardOutput(); QString json = service_stdout; json = json.simplified(); std::cout << "STDOUT : " << json.toStdString() << std::endl; std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; BSONObjBuilder b_datas; BSONObj b_out; QDateTime timestamp = QDateTime::currentDateTime(); try { b_out = mongo::fromjson(json.toAscii()); std::cout << "b_out : " << b_out << std::endl; if (b_out.hasField("action") && b_out.getField("action").str().compare("get_file") == 0) { qDebug() << "WORKER SERVICE BEFORE GET FILE PAYLOAD EMIT"; BSONElement filename = b_out.getField("filename"); b_datas << "type" << "service"; b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "timestamp" << timestamp.toTime_t(); b_datas << "filename" << filename.str(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD BEFORE EMIT"; bool status = true; emit get_stream(s_datas, filename.str(), &status); qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD EMIT"; received_file(filename.str(), status); return; } else if (b_out.hasField("action") && (b_out.getField("action").str().compare("terminate") != 0)) { qDebug() << "WORKER SERVICE BEFORE CREATE PAYLOAD EMIT"; emit push_payload(b_out); qDebug() << "WORKER SERVICE AFTER CREATE PAYLOAD EMIT"; return; } else if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "data" << b_out; } } catch (mongo::MsgAssertionException &e) { std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; std::cout << "m_service_name : " << m_service_name.toStdString() << std::endl; std::cout << "error on parsing JSON : " << e.what() << std::endl; if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "data" << json.toStdString(); } } BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (s_datas.isValid() && !s_datas.isEmpty()) { qDebug() << "WORKER PROCESS BEFORE EMIT"; emit push_payload(s_datas); qDebug() << "WORKER PROCESS AFTER EMIT"; } //m_mutex->unlock(); } <|endoftext|>